Merge branch 't3/server-terminal-watcher'
# Conflicts: # apps/server/package.json # apps/server/src/app.ts # pnpm-lock.yaml
This commit is contained in:
@@ -13,6 +13,8 @@
|
||||
"@fastify/websocket": "^11.0.1",
|
||||
"@shellbook/core": "workspace:*",
|
||||
"fastify": "^5.1.0",
|
||||
"chokidar": "^4.0.3",
|
||||
"node-pty": "^1.1.0",
|
||||
"ssh2": "^1.17.0",
|
||||
"yaml": "^2.9.1"
|
||||
},
|
||||
|
||||
@@ -22,6 +22,7 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
|
||||
await app.register(websocket);
|
||||
await app.register(workspacePlugin, { config: loadConfig(options.config) });
|
||||
await app.register(runsPlugin, { config: loadConfig(options.config), hub: options.events ?? new EventsHub() });
|
||||
await app.register((await import("./terminal/index")).terminalPlugin);
|
||||
|
||||
app.get("/api/health", async () => ({ ok: true }));
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Terminal integration
|
||||
|
||||
`terminalPlugin` registers `/api/terminal?session=<name>` after `@fastify/websocket`.
|
||||
Names must match `[a-z0-9-]{1,32}`. Each connection spawns its own
|
||||
`tmux new-session -A -s shellbook-<name>` attach client. A disconnect kills that
|
||||
client only; the session and its shell survive. Run `claude` in that shell using
|
||||
the user's own CLI login. Multiple tabs may attach to the same session.
|
||||
|
||||
Options: `workspaceDir`, `extraEnv` (string map, e.g. `ANTHROPIC_BASE_URL`), and
|
||||
`ptyFactory` for testing or platform adapters. The default workspace is
|
||||
`SHELLBOOK_WORKSPACE`, falling back to `./workspace`, resolved at registration.
|
||||
The workspace directory must already exist. Environment values are inherited
|
||||
and then overridden by `extraEnv`; input and native spawn exceptions are never
|
||||
logged. tmux keeps the environment of existing sessions: changing environment
|
||||
configuration does not rewrite an already running shell's environment.
|
||||
|
||||
Terminal frames use the core protocol, with raw text output. Invalid/binary
|
||||
messages close with 1008; input is limited to 64 KiB and dimensions to integer
|
||||
values 1..1000. Slow output consumers are disconnected at 1 MiB buffered output.
|
||||
The app's authentication layer must protect WebSocket upgrades too.
|
||||
|
||||
## Deployment
|
||||
|
||||
Install `tmux` and the real Claude Code CLI separately. The locked node-pty 1.1.0
|
||||
package ships macOS/Windows prebuilds but **no Linux prebuilds** (verified in its
|
||||
published package). On Debian 13 x64 / Node 22 install `python3` and
|
||||
`build-essential` before `pnpm install`; node-pty falls back to `node-gyp rebuild`.
|
||||
This checkout's installation and fake-PTY tests were run on Windows / Node 22;
|
||||
the optional real-tmux test runs only when `tmux -V` succeeds. Debian compilation
|
||||
and a real Claude login still require Linux verification.
|
||||
@@ -0,0 +1,93 @@
|
||||
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"); }));
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
# Notebook event source
|
||||
|
||||
`createNotebookWatcher(workspaceDir, { debounceMs?, onError? })` watches
|
||||
`workspaceDir/notebooks` recursively. Await `ready` before relying on events;
|
||||
existing files do not trigger an initial reload. `on(listener)` returns an
|
||||
unsubscribe function. `close()` stops watching and cancels pending notifications.
|
||||
Errors reject readiness during startup and reach `onError` (stderr by default),
|
||||
including errors after readiness. Owners should report failures through their logger.
|
||||
|
||||
Subscribe the `/api/events` broadcaster to this source; it does not create an
|
||||
HTTP route itself. Events are the core protocol's `file.changed` and
|
||||
`file.deleted`, with paths relative to `notebooks/` and forward slashes.
|
||||
Adds are changes, deletes are deletions, and a per-path debounce (100 ms default)
|
||||
keeps the most recent event. Non-Markdown files are ignored; symlinks are not followed.
|
||||
Chokidar 4 provides recursive Linux/Windows watching and normalizes atomic editor
|
||||
saves, avoiding platform-specific recursion and rename handling with raw fs.watch.
|
||||
@@ -0,0 +1,58 @@
|
||||
import { relative, resolve, isAbsolute, sep } from "node:path";
|
||||
import { watch } from "chokidar";
|
||||
import type { ServerEvent } from "@shellbook/core";
|
||||
|
||||
export type NotebookFileEvent = Extract<ServerEvent, { type: "file.changed" | "file.deleted" }>;
|
||||
export interface NotebookWatcher {
|
||||
/** Resolves after the initial scan; existing files do not emit changes. */
|
||||
ready: Promise<void>;
|
||||
/** Returns an unsubscribe function. */
|
||||
on(listener: (event: NotebookFileEvent) => void): () => void;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Watches workspace/notebooks recursively, including newly created directories.
|
||||
* Chokidar normalizes cross-platform events and editor atomic renames; v4 has no glob dependency.
|
||||
*/
|
||||
export function createNotebookWatcher(workspaceDir: string, options: {
|
||||
debounceMs?: number;
|
||||
onError?: (error: unknown) => void;
|
||||
} = {}): NotebookWatcher {
|
||||
const root = resolve(workspaceDir, "notebooks");
|
||||
const listeners = new Set<(event: NotebookFileEvent) => void>();
|
||||
const pending = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
let closed = false;
|
||||
const watcher = watch(root, { ignoreInitial: true, followSymlinks: false, atomic: true });
|
||||
const ready = new Promise<void>((resolveReady, reject) => {
|
||||
watcher.once("ready", resolveReady);
|
||||
watcher.on("error", (error) => {
|
||||
reject(error);
|
||||
if (options.onError) options.onError(error);
|
||||
else console.error("Notebook watcher error", error);
|
||||
});
|
||||
});
|
||||
// Callers can await ready; avoid an unhandled rejection before they attach.
|
||||
void ready.catch(() => {});
|
||||
const schedule = (type: NotebookFileEvent["type"], file: string) => {
|
||||
const path = relative(root, file).split(sep).join("/");
|
||||
if (closed || !path.endsWith(".md") || path.startsWith("../") || isAbsolute(path)) return;
|
||||
clearTimeout(pending.get(path));
|
||||
pending.set(path, setTimeout(() => {
|
||||
pending.delete(path);
|
||||
for (const listener of listeners) listener({ type, path });
|
||||
}, options.debounceMs ?? 100));
|
||||
};
|
||||
watcher.on("add", (file) => schedule("file.changed", file));
|
||||
watcher.on("change", (file) => schedule("file.changed", file));
|
||||
watcher.on("unlink", (file) => schedule("file.deleted", file));
|
||||
return {
|
||||
ready,
|
||||
on(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
||||
async close() {
|
||||
closed = true;
|
||||
for (const timer of pending.values()) clearTimeout(timer);
|
||||
pending.clear(); listeners.clear();
|
||||
await watcher.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { once } from "node:events";
|
||||
import { resolve } from "node:path";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import Fastify from "fastify";
|
||||
import websocket from "@fastify/websocket";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { buildApp } from "../src/app";
|
||||
import { isSessionName, parseTerminalMessage, terminalPlugin, nativePtyFactory, type TerminalPty } from "../src/terminal/index";
|
||||
|
||||
function fakePty() {
|
||||
let output: (text: string) => void = () => {};
|
||||
let exit: () => void = () => {};
|
||||
const dataDispose = vi.fn();
|
||||
const exitDispose = vi.fn();
|
||||
const pty: TerminalPty = {
|
||||
write: vi.fn(), resize: vi.fn(), kill: vi.fn(),
|
||||
onData: (listener) => { output = listener; return { dispose: dataDispose }; },
|
||||
onExit: (listener) => { exit = () => listener({ exitCode: 0 }); return { dispose: exitDispose }; },
|
||||
};
|
||||
return { pty, output: (text: string) => output(text), exit: () => exit(), dataDispose, exitDispose };
|
||||
}
|
||||
|
||||
describe("terminal validation", () => {
|
||||
it.each(["a", "abc-123", "a".repeat(32)])("accepts session %s", (name) => expect(isSessionName(name)).toBe(true));
|
||||
it.each([undefined, "", "A", "../x", "x;y", "a_b", "a".repeat(33), ["a"], "a\n"])("rejects session %s", (name) => expect(isSessionName(name)).toBe(false));
|
||||
it.each([
|
||||
{ type: "input", data: "echo hello\r" }, { type: "input", data: "" },
|
||||
{ type: "resize", cols: 120, rows: 40 },
|
||||
])("accepts %j", (message) => expect(parseTerminalMessage(JSON.stringify(message))).toEqual(message));
|
||||
it.each(["no", "null", "[]", '{}', '{"type":"input","data":1}',
|
||||
'{"type":"resize","cols":0,"rows":24}', '{"type":"resize","cols":80.5,"rows":24}',
|
||||
'{"type":"resize","cols":80,"rows":1001}', '{"type":"resize","cols":"80","rows":24}',
|
||||
JSON.stringify({ type: "input", data: "a".repeat(65537) }),
|
||||
])("rejects invalid frame %#", (text) => expect(parseTerminalMessage(text)).toBeUndefined());
|
||||
});
|
||||
|
||||
describe("terminal plugin", () => {
|
||||
it("is registered by buildApp and rejects invalid sessions", async () => {
|
||||
const app = await buildApp();
|
||||
try {
|
||||
expect(app.hasRoute({ method: "GET", url: "/api/terminal" })).toBe(true);
|
||||
expect((await app.inject("/api/terminal?session=BAD")).statusCode).toBe(400);
|
||||
} finally { await app.close(); }
|
||||
});
|
||||
it("attaches independent clients, forwards raw output/input/resize, and cleans up only each attach", async () => {
|
||||
const app = Fastify();
|
||||
await app.register(websocket);
|
||||
const first = fakePty(); const second = fakePty();
|
||||
const factory = vi.fn().mockReturnValueOnce(first.pty).mockReturnValueOnce(second.pty);
|
||||
await app.register(terminalPlugin, { workspaceDir: ".", extraEnv: { TERMINAL_TEST: "extra" }, ptyFactory: factory });
|
||||
await app.ready();
|
||||
const a = await app.injectWS("/api/terminal?session=main");
|
||||
const b = await app.injectWS("/api/terminal?session=main");
|
||||
try {
|
||||
expect(factory).toHaveBeenCalledTimes(2);
|
||||
expect(factory.mock.calls[0]).toEqual(["tmux", ["new-session", "-A", "-s", "shellbook-main"],
|
||||
expect.objectContaining({ cwd: resolve("."), env: expect.objectContaining({ ...process.env, TERMINAL_TEST: "extra" }) })]);
|
||||
a.send(JSON.stringify({ type: "input", data: "claude\r" }));
|
||||
a.send(JSON.stringify({ type: "resize", cols: 100, rows: 30 }));
|
||||
await vi.waitFor(() => expect(first.pty.resize).toHaveBeenCalledWith(100, 30));
|
||||
expect(first.pty.write).toHaveBeenCalledWith("claude\r");
|
||||
const received = once(a, "message");
|
||||
first.output("\u001b[32mhello\r\n");
|
||||
expect((await received)[0].toString()).toBe("\u001b[32mhello\r\n");
|
||||
// injectWS uses in-memory Duplexify streams whose close handshake does not
|
||||
// finish like a TCP socket. Terminate the server peer to model a lost tab.
|
||||
const peers = [...app.websocketServer.clients];
|
||||
peers[0].terminate();
|
||||
await vi.waitFor(() => expect(first.pty.kill).toHaveBeenCalledTimes(1));
|
||||
expect(second.pty.kill).not.toHaveBeenCalled();
|
||||
expect(first.dataDispose).toHaveBeenCalledOnce();
|
||||
const closed = once(b, "close"); second.exit(); await closed;
|
||||
expect(second.pty.kill).not.toHaveBeenCalled();
|
||||
expect(second.exitDispose).toHaveBeenCalledOnce();
|
||||
} finally { a.terminate(); b.terminate(); await app.close(); }
|
||||
});
|
||||
it.each(["malformed", JSON.stringify({ type: "resize", cols: -1, rows: 30 })])("closes invalid messages without forwarding", async (message) => {
|
||||
const app = Fastify(); await app.register(websocket);
|
||||
const fake = fakePty();
|
||||
await app.register(terminalPlugin, { ptyFactory: () => fake.pty }); await app.ready();
|
||||
const socket = await app.injectWS("/api/terminal?session=test");
|
||||
try {
|
||||
const closed = once(socket, "close"); socket.send(message);
|
||||
expect((await closed)[0]).toBe(1008);
|
||||
expect(fake.pty.kill).toHaveBeenCalledOnce();
|
||||
expect(fake.pty.write).not.toHaveBeenCalled(); expect(fake.pty.resize).not.toHaveBeenCalled();
|
||||
} finally { socket.terminate(); await app.close(); }
|
||||
});
|
||||
it("closes cleanly when spawning fails", async () => {
|
||||
const app = Fastify(); await app.register(websocket);
|
||||
await app.register(terminalPlugin, { ptyFactory: () => { throw new Error("missing tmux"); } }); await app.ready();
|
||||
const socket = await app.injectWS("/api/terminal?session=test");
|
||||
try { expect((await once(socket, "close"))[0]).toBe(1011); }
|
||||
finally { socket.terminate(); await app.close(); }
|
||||
});
|
||||
it("cleans up the attach client after a real TCP WebSocket close handshake", async () => {
|
||||
const app = Fastify(); await app.register(websocket);
|
||||
const fake = fakePty();
|
||||
await app.register(terminalPlugin, { ptyFactory: () => fake.pty });
|
||||
const address = await app.listen({ host: "127.0.0.1", port: 0 });
|
||||
const socket = new WebSocket(address.replace("http:", "ws:") + "/api/terminal?session=tcp");
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.addEventListener("open", () => resolve(), { once: true });
|
||||
socket.addEventListener("error", reject, { once: true });
|
||||
});
|
||||
const closed = new Promise<void>((resolve) => socket.addEventListener("close", () => resolve(), { once: true }));
|
||||
socket.close(); await closed;
|
||||
await vi.waitFor(() => expect(fake.pty.kill).toHaveBeenCalledOnce());
|
||||
expect(fake.dataDispose).toHaveBeenCalledOnce();
|
||||
} finally { socket.close(); await app.close(); }
|
||||
});
|
||||
});
|
||||
|
||||
const hasTmux = spawnSync("tmux", ["-V"]).status === 0;
|
||||
it.skipIf(!hasTmux)("real tmux session survives the attach client's exit and reattaches", async () => {
|
||||
const name = `shellbook-test-${process.pid}-${Date.now()}`;
|
||||
let pty: TerminalPty | undefined;
|
||||
try {
|
||||
pty = nativePtyFactory("tmux", ["new-session", "-A", "-s", name], { cwd: process.cwd(), cols: 80, rows: 24, env: { ...process.env, TERM: "xterm-256color" } });
|
||||
await vi.waitFor(() => expect(spawnSync("tmux", ["has-session", "-t", name]).status).toBe(0));
|
||||
pty.kill(); pty = undefined;
|
||||
expect(spawnSync("tmux", ["has-session", "-t", name]).status).toBe(0);
|
||||
pty = nativePtyFactory("tmux", ["new-session", "-A", "-s", name], { cols: 80, rows: 24, env: { ...process.env, TERM: "xterm-256color" } });
|
||||
let output = ""; pty.onData((data) => { output += data; });
|
||||
pty.write("printf 'shellbook-%s\\n' 'reattached'\r");
|
||||
await vi.waitFor(() => expect(output).toContain("shellbook-reattached"));
|
||||
} finally { pty?.kill(); try { execFileSync("tmux", ["kill-session", "-t", name]); } catch { /* Test cleanup only. */ } }
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { mkdtemp, mkdir, writeFile, rm, rename } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { createNotebookWatcher, type NotebookFileEvent } from "../src/watch/index";
|
||||
|
||||
it("watches nested Markdown, debounces writes, handles atomic saves/deletes and unsubscribes", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "shellbook-watch-"));
|
||||
await mkdir(join(dir, "notebooks", "setup"), { recursive: true });
|
||||
const file = join(dir, "notebooks", "setup", "test.md");
|
||||
await writeFile(file, "initial");
|
||||
const watcher = createNotebookWatcher(dir, { debounceMs: 100 });
|
||||
const events: NotebookFileEvent[] = [];
|
||||
const off = watcher.on((event) => events.push(event));
|
||||
try {
|
||||
await watcher.ready;
|
||||
expect(events).toEqual([]);
|
||||
await writeFile(file, "first"); await writeFile(file, "second");
|
||||
await vi.waitFor(() => expect(events).toEqual([{ type: "file.changed", path: "setup/test.md" }]));
|
||||
await writeFile(`${file}.tmp`, "replacement"); await rename(`${file}.tmp`, file);
|
||||
await vi.waitFor(() => expect(events).toHaveLength(2));
|
||||
expect(events[1]).toEqual({ type: "file.changed", path: "setup/test.md" });
|
||||
await rm(file);
|
||||
await vi.waitFor(() => expect(events[2]).toEqual({ type: "file.deleted", path: "setup/test.md" }));
|
||||
await mkdir(join(dir, "notebooks", "new"));
|
||||
await writeFile(join(dir, "notebooks", "new", "added.md"), "new");
|
||||
await vi.waitFor(() => expect(events[3]).toEqual({ type: "file.changed", path: "new/added.md" }));
|
||||
await writeFile(join(dir, "notebooks", "ignored.txt"), "ignore");
|
||||
await writeFile(join(dir, "outside.md"), "ignore");
|
||||
await new Promise((r) => setTimeout(r, 300)); expect(events).toHaveLength(4);
|
||||
off(); await writeFile(file, "unsubscribed");
|
||||
await new Promise((r) => setTimeout(r, 300)); expect(events).toHaveLength(4);
|
||||
} finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it("starts before notebooks exists and cancels pending notifications on close", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "shellbook-watch-"));
|
||||
const watcher = createNotebookWatcher(dir, { debounceMs: 500 });
|
||||
const listener = vi.fn(); watcher.on(listener);
|
||||
try {
|
||||
await watcher.ready; await mkdir(join(dir, "notebooks"));
|
||||
await writeFile(join(dir, "notebooks", "new.md"), "new");
|
||||
await new Promise((r) => setTimeout(r, 100)); await watcher.close();
|
||||
await new Promise((r) => setTimeout(r, 600)); expect(listener).not.toHaveBeenCalled();
|
||||
} finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
Generated
+32
@@ -26,9 +26,15 @@ importers:
|
||||
'@shellbook/core':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/core
|
||||
chokidar:
|
||||
specifier: ^4.0.3
|
||||
version: 4.0.3
|
||||
fastify:
|
||||
specifier: ^5.1.0
|
||||
version: 5.12.8
|
||||
node-pty:
|
||||
specifier: ^1.1.0
|
||||
version: 1.1.0
|
||||
ssh2:
|
||||
specifier: ^1.17.0
|
||||
version: 1.17.0
|
||||
@@ -599,6 +605,10 @@ packages:
|
||||
resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
|
||||
engines: {node: '>= 16'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==}
|
||||
engines: {node: '>= 14.16.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==}
|
||||
engines: {node: '>=22'}
|
||||
@@ -719,6 +729,12 @@ packages:
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
hasBin: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
@@ -760,6 +776,10 @@ packages:
|
||||
resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}
|
||||
engines: {node: '>= 6'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==}
|
||||
engines: {node: '>= 14.18.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==}
|
||||
|
||||
@@ -1340,6 +1360,10 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
readdirp: 4.1.2
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
@@ -1514,6 +1538,12 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
node-addon-api: 7.1.1
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
@@ -1562,6 +1592,8 @@ snapshots:
|
||||
string_decoder: 1.3.0
|
||||
util-deprecate: 1.0.2
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Local credentials and runtime data never belong in the workspace repository.
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
known_hosts
|
||||
data/
|
||||
*.pem
|
||||
*.key
|
||||
id_ed25519*
|
||||
id_rsa*
|
||||
*.swp
|
||||
*~
|
||||
@@ -0,0 +1,113 @@
|
||||
# Writing ShellBook notebooks
|
||||
|
||||
This repository is the user's workspace. Write runbooks as ordinary Markdown in
|
||||
`notebooks/**/*.md`. ShellBook renders these files live as you edit them. This
|
||||
terminal is a real shell in a persistent tmux session; start `claude` here using
|
||||
the user's CLI login. Do not add API clients, subscription tokens, or chat wrappers.
|
||||
|
||||
## Style and safety
|
||||
|
||||
- Show literal shell commands, directly in `sh` or `bash` fences. The displayed
|
||||
script is exactly what executes. No Python/JavaScript wrappers, generated command
|
||||
strings, hidden scripts, or `eval`.
|
||||
- One logical action per step. Explain the target, effect and prerequisites in prose.
|
||||
- Put checks before runs. Checks are strictly side-effect free: no writes, installs,
|
||||
service restarts, uploads or redirection to files. Exit 0 means passed; nonzero fails.
|
||||
- Make runs idempotent; test existing state before appending or replacing things.
|
||||
- Never put secrets in notebooks, defaults, prose, commands, captures, logs or artifact
|
||||
metadata. Never use `set -x` with secrets or print them. A secret parameter is an
|
||||
environment variable named exactly as declared; reference `$TOKEN`, never `{{TOKEN}}`.
|
||||
- Scripts execute as `bash -euo pipefail -s` without a TTY. Interactive tools belong
|
||||
in the terminal. Steps with `sudo` need passwordless `sudo -n`.
|
||||
- Never disable SSH host-key checking. Inventory names come from `hosts.yaml`.
|
||||
|
||||
## Frontmatter and substitution
|
||||
|
||||
```yaml
|
||||
---
|
||||
title: Example runbook
|
||||
params:
|
||||
host: { type: host, required: true, label: Target host }
|
||||
user: { type: name, default: admin, label: Login user }
|
||||
keyname: { type: name, default: "id_ed25519_{{host}}" }
|
||||
destination: { type: path, default: /etc/example.conf }
|
||||
comment: { type: string, label: Description }
|
||||
mode: { type: choice, options: [safe, full], default: safe }
|
||||
TOKEN: { type: secret, required: true, label: Access token }
|
||||
---
|
||||
```
|
||||
|
||||
All parameter fields: `type`, `required`, `default`, `label`, `options`. Omitted
|
||||
`required` is false. `options` is for `choice`; never set a default for a secret.
|
||||
Types: `host` selects an inventory name; `name` allows `[A-Za-z0-9._-]+`;
|
||||
`path` allows absolute/relative paths without NUL or newline; `string` is free text;
|
||||
`choice` must match an option; `secret` is supplied only through the environment.
|
||||
Non-secret defaults may reference other parameters.
|
||||
|
||||
Use `{{name}}` in prose, attributes and scripts. Script substitution is already
|
||||
shell-quoted by ShellBook's core: write `id {{user}}`, not `id '{{user}}'`.
|
||||
Do not invent escaping rules or assume templates expand like shell variables.
|
||||
Missing required parameters disable execution. In shell strings use ordinary
|
||||
shell variables where needed, e.g. `destination={{destination}}` then `"$destination"`.
|
||||
|
||||
## Step syntax and every attribute
|
||||
|
||||
````markdown
|
||||
```sh {check host="{{host}}" id=user-exists title="User exists" timeout=10}
|
||||
id {{user}}
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=os title="Read operating system" capture=os_id}
|
||||
. /etc/os-release
|
||||
printf '%s\n' "$ID"
|
||||
```
|
||||
|
||||
```sh {run host="{{host}}" id=reload title="Reload SSH configuration" sudo confirm timeout=60}
|
||||
sshd -t
|
||||
systemctl reload ssh
|
||||
```
|
||||
````
|
||||
|
||||
- `run` or `check`: required kind. `sh` and `bash` retain Markdown highlighting.
|
||||
- `host="{{host}}"`: remote target. `on=local`: ShellBook service host instead;
|
||||
use one target form per step. Local does **not** mean the browser's computer.
|
||||
- `id=...`: unique, stable identifier; default is the title's slug. Use explicit
|
||||
IDs for references. `title="..."`: human-readable heading.
|
||||
- `sudo`: passwordless elevation, both kinds. `confirm`: run only, prompts first;
|
||||
remote runs against hosts tagged `prod` already default to confirmation.
|
||||
- `timeout=60`: seconds; defaults are 300 for run and 30 for check.
|
||||
- `capture=var`: both kinds, stores trimmed stdout as a runtime value for subsequent
|
||||
steps. Print only the desired value; use `{{var}}` later. Never capture secrets.
|
||||
- `artifacts="a,b"`: run only, comma-separated files relative to that run's fresh
|
||||
workdir. Offered after success; remote files are fetched using SFTP.
|
||||
- `upload="src:dst"`: run only, copies a prior artifact to a remote destination
|
||||
before executing. Use explicit, non-colliding temporary destinations and clean up.
|
||||
|
||||
## Artifacts and conditional follow-up
|
||||
|
||||
````markdown
|
||||
```sh {run on=local id=keygen title="Generate key pair" artifacts="{{keyname}},{{keyname}}.pub"}
|
||||
ssh-keygen -q -t ed25519 -N '' -C {{user}}@{{host}} -f {{keyname}}
|
||||
```
|
||||
|
||||
```sh {run host="{{host}}" id=inspect-key title="Inspect uploaded public key" upload="{{keyname}}.pub:/tmp/shellbook-key.pub"}
|
||||
ssh-keygen -lf /tmp/shellbook-key.pub
|
||||
rm -f /tmp/shellbook-key.pub
|
||||
```
|
||||
|
||||
:::after{step=keygen}
|
||||
Download the private key and store it securely with mode 600.
|
||||
:::
|
||||
|
||||
:::after{step=inspect-key failed}
|
||||
Inspect the error before retrying; check that the earlier artifact is still available.
|
||||
:::
|
||||
````
|
||||
|
||||
`:::after{step=id}` appears after that step succeeds in the current browser session;
|
||||
add `failed` for failure. Refer to a real step ID. Each local run gets a fresh
|
||||
`data/runs/<run-id>/` workdir; do not assume files survive between steps. Use artifact
|
||||
uploads to transfer earlier results. Artifacts expire after 24 hours by default;
|
||||
private keys are sensitive, downloadable once, then removed. Do not commit them.
|
||||
|
||||
See the three notebooks for complete SSH-key, read-only hardening and Debian package examples.
|
||||
@@ -0,0 +1,13 @@
|
||||
# Replace these examples with your own inventory. No passwords or private keys.
|
||||
# ShellBook uses its own SSH identity and confirms unknown host keys explicitly.
|
||||
hosts:
|
||||
- name: staging
|
||||
address: 192.0.2.10
|
||||
user: admin
|
||||
port: 22
|
||||
tags: [staging]
|
||||
# - name: production
|
||||
# address: 192.0.2.20
|
||||
# user: admin
|
||||
# port: 22
|
||||
# tags: [prod] # Remote run steps ask for confirmation by default.
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
title: Base hardening checks
|
||||
params:
|
||||
host: { type: host, required: true, label: Target server }
|
||||
---
|
||||
|
||||
# Base hardening checks
|
||||
|
||||
Read-only baseline for Debian servers. These checks report state; they do not
|
||||
change configuration. A failed check needs investigation, not an automatic fix.
|
||||
SSH configuration checks need passwordless sudo to read all included files.
|
||||
|
||||
```sh {check host="{{host}}" id=os title="Identify operating system" capture=os_id}
|
||||
. /etc/os-release
|
||||
printf '%s\n' "$ID"
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=no-root-password title="Root password login disabled" sudo}
|
||||
sshd -T | grep -Eq '^permitrootlogin (no|prohibit-password|without-password)$'
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=no-password-auth title="SSH password authentication disabled" sudo}
|
||||
sshd -T | grep -qx 'passwordauthentication no'
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=no-interactive-auth title="SSH keyboard-interactive authentication disabled" sudo}
|
||||
sshd -T | grep -qx 'kbdinteractiveauthentication no'
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=firewall title="Firewall rules present" sudo timeout=10}
|
||||
nft list ruleset | grep -q 'hook input'
|
||||
```
|
||||
|
||||
This confirms an input hook exists, not that the complete firewall policy is safe.
|
||||
|
||||
```sh {check host="{{host}}" id=security-updates title="Automatic security updates active"}
|
||||
systemctl is-enabled unattended-upgrades.service
|
||||
systemctl is-active unattended-upgrades.service
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=no-failed-units title="No failed systemd units"}
|
||||
test "$(systemctl --failed --no-legend --plain | wc -l)" -eq 0
|
||||
```
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
title: Install and enable a package
|
||||
params:
|
||||
host: { type: host, required: true, label: Debian server }
|
||||
package: { type: name, required: true, default: nginx, label: Package }
|
||||
service: { type: name, required: true, default: nginx, label: Systemd service }
|
||||
---
|
||||
|
||||
# Install and enable {{package}}
|
||||
|
||||
For Debian hosts using apt and systemd. Check the package/service pairing before
|
||||
running; installing packages can start services and expose network ports. Existing
|
||||
apt indexes must be available. Runs require passwordless sudo and confirmation.
|
||||
|
||||
```sh {check host="{{host}}" id=apt-available title="APT is available"}
|
||||
command -v apt-get
|
||||
command -v systemctl
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=package-available title="Package exists in configured repositories"}
|
||||
apt-cache show -- {{package}} > /dev/null
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=installed title="Package already installed"}
|
||||
dpkg-query -W -f='${Status}\n' -- {{package}} | grep -qx 'install ok installed'
|
||||
```
|
||||
|
||||
An absent package is an expected failed check. Proceed with installation only
|
||||
after the repository check succeeds.
|
||||
|
||||
```sh {run host="{{host}}" id=install title="Install package if absent" sudo confirm timeout=300}
|
||||
if ! dpkg-query -W -f='${Status}\n' -- {{package}} 2>/dev/null | grep -qx 'install ok installed'; then
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -- {{package}}
|
||||
fi
|
||||
```
|
||||
|
||||
```sh {run host="{{host}}" id=enable title="Enable and start service" sudo confirm timeout=60}
|
||||
systemctl enable --now -- {{service}}
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=enabled title="Service enabled"}
|
||||
systemctl is-enabled -- {{service}}
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=active title="Service active"}
|
||||
systemctl is-active -- {{service}}
|
||||
```
|
||||
|
||||
:::after{step=enable}
|
||||
The enable command succeeded. Run the final checks and verify application health
|
||||
and firewall policy before directing traffic to **{{host}}**.
|
||||
:::
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: New server SSH key
|
||||
params:
|
||||
host: { type: host, required: true, label: Target server }
|
||||
user: { type: name, required: true, default: admin, label: Login user }
|
||||
keyname: { type: name, default: "id_ed25519_{{host}}" }
|
||||
---
|
||||
|
||||
# New server SSH key
|
||||
|
||||
Creates a key pair for **{{user}}** on **{{host}}** and authorizes it.
|
||||
The host needs OpenSSH and passwordless sudo. The private key stays local to
|
||||
ShellBook until downloaded; only the public key is uploaded.
|
||||
|
||||
```sh {check host="{{host}}" id=user-exists title="User exists"}
|
||||
id {{user}}
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" id=password-login-disabled title="Password login disabled" sudo}
|
||||
sshd -T | grep -qx 'passwordauthentication no'
|
||||
```
|
||||
|
||||
```sh {run on=local id=keygen title="Generate key pair" artifacts="{{keyname}},{{keyname}}.pub"}
|
||||
ssh-keygen -q -t ed25519 -N '' -C {{user}}@{{host}} -f {{keyname}}
|
||||
```
|
||||
|
||||
Each execution generates a fresh pair in its own workdir. Rerunning this step
|
||||
intentionally creates a new key; it does not overwrite a key from an earlier run.
|
||||
|
||||
```sh {run host="{{host}}" id=authorize title="Authorize key" sudo confirm upload="{{keyname}}.pub:/tmp/shellbook-new-key.pub"}
|
||||
home=$(getent passwd {{user}} | cut -d: -f6)
|
||||
test -n "$home"
|
||||
group=$(id -gn {{user}})
|
||||
install -d -m 700 -o {{user}} -g "$group" "$home/.ssh"
|
||||
touch "$home/.ssh/authorized_keys"
|
||||
key=$(cat /tmp/shellbook-new-key.pub)
|
||||
if ! grep -qxF -- "$key" "$home/.ssh/authorized_keys"; then
|
||||
printf '%s\n' "$key" >> "$home/.ssh/authorized_keys"
|
||||
fi
|
||||
chown {{user}}:"$group" "$home/.ssh/authorized_keys"
|
||||
chmod 600 "$home/.ssh/authorized_keys"
|
||||
rm -f /tmp/shellbook-new-key.pub
|
||||
```
|
||||
|
||||
:::after{step=keygen}
|
||||
Download the private key once and save it securely:
|
||||
|
||||
- **Linux:** `~/.ssh/{{keyname}}`, then `chmod 600 ~/.ssh/{{keyname}}`.
|
||||
- **Windows:** `C:\Users\<you>\.ssh\{{keyname}}`, accessible only to your user.
|
||||
|
||||
Keep the public artifact available for the authorization step. Never commit the private key.
|
||||
:::
|
||||
|
||||
:::after{step=authorize failed}
|
||||
Inspect the output and confirm the account and sudo access before retrying.
|
||||
:::
|
||||
Reference in New Issue
Block a user