Use node-pty for native terminal support and chokidar for recursive cross-platform watching with atomic-save normalization. Validate terminal messages, detach clients safely, and expose debounced typed notebook events.
94 lines
4.2 KiB
TypeScript
94 lines
4.2 KiB
TypeScript
import { createRequire } from "node:module";
|
|
import { resolve } from "node:path";
|
|
import type { FastifyPluginAsync } from "fastify";
|
|
import type { IPty, IPtyForkOptions } from "node-pty";
|
|
import type { TerminalClientMessage } from "@shellbook/core";
|
|
|
|
export type TerminalPty = Pick<IPty, "write" | "resize" | "kill" | "onData" | "onExit">;
|
|
export type PtyFactory = (file: string, args: string[], options: IPtyForkOptions) => TerminalPty;
|
|
export interface TerminalOptions {
|
|
/** Defaults to SHELLBOOK_WORKSPACE, then ./workspace. */
|
|
workspaceDir?: string;
|
|
extraEnv?: Record<string, string>;
|
|
ptyFactory?: PtyFactory;
|
|
}
|
|
|
|
export function isSessionName(value: unknown): value is string {
|
|
return typeof value === "string" && /^[a-z0-9-]{1,32}$/.test(value);
|
|
}
|
|
|
|
/** Limits bound PTY resource use and reject non-integral/zero terminal sizes. */
|
|
export function parseTerminalMessage(text: string): TerminalClientMessage | undefined {
|
|
let value: unknown;
|
|
try { value = JSON.parse(text); } catch { return undefined; }
|
|
if (!value || typeof value !== "object") return undefined;
|
|
const m = value as Record<string, unknown>;
|
|
if (m.type === "input" && typeof m.data === "string" && m.data.length <= 64 * 1024) {
|
|
return { type: "input", data: m.data };
|
|
}
|
|
if (m.type === "resize" && Number.isInteger(m.cols) && Number.isInteger(m.rows)
|
|
&& (m.cols as number) >= 1 && (m.cols as number) <= 1000
|
|
&& (m.rows as number) >= 1 && (m.rows as number) <= 1000) {
|
|
return { type: "resize", cols: m.cols as number, rows: m.rows as number };
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
const require = createRequire(import.meta.url);
|
|
export const nativePtyFactory: PtyFactory = (file, args, options) =>
|
|
(require("node-pty") as typeof import("node-pty")).spawn(file, args, options);
|
|
|
|
/** Each socket owns only a tmux attach client. Never send kill-session to tmux. */
|
|
export const terminalPlugin: FastifyPluginAsync<TerminalOptions> = async (app, options) => {
|
|
const spawn = options.ptyFactory ?? nativePtyFactory;
|
|
const cwd = resolve(options.workspaceDir ?? process.env.SHELLBOOK_WORKSPACE ?? "workspace");
|
|
app.get<{ Querystring: { session?: string } }>("/api/terminal", {
|
|
websocket: true,
|
|
preValidation: async (request, reply) => {
|
|
if (!isSessionName(request.query.session)) {
|
|
return reply.code(400).send({ error: "Invalid terminal session name" });
|
|
}
|
|
},
|
|
}, (socket, request) => {
|
|
let pty: TerminalPty;
|
|
try {
|
|
pty = spawn("tmux", ["new-session", "-A", "-s", `shellbook-${request.query.session}`], {
|
|
name: "xterm-256color", cols: 80, rows: 24, cwd,
|
|
env: { ...process.env, ...options.extraEnv },
|
|
});
|
|
} catch {
|
|
// No exception details: native errors may include environment values.
|
|
socket.close(1011, "Terminal unavailable");
|
|
return;
|
|
}
|
|
let disposed = false;
|
|
const subscriptions: Array<{ dispose(): void }> = [];
|
|
const cleanup = (kill: boolean) => {
|
|
if (disposed) return;
|
|
disposed = true;
|
|
for (const subscription of subscriptions) subscription.dispose();
|
|
if (kill) { try { pty.kill(); } catch { /* Already exited. */ } }
|
|
};
|
|
socket.on("close", () => cleanup(true));
|
|
socket.on("error", () => { cleanup(true); socket.close(); });
|
|
socket.on("message", (data: { toString(): string }, binary: boolean) => {
|
|
if (disposed) return;
|
|
const message = binary ? undefined : parseTerminalMessage(data.toString());
|
|
if (!message) { cleanup(true); socket.close(1008, "Invalid terminal message"); return; }
|
|
try {
|
|
if (message.type === "input") pty.write(message.data);
|
|
else pty.resize(message.cols, message.rows);
|
|
} catch { cleanup(true); socket.close(1011, "Terminal unavailable"); }
|
|
});
|
|
subscriptions.push(pty.onData((data) => {
|
|
if (socket.readyState !== 1) return;
|
|
// Disconnect slow clients rather than accumulate unbounded terminal output.
|
|
if (socket.bufferedAmount > 1024 * 1024) {
|
|
cleanup(true); socket.close(1013, "Terminal client too slow"); return;
|
|
}
|
|
socket.send(data, (error?: Error) => { if (error) { cleanup(true); socket.close(); } });
|
|
}));
|
|
subscriptions.push(pty.onExit(() => { cleanup(false); socket.close(1000, "Terminal exited"); }));
|
|
});
|
|
};
|