Files
2025-06-24 22:17:56 -04:00

84 lines
2.0 KiB
JavaScript

import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import expressWs from 'express-ws';
import { spawn } from 'node-pty';
// import json from './secrets/config.json' with { type: 'json' };
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT || 5164;
const app = express();
expressWs(app); // enable websockets for the app
// parse form data
app.use(express.urlencoded({ extended: true }));
app.use(express.json({ extended: true }));
app.use('/node_modules', express.static('node_modules'));
// map of active sessions
const sessions = new Map();
// shell interface
app.get('/', (req, res) => {
res.sendFile('shell.html', { root: path.join(__dirname, 'HTML') });
});
// websocket endpoint that spawns/attaches to a fish shell
app.ws('/shell-ws', (ws, req) => {
const { id } = req.query;
if (!id) {
ws.close();
return;
}
let session = sessions.get(id);
if (!session) {
const shell = spawn('su', ['-', 'ion606', '-s', '/usr/bin/fish'], {
cols: 80,
rows: 24,
cwd: process.env.HOME,
env: process.env
});
session = { shell, clients: new Set() };
sessions.set(id, session);
shell.onData((data) => {
for (const client of session.clients) {
client.send(JSON.stringify({ data }));
}
});
shell.onExit((e) => {
for (const client of session.clients) {
client.send(JSON.stringify({ event: 'exit', code: e }));
}
sessions.delete(id);
});
}
session.clients.add(ws);
ws.on('message', (msg) => session.shell.write(msg));
ws.on('close', () => {
session.clients.delete(ws);
});
});
// endpoint used by the client to explicitly close a session
app.post('/kill-session', (req, res) => {
const { id } = req.query;
const session = sessions.get(id);
if (session) {
session.shell.kill();
sessions.delete(id);
}
res.end();
});
app.get('*', (req, res) => res.end());
app.listen(PORT, '0.0.0.0', () =>
console.log(`server listening on http://localhost:${PORT}`)
);