-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
133 lines (112 loc) · 3.97 KB
/
Copy pathserver.js
File metadata and controls
133 lines (112 loc) · 3.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const { createServer } = require('http');
const next = require('next');
const { WebSocketServer } = require('ws');
const pty = require('node-pty');
const { execSync } = require('child_process');
// Capture startup fingerprint for stale-server detection
const STARTED_AT = new Date().toISOString();
let GIT_SHA = 'unknown';
try { GIT_SHA = execSync('git rev-parse --short HEAD', { timeout: 3000 }).toString().trim(); } catch { /* ok */ }
const dev = process.env.NODE_ENV !== 'production';
const hostname = 'localhost';
const port = parseInt(process.env.PORT || '3000', 10);
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
// Shell sessions storage
const sessions = new Map();
app.prepare().then(() => {
const upgradeHandler = app.getUpgradeHandler();
const server = createServer(async (req, res) => {
try {
await handle(req, res);
} catch (err) {
console.error('Error occurred handling', req.url, err);
res.statusCode = 500;
res.end('internal server error');
}
});
// WebSocket server for shell - noServer mode so we can handle upgrade manually
const wss = new WebSocketServer({ noServer: true });
// Handle WebSocket upgrades
server.on('upgrade', (req, socket, head) => {
const { pathname } = new URL(req.url, `http://${hostname}:${port}`);
if (pathname === '/api/shell/ws') {
// Handle shell WebSocket
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
} else {
// Let Next.js handle HMR and other WebSocket connections
upgradeHandler(req, socket, head);
}
});
wss.on('connection', (ws, req) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const cwd = url.searchParams.get('cwd') || process.cwd();
const sessionId = `shell-${Date.now()}`;
console.log(`Shell session ${sessionId} starting in ${cwd}`);
const shell = process.env.SHELL || '/bin/bash';
const ptyProcess = pty.spawn(shell, [], {
name: 'xterm-256color',
cols: 80,
rows: 24,
cwd,
env: {
...process.env,
TERM: 'xterm-256color',
},
});
sessions.set(sessionId, { pty: ptyProcess, ws });
// Send data from pty to websocket
ptyProcess.onData((data) => {
if (ws.readyState === ws.OPEN) {
ws.send(JSON.stringify({ type: 'output', data }));
}
});
ptyProcess.onExit(({ exitCode }) => {
console.log(`Shell session ${sessionId} exited with code ${exitCode}`);
if (ws.readyState === ws.OPEN) {
ws.send(JSON.stringify({ type: 'exit', code: exitCode }));
}
sessions.delete(sessionId);
});
// Handle messages from websocket
ws.on('message', (message) => {
try {
const msg = JSON.parse(message.toString());
switch (msg.type) {
case 'input':
ptyProcess.write(msg.data);
break;
case 'resize':
if (msg.cols && msg.rows) {
ptyProcess.resize(msg.cols, msg.rows);
}
break;
}
} catch (err) {
console.error('Error processing message:', err);
}
});
ws.on('close', () => {
console.log(`Shell session ${sessionId} closed`);
ptyProcess.kill();
sessions.delete(sessionId);
});
ws.on('error', (err) => {
console.error(`Shell session ${sessionId} error:`, err);
ptyProcess.kill();
sessions.delete(sessionId);
});
// Send ready message
ws.send(JSON.stringify({ type: 'ready', sessionId, cwd }));
});
server.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
console.log(`> Shell WebSocket available at ws://${hostname}:${port}/api/shell/ws`);
console.log(`> Started at ${STARTED_AT} (git: ${GIT_SHA}) — restart server after API route changes in dev mode`);
// Expose via global so /api/health can surface it
global.__hexops_started_at = STARTED_AT;
global.__hexops_git_sha = GIT_SHA;
});
});