Skip to content

Commit dd2e1fd

Browse files
author
linyuan.yang
committed
ptyworker
1 parent 8561313 commit dd2e1fd

2 files changed

Lines changed: 302 additions & 53 deletions

File tree

‎packages/sbot/src/Channel/web/PtyService.ts‎

Lines changed: 198 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,14 @@ import http from 'http';
22
import fs from 'fs';
33
import path from 'path';
44
import os from 'os';
5+
import { fork, type ChildProcess } from 'child_process';
56
import { WebSocketServer, WebSocket } from 'ws';
6-
import type * as PtyTypes from '@lydell/node-pty';
77
import { LoggerService } from '../../Core/LoggerService';
88

99
const logger = LoggerService.getLogger('PtyService.ts');
10-
11-
let ptyMod: typeof PtyTypes | null = null;
12-
let ptyLoadError: string | null = null;
13-
14-
function loadPty(): typeof PtyTypes | null {
15-
if (ptyMod) return ptyMod;
16-
if (ptyLoadError) return null;
17-
try {
18-
ptyMod = require('@lydell/node-pty') as typeof PtyTypes;
19-
} catch (e: any) {
20-
ptyLoadError = e?.message ?? String(e);
21-
logger.warn(`@lydell/node-pty unavailable, terminal feature disabled: ${ptyLoadError}`);
22-
}
23-
return ptyMod;
24-
}
10+
const OPEN_TIMEOUT_MS = 10_000;
11+
const WORKER_READY_TIMEOUT_MS = 10_000;
12+
const OUTPUT_BACKPRESSURE_LIMIT = 2 * 1024 * 1024;
2513

2614
export interface ShellOption {
2715
/** Stable id, used by client when requesting `open`. */
@@ -30,6 +18,8 @@ export interface ShellOption {
3018
label: string;
3119
/** Absolute executable path. */
3220
path: string;
21+
/** Server-side default arguments for safer interactive startup. */
22+
args?: string[];
3323
}
3424

3525
interface OpenMessage {
@@ -45,6 +35,12 @@ interface InputMessage { type: 'input'; data: string; }
4535
interface ResizeMessage { type: 'resize'; cols: number; rows: number; }
4636
type ClientMessage = OpenMessage | InputMessage | ResizeMessage;
4737

38+
type WorkerMessage =
39+
| { type: 'ready'; shell: string; cwd: string; pid: number }
40+
| { type: 'data'; data: string }
41+
| { type: 'exit'; code?: number; signal?: number }
42+
| { type: 'error'; message: string };
43+
4844
let cachedShells: ShellOption[] | null = null;
4945

5046
function fileExists(p: string): boolean {
@@ -59,20 +55,19 @@ function detectWindowsShells(): ShellOption[] {
5955
const programFilesX86 = process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)';
6056
const localAppData = process.env.LOCALAPPDATA ?? '';
6157

62-
const candidates: Array<[string, string]> = [
63-
[path.join(sysRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), 'PowerShell'],
58+
const candidates: Array<[string, string, string[]?]> = [
6459
[path.join(sysRoot, 'System32', 'cmd.exe'), 'Command Prompt'],
65-
[path.join(programFiles, 'PowerShell', '7', 'pwsh.exe'), 'PowerShell 7'],
66-
[path.join(programFilesX86, 'PowerShell', '7', 'pwsh.exe'), 'PowerShell 7 (x86)'],
60+
[path.join(programFiles, 'PowerShell', '7', 'pwsh.exe'), 'PowerShell 7', ['-NoLogo', '-NoProfile']],
61+
[path.join(programFilesX86, 'PowerShell', '7', 'pwsh.exe'), 'PowerShell 7 (x86)', ['-NoLogo', '-NoProfile']],
6762
[path.join(programFiles, 'Git', 'bin', 'bash.exe'), 'Git Bash'],
6863
[path.join(programFilesX86, 'Git', 'bin', 'bash.exe'), 'Git Bash (x86)'],
6964
[path.join(localAppData, 'Microsoft', 'WindowsApps', 'wsl.exe'), 'WSL'],
7065
];
7166
const seen = new Set<string>();
72-
for (const [p, label] of candidates) {
67+
for (const [p, label, args] of candidates) {
7368
if (!p || seen.has(p.toLowerCase()) || !fileExists(p)) continue;
7469
seen.add(p.toLowerCase());
75-
out.push({ id: p, label, path: p });
70+
out.push({ id: p, label, path: p, args });
7671
}
7772
return out;
7873
}
@@ -117,6 +112,23 @@ function defaultShell(shells: ShellOption[]): string {
117112
return process.env.SHELL ?? shells[0]?.path ?? '/bin/sh';
118113
}
119114

115+
function resolveShell(requested: string | undefined, shells: ShellOption[]): { path: string; args: string[] } {
116+
if (requested) {
117+
const known = shells.find(s => s.path.toLowerCase() === requested.toLowerCase());
118+
if (known) return { path: known.path, args: known.args ?? [] };
119+
if (fileExists(requested)) return { path: requested, args: [] };
120+
}
121+
const fallbackPath = defaultShell(shells);
122+
const fallback = shells.find(s => s.path.toLowerCase() === fallbackPath.toLowerCase());
123+
return { path: fallbackPath, args: fallback?.args ?? [] };
124+
}
125+
126+
function isBlockedShell(shellPath: string): boolean {
127+
if (process.platform !== 'win32') return false;
128+
const normalized = shellPath.toLowerCase();
129+
return normalized.endsWith('\\windowspowershell\\v1.0\\powershell.exe');
130+
}
131+
120132
function sanitizeCwd(cwd?: string): string | undefined {
121133
if (!cwd) return undefined;
122134
try {
@@ -126,6 +138,10 @@ function sanitizeCwd(cwd?: string): string | undefined {
126138
return undefined;
127139
}
128140

141+
function workerScriptPath(): string {
142+
return path.join(__dirname, 'PtyWorker.js');
143+
}
144+
129145
/**
130146
* Per-connection: one WebSocket drives one pty. Closing either side tears down the other.
131147
*
@@ -142,37 +158,85 @@ export class PtyService {
142158
// own — corrupting the already-101'd response of whichever WSS handled the
143159
// request. Routing here keeps each WSS to its own path.
144160
const wss = this.wss = new WebSocketServer({ noServer: true });
145-
wss.on('connection', (ws) => this.handleConnection(ws));
161+
wss.on('connection', (ws, req) => this.handleConnection(ws, req));
162+
wss.on('error', e => logger.warn(`pty websocket server error: ${e?.message ?? e}`));
146163
server.on('upgrade', (req, socket, head) => {
147164
const url = req.url ?? '';
148165
const pathname = url.split('?')[0];
149166
if (pathname !== '/ws/pty') return;
150-
wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req));
167+
try {
168+
wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req));
169+
} catch (e: any) {
170+
logger.error(`pty upgrade failed: ${e?.message ?? e}`);
171+
try { socket.destroy(); } catch { /* ignore */ }
172+
}
151173
});
152174
logger.info('PtyService attached to /ws/pty');
153175
}
154176

155-
private handleConnection(ws: WebSocket): void {
156-
let term: PtyTypes.IPty | null = null;
177+
private handleConnection(ws: WebSocket, req: http.IncomingMessage): void {
178+
let worker: ChildProcess | null = null;
157179
let opened = false;
180+
let ready = false;
158181
let exited = false;
182+
let readyTimer: ReturnType<typeof setTimeout> | null = null;
183+
const peer = `${req.socket.remoteAddress}:${req.socket.remotePort}`;
159184

160185
const sendControl = (obj: object) => {
161-
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(obj));
186+
if (ws.readyState !== WebSocket.OPEN) return;
187+
try {
188+
ws.send(JSON.stringify(obj), err => {
189+
if (err) logger.warn(`pty control send failed: peer=${peer} err=${err.message}`);
190+
});
191+
} catch (e: any) {
192+
logger.warn(`pty control send failed: peer=${peer} err=${e?.message ?? e}`);
193+
}
194+
};
195+
196+
const clearReadyTimer = () => {
197+
if (readyTimer) {
198+
clearTimeout(readyTimer);
199+
readyTimer = null;
200+
}
201+
};
202+
203+
const sendWorker = (obj: object) => {
204+
if (!worker?.connected) return;
205+
try {
206+
worker.send(obj, err => {
207+
if (err) logger.warn(`pty worker send failed: peer=${peer} err=${err.message}`);
208+
});
209+
} catch (e: any) {
210+
logger.warn(`pty worker send failed: peer=${peer} err=${e?.message ?? e}`);
211+
}
162212
};
163213

164214
const cleanup = () => {
165-
if (term && !exited) {
166-
try { term.kill(); } catch { /* pty already dead */ }
215+
clearTimeout(openTimer);
216+
clearReadyTimer();
217+
if (worker && !exited) {
218+
try {
219+
if (worker.connected) worker.send({ type: 'kill' });
220+
} catch { /* worker may already be wedged */ }
221+
try { worker.kill(); } catch { /* already gone */ }
167222
}
168-
term = null;
223+
worker = null;
169224
};
170225

226+
const openTimer = setTimeout(() => {
227+
if (opened || ws.readyState !== WebSocket.OPEN) return;
228+
logger.warn(`pty open timeout: peer=${peer}`);
229+
sendControl({ type: 'error', message: 'Terminal open timeout' });
230+
try { ws.close(1008, 'open timeout'); } catch { /* ignore */ }
231+
}, OPEN_TIMEOUT_MS);
232+
233+
logger.info(`pty connected: peer=${peer}`);
234+
171235
ws.on('message', (raw, isBinary) => {
172236
// Bytes only make sense once the pty is open, and they are user input.
173237
if (isBinary) {
174-
if (!term) return;
175-
try { term.write(raw.toString('utf8')); } catch (e: any) { logger.warn(`pty.write: ${e?.message ?? e}`); }
238+
if (!ready) return;
239+
sendWorker({ type: 'input', data: raw.toString('utf8') });
176240
return;
177241
}
178242
let msg: ClientMessage;
@@ -181,58 +245,139 @@ export class PtyService {
181245
if (msg.type === 'open') {
182246
if (opened) return;
183247
opened = true;
184-
const mod = loadPty();
185-
if (!mod) {
186-
sendControl({ type: 'error', message: `Terminal feature unavailable on this server: ${ptyLoadError}` });
248+
clearTimeout(openTimer);
249+
const shells = listShells();
250+
const requested = msg.shell?.trim();
251+
const shell = resolveShell(requested, shells);
252+
if (isBlockedShell(shell.path)) {
253+
logger.warn(`pty blocked shell: peer=${peer} shell=${shell.path}`);
254+
sendControl({ type: 'error', message: 'Windows PowerShell 5.1 is disabled for the built-in terminal because it can block node-pty startup on this server. Use Command Prompt, PowerShell 7, Git Bash, or WSL instead.' });
187255
ws.close();
188256
return;
189257
}
190-
const shells = listShells();
191-
const requested = msg.shell?.trim();
192-
const shellPath = requested && fileExists(requested) ? requested : defaultShell(shells);
193258
const cwd = sanitizeCwd(msg.cwd) ?? os.homedir();
194259
const cols = Math.max(2, Math.min(500, msg.cols ?? 80));
195260
const rows = Math.max(2, Math.min(200, msg.rows ?? 24));
196261
const env: NodeJS.ProcessEnv = { ...process.env, ...msg.env, TERM: 'xterm-256color' };
262+
logger.info(`pty opening: peer=${peer} shell=${shell.path} cwd=${cwd} size=${cols}x${rows}`);
263+
264+
const workerPath = workerScriptPath();
265+
if (!fs.existsSync(workerPath)) {
266+
logger.error(`pty worker script missing: ${workerPath}`);
267+
sendControl({ type: 'error', message: 'Terminal worker script is missing. Please rebuild sbot.' });
268+
ws.close();
269+
return;
270+
}
197271
try {
198-
term = mod.spawn(shellPath, [], {
199-
name: 'xterm-256color',
200-
cols, rows, cwd, env,
272+
worker = fork(workerPath, [], {
273+
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
274+
execArgv: [],
275+
env: { ...process.env, NODE_OPTIONS: '' },
201276
});
202277
} catch (e: any) {
203-
logger.error(`pty.spawn failed (shell=${shellPath}): ${e?.message ?? e}`);
204-
sendControl({ type: 'error', message: `Failed to spawn shell: ${e?.message ?? e}` });
278+
logger.error(`pty worker fork failed: ${e?.message ?? e}`);
279+
sendControl({ type: 'error', message: `Failed to start terminal worker: ${e?.message ?? e}` });
205280
ws.close();
206281
return;
207282
}
208-
term.onData(data => {
209-
if (ws.readyState === WebSocket.OPEN) ws.send(data);
283+
284+
readyTimer = setTimeout(() => {
285+
if (ready || exited) return;
286+
logger.error(`pty worker ready timeout: peer=${peer} shell=${shell.path}`);
287+
sendControl({ type: 'error', message: 'Terminal startup timed out; the pty worker was stopped.' });
288+
try { ws.close(1011, 'pty startup timeout'); } catch { /* ignore */ }
289+
cleanup();
290+
}, WORKER_READY_TIMEOUT_MS);
291+
292+
worker.on('message', (raw: WorkerMessage) => {
293+
if (!raw || typeof raw !== 'object') return;
294+
295+
if (raw.type === 'ready') {
296+
ready = true;
297+
clearReadyTimer();
298+
logger.info(`pty ready: peer=${peer} pid=${raw.pid}`);
299+
sendControl({ type: 'ready', shell: raw.shell, cwd: raw.cwd, pid: raw.pid });
300+
return;
301+
}
302+
303+
if (raw.type === 'data') {
304+
if (ws.readyState !== WebSocket.OPEN) return;
305+
if (ws.bufferedAmount > OUTPUT_BACKPRESSURE_LIMIT) {
306+
logger.warn(`pty output backpressure, closing: peer=${peer} buffered=${ws.bufferedAmount}`);
307+
sendControl({ type: 'error', message: 'Terminal output is too large or the client is too slow; closing terminal.' });
308+
try { ws.close(1011, 'pty output backpressure'); } catch { /* ignore */ }
309+
cleanup();
310+
return;
311+
}
312+
try {
313+
ws.send(raw.data, err => {
314+
if (err) logger.warn(`pty output send failed: peer=${peer} err=${err.message}`);
315+
});
316+
} catch (e: any) {
317+
logger.warn(`pty output send failed: peer=${peer} err=${e?.message ?? e}`);
318+
}
319+
return;
320+
}
321+
322+
if (raw.type === 'error') {
323+
logger.error(`pty worker error: peer=${peer} message=${raw.message}`);
324+
sendControl({ type: 'error', message: raw.message });
325+
try { ws.close(); } catch { /* ignore */ }
326+
cleanup();
327+
return;
328+
}
329+
330+
if (raw.type === 'exit') {
331+
exited = true;
332+
clearReadyTimer();
333+
logger.info(`pty exited: peer=${peer} code=${raw.code} signal=${raw.signal ?? ''}`);
334+
sendControl({ type: 'exit', code: raw.code, signal: raw.signal });
335+
try { ws.close(); } catch { /* ignore */ }
336+
}
210337
});
211-
term.onExit(({ exitCode, signal }) => {
338+
worker.on('exit', (code, signal) => {
339+
clearReadyTimer();
340+
if (exited) return;
212341
exited = true;
213-
sendControl({ type: 'exit', code: exitCode, signal });
342+
logger.info(`pty worker exited: peer=${peer} code=${code} signal=${signal ?? ''}`);
343+
if (ws.readyState === WebSocket.OPEN) {
344+
sendControl({ type: 'exit', code, signal });
345+
}
346+
try { ws.close(); } catch { /* ignore */ }
347+
});
348+
worker.on('error', e => {
349+
clearReadyTimer();
350+
logger.error(`pty worker process error: peer=${peer} err=${e?.message ?? e}`);
351+
sendControl({ type: 'error', message: `Terminal worker error: ${e?.message ?? e}` });
214352
try { ws.close(); } catch { /* ignore */ }
353+
cleanup();
215354
});
216-
sendControl({ type: 'ready', shell: shellPath, cwd, pid: term.pid });
355+
sendWorker({ type: 'open', shell: shell.path, args: shell.args, cwd, cols, rows, env });
217356
return;
218357
}
219358

220-
if (!term) return;
359+
if (!ready) return;
221360

222361
if (msg.type === 'input') {
223-
try { term.write(msg.data); } catch (e: any) { logger.warn(`pty.write: ${e?.message ?? e}`); }
362+
sendWorker({ type: 'input', data: msg.data });
224363
return;
225364
}
226365

227366
if (msg.type === 'resize') {
228367
const cols = Math.max(2, Math.min(500, msg.cols));
229368
const rows = Math.max(2, Math.min(200, msg.rows));
230-
try { term.resize(cols, rows); } catch (e: any) { logger.warn(`pty.resize: ${e?.message ?? e}`); }
369+
sendWorker({ type: 'resize', cols, rows });
231370
}
232371
});
233372

234-
ws.on('close', cleanup);
235-
ws.on('error', () => cleanup());
373+
ws.on('close', (code, reason) => {
374+
logger.info(`pty closed: peer=${peer} code=${code} reason=${reason?.toString() || ''}`);
375+
cleanup();
376+
});
377+
ws.on('error', e => {
378+
logger.warn(`pty websocket error: peer=${peer} err=${e?.message ?? e}`);
379+
cleanup();
380+
});
236381
}
237382

238383
dispose(): void {

0 commit comments

Comments
 (0)