elemental-to-web/index.js
2025-04-02 22:55:51 -04:00

66 lines
No EOL
1.7 KiB
JavaScript

import { spawn } from "node:child_process";
import { mkdir } from 'node:fs/promises';
import { createHash } from "node:crypto";
import express from "express";
let sessions = {};
let channels = {};
const app = express();
app.use(express.json())
app.set('trust proxy', true)
app.use(express.static('static'));
app.post('/', async function (req, res) {
let id = 'web:' + createHash('sha256').update(req.ip).digest('hex');
console.log(req.ip)
id = id.slice(0, 24);
if (!sessions[id]) {
try {
await mkdir(`./bin/${id}`);
} catch (err) {
console.log(err)
}
sessions[id] = spawn('../elem', [id], {
'cwd': `./bin/${id}`
});
sessions[id].stdout.on('data', (chunk) => {
if (chunk.toString().length > 1) {
let str = chunk.toString();
//str = str.replaceAll(/user:([0-9]+)/g, '<@$1>');
if (channels[id].headersSent) return;
try {
channels[id].send(str).header('access-allow-control-origin', '*')
} catch (err) { }
}
});
sessions[id].on('close', () => {
delete sessions[id];
})
}
setTimeout(async function () {
if (!sessions[id]) return;
if (channels[id].headersSent) return;
try {
channels[id].send('Input is possibly malformed.').header('access-allow-control-origin', '*')
} catch (err) {
}
}, 1000);
channels[id] = res;
let msgs = req.body.data.split('\n');
setTimeout(async function () {
sessions[id].stdin.write(msgs[0] + '\n');
}, 100);
});
app.listen(process.env.port || 3007)