-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.ts
More file actions
276 lines (243 loc) · 7.58 KB
/
Copy pathserver.ts
File metadata and controls
276 lines (243 loc) · 7.58 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import { createServer } from "http";
import { parse } from "url";
import next from "next";
import { WebSocketServer, WebSocket } from "ws";
import * as pty from "node-pty";
import { initDb } from "@/lib/db";
import { startWatcher, addUpdateClient } from "@/lib/claude/watcher";
import { startStatusMonitor } from "@/lib/status-monitor";
import { setupHooks } from "@/lib/hooks/setup";
import {
validateSession,
parseCookies,
COOKIE_NAME,
hasUsers,
} from "@/lib/auth";
import { stopAllTunnels } from "@/lib/tunnels";
const dev = process.env.NODE_ENV !== "production";
const hostname = process.env.HOST || (dev ? "localhost" : "0.0.0.0");
// Support: npm run dev -- -p 3012
const pFlagIndex = process.argv.indexOf("-p");
const portArg = pFlagIndex !== -1 ? process.argv[pFlagIndex + 1] : undefined;
const port = parseInt(portArg || process.env.PORT || "3011", 10);
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(async () => {
const server = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url!, true);
await handle(req, res, parsedUrl);
} catch (err) {
console.error("Error occurred handling", req.url, err);
res.statusCode = 500;
res.end("internal server error");
}
});
const terminalWss = new WebSocketServer({ noServer: true });
const updatesWss = new WebSocketServer({ noServer: true });
server.on("upgrade", (request, socket, head) => {
const { pathname } = parse(request.url || "");
// Validate auth for WebSocket connections
if (hasUsers()) {
const cookies = parseCookies(request.headers.cookie);
const token = cookies[COOKIE_NAME];
const user = token ? validateSession(token) : null;
if (!user) {
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
socket.destroy();
return;
}
}
if (pathname === "/ws/terminal") {
terminalWss.handleUpgrade(request, socket, head, (ws) => {
terminalWss.emit("connection", ws, request);
});
} else if (pathname === "/ws/updates") {
updatesWss.handleUpgrade(request, socket, head, (ws) => {
setupHeartbeat(ws);
addUpdateClient(ws);
});
}
});
// Heartbeat: ping every 30s, kill if no pong in 10s
const HEARTBEAT_INTERVAL = 30000;
const _HEARTBEAT_TIMEOUT = 10000;
function setupHeartbeat(ws: WebSocket) {
let alive = true;
ws.on("pong", () => {
alive = true;
});
const interval = setInterval(() => {
if (!alive) {
ws.terminate();
clearInterval(interval);
return;
}
alive = false;
ws.ping();
}, HEARTBEAT_INTERVAL);
ws.on("close", () => clearInterval(interval));
}
interface PtyEntry {
process: pty.IPty;
ws: WebSocket | null;
buffer: string[];
idleTimer: NodeJS.Timeout | null;
}
const ptyPool = new Map<string, PtyEntry>();
const MAX_SCROLLBACK_BUFFER = 50000;
const PTY_IDLE_TIMEOUT_MS = parseInt(
process.env.CLAUDE_DECK_PTY_IDLE_TIMEOUT_MS || "300000",
10
);
function scheduleEviction(id: string, entry: PtyEntry) {
cancelEviction(entry);
entry.idleTimer = setTimeout(() => {
entry.idleTimer = null;
try {
entry.process.kill();
} catch {}
ptyPool.delete(id);
}, PTY_IDLE_TIMEOUT_MS);
}
function cancelEviction(entry: PtyEntry) {
if (entry.idleTimer) {
clearTimeout(entry.idleTimer);
entry.idleTimer = null;
}
}
function spawnPty(): { id: string; entry: PtyEntry } {
const shell = process.env.SHELL || "/bin/zsh";
const minimalEnv: { [key: string]: string } = {
PATH: process.env.PATH || "/usr/local/bin:/usr/bin:/bin",
HOME: process.env.HOME || "/",
USER: process.env.USER || "",
SHELL: shell,
TERM: "xterm-256color",
COLORTERM: "truecolor",
LANG: process.env.LANG || "en_US.UTF-8",
};
const proc = pty.spawn(shell, [], {
name: "xterm-256color",
cols: 80,
rows: 24,
cwd: process.env.HOME || "/",
env: minimalEnv,
});
const id = `pty_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
const entry: PtyEntry = {
process: proc,
ws: null,
buffer: [],
idleTimer: null,
};
proc.onData((data: string) => {
entry.buffer.push(data);
if (entry.buffer.length > MAX_SCROLLBACK_BUFFER) {
entry.buffer.splice(0, entry.buffer.length - MAX_SCROLLBACK_BUFFER);
}
if (entry.ws?.readyState === WebSocket.OPEN) {
entry.ws.send(JSON.stringify({ type: "output", data }));
}
});
proc.onExit(({ exitCode }) => {
if (entry.ws?.readyState === WebSocket.OPEN) {
entry.ws.send(JSON.stringify({ type: "exit", code: exitCode }));
}
cancelEviction(entry);
ptyPool.delete(id);
});
ptyPool.set(id, entry);
return { id, entry };
}
function attachWsToPty(ws: WebSocket, entry: PtyEntry, id: string) {
// Detach previous WebSocket if any
if (entry.ws && entry.ws !== ws && entry.ws.readyState === WebSocket.OPEN) {
entry.ws.onclose = null;
entry.ws.onerror = null;
entry.ws.close(1000, "Replaced by new connection");
}
entry.ws = ws;
cancelEviction(entry);
// Replay buffered output so the client sees prior terminal state
if (entry.buffer.length > 0) {
ws.send(JSON.stringify({ type: "output", data: entry.buffer.join("") }));
}
ws.on("message", (message: Buffer) => {
try {
const msg = JSON.parse(message.toString());
switch (msg.type) {
case "input":
entry.process.write(msg.data);
break;
case "resize":
entry.process.resize(msg.cols, msg.rows);
break;
case "command":
entry.process.write(msg.data + "\r");
break;
}
} catch (err) {
console.error("Error parsing message:", err);
}
});
ws.on("close", () => {
if (entry.ws === ws) {
entry.ws = null;
scheduleEviction(id, entry);
}
});
ws.on("error", () => {
if (entry.ws === ws) {
entry.ws = null;
scheduleEviction(id, entry);
}
});
}
// Terminal connections
terminalWss.on("connection", (ws: WebSocket, request) => {
setupHeartbeat(ws);
const { query } = parse(request.url || "", true);
const requestedPtyId = typeof query.ptyId === "string" ? query.ptyId : null;
// Try to reattach to existing PTY
if (requestedPtyId && ptyPool.has(requestedPtyId)) {
const entry = ptyPool.get(requestedPtyId)!;
ws.send(JSON.stringify({ type: "pty-id", ptyId: requestedPtyId }));
attachWsToPty(ws, entry, requestedPtyId);
return;
}
// Spawn new PTY
try {
const { id, entry } = spawnPty();
ws.send(JSON.stringify({ type: "pty-id", ptyId: id }));
attachWsToPty(ws, entry, id);
} catch (err) {
console.error("Failed to spawn pty:", err);
ws.send(
JSON.stringify({ type: "error", message: "Failed to start terminal" })
);
ws.close();
}
});
await initDb();
console.log("> Database initialized");
setupHooks();
startWatcher();
startStatusMonitor();
const shutdown = () => {
stopAllTunnels();
for (const entry of ptyPool.values()) {
cancelEviction(entry);
try {
entry.process.kill();
} catch {}
}
ptyPool.clear();
process.exit(0);
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
server.listen(port, () => {
console.log(`> ClaudeDeck ready on http://${hostname}:${port}`);
});
});