Compare commits

..
12 Commits
Author SHA1 Message Date
Florian Schmidt 27be03d79a test(server): make the notebook watcher test robust under load
The full parallel test run on Windows can delay file events by more
than the 100 ms debounce, which split one burst into two events and
failed the test intermittently. Use a 300 ms debounce, longer quiet
windows and explicit wait timeouts.
2026-11-16 10:31:11 +01:00
Florian Schmidt 324ad4b39a fix: show why SSH connection tests and runs fail (#7)
Test connection, key installation and runs now tell authentication
failures apart from unreachable hosts (refused, timeout, DNS, ...)
instead of a generic "SSH connection failed".

The web client keeps the server's deliberate error messages (4xx,
502, 503) and shows them in the hosts page; unexpected 500 errors
still show only the status. The reload hint appears only on 409
conflicts.
2026-11-16 10:31:11 +01:00
Florian Schmidt 83e4e3f15e Merge branch 't3/manage-host-ssh-credentials'
# Conflicts:
#	.agents/mind/architecture.md
#	apps/server/src/app.ts
#	apps/web/src/App.tsx
#	packages/core/src/protocol.ts
2026-11-16 10:24:42 +01:00
Florian Schmidt 488f992bd3 fix(web): send workspace-relative notebook paths from the chat panel (#8)
The app passes notebook paths relative to notebooks/, but the chat
protocol uses workspace paths (notebooks/...). Every message sent while a
notebook was open was rejected as invalid, and "Open notebook" links on
Claude's edits loaded a non-existent path. ChatPanel now converts at its
boundary in both directions.
2026-11-16 10:23:05 +01:00
Florian Schmidt 63458dd3e4 Merge branch 't3/claude-chat-panel'
# Conflicts:
#	.agents/mind/gotchas.md
#	packages/core/src/protocol.ts
2026-11-16 10:23:05 +01:00
Florian Schmidt df6698c67d Merge branch 't3/notebook-management-authoring'
# Conflicts:
#	.agents/mind/architecture.md
#	packages/core/src/protocol.ts
2026-11-16 10:19:57 +01:00
Florian Schmidt 4d9a632625 feat(hosts): manage servers and encrypted SSH credentials in UI (#7) 2026-11-16 10:19:52 +01:00
Florian Schmidt 2e907b75f2 fix(server): keep existing notebooks manageable and pruning inside notebooks/ (#9)
Reading, saving, renaming and deleting applied the create-time name rules
to existing files, so notebooks named outside those rules (umlauts,
brackets; written by git or Claude) were listed but returned 400. Name rules
now apply to new paths only; existing paths keep the traversal/symlink checks.

Empty-folder pruning compared a realpath against an unresolved root. With a
symlinked workspace path it walked past notebooks/ and removed the
notebooks folder itself. It now uses the resolved root and stops at it.
2026-11-16 10:19:02 +01:00
Florian Schmidt 0055001abf feat(web): add notebook chat panel (#8) 2026-11-16 10:17:20 +01:00
Florian Schmidt 911387264b feat(notebooks): manage and author notebooks in the web UI (#9)
Add atomic, versioned notebook mutations, a searchable folder tree, and editor insertion forms. Validate notebook paths and symlink roots and retain drafts after external changes.

Add yaml as a direct web dependency, reusing the existing workspace library for comment-preserving frontmatter edits.
2026-11-16 10:16:43 +01:00
Florian Schmidt 7095842cf0 Merge branch 't3/settings-first-run-setup' 2026-11-16 10:15:50 +01:00
Florian Schmidt 02a22bef40 feat(settings): add browser setup and administration (#10) 2026-11-16 10:15:04 +01:00
65 changed files with 4753 additions and 155 deletions
+5 -1
View File
@@ -2,10 +2,14 @@
- [2026-11-15] **Custom app instead of marimo/Atuin/Runme.** Need: literal, copyable shell + SSH run + checks + params + dynamic downloads + Claude Code CLI next to the notebook. No existing tool covers all; marimo hid commands behind Python. - [2026-11-15] **Custom app instead of marimo/Atuin/Runme.** Need: literal, copyable shell + SSH run + checks + params + dynamic downloads + Claude Code CLI next to the notebook. No existing tool covers all; marimo hid commands behind Python.
- [2026-11-15] **TypeScript monorepo** (core / server / web). One language; node-pty + xterm.js is the proven path for the embedded Claude terminal. - [2026-11-15] **TypeScript monorepo** (core / server / web). One language; node-pty + xterm.js is the proven path for the embedded Claude terminal.
- [2026-11-15] **AI = real `claude` CLI in a tmux-backed terminal panel.** Uses the user's subscription legitimately; marimo's ACP panel was deprecated and API-key chat is not wanted. - [2026-11-15] **AI = real `claude` CLI in chat or tmux terminal (#8).** Chat uses per-turn headless stream-json with explicit resume; restricted file tools, optional Bash, dedicated authenticated WebSocket. Subscription login stays with the CLI; no SDK/API-key chat.
- [2026-11-15] **Workspace (notebooks, hosts.yaml) is a separate git repo** from the app code; the app ships a `CLAUDE.md` format guide into it. - [2026-11-15] **Workspace (notebooks, hosts.yaml) is a separate git repo** from the app code; the app ships a `CLAUDE.md` format guide into it.
- [2026-11-16] **buildApp wiring:** auth registered first and on by default (`auth:false` only in tests); one EventsHub feeds /api/events from runs and the notebook watcher (`watchNotebooks`); terminal cwd = config.workspaceDir. - [2026-11-16] **buildApp wiring:** auth registered first and on by default (`auth:false` only in tests); one EventsHub feeds /api/events from runs and the notebook watcher (`watchNotebooks`); terminal cwd = config.workspaceDir.
- [2026-11-16] **Secrets on SSH:** exported via `export NAME=<shellQuote>` lines on stdin before the script (sshd AcceptEnv unreliable); redacted from streamed output, captures and audit. - [2026-11-16] **Secrets on SSH:** exported via `export NAME=<shellQuote>` lines on stdin before the script (sshd AcceptEnv unreliable); redacted from streamed output, captures and audit.
- [2026-11-16] **Deploy:** Node 22 from the official nodejs.org tarball verified against SHASUMS256; node-pty 1.1.0 has no Linux prebuilds, so the installer adds build-essential + python3. - [2026-11-16] **Deploy:** Node 22 from the official nodejs.org tarball verified against SHASUMS256; node-pty 1.1.0 has no Linux prebuilds, so the installer adds build-essential + python3.
- [2026-11-16] **Settings (#10):** browser setup consumes private setup-token; cookies are bound to the password hash, and sign-out-all atomically rotates the persisted secret. Browser auth mutations serialize and close active WebSockets.
- [2026-11-16] **Notebook management (#9):** a shared mutation queue serializes saves/create/move/duplicate/delete. Exclusive hard-link publication prevents target replacement; saves use temp+rename. The recursive watcher updates lists; deleted open drafts are retained. Frontmatter helpers use YAML document nodes.
- [2026-11-16] **Host credentials (#7):** write-only AES-256-GCM files under dataDir, host-name AAD; shared SSH connect selects per-host password/key. ssh2 1.17.0 has no client user-certificate pairing API. Hosts plugin owns management routes and preserves inventory comments/version checks.
## Archive ## Archive
+3
View File
@@ -7,4 +7,7 @@
- [2026-11-16] **Env names:** single data dir variable is `SHELLBOOK_DATA_DIR` (server config, auth, CLI, installer). SSH key: `SHELLBOOK_SSH_KEY`. - [2026-11-16] **Env names:** single data dir variable is `SHELLBOOK_DATA_DIR` (server config, auth, CLI, installer). SSH key: `SHELLBOOK_SSH_KEY`.
- [2026-11-16] **Exit codes vs errors:** a non-zero script exit is a normal result (check ❌) and goes only in run.finished; run.error is for transport/setup failures. - [2026-11-16] **Exit codes vs errors:** a non-zero script exit is a normal result (check ❌) and goes only in run.finished; run.error is for transport/setup failures.
- [2026-11-16] **Notebook root symlinks (#9):** validating only child components after realpath(root) permits a symlinked notebooks root. Notebook reads and mutations validate the root itself before walking children; regression-covered. Workspace CLI/filesystem writers remain trusted against concurrent path swaps.
- [2026-11-16] **Chat CLI permissions (#8):** allowedTools only auto-approves; tools + restricted mode (2.1.248+) enforce the file/tool boundary. Synthetic fixture tests never invoke the real CLI; deployment must verify installed-version/login compatibility.
## Archive ## Archive
+2 -2
View File
@@ -14,7 +14,7 @@
- Notebooks stay plain, readable Markdown. - Notebooks stay plain, readable Markdown.
## Table of Contents ## Table of Contents
- `architecture.md` — 7 entries — why custom app, stack, AI integration, workspace split - `architecture.md` — 8 entries — why custom app, stack, AI integration, workspace split
- `attempts.md` — 2 entries — marimo + marimo-pair trial and why it was dropped - `attempts.md` — 2 entries — marimo + marimo-pair trial and why it was dropped
- `open.md` — 2 entries — open design questions - `open.md` — 2 entries — open design questions
- `gotchas.md` — 5 entries — integration foot-guns (CRLF scripts, host-key event order, tmux vs systemd, env names) - `gotchas.md` — 6 entries — integration foot-guns (CRLF scripts, host-key event order, tmux vs systemd, env names)
+3 -2
View File
@@ -18,8 +18,9 @@ hosts over SSH. Spec: `docs/spec.md` — read it before any design change.
- **Strict SSH host key checking.** Unknown keys require explicit user confirmation (TOFU). - **Strict SSH host key checking.** Unknown keys require explicit user confirmation (TOFU).
- **`check` steps must be side-effect free**; only `run` steps change hosts. - **`check` steps must be side-effect free**; only `run` steps change hosts.
- Notebooks stay valid, readable Markdown in any renderer (Gitea/GitHub). - Notebooks stay valid, readable Markdown in any renderer (Gitea/GitHub).
- AI integration uses the real Claude Code CLI in a terminal (user's own login). No - AI integration uses the real `claude` CLI with the user's own login: interactively
embedding of subscription credentials, no SDK-based chat on subscription auth. in the terminal panel or headless (`-p`, stream-json) behind the chat panel. No
embedding of subscription credentials, API-key requirement, or SDK-based chat.
## Stack and layout ## Stack and layout
+29 -1
View File
@@ -8,4 +8,32 @@ Notebook-style runbooks for Linux servers.
- Steps can produce files that appear as downloads, and reveal follow-up notes. - Steps can produce files that appear as downloads, and reveal follow-up notes.
- Claude Code (the real CLI) runs in a built-in terminal panel and edits notebooks live. - Claude Code (the real CLI) runs in a built-in terminal panel and edits notebooks live.
Status: design phase. See [docs/spec.md](docs/spec.md). Host and SSH credential management is available from **Servers & SSH** in the sidebar. See [docs/spec.md](docs/spec.md).
## Manage servers in the browser
Open **Servers & SSH** to add, edit (including rename), or delete a server. Address
accepts a hostname, IPv4 or IPv6; port defaults to 22. Tags remain in `hosts.yaml`.
Disk edits reload live; stale edits return a conflict. Reload hosts explicitly to
start again from the latest inventory.
Select **SSH credentials** for a host to choose the ShellBook key, a password, or a
pasted/uploaded private key with an optional passphrase. Credentials are write-only:
the browser sees their type, key fingerprint and save time, never saved secrets.
Selecting ShellBook key removes the saved password/private key. OpenSSH user
certificates are unavailable with ssh2 1.17.0 (no client certificate pairing API).
**Test connection** verifies SSH authentication with the same strict host-key
confirmation as runbook execution. **Install ShellBook key** requires a saved
password and previews the exact idempotent authorized_keys script before execution.
After success, choose ShellBook key to remove the stored password. **Forget host
key** asks for confirmation; the next connection requires fingerprint verification.
The page also displays ShellBook's public key with a Copy button.
Secrets are AES-256-GCM encrypted in `SHELLBOOK_DATA_DIR/ssh-credentials/`; the
random encryption key is `SHELLBOOK_DATA_DIR/ssh-credentials.key`. Both key and
credential files use mode 0600 on POSIX. Keep this data directory outside the git
workspace, back it up securely, and restore the key together with the ciphertext.
Windows does not implement POSIX file modes; use an appropriately restricted data
directory ACL there. Never put these files into the workspace repository.
+26
View File
@@ -94,3 +94,29 @@ uploads, and capture/runtime rendering without bash. The full shipped `ssh-key.m
flow generates real keys and skips cleanly when bash or ssh-keygen is unavailable; flow generates real keys and skips cleanly when bash or ssh-keygen is unavailable;
it runs in CI/Linux, and also on Windows when a working bash with ssh-keygen is it runs in CI/Linux, and also on Windows when a working bash with ssh-keygen is
installed. No real target host is modified by these tests. installed. No real target host is modified by these tests.
## Setup and settings (#10)
On first startup, `dataDir/setup-token` is created privately (0600). The startup
message names its path, never the token. Read it locally and finish setup in the
browser. GET `/api/auth/setup` returns `{required}`; POST accepts
`{token,newPassword,confirmPassword}`, consumes the token, and returns 204 with a
session cookie (409 once configured). Setup/login share a per-IP limiter and the
origin check. Keep the data directory private and owned by the service user.
Authenticated routes: POST `/api/settings/password` accepts
`{currentPassword,newPassword,confirmPassword}`; POST `/api/settings/sessions/revoke`
rotates the signing key atomically. Both return 204 with a replacement cookie and
close existing WebSockets. Passwords need 12 characters and at most 4096 bytes.
Hash-bound session signatures invalidate cookies after CLI password changes too.
Previously issued cookies from before this feature require a fresh login once.
GET `/api/settings/session` returns `{lifetimeSeconds}`; GET `/api/settings/system`
returns package version, workspace/data paths, and Node version. GET
`/api/settings/claude` runs `claude --version` with no shell, a 3-second timeout
and 4096-byte output limit. `loginAppearsPresent` checks existence only of the
service user's `~/.claude/.credentials.json`; it cannot prove login validity
(and does not inspect macOS Keychain credentials). All status responses are no-store.
Auth mutations are serialized within the single service process. Run one server
per data directory. Already-running host jobs are not cancelled by revocation.
Forward-auth access must be revoked at the upstream provider.
+6
View File
@@ -1,3 +1,5 @@
import { registerSettings } from "./settings";
import { hostsPlugin } from "./hosts";
import Fastify, { type FastifyInstance } from "fastify"; import Fastify, { type FastifyInstance } from "fastify";
import websocket from "@fastify/websocket"; import websocket from "@fastify/websocket";
import { loadConfig, type ServerConfig } from "./config"; import { loadConfig, type ServerConfig } from "./config";
@@ -7,6 +9,7 @@ import { terminalPlugin, type TerminalOptions } from "./terminal";
import { createNotebookWatcher } from "./watch"; import { createNotebookWatcher } from "./watch";
import { registerAuth, type AuthOptions } from "./auth"; import { registerAuth, type AuthOptions } from "./auth";
import { registerStatic } from "./static"; import { registerStatic } from "./static";
import { chatPlugin } from "./chat";
export interface AppOptions { export interface AppOptions {
logger?: boolean; logger?: boolean;
@@ -37,10 +40,13 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
const hub = options.events ?? new EventsHub(); const hub = options.events ?? new EventsHub();
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false }); const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth }); if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
await registerSettings(app, config);
await app.register(websocket); await app.register(websocket);
await app.register(workspacePlugin, { config }); await app.register(workspacePlugin, { config });
await app.register(hostsPlugin, { config });
await app.register(runsPlugin, { config, hub }); await app.register(runsPlugin, { config, hub });
await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir }); await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir });
await app.register(chatPlugin, { config });
if (options.watchNotebooks) { if (options.watchNotebooks) {
const watcher = createNotebookWatcher(config.workspaceDir, { const watcher = createNotebookWatcher(config.workspaceDir, {
+58 -10
View File
@@ -1,6 +1,8 @@
import { createHmac } from "node:crypto";
import { ensureSetupToken, matchesSetupToken, removeSetupToken, setupTokenPath, validNewPassword } from "./setup";
import type { FastifyInstance } from "fastify"; import type { FastifyInstance } from "fastify";
import { readPasswordHash, verifyPassword } from "./credentials"; import { readPasswordHash, verifyPassword, setPassword } from "./credentials";
import { loadSessionSecret, signSession, verifySession } from "./session"; import { loadSessionSecret, signSession, verifySession, rotateSessionSecret } from "./session";
export interface AuthOptions { export interface AuthOptions {
dataDir: string; dataDir: string;
@@ -12,7 +14,17 @@ export interface AuthOptions {
} }
const normalizeIp = (ip: string) => ip.replace(/^::ffff:/, ""); const normalizeIp = (ip: string) => ip.replace(/^::ffff:/, "");
export async function registerAuth(app: FastifyInstance, options: AuthOptions): Promise<void> { export async function registerAuth(app: FastifyInstance, options: AuthOptions): Promise<void> {
const secret = loadSessionSecret(options.dataDir); let secret = loadSessionSecret(options.dataDir);
if (!await readPasswordHash(options.dataDir)) {
await ensureSetupToken(options.dataDir);
app.log.warn(`Set up ShellBook in the browser; read the one-time token at ${setupTokenPath(options.dataDir)}`);
} else await removeSetupToken(options.dataDir);
// Binding to the persisted hash also revokes sessions after CLI password changes.
const sessionKey = async () => createHmac("sha256", secret).update(await readPasswordHash(options.dataDir) ?? "unconfigured").digest();
let mutation: Promise<unknown> = Promise.resolve();
const exclusive = <T,>(action: () => Promise<T>): Promise<T> => {
const next = mutation.then(action); mutation = next.catch(() => {}); return next;
};
const maxAge = options.sessionMaxAgeSeconds ?? 30 * 86400; const maxAge = options.sessionMaxAgeSeconds ?? 30 * 86400;
if (!Number.isSafeInteger(maxAge) || maxAge <= 0) throw new Error("Invalid session lifetime"); if (!Number.isSafeInteger(maxAge) || maxAge <= 0) throw new Error("Invalid session lifetime");
const failures = new Map<string, { count: number; until: number }>(); const failures = new Map<string, { count: number; until: number }>();
@@ -27,7 +39,7 @@ export async function registerAuth(app: FastifyInstance, options: AuthOptions):
try { if (new URL(origin).host !== request.headers.host) return reply.code(403).send({ error: "Origin rejected" }); } try { if (new URL(origin).host !== request.headers.host) return reply.code(403).send({ error: "Origin rejected" }); }
catch { return reply.code(403).send({ error: "Origin rejected" }); } catch { return reply.code(403).send({ error: "Origin rejected" }); }
} }
if (path === "/api/health" || path === "/api/auth/login") return; if (path === "/api/health" || path === "/api/auth/login" || path === "/api/auth/setup") return;
const forward = options.forwardAuth; const forward = options.forwardAuth;
const peer = normalizeIp(request.raw.socket?.remoteAddress ?? ""); const peer = normalizeIp(request.raw.socket?.remoteAddress ?? "");
if (forward && forward.trustedProxyIps.some(ip => normalizeIp(ip) === peer)) { if (forward && forward.trustedProxyIps.some(ip => normalizeIp(ip) === peer)) {
@@ -35,24 +47,60 @@ export async function registerAuth(app: FastifyInstance, options: AuthOptions):
if (typeof user === "string" && user.trim()) return; if (typeof user === "string" && user.trim()) return;
} }
const token = request.headers.cookie?.split(";").map(part => part.trim()).find(part => part.startsWith("shellbook_session="))?.slice("shellbook_session=".length); const token = request.headers.cookie?.split(";").map(part => part.trim()).find(part => part.startsWith("shellbook_session="))?.slice("shellbook_session=".length);
if (!token || !verifySession(secret, token)) return reply.code(401).send({ error: "Authentication required" }); if (!token || !verifySession(await sessionKey(), token)) return reply.code(401).send({ error: "Authentication required" });
}); });
app.post("/api/auth/login", { bodyLimit: 8192 }, async (request, reply) => { function reserveAttempt(ip: string, reply: import("fastify").FastifyReply) {
const now = Date.now(); const now = Date.now();
for (const [key, value] of failures) if (value.until <= now) failures.delete(key); for (const [key, value] of failures) if (value.until <= now) failures.delete(key);
const ip = request.ip;
const entry = failures.get(ip); const entry = failures.get(ip);
if ((entry?.count ?? 0) >= (options.maxAttempts ?? 5) || (!entry && failures.size >= 10000)) { if ((entry?.count ?? 0) >= (options.maxAttempts ?? 5) || (!entry && failures.size >= 10000)) {
return reply.header("Retry-After", String(Math.max(1, Math.ceil(((entry?.until ?? now + 60000) - now) / 1000)))).code(429).send({ error: "Try again later" }); return reply.header("Retry-After", String(Math.max(1, Math.ceil(((entry?.until ?? now + 60000) - now) / 1000)))).code(429).send({ error: "Try again later" });
} }
// Reserve before scrypt awaits, so parallel attempts cannot bypass the limit. // Reserve before scrypt awaits, so parallel attempts cannot bypass the limit.
failures.set(ip, { count: (entry?.count ?? 0) + 1, until: entry?.until ?? now + (options.rateWindowMs ?? 60000) }); failures.set(ip, { count: (entry?.count ?? 0) + 1, until: entry?.until ?? now + (options.rateWindowMs ?? 60000) });
return undefined;
}
const freshCookie = async (secure: boolean) => cookie(signSession(await sessionKey(), Date.now() + maxAge * 1000), secure, maxAge);
app.get("/api/auth/setup", async (_request, reply) => reply.header("Cache-Control", "no-store").send({ required: !await readPasswordHash(options.dataDir) }));
app.post("/api/auth/setup", { bodyLimit: 16384 }, async (request, reply) => exclusive(async () => {
if (await readPasswordHash(options.dataDir)) return reply.code(409).send({ error: "Already configured" });
const limited = reserveAttempt(request.ip, reply); if (limited) return limited;
const body = request.body as { token?: unknown; newPassword?: unknown; confirmPassword?: unknown } | null;
if (!await matchesSetupToken(options.dataDir, body?.token)) return reply.code(401).send({ error: "Invalid setup token" });
if (!validNewPassword(body?.newPassword) || body.newPassword !== body.confirmPassword) return reply.code(400).send({ error: "Passwords must match and contain at least 12 characters (maximum 4096 bytes)" });
await setPassword(options.dataDir, body.newPassword);
await removeSetupToken(options.dataDir);
failures.delete(request.ip);
return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send();
}));
app.post("/api/settings/password", { bodyLimit: 16384 }, async (request, reply) => exclusive(async () => {
const limited = reserveAttempt(request.ip, reply); if (limited) return limited;
const body = request.body as { currentPassword?: unknown; newPassword?: unknown; confirmPassword?: unknown } | null;
const hash = await readPasswordHash(options.dataDir);
if (typeof body?.currentPassword !== "string" || !hash || !await verifyPassword(body.currentPassword, hash)) return reply.code(401).send({ error: "Invalid current password" });
if (!validNewPassword(body.newPassword) || body.newPassword !== body.confirmPassword) return reply.code(400).send({ error: "Passwords must match and contain at least 12 characters (maximum 4096 bytes)" });
await setPassword(options.dataDir, body.newPassword);
app.websocketServer?.clients.forEach(socket => socket.close(1008, "Sessions revoked"));
failures.delete(request.ip);
return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send();
}));
app.post("/api/settings/sessions/revoke", async (request, reply) => exclusive(async () => {
secret = rotateSessionSecret(options.dataDir);
app.websocketServer?.clients.forEach(socket => socket.close(1008, "Sessions revoked"));
return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send();
}));
app.get("/api/settings/session", async () => ({ lifetimeSeconds: maxAge }));
app.post("/api/auth/login", { bodyLimit: 8192 }, async (request, reply) => exclusive(async () => {
const limited = reserveAttempt(request.ip, reply);
if (limited) return limited;
const now = Date.now();
const password = (request.body as { password?: unknown } | null)?.password; const password = (request.body as { password?: unknown } | null)?.password;
const hash = await readPasswordHash(options.dataDir); const hash = await readPasswordHash(options.dataDir);
if (typeof password !== "string" || !hash || !await verifyPassword(password, hash)) return reply.code(401).send({ error: "Invalid credentials" }); if (typeof password !== "string" || !hash || !await verifyPassword(password, hash)) return reply.code(401).send({ error: "Invalid credentials" });
failures.delete(ip); failures.delete(request.ip);
return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(secret, now + maxAge * 1000), request.protocol === "https", maxAge)).code(204).send(); return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(await sessionKey(), now + maxAge * 1000), request.protocol === "https", maxAge)).code(204).send();
}); }));
app.post("/api/auth/logout", async (request, reply) => reply.header("Set-Cookie", cookie("", request.protocol === "https", 0)).code(204).send()); app.post("/api/auth/logout", async (request, reply) => reply.header("Set-Cookie", cookie("", request.protocol === "https", 0)).code(204).send());
app.get("/api/auth/me", async (_request, reply) => reply.header("Cache-Control", "no-store").send({ authenticated: true })); app.get("/api/auth/me", async (_request, reply) => reply.header("Cache-Control", "no-store").send({ authenticated: true }));
} }
+10 -1
View File
@@ -1,5 +1,5 @@
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs"; import { mkdirSync, readFileSync, writeFileSync, chmodSync, renameSync } from "node:fs";
import { join } from "node:path"; import { join } from "node:path";
export function loadSessionSecret(dataDir: string): Buffer { export function loadSessionSecret(dataDir: string): Buffer {
@@ -22,3 +22,12 @@ export function verifySession(secret: Buffer, cookie: string, now = Date.now()):
const expected = signSession(secret, Number(payload)).split(".")[1]!; const expected = signSession(secret, Number(payload)).split(".")[1]!;
return Number(payload) > now && timingSafeEqual(Buffer.from(mac!), Buffer.from(expected)); return Number(payload) > now && timingSafeEqual(Buffer.from(mac!), Buffer.from(expected));
} }
/** Replace before publishing the new key to request handlers. */
export function rotateSessionSecret(dataDir: string): Buffer {
const secret = randomBytes(32);
const temp = join(dataDir, `session-secret.${randomBytes(8).toString("hex")}.tmp`);
writeFileSync(temp, secret, { mode: 0o600, flag: "wx" });
renameSync(temp, join(dataDir, "session-secret"));
return secret;
}
+44
View File
@@ -0,0 +1,44 @@
import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
import { chmod, readFile, writeFile, unlink } from "node:fs/promises";
import { join } from "node:path";
export const setupTokenPath = (dataDir: string) => join(dataDir, "setup-token");
export async function ensureSetupToken(dataDir: string): Promise<void> {
const path = setupTokenPath(dataDir);
try {
await writeFile(path, randomBytes(32).toString("hex") + "\n", {
flag: "wx",
mode: 0o600,
});
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
}
await chmod(path, 0o600);
}
export async function matchesSetupToken(
dataDir: string,
candidate: unknown,
): Promise<boolean> {
if (typeof candidate !== "string" || candidate.length > 4096) return false;
try {
const expected = (await readFile(setupTokenPath(dataDir), "utf8")).trim();
const digest = (value: string) =>
createHash("sha256").update(value).digest();
return timingSafeEqual(digest(candidate), digest(expected));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
throw error;
}
}
export async function removeSetupToken(dataDir: string): Promise<void> {
await unlink(setupTokenPath(dataDir)).catch((error) => {
if (error.code !== "ENOENT") throw error;
});
}
export function validNewPassword(value: unknown): value is string {
return (
typeof value === "string" &&
value.length >= 12 &&
Buffer.byteLength(value) <= 4096
);
}
+57
View File
@@ -0,0 +1,57 @@
# Chat transport and CLI contract (#8)
`/api/chat` is a dedicated JSON WebSocket protected by the existing auth and
same-origin hook. Run events remain on `/api/events`. The socket owns its turn:
disconnect, server shutdown, Stop, a five-minute timeout, malformed CLI output,
or resource overflow terminates the child (SIGTERM, then SIGKILL after 1.5s).
One turn per conversation, one per socket, at most four processes globally.
The lock lasts until process close. Output is capped at 4 MiB per turn, records
at 1 MiB, stderr at 8 KiB and outgoing socket buffering at 1 MiB.
Client frames: `send` with `message` (1–32000 characters), optional
`conversationId`, optional workspace-relative `notebookPath`, and required
`allowShell` boolean; or `cancel`. Server frames: `history`, `conversation`,
`delta`, `tool` (name and optional notebook path only), `finished` (optional
cancelled/costUsd/durationMs), and `error` (code and safe message). See core's
additive Chat section. Tool activity describes requested operations, not proof
that an edit succeeded. The existing watcher reloads actual changed files.
The data directory stores only a private, atomically replaced index of up to
100 conversations: ID, first-message title (120 characters), CLI session ID,
creation and update timestamps. Old inactive entries are evicted first.
Shell permission is per-turn and never persisted. Messages/tool contents are
not stored by ShellBook; Claude retains its own session files for `--resume`.
The browser caches messages only while this panel is mounted. Do not enter
secrets in chat: conversation titles and the CLI's own transcripts persist.
Verified against the official CLI reference and headless guide on 2026-11-16:
- https://code.claude.com/docs/en/cli-reference
- https://code.claude.com/docs/en/headless
Exact base argv: `-p --output-format stream-json --input-format stream-json
--verbose --include-partial-messages --restricted --strict-mcp-config
--disallowedTools mcp__* --tools Read,Glob,Grep,Edit,Write,MultiEdit
--allowedTools Read,Glob,Grep,Edit,Write,MultiEdit --permission-mode acceptEdits
--append-system-prompt <ShellBook context>`. Add `,Bash` to both tool lists only
when the toggle is enabled; append `--resume <session_id>` on follow-ups.
`--allowedTools` auto-approves; `--tools` actually restricts built-ins.
`--restricted` confines file tools to working directories and ignores user/project
settings (requires Claude Code **2.1.248+**). MCP is disabled. No bypass mode.
Restricted mode still reads workspace CLAUDE.md. Unlike `--bare`, this preserves
subscription authentication. The default CLI environment is inherited; no auth
files or tokens are read or copied by ShellBook. Unsupported flags fail closed.
Optional Bash has service-user authority; this toggle is not an OS sandbox.
The user prompt is a single newline-delimited user JSON record on stdin; never
part of argv or a shell string. Init/result session IDs enable explicit resume.
Only text deltas are rendered (assistant snapshots would duplicate them).
Result errors and bounded stderr detect missing login without forwarding raw
records or environment details. Cost is a CLI estimate and can be cumulative
across a resumed session. Terminal recovery says to run `claude`, then `/login`.
Tests use a synthetic captured-format JSONL fixture and a small Node executable
fixture, invoked through Node for portable Windows execution, including a fake
`claude` launcher resolved through PATH (no real CLI or credentials).
The fixture is representative protocol data, not a live recording.
Real installed CLI compatibility, subscription login, Linux process trees and
the visual layout still need deployment verification.
+50
View File
@@ -0,0 +1,50 @@
import type { ChatEvent } from "@shellbook/core";
import { isAbsolute, relative, resolve } from "node:path";
export function notebookPath(value: unknown): value is string {
return typeof value === "string" && /^notebooks\/(?:[^/\\\x00-\x1f]+\/)*[^/\\\x00-\x1f]+\.md$/.test(value)
&& !value.split("/").some(part => part === "." || part === "..");
}
export function buildClaudeArgs(options: { sessionId?: string; notebookPath?: string; allowShell: boolean }): string[] {
const tools = "Read,Glob,Grep,Edit,Write,MultiEdit" + (options.allowShell ? ",Bash" : "");
const args = ["-p", "--output-format", "stream-json", "--input-format", "stream-json", "--verbose",
"--include-partial-messages", "--restricted", "--strict-mcp-config", "--disallowedTools", "mcp__*",
"--tools", tools, "--allowedTools", tools, "--permission-mode", "acceptEdits",
"--append-system-prompt", `You are inside ShellBook. Follow the workspace CLAUDE.md notebook format. Write notebooks in notebooks/**/*.md. Never include secrets in notebooks or responses. Open notebook: ${options.notebookPath ?? "none"}.`];
if (options.sessionId) args.push("--resume", options.sessionId);
return args;
}
export type ParsedEvent = ChatEvent | { type: "session"; sessionId: string };
const loginPattern = /not logged in|please (?:run|use).*\/login|authentication[_ ](?:error|required)|invalid.*(?:api key|oauth)|login required|failed to authenticate/i;
export const needsLogin = (text: string) => loginPattern.test(text);
/** Whitelist fields: never forward full CLI records, tool inputs, or stderr. */
export function parseClaudeLine(line: string, workspace: string): ParsedEvent[] {
const m = JSON.parse(line);
if (!m || typeof m !== "object") throw new Error("Invalid CLI record");
const result: ParsedEvent[] = [];
if (typeof m.session_id === "string" && /^[a-zA-Z0-9-]{1,128}$/.test(m.session_id)) result.push({ type: "session", sessionId: m.session_id });
if (m.type === "stream_event" && m.event?.type === "content_block_delta" && m.event.delta?.type === "text_delta" && typeof m.event.delta.text === "string") {
result.push({ type: "delta", text: m.event.delta.text });
}
if (m.type === "assistant" && Array.isArray(m.message?.content)) {
for (const block of m.message.content) {
if (block.type !== "tool_use" || typeof block.name !== "string") continue;
let target: string | undefined;
const file = block.input?.file_path ?? block.input?.path;
if (typeof file === "string") {
const local = relative(workspace, resolve(workspace, file)).replaceAll("\\", "/");
if (!isAbsolute(local) && !local.startsWith("../") && notebookPath(local)) target = local;
}
result.push({ type: "tool", name: block.name.slice(0, 80), ...(target ? { path: target } : {}) });
}
}
if (m.type === "result") {
if (m.is_error || m.subtype !== "success") {
result.push({ type: "error", code: needsLogin(JSON.stringify(m)) ? "login" : "cli", message: needsLogin(JSON.stringify(m)) ? "Claude needs a login. Open Terminal, run claude, then /login." : "Claude could not complete this turn." });
} else result.push({ type: "finished", ...(typeof m.total_cost_usd === "number" ? { costUsd: m.total_cost_usd } : {}), ...(typeof m.duration_ms === "number" ? { durationMs: m.duration_ms } : {}) });
}
return result;
}
+82
View File
@@ -0,0 +1,82 @@
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { randomUUID } from "node:crypto";
import type { FastifyPluginAsync } from "fastify";
import type { ChatClientMessage, ChatConversation, ChatEvent } from "@shellbook/core";
import type { ServerConfig } from "../config";
import { notebookPath } from "./cli";
import { startTurn, type TurnOptions } from "./process";
export function parseChatMessage(text: string): ChatClientMessage | undefined {
if (text.length > 70_000) return;
let m; try { m = JSON.parse(text); } catch { return; }
if (!m || typeof m !== "object") return;
if (m.type === "cancel") return { type: "cancel" };
if (m.type !== "send" || typeof m.message !== "string" || !m.message.trim() || m.message.length > 32_000
|| typeof m.allowShell !== "boolean" || (m.notebookPath !== undefined && !notebookPath(m.notebookPath))
|| (m.conversationId !== undefined && (typeof m.conversationId !== "string" || !/^[a-f0-9-]{36}$/.test(m.conversationId)))) return;
return { type: "send", message: m.message, allowShell: m.allowShell, notebookPath: m.notebookPath, conversationId: m.conversationId };
}
export const chatPlugin: FastifyPluginAsync<{ config: ServerConfig; processOptions?: Pick<TurnOptions, "executable" | "prefixArgs" | "timeoutMs"> }> = async (app, { config, processOptions }) => {
mkdirSync(config.dataDir, { recursive: true, mode: 0o700 });
const file = join(config.dataDir, "chat-conversations.json");
let conversations: ChatConversation[] = [];
try {
const raw = readFileSync(file);
if (raw.length > 512 * 1024) throw new Error("Conversation index exceeds limit");
const saved = JSON.parse(raw.toString());
if (!Array.isArray(saved) || saved.length > 100 || saved.some(c => !c || !/^[a-f0-9-]{36}$/.test(c.id)
|| typeof c.title !== "string" || c.title.length > 120 || typeof c.createdAt !== "string" || typeof c.updatedAt !== "string"
|| (c.sessionId !== undefined && !/^[a-zA-Z0-9-]{1,128}$/.test(c.sessionId)))) throw new Error("Invalid conversation index");
conversations = saved;
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw new Error("Cannot load chat conversation index"); }
const save = () => {
writeFileSync(file + ".tmp", JSON.stringify(conversations), { mode: 0o600 });
renameSync(file + ".tmp", file);
};
const turns = new Map<string, ReturnType<typeof startTurn>>();
app.addHook("onClose", async () => { for (const turn of turns.values()) turn.cancel(); await Promise.all([...turns.values()].map(t => t.done)); });
app.get("/api/chat", { websocket: true }, socket => {
let active: ReturnType<typeof startTurn> | undefined;
const send = (event: ChatEvent) => {
if (socket.readyState !== 1) return;
if (socket.bufferedAmount > 1024 * 1024) { active?.cancel(); socket.close(1013, "Chat client too slow"); return; }
socket.send(JSON.stringify(event), error => { if (error) active?.cancel(); });
};
send({ type: "history", conversations });
socket.on("close", () => active?.cancel());
socket.on("error", () => { active?.cancel(); socket.close(); });
socket.on("message", (raw, binary) => {
const m = binary ? undefined : parseChatMessage(raw.toString());
if (!m) { send({ type: "error", code: "invalid", message: "Invalid chat message." }); return; }
if (m.type === "cancel") { active?.cancel(); return; }
if (active || (m.conversationId && turns.has(m.conversationId))) { send({ type: "error", code: "busy", message: "A turn is already running in this conversation." }); return; }
// Bound total concurrent CLI processes, not only per-conversation use.
if (turns.size >= 4) { send({ type: "error", code: "busy", message: "Chat is busy. Try again shortly." }); return; }
let conversation = conversations.find(c => c.id === m.conversationId);
if (m.conversationId && !conversation) { send({ type: "error", code: "invalid", message: "Conversation no longer exists." }); return; }
try {
if (!conversation) {
if (conversations.length >= 100) {
const removable = conversations.findIndex(c => !turns.has(c.id));
if (removable < 0) throw new Error("No free conversation slots");
conversations.splice(removable, 1);
}
const now = new Date().toISOString();
conversation = { id: randomUUID(), title: m.message.replace(/\s+/g, " ").slice(0, 120), createdAt: now, updatedAt: now };
conversations.push(conversation);
}
conversation.updatedAt = new Date().toISOString(); save();
const current = conversation;
send({ type: "conversation", conversation: current });
active = startTurn({ ...processOptions, workspaceDir: config.workspaceDir, message: m.message, allowShell: m.allowShell,
notebookPath: m.notebookPath, sessionId: current.sessionId, emit: send,
onSession: id => { current.sessionId = id; try { save(); } catch { active?.cancel(); send({ type: "error", code: "cli", message: "Cannot save conversation." }); } },
});
turns.set(current.id, active);
void active.done.finally(() => { turns.delete(current.id); active = undefined; });
} catch { send({ type: "error", code: "cli", message: "Cannot start or save conversation." }); }
});
});
};
+70
View File
@@ -0,0 +1,70 @@
import { spawn } from "node:child_process";
import { StringDecoder } from "node:string_decoder";
import type { ChatEvent } from "@shellbook/core";
import { buildClaudeArgs, needsLogin, parseClaudeLine } from "./cli";
export interface TurnOptions {
workspaceDir: string; message: string; sessionId?: string; notebookPath?: string; allowShell: boolean;
executable?: string; prefixArgs?: string[]; timeoutMs?: number;
emit(event: ChatEvent): void; onSession(id: string): void;
}
/** One process per turn. Resolves only on close, so cancelled turns retain their lock. */
export function startTurn(options: TurnOptions): { cancel(): void; done: Promise<void> } {
const child = spawn(options.executable ?? "claude", [...(options.prefixArgs ?? []), ...buildClaudeArgs(options)], {
cwd: options.workspaceDir, shell: false, stdio: ["pipe", "pipe", "pipe"], windowsHide: true,
detached: process.platform !== "win32",
});
let terminal: ChatEvent | undefined;
let stopped = false, bytes = 0, pending = "", stderr = "";
const decoder = new StringDecoder("utf8");
let force: ReturnType<typeof setTimeout> | undefined;
const kill = (signal: NodeJS.Signals) => {
// On the Linux service, also stop any shell descendants in the turn's group.
try {
if (process.platform !== "win32" && child.pid) process.kill(-child.pid, signal);
else child.kill(signal);
} catch { /* The process may already have exited. */ }
};
const stop = (event: ChatEvent) => {
if (stopped) return;
stopped = true; terminal = event;
kill("SIGTERM");
force = setTimeout(() => kill("SIGKILL"), 1500);
force.unref();
};
const consume = (line: string) => {
if (!line.trim()) return;
for (const event of parseClaudeLine(line, options.workspaceDir)) {
if (event.type === "session") options.onSession(event.sessionId);
else if (event.type === "finished" || event.type === "error") terminal = event;
else options.emit(event);
}
};
child.stdout.on("data", (chunk: Buffer) => {
if (stopped) return;
bytes += chunk.length;
if (bytes > 4 * 1024 * 1024) { stop({ type: "error", code: "limit", message: "Claude output limit exceeded." }); return; }
pending += decoder.write(chunk);
if (pending.length > 1024 * 1024) { stop({ type: "error", code: "limit", message: "Claude record limit exceeded." }); return; }
const lines = pending.split("\n"); pending = lines.pop()!;
try { for (const line of lines) consume(line); }
catch { stop({ type: "error", code: "cli", message: "Invalid response from Claude CLI." }); }
});
child.stderr.on("data", (chunk: Buffer) => { stderr = (stderr + chunk.toString()).slice(-8192); });
child.stdin.on("error", () => {});
child.stdin.end(JSON.stringify({ type: "user", message: { role: "user", content: options.message } }) + "\n");
const timeout = setTimeout(() => stop({ type: "error", code: "timeout", message: "Claude turn timed out." }), options.timeoutMs ?? 5 * 60_000);
const done = new Promise<void>(resolve => {
child.on("error", (error: NodeJS.ErrnoException) => {
terminal = { type: "error", code: error.code === "ENOENT" ? "missing" : "cli", message: error.code === "ENOENT" ? "Claude CLI is missing from the server PATH. Install it, then open Terminal and run claude followed by /login." : "Unable to start Claude CLI." };
});
child.on("close", code => {
clearTimeout(timeout); clearTimeout(force);
if (!stopped) { try { consume(pending + decoder.end()); } catch { terminal = undefined; } }
if (!stopped && needsLogin(stderr)) terminal = { type: "error", code: "login", message: "Claude needs a login. Open Terminal, run claude, then /login." };
if (!terminal || (!stopped && code !== 0 && terminal.type === "finished")) terminal = { type: "error", code: "cli", message: "Claude CLI exited without completing the turn." };
options.emit(terminal); resolve();
});
});
return { done, cancel: () => stop({ type: "finished", cancelled: true }) };
}
+195
View File
@@ -0,0 +1,195 @@
import {
randomBytes,
createCipheriv,
createDecipheriv,
createHash,
} from "node:crypto";
import {
mkdir,
readFile,
writeFile,
chmod,
rename,
rm,
realpath,
} from "node:fs/promises";
import path from "node:path";
import { utils } from "ssh2";
import type {
HostCredentialInput,
HostCredentialMetadata,
} from "@shellbook/core";
import { SerialQueue, httpError } from "../workspace";
const writes = new SerialQueue();
export type StoredCredential = {
input: Exclude<HostCredentialInput, { type: "shellbook" }>;
metadata: HostCredentialMetadata;
};
export class CredentialStore {
constructor(
private dir: string,
private workspaceDir?: string,
) {}
private file(name: string) {
return path.join(
this.dir,
"ssh-credentials",
createHash("sha256").update(name).digest("hex") + ".json",
);
}
private key() {
return writes.run(path.join(this.dir, "ssh-credentials.key"), () =>
this.loadKey(),
);
}
private async loadKey() {
await mkdir(this.dir, { recursive: true, mode: 0o700 });
if (this.workspaceDir) {
const workspace = await realpath(this.workspaceDir);
const relative = path.relative(workspace, await realpath(this.dir));
if (
!relative ||
(!relative.startsWith(".." + path.sep) &&
relative !== ".." &&
!path.isAbsolute(relative))
) {
throw httpError(
400,
"SSH credential data directory must be outside the workspace",
);
}
}
const file = path.join(this.dir, "ssh-credentials.key");
try {
await writeFile(file, randomBytes(32), { flag: "wx", mode: 0o600 });
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
}
await chmod(file, 0o600);
const key = await readFile(file);
if (key.length !== 32) throw new Error("Invalid credential encryption key");
return key;
}
async get(name: string): Promise<StoredCredential | undefined> {
let bytes: Buffer;
try {
bytes = await readFile(this.file(name));
} catch (e) {
if ((e as NodeJS.ErrnoException).code === "ENOENT") return;
throw new Error("Cannot read SSH credential");
}
try {
const decipher = createDecipheriv(
"aes-256-gcm",
await this.key(),
bytes.subarray(0, 12),
);
decipher.setAAD(Buffer.from(name));
decipher.setAuthTag(bytes.subarray(12, 28));
return JSON.parse(
Buffer.concat([
decipher.update(bytes.subarray(28)),
decipher.final(),
]).toString(),
) as StoredCredential;
} catch {
throw new Error("Cannot decrypt SSH credential");
}
}
async set(name: string, value: unknown): Promise<HostCredentialMetadata> {
const input = value as HostCredentialInput;
if (!input || typeof input !== "object")
throw httpError(400, "Invalid credential");
let safe: StoredCredential["input"];
const metadata: HostCredentialMetadata = {
type: input.type,
setAt: new Date().toISOString(),
};
if (input.type === "shellbook") {
await this.delete(name);
return { type: "shellbook" };
}
if (input.type === "password") {
if (
typeof input.password !== "string" ||
!input.password ||
input.password.length > 16384 ||
input.password.includes("\0")
)
throw httpError(400, "Invalid password");
safe = { type: "password", password: input.password };
} else if (input.type === "privateKey") {
if (
typeof input.privateKey !== "string" ||
input.privateKey.length > 65536 ||
(input.passphrase !== undefined &&
(typeof input.passphrase !== "string" ||
input.passphrase.length > 16384))
)
throw httpError(400, "Invalid private key");
const parsed = utils.parseKey(input.privateKey, input.passphrase);
if (
parsed instanceof Error ||
Array.isArray(parsed) ||
!parsed.isPrivateKey()
)
throw httpError(400, "Invalid private key or passphrase");
metadata.fingerprint =
"SHA256:" +
createHash("sha256")
.update(parsed.getPublicSSH())
.digest("base64")
.replace(/=+$/, "");
safe = {
type: "privateKey",
privateKey: input.privateKey,
...(input.passphrase !== undefined
? { passphrase: input.passphrase }
: {}),
};
} else throw httpError(400, "Unsupported SSH authentication type");
return writes.run(this.file(name), async () => {
const key = await this.key();
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", key, iv);
cipher.setAAD(Buffer.from(name));
const encrypted = Buffer.concat([
cipher.update(JSON.stringify({ input: safe, metadata })),
cipher.final(),
]);
await mkdir(path.dirname(this.file(name)), {
recursive: true,
mode: 0o700,
});
const temp = this.file(name) + "." + randomBytes(8).toString("hex");
try {
await writeFile(
temp,
Buffer.concat([iv, cipher.getAuthTag(), encrypted]),
{ mode: 0o600, flag: "wx" },
);
await rename(temp, this.file(name));
} finally {
await rm(temp, { force: true });
}
return metadata;
});
}
async delete(name: string) {
await writes.run(this.file(name), () =>
rm(this.file(name), { force: true }),
);
}
}
export function credentialSecrets(stored?: StoredCredential): string[] {
if (!stored) return [];
return stored.input.type === "password"
? [stored.input.password]
: [
stored.input.privateKey,
...stored.input.privateKey
.split(/\r?\n/)
.filter((line) => line && !line.startsWith("-----")),
stored.input.passphrase ?? "",
];
}
+230
View File
@@ -0,0 +1,230 @@
import { readFile, writeFile, rename, rm } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import path from "node:path";
import { parseDocument, isSeq, isMap } from "yaml";
import { utils } from "ssh2";
import {
shellQuote,
type HostActionRequest,
type SaveHostRequest,
} from "@shellbook/core";
import type { FastifyInstance } from "fastify";
import type { ServerConfig } from "../config";
import {
readHosts,
parseHosts,
version,
httpError,
SerialQueue,
} from "../workspace";
import { connect, exec, forgetHostKey, HostKeyError, sshFailure } from "../ssh";
import { CredentialStore } from "./credentials";
import { validateHost } from "./validation";
const saves = new SerialQueue();
export const certificateSupport = {
available: false as const,
reason:
"ssh2 1.17.0 has no client user-certificate authentication API. Use a private key or password.",
};
export function installKeyScript(publicKey: string) {
return `umask 077
mkdir -p "$HOME/.ssh"
chmod 700 "$HOME/.ssh"
touch "$HOME/.ssh/authorized_keys"
chmod 600 "$HOME/.ssh/authorized_keys"
grep -qxF -- ${shellQuote(publicKey)} "$HOME/.ssh/authorized_keys" || printf '\\n%s\\n' ${shellQuote(publicKey)} >> "$HOME/.ssh/authorized_keys"
`;
}
export async function shellbookPublicKey(config: ServerConfig) {
const parsed = utils.parseKey(await readFile(config.sshKeyPath));
if (parsed instanceof Error || Array.isArray(parsed))
throw httpError(503, "ShellBook key unavailable");
return `${parsed.type} ${parsed.getPublicSSH().toString("base64")}`;
}
export async function hostsPlugin(
app: FastifyInstance,
{ config }: { config: ServerConfig },
) {
const store = new CredentialStore(config.dataDir, config.workspaceDir);
const file = path.join(config.workspaceDir, "hosts.yaml");
app.addHook("onSend", async (_req, reply) => {
reply.header("Cache-Control", "no-store");
});
const hostByName = async (name: string) => {
const host = (await readHosts(config)).find((h) => h.name === name);
if (!host) throw httpError(404, "Host not found");
return host;
};
app.get("/api/host-management", async () => {
const source = await readFile(file, "utf8");
return {
hosts: await Promise.all(
parseHosts(source).map(async (host) => ({
...host,
credential: (await store.get(host.name))?.metadata ?? {
type: "shellbook",
},
})),
),
version: version(source),
publicKey: await shellbookPublicKey(config),
certificateSupport,
};
});
async function save(
name: string | undefined,
body: SaveHostRequest | { baseVersion: string },
remove = false,
) {
if (!body || typeof body.baseVersion !== "string")
throw httpError(400, "baseVersion required");
return saves.run(file, async () => {
const source = await readFile(file, "utf8");
if (version(source) !== body.baseVersion)
throw httpError(409, "Hosts changed; reload before saving");
const hosts = parseHosts(source);
const index = hosts.findIndex((h) => h.name === name);
if (name !== undefined && index < 0)
throw httpError(404, "Host not found");
const host = remove
? undefined
: validateHost((body as SaveHostRequest).host);
if (host && hosts.some((h, i) => h.name === host.name && i !== index))
throw httpError(409, "Host name already exists");
const doc = parseDocument(source);
const list = isSeq(doc.contents) ? doc.contents : doc.get("hosts", true);
if (doc.errors.length || !isSeq(list))
throw httpError(400, "Invalid hosts.yaml");
if (remove) list.delete(index);
else if (index < 0) list.add(doc.createNode(host!));
else {
const node = list.items[index];
if (!isMap(node)) throw httpError(400, "Invalid host entry");
for (const [key, value] of Object.entries(host!)) node.set(key, value);
}
const next = String(doc);
const renamedCredential =
host && name && host.name !== name ? await store.get(name) : undefined;
if (renamedCredential)
await store.set(host!.name, renamedCredential.input);
const temp = file + "." + randomUUID();
try {
await writeFile(temp, next, { flag: "wx" });
await rename(temp, file);
} finally {
await rm(temp, { force: true });
}
if (remove || (host && name && host.name !== name))
await store.delete(name!);
return { version: version(next) };
});
}
app.post<{ Body: SaveHostRequest }>("/api/host-management", (req) =>
save(undefined, req.body),
);
app.put<{ Params: { name: string }; Body: SaveHostRequest }>(
"/api/host-management/:name",
(req) => save(req.params.name, req.body),
);
app.delete<{ Params: { name: string }; Body: { baseVersion: string } }>(
"/api/host-management/:name",
(req) => save(req.params.name, req.body, true),
);
app.put<{ Params: { name: string } }>(
"/api/host-management/:name/credential",
async (req) => {
return saves.run(file, async () => {
await hostByName(req.params.name);
return store.set(req.params.name, req.body);
});
},
);
app.delete<{ Params: { name: string } }>(
"/api/host-management/:name/credential",
async (req) => {
return saves.run(file, async () => {
await hostByName(req.params.name);
await store.delete(req.params.name);
return { type: "shellbook" };
});
},
);
app.get<{ Params: { name: string } }>(
"/api/host-management/:name/install-key",
async (req) => {
await hostByName(req.params.name);
return { script: installKeyScript(await shellbookPublicKey(config)) };
},
);
app.delete<{ Params: { name: string } }>(
"/api/host-management/:name/known-key",
async (req, reply) => {
await forgetHostKey(config, await hostByName(req.params.name));
return reply.code(204).send();
},
);
app.post<{ Params: { name: string }; Body: HostActionRequest }>(
"/api/host-management/:name/action",
async (req) => {
const host = await hostByName(req.params.name);
const body = req.body;
if (
!body ||
!["test", "install-key"].includes(body.action) ||
(body.acceptHostKey !== undefined &&
typeof body.acceptHostKey !== "string")
)
throw httpError(400, "Invalid host action");
const script =
body.action === "test"
? "true\n"
: installKeyScript(await shellbookPublicKey(config));
if (body.action === "install-key" && body.script !== script)
throw httpError(
409,
"Displayed script changed; reload it before running",
);
const credential = await store.get(host.name);
if (
body.action === "install-key" &&
credential?.input.type !== "password"
)
throw httpError(
400,
"Store a password before installing the ShellBook key",
);
let client;
try {
client = await connect(
config,
host,
body.acceptHostKey,
credential ?? null,
);
// Deliberately discard all remote output: these actions expose exit status only.
return {
exitCode: await exec(
client,
"bash -euo pipefail -s",
script,
30000,
() => {},
),
};
} catch (e) {
if (e instanceof HostKeyError)
return {
hostKey: {
host: host.name,
fingerprint: e.fingerprint,
changed: e.changed,
},
};
throw httpError(502, sshFailure(e) ?? "SSH connection or action failed");
} finally {
client?.end();
}
},
);
}
+34
View File
@@ -0,0 +1,34 @@
import { isIP } from "node:net";
import type { HostInfo } from "@shellbook/core";
import { httpError } from "../workspace";
export function validateHost(value: unknown): HostInfo {
if (!value || typeof value !== "object") throw httpError(400, "Invalid host");
const { name, address, user, port = 22, tags = [] } = value as HostInfo;
const hostname =
typeof address === "string" &&
address.length <= 253 &&
address
.replace(/\.$/, "")
.split(".")
.every((label) =>
/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(label),
);
if (
typeof name !== "string" ||
!/^[A-Za-z0-9._-]{1,128}$/.test(name) ||
typeof address !== "string" ||
(!isIP(address) && (!hostname || /^[0-9.]+$/.test(address))) ||
typeof user !== "string" ||
!/^[A-Za-z_][A-Za-z0-9._-]{0,63}\$?$/.test(user) ||
!Number.isInteger(port) ||
port < 1 ||
port > 65535 ||
!Array.isArray(tags) ||
tags.length > 100 ||
tags.some(
(t) => typeof t !== "string" || t.length > 128 || /[\x00-\x1f]/.test(t),
)
)
throw httpError(400, "Invalid host fields");
return { name, address, user, port, tags };
}
+9 -4
View File
@@ -1,3 +1,4 @@
import { CredentialStore, credentialSecrets } from "../hosts/credentials";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { appendFile, mkdir, copyFile, stat, rm } from "node:fs/promises"; import { appendFile, mkdir, copyFile, stat, rm } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
@@ -7,7 +8,7 @@ import type { FastifyInstance } from "fastify";
import type { Client } from "ssh2"; import type { Client } from "ssh2";
import type { ServerConfig } from "../config"; import type { ServerConfig } from "../config";
import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace"; import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace";
import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, type Output } from "../ssh"; import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, sshFailure, type Output } from "../ssh";
import { EventsHub } from "./events"; import { EventsHub } from "./events";
import { runRoot, artifactFile, persistArtifacts, isSensitive, claimArtifact, sweepRuns } from "./artifacts"; import { runRoot, artifactFile, persistArtifacts, isSensitive, claimArtifact, sweepRuns } from "./artifacts";
export { EventsHub } from "./events"; export { EventsHub } from "./events";
@@ -38,9 +39,10 @@ export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: Host
/** Streaming redaction retains possible secret prefixes across chunks. */ /** Streaming redaction retains possible secret prefixes across chunks. */
export function redactor(secrets: string[], output: (data: string) => void) { export function redactor(secrets: string[], output: (data: string) => void) {
const values = secrets.filter(Boolean).sort((a, b) => b.length - a.length);
let pending = ""; let pending = "";
function flush(final: boolean) { function flush(final: boolean) {
// The run adds its credential snapshot before emitting any output.
const values = secrets.filter(Boolean).sort((a, b) => b.length - a.length);
let result = ""; let result = "";
while (pending) { while (pending) {
if (!final && values.some(value => value.startsWith(pending))) break; if (!final && values.some(value => value.startsWith(pending))) break;
@@ -64,6 +66,7 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
const workdir = path.join(root, "work"); const workdir = path.join(root, "work");
const artifactDir = path.join(root, "artifacts"); const artifactDir = path.join(root, "artifacts");
const secrets = Object.values(env).filter(Boolean); const secrets = Object.values(env).filter(Boolean);
let credential: Awaited<ReturnType<CredentialStore["get"]>>;
const clean = (value: string) => { for (const secret of [...secrets].sort((a,b) => b.length-a.length)) value = value.split(secret).join("[REDACTED]"); return value; }; const clean = (value: string) => { for (const secret of [...secrets].sort((a,b) => b.length-a.length)) value = value.split(secret).join("[REDACTED]"); return value; };
let stdout = ""; let stdout = "";
let captureTooLarge = false; let captureTooLarge = false;
@@ -85,13 +88,14 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
}; };
const output: Output = (stream, data) => streams[stream].write(data); const output: Output = (stream, data) => streams[stream].write(data);
try { try {
if (host) { credential = await new CredentialStore(config.dataDir, config.workspaceDir).get(host.name); secrets.push(...credentialSecrets(credential).filter(Boolean)); }
await mkdir(workdir, { recursive: true, mode: 0o700 }); await mkdir(workdir, { recursive: true, mode: 0o700 });
await mkdir(artifactDir, { mode: 0o700 }); await mkdir(artifactDir, { mode: 0o700 });
hub.publish({ type: "run.started", runId, notebookPath: request.notebookPath, stepId: rendered.stepId, host: rendered.host, script: clean(rendered.script) }); hub.publish({ type: "run.started", runId, notebookPath: request.notebookPath, stepId: rendered.stepId, host: rendered.host, script: clean(rendered.script) });
const timeout = step.attrs.timeoutSec * 1000; const timeout = step.attrs.timeoutSec * 1000;
if (!rendered.local) { if (!rendered.local) {
failureReason = `Cannot connect to ${host!.address}:${host!.port}`; failureReason = `Cannot connect to ${host!.address}:${host!.port}`;
client = await connect(config, host!, request.acceptHostKey); client = await connect(config, host!, request.acceptHostKey, credential ?? null);
failureReason = "Cannot create remote workdir"; failureReason = "Cannot create remote workdir";
let directory = ""; let directory = "";
const code = await exec(client, "mktemp -d", "", timeout, (stream, data) => { if (stream === "stdout") directory += data; }); const code = await exec(client, "mktemp -d", "", timeout, (stream, data) => { if (stream === "stdout") directory += data; });
@@ -228,7 +232,8 @@ export async function runsPlugin(app: FastifyInstance, { config, hub }: { config
function runFailure(error: unknown, fallback: string, timeoutSec: number): string { function runFailure(error: unknown, fallback: string, timeoutSec: number): string {
const e = error as { message?: string; level?: string; code?: string }; const e = error as { message?: string; level?: string; code?: string };
if (e.message === "Execution timed out") return `Execution timed out after ${timeoutSec} s`; if (e.message === "Execution timed out") return `Execution timed out after ${timeoutSec} s`;
if (e.level === "client-authentication") return "SSH authentication failed"; const ssh = sshFailure(error);
if (ssh) return ssh;
if (e.message === "Captured output exceeds 1 MiB") return e.message; if (e.message === "Captured output exceeds 1 MiB") return e.message;
if (e.message?.startsWith("SFTP ") && e.message.endsWith(" timed out")) return "File transfer timed out"; if (e.message?.startsWith("SFTP ") && e.message.endsWith(" timed out")) return "File transfer timed out";
return fallback; return fallback;
+52
View File
@@ -0,0 +1,52 @@
import { execFile } from "node:child_process";
import { access } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import type { FastifyInstance } from "fastify";
import type { ClaudeStatusResponse, SystemInfoResponse } from "@shellbook/core";
import type { ServerConfig } from "../config";
import { version } from "../../package.json";
/** No shell, bounded runtime/output, and no credential contents are accessed. */
export async function claudeStatus(
home = homedir(),
env = process.env,
): Promise<ClaudeStatusResponse> {
const loginAppearsPresent = await access(
join(home, ".claude", ".credentials.json"),
).then(
() => true,
() => false,
);
return new Promise((resolve) => {
execFile(
"claude",
["--version"],
{ env, timeout: 3000, maxBuffer: 4096, windowsHide: true },
(error, stdout) => {
resolve({
available: !error,
version: error ? null : stdout.trim(),
loginAppearsPresent,
});
},
);
});
}
export async function registerSettings(
app: FastifyInstance,
config: ServerConfig,
): Promise<void> {
app.get("/api/settings/claude", async (_request, reply) =>
reply.header("Cache-Control", "no-store").send(await claudeStatus()),
);
app.get("/api/settings/system", async (_request, reply) => {
const info: SystemInfoResponse = {
version,
workspacePath: config.workspaceDir,
dataDirPath: config.dataDir,
nodeVersion: process.version,
};
return reply.header("Cache-Control", "no-store").send(info);
});
}
+43 -3
View File
@@ -7,6 +7,7 @@ import { StringDecoder } from "node:string_decoder";
import { shellQuote, type HostInfo } from "@shellbook/core"; import { shellQuote, type HostInfo } from "@shellbook/core";
import type { ServerConfig } from "../config"; import type { ServerConfig } from "../config";
import { SerialQueue } from "../workspace"; import { SerialQueue } from "../workspace";
import { CredentialStore, type StoredCredential } from "../hosts/credentials";
export type Output = (stream: "stdout" | "stderr", data: string) => void; export type Output = (stream: "stdout" | "stderr", data: string) => void;
export class HostKeyError extends Error { export class HostKeyError extends Error {
@@ -15,9 +16,12 @@ export class HostKeyError extends Error {
const keyWrites = new SerialQueue(); const keyWrites = new SerialQueue();
export function fingerprint(key: Buffer) { return "SHA256:" + createHash("sha256").update(key).digest("base64").replace(/=+$/, ""); } export function fingerprint(key: Buffer) { return "SHA256:" + createHash("sha256").update(key).digest("base64").replace(/=+$/, ""); }
export async function connect(config: ServerConfig, host: HostInfo, accepted?: string): Promise<Client> { export async function connect(config: ServerConfig, host: HostInfo, accepted?: string, credential?: StoredCredential | null): Promise<Client> {
const file = path.join(config.workspaceDir, "known_hosts"); const file = path.join(config.workspaceDir, "known_hosts");
const privateKey = await readFile(config.sshKeyPath); const stored = credential === undefined ? await new CredentialStore(config.dataDir, config.workspaceDir).get(host.name) : credential;
const auth = stored?.input.type === "password" ? { password: stored.input.password, tryKeyboard: true } :
stored?.input.type === "privateKey" ? { privateKey: stored.input.privateKey, passphrase: stored.input.passphrase } :
{ privateKey: await readFile(config.sshKeyPath) };
// Serialize read/verify/write, so simultaneous first connections cannot overwrite pins. // Serialize read/verify/write, so simultaneous first connections cannot overwrite pins.
return keyWrites.run(file, async () => { return keyWrites.run(file, async () => {
const contents = await readFile(file, "utf8").catch((e: NodeJS.ErrnoException) => { if (e.code === "ENOENT") return ""; throw e; }); const contents = await readFile(file, "utf8").catch((e: NodeJS.ErrnoException) => { if (e.code === "ENOENT") return ""; throw e; });
@@ -31,7 +35,14 @@ export async function connect(config: ServerConfig, host: HostInfo, accepted?: s
client.once("ready", resolve); client.once("ready", resolve);
client.on("error", err => reject(failure ?? err)); client.on("error", err => reject(failure ?? err));
client.once("close", () => reject(failure ?? new Error("SSH connection closed"))); client.once("close", () => reject(failure ?? new Error("SSH connection closed")));
client.connect({ host: host.address, port: host.port, username: host.user, privateKey, readyTimeout: 10000, if (stored?.input.type === "password") {
const password = stored.input.password;
client.on("keyboard-interactive", (_name, _instructions, _lang, prompts, finish) => {
// Answer password prompts only; never send a password as an OTP or echoed text.
finish(prompts.map(prompt => !prompt.echo && /password/i.test(prompt.prompt) ? password : ""));
});
}
client.connect({ host: host.address, port: host.port, username: host.user, ...auth, readyTimeout: 10000,
hostVerifier(key: Buffer) { hostVerifier(key: Buffer) {
const encoded = key.toString("base64"); const encoded = key.toString("base64");
if (matches.some(line => line.split(/\s+/)[2] === encoded)) return true; if (matches.some(line => line.split(/\s+/)[2] === encoded)) return true;
@@ -136,3 +147,32 @@ export function sftpRequest<T>(session: SFTPWrapper, request: (done: (error: Err
}); });
} }
export async function forgetHostKey(config: ServerConfig, host: HostInfo) {
const file = path.join(config.workspaceDir, "known_hosts");
return keyWrites.run(file, async () => {
const source = await readFile(file, "utf8").catch((e: NodeJS.ErrnoException) => { if (e.code === "ENOENT") return ""; throw e; });
const identity = host.port === 22 ? host.address : `[${host.address}]:${host.port}`;
const lines = source.split(/\r?\n/).flatMap(line => {
const fields = line.split(/\s+/);
if (!fields[0]?.split(",").includes(identity)) return [line];
const aliases = fields[0].split(",").filter(alias => alias !== identity);
return aliases.length ? [[aliases.join(","), ...fields.slice(1)].join(" ")] : [];
});
await writeFile(file, lines.join("\n"), { mode: 0o600 });
});
}
const unreachable: Record<string, string> = {
ECONNREFUSED: "connection refused", EHOSTUNREACH: "host unreachable", ENETUNREACH: "network unreachable",
ENOTFOUND: "unknown host name", EAI_AGAIN: "host name lookup failed", ETIMEDOUT: "connection timed out",
ECONNRESET: "connection reset",
};
/** User-facing reason for a failed SSH connection; undefined when not a connection problem. Never includes secrets. */
export function sshFailure(error: unknown): string | undefined {
const e = error as { level?: string; code?: string } | null;
if (e?.level === "client-authentication") return "SSH authentication failed: check the user and the saved password or key";
if (e?.level === "client-timeout") return "Cannot reach the server: SSH handshake timed out";
if (e?.code && unreachable[e.code]) return `Cannot reach the server: ${unreachable[e.code]}`;
return undefined;
}
+3 -3
View File
@@ -22,7 +22,7 @@ export function createNotebookWatcher(workspaceDir: string, options: {
const listeners = new Set<(event: NotebookFileEvent) => void>(); const listeners = new Set<(event: NotebookFileEvent) => void>();
const pending = new Map<string, ReturnType<typeof setTimeout>>(); const pending = new Map<string, ReturnType<typeof setTimeout>>();
let closed = false; let closed = false;
const watcher = watch(root, { ignoreInitial: true, followSymlinks: false, atomic: true }); const watcher = watch([root, resolve(workspaceDir, "hosts.yaml")], { ignoreInitial: true, followSymlinks: false, atomic: true });
const ready = new Promise<void>((resolveReady, reject) => { const ready = new Promise<void>((resolveReady, reject) => {
watcher.once("ready", resolveReady); watcher.once("ready", resolveReady);
watcher.on("error", (error) => { watcher.on("error", (error) => {
@@ -34,8 +34,8 @@ export function createNotebookWatcher(workspaceDir: string, options: {
// Callers can await ready; avoid an unhandled rejection before they attach. // Callers can await ready; avoid an unhandled rejection before they attach.
void ready.catch(() => {}); void ready.catch(() => {});
const schedule = (type: NotebookFileEvent["type"], file: string) => { const schedule = (type: NotebookFileEvent["type"], file: string) => {
const path = relative(root, file).split(sep).join("/"); const path = resolve(file) === resolve(workspaceDir, "hosts.yaml") ? "hosts.yaml" : relative(root, file).split(sep).join("/");
if (closed || !path.endsWith(".md") || path.startsWith("../") || isAbsolute(path)) return; if (closed || (!path.endsWith(".md") && path !== "hosts.yaml") || path.startsWith("../") || isAbsolute(path)) return;
clearTimeout(pending.get(path)); clearTimeout(pending.get(path));
pending.set(path, setTimeout(() => { pending.set(path, setTimeout(() => {
pending.delete(path); pending.delete(path);
+18 -13
View File
@@ -1,7 +1,9 @@
import { atomicNotebookWrite, notebookRoot, notebookManagement } from "./notebooks";
import { createHash } from "node:crypto"; import { createHash } from "node:crypto";
import { readFile, writeFile, readdir, realpath, lstat } from "node:fs/promises"; import { readFile, readdir, realpath, lstat } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { parse } from "yaml"; import { parse } from "yaml";
import { validateHost } from "../hosts/validation";
import { parseNotebook, type HostInfo } from "@shellbook/core"; import { parseNotebook, type HostInfo } from "@shellbook/core";
import type { FastifyInstance } from "fastify"; import type { FastifyInstance } from "fastify";
import type { ServerConfig } from "../config"; import type { ServerConfig } from "../config";
@@ -34,26 +36,27 @@ export async function safeFile(root: string, name: string): Promise<string> {
} }
export async function readNotebook(config: ServerConfig, name: string) { export async function readNotebook(config: ServerConfig, name: string) {
// Name rules apply to creating notebooks only; existing files (git, Claude) stay readable.
await notebookRoot(config);
if (!name.endsWith(".md")) throw httpError(400, "Only Markdown notebooks are allowed"); if (!name.endsWith(".md")) throw httpError(400, "Only Markdown notebooks are allowed");
const file = await safeFile(path.join(config.workspaceDir, "notebooks"), name); const file = await safeFile(path.join(config.workspaceDir, "notebooks"), name);
return { file, source: await readFile(file, "utf8") }; return { file, source: await readFile(file, "utf8") };
} }
export async function readHosts(config: ServerConfig): Promise<HostInfo[]> { export async function readHosts(config: ServerConfig): Promise<HostInfo[]> {
const document: unknown = parse(await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8")); return parseHosts(await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8"));
}
export function parseHosts(source: string): HostInfo[] {
let document: unknown;
try { document = parse(source); } catch { throw httpError(400, "Invalid hosts.yaml"); }
const entries = Array.isArray(document) ? document : (document as { hosts?: unknown } | null)?.hosts; const entries = Array.isArray(document) ? document : (document as { hosts?: unknown } | null)?.hosts;
if (!Array.isArray(entries)) throw httpError(400, "hosts.yaml must contain a host list"); if (!Array.isArray(entries)) throw httpError(400, "hosts.yaml must contain a host list");
const names = new Set<string>(); const names = new Set<string>();
return entries.map((entry: Record<string, unknown>) => { return entries.map((entry: Record<string, unknown>) => {
if (!entry || typeof entry !== "object") throw httpError(400, "Invalid host"); const host = validateHost(entry);
const { name, address, user, port = 22, tags = [] } = entry; if (names.has(host.name)) throw httpError(400, "Duplicate host name");
if (typeof name !== "string" || !/^[A-Za-z0-9._-]+$/.test(name) || names.has(name) || names.add(host.name);
typeof address !== "string" || !address || /[\s\x00]/.test(address) || return host;
typeof user !== "string" || !/^[A-Za-z0-9._-]+$/.test(user) ||
!Number.isInteger(port) || Number(port) < 1 || Number(port) > 65535 ||
!Array.isArray(tags) || tags.some(t => typeof t !== "string")) throw httpError(400, "Invalid or duplicate host entry");
names.add(name);
return { name, address, user, port: Number(port), tags: tags as string[] };
}); });
} }
@@ -71,6 +74,7 @@ export class SerialQueue {
export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) { export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) {
const saves = new SerialQueue(); const saves = new SerialQueue();
notebookManagement(app, config, saves);
app.get("/api/hosts", async () => ({ hosts: await readHosts(config) })); app.get("/api/hosts", async () => ({ hosts: await readHosts(config) }));
app.get("/api/notebooks", async () => { app.get("/api/notebooks", async () => {
const notebooks: { path: string; title: string }[] = []; const notebooks: { path: string; title: string }[] = [];
@@ -84,6 +88,7 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config
} }
} }
} }
await notebookRoot(config);
await walk(path.join(config.workspaceDir, "notebooks")); await walk(path.join(config.workspaceDir, "notebooks"));
return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) }; return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) };
}); });
@@ -93,10 +98,10 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config
}); });
app.put<{ Params: { path: string }; Body: { source: string; baseVersion: string } }>("/api/notebooks/:path", async req => { app.put<{ Params: { path: string }; Body: { source: string; baseVersion: string } }>("/api/notebooks/:path", async req => {
if (!req.body || typeof req.body.source !== "string" || typeof req.body.baseVersion !== "string") throw httpError(400, "Invalid save request"); if (!req.body || typeof req.body.source !== "string" || typeof req.body.baseVersion !== "string") throw httpError(400, "Invalid save request");
return saves.run(req.params.path, async () => { return saves.run("notebooks", async () => {
const { file, source } = await readNotebook(config, req.params.path); const { file, source } = await readNotebook(config, req.params.path);
if (version(source) !== req.body.baseVersion) throw httpError(409, "Notebook changed"); if (version(source) !== req.body.baseVersion) throw httpError(409, "Notebook changed");
await writeFile(file, req.body.source, "utf8"); await atomicNotebookWrite(file, req.body.source);
return { version: version(req.body.source) }; return { version: version(req.body.source) };
}); });
}); });
+183
View File
@@ -0,0 +1,183 @@
import { randomUUID } from "node:crypto";
import {
lstat,
mkdir,
realpath,
writeFile,
rename,
unlink,
rmdir,
link,
} from "node:fs/promises";
import path from "node:path";
import type { FastifyInstance } from "fastify";
import type {
CreateNotebookRequest,
MoveNotebookRequest,
DeleteNotebookRequest,
} from "@shellbook/core";
import { httpError, readNotebook, SerialQueue, version } from "./index";
import type { ServerConfig } from "../config";
export function notebookName(name: string): string {
if (
typeof name !== "string" ||
name.length > 240 ||
!name.endsWith(".md") ||
name
.split("/")
.some(
(p) =>
!/^[A-Za-z0-9][A-Za-z0-9 _.-]*$/.test(p) ||
p.includes("..") ||
/[. ]$/.test(p) ||
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p),
)
) {
throw httpError(
400,
"Use a relative .md path with letters, numbers, spaces, dots, underscores or hyphens",
);
}
return name;
}
/** Validate the root before resolving any notebook path. */
export async function notebookRoot(config: ServerConfig): Promise<string> {
const root = path.join(await realpath(config.workspaceDir), "notebooks");
try {
const info = await lstat(root);
if (info.isSymbolicLink() || !info.isDirectory())
throw httpError(
400,
"Symlinks and non-directory parents are not allowed",
);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
}
return root;
}
/** Walk every component; never follow symlinks. */
export async function notebookDestination(
config: ServerConfig,
name: string,
): Promise<string> {
notebookName(name);
let current = await notebookRoot(config);
const parts = name.split("/");
for (let i = 0; i < parts.length; i++) {
current = path.join(current, parts[i]!);
try {
const info = await lstat(current);
if (
info.isSymbolicLink() ||
(i < parts.length - 1 && !info.isDirectory())
)
throw httpError(
400,
"Symlinks and non-directory parents are not allowed",
);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
}
}
return current;
}
export async function atomicNotebookWrite(
file: string,
source: string,
exclusive = false,
) {
await mkdir(path.dirname(file), { recursive: true });
const temp = path.join(path.dirname(file), `.shellbook-${randomUUID()}.tmp`);
try {
await writeFile(temp, source, {
encoding: "utf8",
flag: "wx",
mode: 0o600,
});
// link publishes a complete file without replacing an existing destination.
if (exclusive) await link(temp, file);
else await rename(temp, file);
} catch (e) {
if ((e as NodeJS.ErrnoException).code === "EEXIST")
throw httpError(409, "Notebook already exists");
throw e;
} finally {
await unlink(temp).catch(() => {});
}
}
async function prune(config: ServerConfig, file: string) {
// Same resolved root as the file path; stop at it, never walk above it.
const root = await notebookRoot(config);
for (let dir = path.dirname(file); dir.startsWith(root + path.sep); dir = path.dirname(dir)) {
try {
await rmdir(dir);
} catch (e) {
if (
["ENOTEMPTY", "EEXIST", "ENOENT"].includes(
(e as NodeJS.ErrnoException).code ?? "",
)
)
return;
throw e;
}
}
}
export function notebookManagement(
app: FastifyInstance,
config: ServerConfig,
queue: SerialQueue,
) {
app.post<{ Body: CreateNotebookRequest }>("/api/notebooks", async (req) =>
queue.run("notebooks", async () => {
if (!req.body || typeof req.body.source !== "string")
throw httpError(400, "Invalid notebook");
const file = await notebookDestination(config, req.body.path);
await atomicNotebookWrite(file, req.body.source, true);
return { path: req.body.path, version: version(req.body.source) };
}),
);
for (const operation of ["rename", "duplicate"] as const) {
app.post<{ Params: { path: string }; Body: MoveNotebookRequest }>(
`/api/notebooks/:path/${operation}`,
async (req) =>
queue.run("notebooks", async () => {
if (!req.body || typeof req.body.baseVersion !== "string")
throw httpError(400, "Missing baseVersion");
// Only the new path must satisfy the create rules; the source may predate them.
const { file: original, source } = await readNotebook(config, req.params.path);
if (version(source) !== req.body.baseVersion)
throw httpError(409, "Notebook changed");
const target = await notebookDestination(config, req.body.path);
await atomicNotebookWrite(target, source, true);
if (operation === "rename") {
try {
await unlink(original);
} catch (e) {
await unlink(target);
throw e;
}
await prune(config, original);
}
return { path: req.body.path, version: version(source) };
}),
);
}
app.delete<{ Params: { path: string }; Body: DeleteNotebookRequest }>(
"/api/notebooks/:path",
async (req) =>
queue.run("notebooks", async () => {
if (!req.body || typeof req.body.baseVersion !== "string")
throw httpError(400, "Missing baseVersion");
const { file, source } = await readNotebook(config, req.params.path);
if (version(source) !== req.body.baseVersion)
throw httpError(409, "Notebook changed");
await unlink(file);
await prune(config, file);
return { deleted: true };
}),
);
}
+104
View File
@@ -0,0 +1,104 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { copyFileSync, linkSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import Fastify from "fastify";
import websocket from "@fastify/websocket";
import { buildClaudeArgs, notebookPath, parseClaudeLine } from "../src/chat/cli";
import { startTurn } from "../src/chat/process";
import { chatPlugin, parseChatMessage } from "../src/chat";
import { buildApp } from "../src/app";
import { loadConfig } from "../src/config";
import { loadSessionSecret, signSession } from "../src/auth/session";
import type { ChatEvent } from "@shellbook/core";
const dirs: string[] = [];
const temp = () => { const dir = mkdtempSync(join(tmpdir(), "shellbook-chat-")); dirs.push(dir); return dir; };
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
const fixture = resolve("test/fixtures/fake-claude.cjs");
const processOptions = { executable: process.execPath, prefixArgs: [fixture], timeoutMs: 3000 };
const run = (message: string, extra = {}) => {
const events: ChatEvent[] = []; const sessions: string[] = [];
const turn = startTurn({ ...processOptions, workspaceDir: process.cwd(), message, allowShell: false,
emit: e => events.push(e), onSession: id => sessions.push(id), ...extra });
return { ...turn, events, sessions };
};
describe("chat CLI contract", () => {
it("restricts tools, keeps prompts out of argv, resumes explicitly", () => {
const args = buildClaudeArgs({ allowShell: false, sessionId: "abc", notebookPath: "notebooks/a.md" });
expect(args).toEqual(expect.arrayContaining(["-p", "--restricted", "--strict-mcp-config", "mcp__*", "--include-partial-messages", "--resume", "abc", "acceptEdits"]));
expect(args[args.indexOf("--tools") + 1]).toBe("Read,Glob,Grep,Edit,Write,MultiEdit");
expect(args.join(" ")).not.toContain("bypassPermissions");
expect(args[args.indexOf("--append-system-prompt") + 1]).toContain("notebooks/a.md");
const shell = buildClaudeArgs({ allowShell: true });
expect(shell[shell.indexOf("--allowedTools") + 1]).toContain(",Bash");
});
it("parses captured-format fixture records without duplicating text or exposing tool contents", () => {
const events = readFileSync(resolve("test/fixtures/chat.jsonl"), "utf8").trim().split("\n").flatMap(line => parseClaudeLine(line, process.cwd()));
expect(events.filter(e => e.type === "delta")).toEqual([{ type: "delta", text: "Hello notebook" }]);
expect(events).toContainEqual({ type: "tool", name: "Edit", path: "notebooks/setup/nginx.md" });
expect(events).toContainEqual({ type: "finished", costUsd: .002, durationMs: 1234 });
expect(JSON.stringify(events)).not.toContain("private contents");
expect(parseClaudeLine('{"type":"future"}', process.cwd())).toEqual([]);
expect(() => parseClaudeLine("bad", process.cwd())).toThrow();
});
it.each(["../secret", "notebooks/../secret.md", "notebooks/a\\b.md", "/notebooks/a.md", "notebooks/x\n.md"])("rejects invalid notebook %s", path => expect(notebookPath(path)).toBe(false));
it.each(["null", "bad", '{"type":"send","message":"a","allowShell":"yes"}', JSON.stringify({ type: "send", message: "a".repeat(32001), allowShell: false })])("rejects invalid client frame %#", text => expect(parseChatMessage(text)).toBeUndefined());
});
describe("fake CLI lifecycle", () => {
it("streams text, extracts session ID, and waits for exit", async () => {
const turn = run("hello ' ; $(test)"); await turn.done;
expect(turn.sessions).toContain("11111111-1111-4111-8111-111111111111");
expect(turn.events.at(-1)).toEqual({ type: "finished", costUsd: .002, durationMs: 1234 });
});
it.each(["login", "stderr-login"])("detects login failure: %s", async message => {
const turn = run(message); await turn.done; expect(turn.events.at(-1)).toMatchObject({ type: "error", code: "login" });
});
it("detects missing CLI", async () => { const turn = run("a", { executable: join(temp(), "missing-claude"), prefixArgs: [] }); await turn.done; expect(turn.events.at(-1)).toMatchObject({ code: "missing" }); });
it("resolves the fake executable on PATH without a shell", async () => {
const dir = temp(); const launcher = join(dir, process.platform === "win32" ? "claude.exe" : "claude");
if (process.platform === "win32") { try { linkSync(process.execPath, launcher); } catch { copyFileSync(process.execPath, launcher); } }
else symlinkSync(process.execPath, launcher);
const previous = process.env.PATH;
process.env.PATH = dir + (process.platform === "win32" ? ";" : ":") + previous;
try { const turn = run("hello", { executable: "claude" }); await turn.done; expect(turn.events.at(-1)?.type).toBe("finished"); }
finally { process.env.PATH = previous; }
});
it.each(["bad", "failed", "huge"])("fails safely on %s output", async message => { const turn = run(message); await turn.done; expect(turn.events.at(-1)?.type).toBe("error"); });
it("cancels and reaps the process", async () => { const turn = run("hang"); turn.cancel(); await turn.done; expect(turn.events.at(-1)).toEqual({ type: "finished", cancelled: true }); });
it("times out and reaps the process", async () => { const turn = run("hang", { timeoutMs: 100 }); await turn.done; expect(turn.events.at(-1)).toMatchObject({ code: "timeout" }); });
});
describe("chat route", () => {
it("rejects unauthenticated upgrades and foreign origins", async () => {
const dir = temp(); const app = await buildApp({ config: { dataDir: dir } });
try {
expect((await app.inject("/api/chat")).statusCode).toBe(401);
await expect(app.injectWS("/api/chat")).rejects.toThrow("401");
const cookie = `shellbook_session=${signSession(loadSessionSecret(dir), Date.now() + 60000)}`;
expect((await app.inject({ url: "/api/chat", headers: { cookie, origin: "https://evil.example" } })).statusCode).toBe(403);
} finally { await app.close(); }
});
it("persists metadata, prevents concurrent turns, and cancels on disconnect", async () => {
const dir = temp(); const config = loadConfig({ dataDir: dir, workspaceDir: process.cwd() });
const app = Fastify(); await app.register(websocket); await app.register(chatPlugin, { config, processOptions }); await app.ready();
const a = await app.injectWS("/api/chat"); const b = await app.injectWS("/api/chat");
const first: any[] = [], second: any[] = [];
a.on("message", raw => first.push(JSON.parse(raw.toString()))); b.on("message", raw => second.push(JSON.parse(raw.toString())));
try {
a.send(JSON.stringify({ type: "send", message: "hang", allowShell: false }));
await vi.waitFor(() => expect(first.some(e => e.type === "conversation")).toBe(true));
const id = first.find(e => e.type === "conversation").conversation.id;
b.send(JSON.stringify({ type: "send", message: "hello", allowShell: false, conversationId: id }));
await vi.waitFor(() => expect(second.some(e => e.code === "busy")).toBe(true));
[...app.websocketServer.clients][0]!.terminate();
await vi.waitFor(() => expect(a.readyState).toBe(3));
b.send(JSON.stringify({ type: "send", message: "hello", allowShell: false }));
await vi.waitFor(() => expect(second.some(e => e.type === "finished")).toBe(true));
const saved = JSON.parse(readFileSync(join(dir, "chat-conversations.json"), "utf8"));
expect(saved).toHaveLength(2); expect(saved[1].sessionId).toBeTruthy();
expect(Object.keys(saved[1]).sort()).toEqual(["createdAt", "id", "sessionId", "title", "updatedAt"]);
} finally { a.terminate(); b.terminate(); await app.close(); }
const restart = Fastify(); await restart.register(websocket); await restart.register(chatPlugin, { config, processOptions });
try { await restart.ready(); } finally { await restart.close(); }
});
});
+4
View File
@@ -0,0 +1,4 @@
{"type":"system","subtype":"init","session_id":"11111111-1111-4111-8111-111111111111"}
{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello notebook"}}}
{"type":"assistant","message":{"content":[{"type":"text","text":"Hello notebook"},{"type":"tool_use","id":"tool-1","name":"Edit","input":{"file_path":"notebooks/setup/nginx.md","old_string":"private contents","new_string":"other contents"}}]}}
{"type":"result","subtype":"success","is_error":false,"session_id":"11111111-1111-4111-8111-111111111111","total_cost_usd":0.002,"duration_ms":1234,"result":"Hello notebook"}
+15
View File
@@ -0,0 +1,15 @@
// Test-only executable. No external network or real CLI calls.
const fs = require('node:fs');
let input = '';
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => {
const message = JSON.parse(input).message.content;
if (message === 'hang') { setInterval(() => {}, 1000); return; }
if (message === 'login') { console.log(JSON.stringify({ type: 'result', subtype: 'error_during_execution', is_error: true, result: 'Not logged in · Please run /login' })); process.exitCode = 1; return; }
if (message === 'stderr-login') { process.stderr.write('Authentication required'); process.exitCode = 1; return; }
if (message === 'bad') { console.log('not JSON'); return; }
if (message === 'huge') { process.stdout.write('x'.repeat(1024 * 1024 + 1)); return; }
if (message === 'failed') { process.exitCode = 2; return; }
const lines = fs.readFileSync(__dirname + '/chat.jsonl', 'utf8');
process.stdout.write(lines);
});
+475
View File
@@ -0,0 +1,475 @@
import { afterEach, expect, it } from "vitest";
import {
mkdtemp,
mkdir,
writeFile,
readFile,
rm,
readdir,
stat,
} from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { generateKeyPairSync, randomUUID, createPrivateKey } from "node:crypto";
import { utils } from "ssh2";
import { buildApp } from "../src/app";
import { loadConfig } from "../src/config";
import { validateHost } from "../src/hosts/validation";
import { CredentialStore } from "../src/hosts/credentials";
import { installKeyScript } from "../src/hosts";
import { connect, exec, forgetHostKey, sftp, transfer } from "../src/ssh";
import { createSshFixture } from "./ssh-fixture";
import { executeRun, EventsHub } from "../src/runs";
import { shellQuote, type ServerEvent } from "@shellbook/core";
const cleanup: (() => Promise<unknown>)[] = [];
afterEach(async () => {
for (const fn of cleanup.splice(0).reverse()) await fn();
});
const host = {
name: "demo",
address: "example.org",
user: "ops",
port: 22,
tags: ["prod"],
};
async function fixture(auth = false) {
const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-hosts-"));
cleanup.push(() =>
rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }),
);
const config = loadConfig({
workspaceDir: path.join(dir, "workspace"),
dataDir: path.join(dir, "data"),
sshKeyPath: path.join(dir, "key"),
});
await mkdir(config.workspaceDir);
await mkdir(path.join(config.workspaceDir, "notebooks"));
await writeFile(
path.join(config.workspaceDir, "hosts.yaml"),
"# Inventory\nhosts:\n # Production\n - name: demo # stable name\n address: example.org # endpoint\n user: ops\n",
);
const key = generateKeyPairSync("rsa", { modulusLength: 2048 })
.privateKey.export({ format: "pem", type: "pkcs1" })
.toString();
await writeFile(config.sshKeyPath, key);
const app = await buildApp({ config, auth: auth ? {} : false });
cleanup.push(() => app.close());
return { config, app, key, store: new CredentialStore(config.dataDir) };
}
it.each([
{ name: "../bad" },
{ name: "" },
{ address: "a b" },
{ address: "a/b" },
{ address: "999.1.1.1" },
{ address: "-host" },
{ address: "host:22" },
{ user: "-x" },
{ user: "a;id" },
{ port: 0 },
{ port: 65536 },
{ port: 1.5 },
{ tags: [2] },
])("rejects invalid host fields %j", (value) => {
expect(() => validateHost({ ...host, ...value })).toThrow();
});
it.each([
"localhost",
"example.org",
"host-1.example.org.",
"127.0.0.1",
"::1",
"2001:db8::1",
])("accepts address %s", (address) => {
expect(validateHost({ ...host, address }).address).toBe(address);
});
it("round-trips YAML comments/order, validates uniqueness, renames and rejects stale saves", async () => {
const { app, config, store } = await fixture();
const first = (await app.inject("/api/host-management")).json();
const url = "/api/host-management/demo";
await store.set("demo", { type: "password", password: "kept-on-rename" });
const payload = {
host: { ...host, name: "renamed" },
baseVersion: first.version,
};
const results = await Promise.all([
app.inject({ method: "PUT", url, payload }),
app.inject({ method: "PUT", url, payload }),
]);
expect(results.map((r) => r.statusCode).sort()).toEqual([200, 409]);
const source = await readFile(
path.join(config.workspaceDir, "hosts.yaml"),
"utf8",
);
for (const comment of [
"# Inventory",
"# Production",
"# stable name",
"# endpoint",
])
expect(source).toContain(comment);
expect((await store.get("renamed"))?.input).toEqual({
type: "password",
password: "kept-on-rename",
});
expect(await store.get("demo")).toBeUndefined();
const current = (await app.inject("/api/host-management")).json();
expect(
(
await app.inject({
method: "POST",
url: "/api/host-management",
payload: {
host: { ...host, name: "renamed" },
baseVersion: current.version,
},
})
).statusCode,
).toBe(409);
expect(
(
await app.inject({
method: "DELETE",
url: "/api/host-management/renamed",
payload: { baseVersion: current.version },
})
).statusCode,
).toBe(200);
expect(await store.get("renamed")).toBeUndefined();
});
it("encrypts credentials, rejects tampering and stores no secrets in workspace", async () => {
const { config, store, key } = await fixture();
await store.set("demo", { type: "password", password: "very-secret-value" });
expect((await store.get("demo"))?.input).toEqual({
type: "password",
password: "very-secret-value",
});
const dir = path.join(config.dataDir, "ssh-credentials");
const file = path.join(dir, (await readdir(dir))[0]!);
const bytes = await readFile(file);
expect(bytes.toString()).not.toContain("very-secret-value");
if (process.platform !== "win32")
for (const f of [file, path.join(config.dataDir, "ssh-credentials.key")])
expect((await stat(f)).mode & 0o777).toBe(0o600);
bytes[30] = bytes[30]! ^ 1;
await writeFile(file, bytes);
await expect(store.get("demo")).rejects.toThrow("Cannot decrypt");
expect(
(await store.set("demo", { type: "privateKey", privateKey: key }))
.fingerprint,
).toMatch(/^SHA256:/);
expect((await store.get("demo"))?.input).toEqual({
type: "privateKey",
privateKey: key,
});
await expect(
store.set("demo", { type: "privateKey", privateKey: "bad secret" }),
).rejects.toThrow("Invalid private key");
expect(
await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8"),
).not.toContain("very-secret-value");
});
it("keeps the API write-only and removes credentials when selecting the default", async () => {
const { app } = await fixture();
const url = "/api/host-management/demo/credential";
const response = await app.inject({
method: "PUT",
url,
payload: { type: "password", password: "browser-never-gets-this" },
});
expect(response.statusCode).toBe(200);
expect(response.json()).toMatchObject({
type: "password",
setAt: expect.any(String),
});
const inventory = await app.inject("/api/host-management");
expect(inventory.body + response.body).not.toContain(
"browser-never-gets-this",
);
expect(inventory.headers["cache-control"]).toBe("no-store");
expect((await app.inject(url)).statusCode).toBe(404);
expect(
(
await app.inject({
method: "PUT",
url,
payload: { type: "certificate", privateKey: "secret" },
})
).statusCode,
).toBe(400);
await app.inject({ method: "DELETE", url });
expect(
(await app.inject("/api/host-management")).json().hosts[0].credential,
).toEqual({ type: "shellbook" });
});
it.each([
["GET", ""],
["POST", ""],
["PUT", "/demo"],
["DELETE", "/demo"],
["PUT", "/demo/credential"],
["DELETE", "/demo/credential"],
["GET", "/demo/install-key"],
["POST", "/demo/action"],
["DELETE", "/demo/known-key"],
] as const)(
"guards %s host management%s with session and origin checks",
async (method, suffix) => {
const { app } = await fixture(true);
expect(
(await app.inject({ method, url: "/api/host-management" + suffix }))
.statusCode,
).toBe(401);
expect(
(
await app.inject({
method,
url: "/api/host-management" + suffix,
headers: { origin: "https://evil.invalid" },
})
).statusCode,
).toBe(403);
},
);
it.each(["password", "keyboard", "privateKey", "encryptedKey"])(
"uses stored %s authentication with strict TOFU",
async (mode) => {
const { config, store, key } = await fixture();
const parsed = utils.parseKey(key);
if (parsed instanceof Error || Array.isArray(parsed))
throw new Error("key");
let accepted = false;
const ssh = await createSshFixture(config, cleanup, (ctx) => {
if (
mode === "password" &&
ctx.method === "password" &&
ctx.password === "ssh-password"
) {
accepted = true;
ctx.accept();
} else if (mode === "keyboard" && ctx.method === "keyboard-interactive")
ctx.prompt([{ prompt: "Password: ", echo: false }], (answers) => {
if (answers[0] === "ssh-password") {
accepted = true;
ctx.accept();
} else ctx.reject();
});
else if (
(mode === "privateKey" || mode === "encryptedKey") &&
ctx.method === "publickey" &&
ctx.key.data.equals(parsed.getPublicSSH()) &&
(!ctx.signature ||
parsed.verify(ctx.blob!, ctx.signature, ctx.hashAlgo) === true)
) {
accepted = true;
ctx.accept();
} else
ctx.reject(
mode === "keyboard"
? ["keyboard-interactive"]
: mode === "password"
? ["password"]
: ["publickey"],
);
});
await store.set(
ssh.host.name,
mode === "privateKey" || mode === "encryptedKey"
? {
type: "privateKey",
privateKey:
mode === "encryptedKey"
? createPrivateKey(key)
.export({
type: "pkcs1",
format: "pem",
cipher: "aes-256-cbc",
passphrase: "key-passphrase",
})
.toString()
: key,
...(mode === "encryptedKey"
? { passphrase: "key-passphrase" }
: {}),
}
: { type: "password", password: "ssh-password" },
);
await expect(connect(config, ssh.host)).rejects.toMatchObject({
fingerprint: ssh.fp,
});
const client = await connect(config, ssh.host, ssh.fp);
expect(await exec(client, "true", "", 2000, () => {})).toBe(0);
const session = await sftp(client);
const output = path.join(config.dataDir, "download.txt");
await transfer(session, "fastGet", "/tmp/shellbook-test/out.txt", output);
await transfer(session, "fastPut", output, "/tmp/uploaded.txt");
expect(ssh.files.get("/tmp/uploaded.txt")?.toString()).toBe(
"artifact bytes",
);
session.end();
client.end();
expect(accepted).toBe(true);
await forgetHostKey(config, ssh.host);
await expect(connect(config, ssh.host)).rejects.toMatchObject({
fingerprint: ssh.fp,
});
},
);
it("renders the exact install command using core quoting and checks the preview before execution", async () => {
const publicKey = "ssh-ed25519 AAAA a'comment";
const script = installKeyScript(publicKey);
expect(script).toContain(`grep -qxF -- ${shellQuote(publicKey)}`);
expect(script).toContain(`printf '\\n%s\\n' ${shellQuote(publicKey)}`);
const { app, config, store } = await fixture();
const ssh = await createSshFixture(config, cleanup);
await writeFile(
path.join(config.workspaceDir, "hosts.yaml"),
JSON.stringify([ssh.host]),
);
await store.set(ssh.host.name, { type: "password", password: "ssh-secret" });
const root = `/api/host-management/${ssh.host.name}`;
const preview = (await app.inject(root + "/install-key")).json().script;
expect(
(
await app.inject({
method: "POST",
url: root + "/action",
payload: { action: "install-key", script: "other" },
})
).statusCode,
).toBe(409);
const untrusted = (
await app.inject({
method: "POST",
url: root + "/action",
payload: { action: "test" },
})
).json();
expect(untrusted.hostKey).toMatchObject({
fingerprint: ssh.fp,
changed: false,
});
const result = await app.inject({
method: "POST",
url: root + "/action",
payload: { action: "install-key", script: preview, acceptHostKey: ssh.fp },
});
expect(result.json()).toEqual({ exitCode: 0 });
expect(ssh.received.at(-1)?.input).toBe(preview);
});
it("redacts credential values in streamed run output and audit", async () => {
const { config, store } = await fixture();
const ssh = await createSshFixture(config, cleanup);
await store.set(ssh.host.name, { type: "password", password: "hello" });
const events: ServerEvent[] = [];
const hub = new EventsHub();
hub.subscribe((e) => events.push(e));
await executeRun({
config,
hub,
host: ssh.host,
runId: randomUUID(),
env: {},
request: {
notebookPath: "a.md",
stepId: "x",
params: {},
runtime: {},
artifactSources: {},
acceptHostKey: ssh.fp,
},
step: {
kind: "check",
lang: "sh",
script: "true",
range: { startLine: 1, endLine: 3 },
attrs: {
id: "x",
local: false,
sudo: false,
confirm: false,
artifacts: [],
uploads: [],
timeoutSec: 5,
},
},
rendered: {
stepId: "x",
kind: "check",
host: ssh.host.name,
local: false,
script: "true",
artifacts: [],
uploads: [],
missing: [],
invalid: {},
},
});
expect(JSON.stringify(events)).not.toContain("hello");
expect(JSON.stringify(events)).toContain("[REDACTED]");
expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: 0 });
});
it("creates one encryption key under concurrent writes", async () => {
const { config } = await fixture();
await Promise.all(
Array.from({ length: 20 }, (_, i) =>
new CredentialStore(config.dataDir).set(String(i), {
type: "password",
password: `password-${i}`,
}),
),
);
for (let i = 0; i < 20; i++)
expect(
(await new CredentialStore(config.dataDir).get(String(i)))?.input,
).toEqual({ type: "password", password: `password-${i}` });
});
it("separates appended public keys from an existing unterminated line", () => {
expect(installKeyScript("ssh-ed25519 AAA")).toContain("printf '\\n%s\\n'");
});
it("pins an explicit ShellBook authentication snapshot instead of rereading a changed credential", async () => {
const { config, store } = await fixture();
const ssh = await createSshFixture(config, cleanup, (ctx) =>
ctx.method === "publickey" ? ctx.accept() : ctx.reject(["publickey"]),
);
await store.set(ssh.host.name, {
type: "password",
password: "wrong-method",
});
const client = await connect(config, ssh.host, ssh.fp, null);
client.end();
});
it("refuses to write credential secrets inside the git workspace", async () => {
const { config } = await fixture();
const dir = path.join(config.workspaceDir, "data");
await expect(
new CredentialStore(dir, config.workspaceDir).set("demo", {
type: "password",
password: "must-not-write",
}),
).rejects.toThrow("outside the workspace");
expect(await readdir(dir)).not.toContain("ssh-credentials.key");
});
it("tells wrong credentials apart from unreachable hosts on Test connection", async () => {
const { app, config, store } = await fixture();
const ssh = await createSshFixture(config, cleanup, false);
const { createServer } = await import("node:net");
const closed = createServer();
await new Promise<void>(resolve => closed.listen(0, "127.0.0.1", resolve));
const port = (closed.address() as import("node:net").AddressInfo).port;
await new Promise(resolve => closed.close(resolve));
const offline = { ...ssh.host, name: "offline", port };
await writeFile(path.join(config.workspaceDir, "hosts.yaml"), JSON.stringify([ssh.host, offline]));
await store.set(ssh.host.name, { type: "password", password: "wrong" });
const denied = await app.inject({ method: "POST", url: `/api/host-management/${ssh.host.name}/action`, payload: { action: "test", acceptHostKey: ssh.fp } });
expect(denied.statusCode).toBe(502);
expect(denied.body).toMatch(/authentication failed/i);
expect(denied.body).not.toContain("wrong");
const unreachable = await app.inject({ method: "POST", url: "/api/host-management/offline/action", payload: { action: "test" } });
expect(unreachable.statusCode).toBe(502);
expect(unreachable.body).toMatch(/cannot reach/i);
});
+1 -1
View File
@@ -205,5 +205,5 @@ it("reports SSH authentication failure without raw transport details", async ()
const f = await httpFixture(false); const f = await httpFixture(false);
const result = await run(f, 'authorize'); const result = await run(f, 'authorize');
expect(result.finished.exitCode).toBe(-1); expect(result.finished.exitCode).toBe(-1);
expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: 'SSH authentication failed' }); expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: 'SSH authentication failed: check the user and the saved password or key' });
}); });
+304
View File
@@ -0,0 +1,304 @@
import { afterEach, expect, it } from "vitest";
import { mkdtemp, mkdir, rm, symlink, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildApp } from "../src/app";
import { notebookName, notebookDestination } from "../src/workspace/notebooks";
import { setPassword } from "../src/auth/credentials";
const dirs: string[] = [];
afterEach(async () => {
for (const dir of dirs.splice(0))
await rm(dir, { recursive: true, force: true });
});
async function setup(auth = false) {
const dir = await mkdtemp(join(tmpdir(), "shellbook-notebooks-"));
dirs.push(dir);
await mkdir(join(dir, "notebooks"));
await setPassword(dir, "test password");
return {
dir,
app: await buildApp({
config: { workspaceDir: dir, dataDir: dir },
auth: auth ? { dataDir: dir } : false,
}),
};
}
it.each([
"../x.md",
"/x.md",
"C:/x.md",
"a\\x.md",
"a/../x.md",
"a//x.md",
"a.txt",
"a/./x.md",
"nul.md",
"x\u0000.md",
"a./x.md",
])("rejects invalid notebook path %s", (name) => {
expect(() => notebookName(name)).toThrow();
});
it("rejects symlink parents, files and notebook root", async () => {
const { app, dir } = await setup();
try {
await mkdir(join(dir, "outside"));
await symlink(
join(dir, "outside"),
join(dir, "notebooks", "linked"),
"junction",
);
await expect(
notebookDestination({ workspaceDir: dir } as never, "linked/new.md"),
).rejects.toThrow("Symlinks");
await rm(join(dir, "notebooks"), { recursive: true });
await symlink(join(dir, "outside"), join(dir, "notebooks"), "junction");
await expect(
notebookDestination({ workspaceDir: dir } as never, "new.md"),
).rejects.toThrow("Symlinks");
} finally {
await app.close();
}
});
it("creates, duplicates, moves, saves and deletes with conflicts and prunes folders", async () => {
const { app, dir } = await setup();
const url = (p: string) => `/api/notebooks/${encodeURIComponent(p)}`;
try {
const created = await app.inject({
method: "POST",
url: "/api/notebooks",
payload: { path: "old/a.md", source: "# A\n" },
});
expect(created.statusCode).toBe(200);
let baseVersion = created.json().version;
expect(
(
await app.inject({
method: "POST",
url: "/api/notebooks",
payload: { path: "old/a.md", source: "overwrite" },
})
).statusCode,
).toBe(409);
for (const op of ["rename", "duplicate"]) {
expect(
(
await app.inject({
method: "POST",
url: url("old/a.md") + `/${op}`,
payload: { path: "new/b.md", baseVersion: "stale" },
})
).statusCode,
).toBe(409);
}
expect(
(
await app.inject({
method: "POST",
url: url("old/a.md") + "/duplicate",
payload: { path: "copy.md", baseVersion },
})
).statusCode,
).toBe(200);
expect(
(
await app.inject({
method: "POST",
url: url("old/a.md") + "/rename",
payload: { path: "copy.md", baseVersion },
})
).statusCode,
).toBe(409);
expect(
(
await app.inject({
method: "POST",
url: url("old/a.md") + "/rename",
payload: { path: "new/b.md", baseVersion },
})
).statusCode,
).toBe(200);
await expect(stat(join(dir, "notebooks", "old"))).rejects.toThrow();
expect((await app.inject(url("new/b.md"))).json().source).toBe("# A\n");
const saved = await app.inject({
method: "PUT",
url: url("new/b.md"),
payload: { source: "# B", baseVersion },
});
expect(saved.statusCode).toBe(200);
baseVersion = saved.json().version;
expect(
(
await app.inject({
method: "DELETE",
url: url("new/b.md"),
payload: { baseVersion: "stale" },
})
).statusCode,
).toBe(409);
expect(
(
await app.inject({
method: "DELETE",
url: url("new/b.md"),
payload: { baseVersion },
})
).statusCode,
).toBe(200);
await expect(stat(join(dir, "notebooks", "new"))).rejects.toThrow();
expect((await app.inject(url("new/b.md"))).statusCode).toBe(404);
} finally {
await app.close();
}
});
it("guards every management route with session and origin checks", async () => {
const { app } = await setup(true);
try {
const login = await app.inject({
method: "POST",
url: "/api/auth/login",
payload: { password: "test password" },
});
const cookie = String(login.headers["set-cookie"]).split(";")[0]!;
for (const [method, url] of [
["POST", "/api/notebooks"],
["POST", "/api/notebooks/a.md/rename"],
["POST", "/api/notebooks/a.md/duplicate"],
["DELETE", "/api/notebooks/a.md"],
] as const) {
expect((await app.inject({ method, url, payload: {} })).statusCode).toBe(
401,
);
expect(
(
await app.inject({
method,
url,
payload: {},
headers: { cookie, origin: "https://evil.test" },
})
).statusCode,
).toBe(403);
}
} finally {
await app.close();
}
});
it("rejects notebook reads through a symlinked notebooks root", async () => {
const { app, dir } = await setup();
try {
const { writeFile } = await import("node:fs/promises");
await mkdir(join(dir, "outside"));
await writeFile(join(dir, "outside", "secret.md"), "private");
await rm(join(dir, "notebooks"), { recursive: true });
await symlink(join(dir, "outside"), join(dir, "notebooks"), "junction");
expect((await app.inject("/api/notebooks/secret.md")).statusCode).toBe(400);
} finally {
await app.close();
}
});
it("publishes create/move/delete changes to other tabs through the watcher", async () => {
const { vi } = await import("vitest");
const { EventsHub } = await import("../src/runs");
const dir = await mkdtemp(join(tmpdir(), "shellbook-events-"));
dirs.push(dir);
await mkdir(join(dir, "notebooks"));
const hub = new EventsHub();
const events: unknown[] = [];
hub.subscribe((event) => events.push(event));
const app = await buildApp({
config: { workspaceDir: dir, dataDir: dir },
auth: false,
events: hub,
watchNotebooks: true,
});
try {
const created = await app.inject({
method: "POST",
url: "/api/notebooks",
payload: { path: "old/a.md", source: "# A" },
});
await vi.waitFor(() =>
expect(events).toContainEqual({ type: "file.changed", path: "old/a.md" }),
);
expect(
(
await app.inject({
method: "POST",
url: "/api/notebooks/old%2Fa.md/rename",
payload: { path: "new/a.md", baseVersion: created.json().version },
})
).statusCode,
).toBe(200);
await vi.waitFor(() => {
expect(events).toContainEqual({ type: "file.deleted", path: "old/a.md" });
expect(events).toContainEqual({ type: "file.changed", path: "new/a.md" });
});
await app.inject({
method: "DELETE",
url: "/api/notebooks/new%2Fa.md",
payload: { baseVersion: created.json().version },
});
await vi.waitFor(() =>
expect(events).toContainEqual({ type: "file.deleted", path: "new/a.md" }),
);
} finally {
await app.close();
}
});
it("does not overwrite concurrent creates", async () => {
const { app } = await setup();
try {
const responses = await Promise.all(
["one", "two"].map((source) =>
app.inject({
method: "POST",
url: "/api/notebooks",
payload: { path: "race.md", source },
}),
),
);
expect(responses.map((r) => r.statusCode).sort()).toEqual([200, 409]);
} finally {
await app.close();
}
});
it("still opens and saves existing notebooks whose names the create rules would reject", async () => {
const { app, dir } = await setup();
try {
const { writeFile } = await import("node:fs/promises");
// Written by git or Claude, not through the create API.
await writeFile(join(dir, "notebooks", "Übersicht (alt).md"), "# Old\n");
const name = encodeURIComponent("Übersicht (alt).md");
const read = await app.inject(`/api/notebooks/${name}`);
expect(read.statusCode).toBe(200);
const save = await app.inject({ method: "PUT", url: `/api/notebooks/${name}`, payload: { source: "# New\n", baseVersion: read.json().version } });
expect(save.statusCode).toBe(200);
const moved = await app.inject({ method: "POST", url: `/api/notebooks/${name}/rename`, payload: { path: "uebersicht.md", baseVersion: save.json().version } });
expect(moved.statusCode).toBe(200);
expect((await app.inject("/api/notebooks/uebersicht.md")).statusCode).toBe(200);
} finally {
await app.close();
}
});
it("never removes folders outside notebooks/ when the workspace path is a symlink", async () => {
const real = await mkdtemp(join(tmpdir(), "shellbook-real-"));
const linkParent = await mkdtemp(join(tmpdir(), "shellbook-link-"));
dirs.push(real, linkParent);
await mkdir(join(real, "notebooks"));
const workspace = join(linkParent, "ws");
await symlink(real, workspace, "junction");
const app = await buildApp({ config: { workspaceDir: workspace, dataDir: real }, auth: false });
try {
const created = await app.inject({ method: "POST", url: "/api/notebooks", payload: { path: "a/x.md", source: "# X\n" } });
expect(created.statusCode).toBe(200);
const deleted = await app.inject({ method: "DELETE", url: `/api/notebooks/${encodeURIComponent("a/x.md")}`, payload: { baseVersion: created.json().version } });
expect(deleted.statusCode).toBe(200);
expect((await stat(join(real, "notebooks"))).isDirectory()).toBe(true);
} finally {
await app.close();
}
});
+310
View File
@@ -0,0 +1,310 @@
import { afterEach, expect, it } from "vitest";
import {
mkdtemp,
readFile,
rm,
stat,
writeFile,
mkdir,
copyFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { FastifyInstance } from "fastify";
import { buildApp } from "../src/app";
import { setPassword } from "../src/auth/credentials";
import { claudeStatus } from "../src/settings";
const dirs: string[] = [],
apps: FastifyInstance[] = [];
async function dir() {
const path = await mkdtemp(join(tmpdir(), "settings-"));
dirs.push(path);
return path;
}
async function setup(maxAttempts = 5) {
const dataDir = await dir();
const app = await buildApp({ config: { dataDir }, auth: { maxAttempts } });
apps.push(app);
return { app, dataDir };
}
const password = "a long test password";
const cookieOf = (r: { headers: Record<string, unknown> }) =>
String(r.headers["set-cookie"]).split(";")[0]!;
afterEach(async () => {
for (const app of apps.splice(0)) await app.close();
for (const path of dirs.splice(0))
await rm(path, { recursive: true, force: true });
});
it("creates a persistent private token and consumes it once, including parallel setup", async () => {
const { app, dataDir } = await setup();
const token = (await readFile(join(dataDir, "setup-token"), "utf8")).trim();
expect(token).toMatch(/^[a-f0-9]{64}$/);
if (process.platform !== "win32")
expect((await stat(join(dataDir, "setup-token"))).mode & 0o777).toBe(0o600);
expect((await app.inject("/api/auth/setup")).json()).toEqual({
required: true,
});
expect(
(
await app.inject({
method: "POST",
url: "/api/auth/setup",
payload: {
token: "wrong",
newPassword: password,
confirmPassword: password,
},
})
).statusCode,
).toBe(401);
const payload = { token, newPassword: password, confirmPassword: password };
const results = await Promise.all(
[1, 2].map(() =>
app.inject({ method: "POST", url: "/api/auth/setup", payload }),
),
);
expect(results.map((r) => r.statusCode).sort()).toEqual([204, 409]);
await expect(stat(join(dataDir, "setup-token"))).rejects.toMatchObject({
code: "ENOENT",
});
expect((await app.inject("/api/auth/setup")).json()).toEqual({
required: false,
});
const cookie = cookieOf(results.find((r) => r.statusCode === 204)!);
expect(
(await app.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode,
).toBe(200);
if (process.platform !== "win32")
expect((await stat(join(dataDir, "auth.json"))).mode & 0o777).toBe(0o600);
});
it("retains the setup token across restart and removes stale tokens with configured password", async () => {
const { app, dataDir } = await setup();
const token = await readFile(join(dataDir, "setup-token"), "utf8");
await app.close();
apps.splice(apps.indexOf(app), 1);
const second = await buildApp({ config: { dataDir } });
apps.push(second);
expect(await readFile(join(dataDir, "setup-token"), "utf8")).toBe(token);
await setPassword(dataDir, password);
const third = await buildApp({ config: { dataDir } });
apps.push(third);
await expect(stat(join(dataDir, "setup-token"))).rejects.toMatchObject({
code: "ENOENT",
});
});
it("shares setup/login limits and rejects weak or mismatched passwords", async () => {
const { app, dataDir } = await setup(3);
const token = (await readFile(join(dataDir, "setup-token"), "utf8")).trim();
for (const [newPassword, confirmPassword] of [
["short", "short"],
[password, "different"],
]) {
expect(
(
await app.inject({
method: "POST",
url: "/api/auth/setup",
payload: { token, newPassword, confirmPassword },
})
).statusCode,
).toBe(400);
}
expect(
(
await app.inject({
method: "POST",
url: "/api/auth/login",
payload: { password },
})
).statusCode,
).toBe(401);
const response = await app.inject({
method: "POST",
url: "/api/auth/setup",
payload: { token, newPassword: password, confirmPassword: password },
});
expect(response.statusCode).toBe(429);
expect(response.headers["retry-after"]).toBeDefined();
});
it("keeps every settings route private and setup under the origin check", async () => {
const { app } = await setup();
for (const [method, url] of [
["GET", "/api/settings/system"],
["GET", "/api/settings/claude"],
["GET", "/api/settings/session"],
["POST", "/api/settings/password"],
["POST", "/api/settings/sessions/revoke"],
["GET", "/api/auth/setup/"],
["GET", "/api/auth/setup/extra"],
] as const) {
expect((await app.inject({ method, url })).statusCode, url).toBe(401);
}
expect(
(
await app.inject({
method: "POST",
url: "/api/auth/setup",
headers: { origin: "https://evil.test" },
payload: {},
})
).statusCode,
).toBe(403);
});
it("checks current password, revokes cookies on password change and rotation, survives restart", async () => {
const { app, dataDir } = await setup();
await setPassword(dataDir, password);
const login = async () =>
cookieOf(
await app.inject({
method: "POST",
url: "/api/auth/login",
payload: { password },
}),
);
const cookie = await login();
const payload = {
currentPassword: "wrong",
newPassword: "new long password",
confirmPassword: "new long password",
};
const change = () =>
app.inject({
method: "POST",
url: "/api/settings/password",
headers: { cookie },
payload,
});
expect((await change()).statusCode).toBe(401);
payload.currentPassword = password;
payload.confirmPassword = "mismatch";
expect((await change()).statusCode).toBe(400);
payload.confirmPassword = payload.newPassword;
const changed = await change();
expect(changed.statusCode).toBe(204);
const fresh = cookieOf(changed);
expect(
(await app.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode,
).toBe(401);
expect(
(
await app.inject({
url: "/api/settings/session",
headers: { cookie: fresh },
})
).json(),
).toEqual({ lifetimeSeconds: 2592000 });
const oldSecret = await readFile(join(dataDir, "session-secret"));
const revoked = await app.inject({
method: "POST",
url: "/api/settings/sessions/revoke",
headers: { cookie: fresh },
});
expect(revoked.statusCode).toBe(204);
expect(await readFile(join(dataDir, "session-secret"))).not.toEqual(
oldSecret,
);
expect(
(await app.inject({ url: "/api/auth/me", headers: { cookie: fresh } }))
.statusCode,
).toBe(401);
const renewed = cookieOf(revoked);
const second = await buildApp({ config: { dataDir } });
apps.push(second);
expect(
(
await second.inject({
url: "/api/settings/system",
headers: { cookie: renewed },
})
).json(),
).toMatchObject({
dataDirPath: dataDir,
nodeVersion: process.version,
version: "0.0.0",
});
await setPassword(dataDir, "CLI changed password");
expect(
(await second.inject({ url: "/api/auth/me", headers: { cookie: renewed } }))
.statusCode,
).toBe(401);
});
it("reports absent CLI/credentials without reading contents", async () => {
const home = await dir();
expect(await claudeStatus(home, { PATH: home })).toEqual({
available: false,
version: null,
loginAppearsPresent: false,
});
await mkdir(join(home, ".claude"));
await mkdir(join(home, ".claude", ".credentials.json"));
expect((await claudeStatus(home, { PATH: home })).loginAppearsPresent).toBe(
true,
);
});
it("runs a fake Claude executable from PATH with argv", async () => {
const home = await dir();
if (process.platform === "win32") {
await copyFile(process.execPath, join(home, "claude.exe"));
expect(
await claudeStatus(home, {
PATH: home,
SystemRoot: process.env.SystemRoot,
}),
).toEqual({
available: true,
version: process.version,
loginAppearsPresent: false,
});
return;
}
await writeFile(
join(home, "claude"),
'#!/bin/sh\n[ "$1" = --version ] || exit 1\nprintf "fake-claude 1.0\\n"\n',
{ mode: 0o700 },
);
expect(await claudeStatus(home, { PATH: home })).toEqual({
available: true,
version: "fake-claude 1.0",
loginAppearsPresent: false,
});
});
it("closes active WebSockets on password changes and sign-out-all", async () => {
const { app, dataDir } = await setup();
await setPassword(dataDir, password);
app.get("/api/test-socket", { websocket: true }, (socket) => {
socket.send("ready");
});
let cookie = cookieOf(
await app.inject({
method: "POST",
url: "/api/auth/login",
payload: { password },
}),
);
for (const url of [
"/api/settings/password",
"/api/settings/sessions/revoke",
]) {
const ws = await app.injectWS("/api/test-socket", { headers: { cookie } });
const closed = new Promise((resolve) => ws.on("close", resolve));
const response = await app.inject({
method: "POST",
url,
headers: { cookie },
payload: url.endsWith("password")
? {
currentPassword: password,
newPassword: "changed test password",
confirmPassword: "changed test password",
}
: {},
});
expect(response.statusCode).toBe(204);
await closed;
await expect(
app.injectWS("/api/test-socket", { headers: { cookie } }),
).rejects.toThrow("401");
cookie = cookieOf(response);
}
});
+2 -2
View File
@@ -3,7 +3,7 @@ import { Server, utils, type Connection } from "ssh2";
import type { HostInfo } from "@shellbook/core"; import type { HostInfo } from "@shellbook/core";
import type { ServerConfig } from "../src/config"; import type { ServerConfig } from "../src/config";
import { fingerprint } from "../src/ssh"; import { fingerprint } from "../src/ssh";
export async function createSshFixture(config: ServerConfig, cleanup: (() => Promise<unknown>)[], authenticate = true) { export async function createSshFixture(config: ServerConfig, cleanup: (() => Promise<unknown>)[], authenticate: boolean | ((ctx: import("ssh2").AuthContext) => void) = true) {
const key = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString(); const key = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString();
const parsed = utils.parseKey(key); const parsed = utils.parseKey(key);
if (parsed instanceof Error) throw parsed; if (parsed instanceof Error) throw parsed;
@@ -15,7 +15,7 @@ export async function createSshFixture(config: ServerConfig, cleanup: (() => Pro
clients.add(client); clients.add(client);
client.on("error", () => {}); client.on("error", () => {});
client.on("close", () => clients.delete(client)); client.on("close", () => clients.delete(client));
client.on("authentication", ctx => authenticate ? ctx.accept() : ctx.reject()); client.on("authentication", ctx => typeof authenticate === "function" ? authenticate(ctx) : authenticate ? ctx.accept() : ctx.reject());
client.on("ready", () => client.on("session", accept => { client.on("ready", () => client.on("session", accept => {
const session = accept(); const session = accept();
session.on("exec", (acceptExec, _reject, info) => { session.on("exec", (acceptExec, _reject, info) => {
+26 -8
View File
@@ -4,34 +4,39 @@ import { join } from "node:path";
import { expect, it, vi } from "vitest"; import { expect, it, vi } from "vitest";
import { createNotebookWatcher, type NotebookFileEvent } from "../src/watch/index"; import { createNotebookWatcher, type NotebookFileEvent } from "../src/watch/index";
// Generous timings: the full parallel test run on Windows can delay fs events by >100 ms.
const debounceMs = 300;
const settle = { timeout: 5000 };
const quiet = () => new Promise((r) => setTimeout(r, debounceMs * 3));
it("watches nested Markdown, debounces writes, handles atomic saves/deletes and unsubscribes", async () => { it("watches nested Markdown, debounces writes, handles atomic saves/deletes and unsubscribes", async () => {
const dir = await mkdtemp(join(tmpdir(), "shellbook-watch-")); const dir = await mkdtemp(join(tmpdir(), "shellbook-watch-"));
await mkdir(join(dir, "notebooks", "setup"), { recursive: true }); await mkdir(join(dir, "notebooks", "setup"), { recursive: true });
const file = join(dir, "notebooks", "setup", "test.md"); const file = join(dir, "notebooks", "setup", "test.md");
await writeFile(file, "initial"); await writeFile(file, "initial");
const watcher = createNotebookWatcher(dir, { debounceMs: 100 }); const watcher = createNotebookWatcher(dir, { debounceMs });
const events: NotebookFileEvent[] = []; const events: NotebookFileEvent[] = [];
const off = watcher.on((event) => events.push(event)); const off = watcher.on((event) => events.push(event));
try { try {
await watcher.ready; await watcher.ready;
expect(events).toEqual([]); expect(events).toEqual([]);
await writeFile(file, "first"); await writeFile(file, "second"); await writeFile(file, "first"); await writeFile(file, "second");
await vi.waitFor(() => expect(events).toEqual([{ type: "file.changed", path: "setup/test.md" }])); await vi.waitFor(() => expect(events).toEqual([{ type: "file.changed", path: "setup/test.md" }]), settle);
await writeFile(`${file}.tmp`, "replacement"); await rename(`${file}.tmp`, file); await writeFile(`${file}.tmp`, "replacement"); await rename(`${file}.tmp`, file);
await vi.waitFor(() => expect(events).toHaveLength(2)); await vi.waitFor(() => expect(events).toHaveLength(2), settle);
expect(events[1]).toEqual({ type: "file.changed", path: "setup/test.md" }); expect(events[1]).toEqual({ type: "file.changed", path: "setup/test.md" });
await rm(file); await rm(file);
await vi.waitFor(() => expect(events[2]).toEqual({ type: "file.deleted", path: "setup/test.md" })); await vi.waitFor(() => expect(events[2]).toEqual({ type: "file.deleted", path: "setup/test.md" }), settle);
await mkdir(join(dir, "notebooks", "new")); await mkdir(join(dir, "notebooks", "new"));
await writeFile(join(dir, "notebooks", "new", "added.md"), "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 vi.waitFor(() => expect(events[3]).toEqual({ type: "file.changed", path: "new/added.md" }), settle);
await writeFile(join(dir, "notebooks", "ignored.txt"), "ignore"); await writeFile(join(dir, "notebooks", "ignored.txt"), "ignore");
await writeFile(join(dir, "outside.md"), "ignore"); await writeFile(join(dir, "outside.md"), "ignore");
await new Promise((r) => setTimeout(r, 300)); expect(events).toHaveLength(4); await quiet(); expect(events).toHaveLength(4);
off(); await writeFile(file, "unsubscribed"); off(); await writeFile(file, "unsubscribed");
await new Promise((r) => setTimeout(r, 300)); expect(events).toHaveLength(4); await quiet(); expect(events).toHaveLength(4);
} finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); } } finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); }
}); }, 30_000);
it("starts before notebooks exists and cancels pending notifications on close", async () => { it("starts before notebooks exists and cancels pending notifications on close", async () => {
const dir = await mkdtemp(join(tmpdir(), "shellbook-watch-")); const dir = await mkdtemp(join(tmpdir(), "shellbook-watch-"));
@@ -44,3 +49,16 @@ it("starts before notebooks exists and cancels pending notifications on close",
await new Promise((r) => setTimeout(r, 600)); expect(listener).not.toHaveBeenCalled(); await new Promise((r) => setTimeout(r, 600)); expect(listener).not.toHaveBeenCalled();
} finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); } } finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); }
}); });
it("publishes hosts.yaml changes, atomic replacements and deletion", async () => {
const dir = await mkdtemp(join(tmpdir(), "shellbook-hostwatch-"));
const file = join(dir, "hosts.yaml"); await writeFile(file, "[]");
const watcher = createNotebookWatcher(dir, { debounceMs: 10 });
const events: NotebookFileEvent[] = []; watcher.on(e => events.push(e));
try {
await watcher.ready; await writeFile(file + ".tmp", "# changed\n[]"); await rename(file + ".tmp", file);
await vi.waitFor(() => expect(events).toContainEqual({ type: "file.changed", path: "hosts.yaml" }));
await rm(file);
await vi.waitFor(() => expect(events).toContainEqual({ type: "file.deleted", path: "hosts.yaml" }));
} finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); }
});
+28
View File
@@ -82,3 +82,31 @@ and reconnect. App tests drive the SSH-key fixture through keygen, sensitive art
downloads (including 410), after sections, capture substitution, and authorize downloads (including 410), after sections, capture substitution, and authorize
artifact provenance. Real tmux/Claude login and browser terminal rendering still artifact provenance. Real tmux/Claude login and browser terminal rendering still
need an interactive server check. need an interactive server check.
## Notebook management and authoring
The sidebar groups notebooks into folders and filters by title or path. **New notebook**
asks for a name, optional folder and title, then opens a valid starter with a host
parameter, a read-only check, and a confirmed run placeholder. **Rename / move** and
**Duplicate** take a destination path relative to `notebooks/` (including `.md`).
Folders are created automatically; empty folders disappear after moves or deletes.
**Delete** requires explicit confirmation. Names use letters, numbers, spaces, dots,
underscores and hyphens; traversal, absolute paths, symlinks and Windows device names
are rejected. Management needs a real server; the demo reports that limitation.
In edit mode, the toolbar inserts Check, Run, Artifacts, Upload or Capture examples
at the cursor, targeting the local ShellBook server or a declared host parameter.
Review example commands and file names before execution. **Parameter** adds a YAML
mapping via a form (including choice options and secret rules), preserving unrelated
YAML and comments. **After step** selects an existing step for conditional instructions.
**Format help** explains attributes and parameter references. Save and live preview
continue to use the core parser. Attribute editing remains available in Markdown.
All mutations use authenticated, same-origin API calls. Save, move, duplicate and
delete use optimistic versions (409 means stale content or an occupied destination).
Files publish atomically, and the existing watcher refreshes other tabs' lists and
clean open documents. External rename/delete retains the old open draft with a
notice; select the new path from the refreshed list. Unsaved edits require confirmation
before navigation or management. External filesystem writers must be trusted: as with
other workspace operations, symlink checks cannot prevent a privileged local process
from swapping path components between filesystem calls.
+2 -1
View File
@@ -19,7 +19,8 @@
"codemirror": "^6.0.1", "codemirror": "^6.0.1",
"highlight.js": "^11.10.0", "highlight.js": "^11.10.0",
"@xterm/xterm": "^5.5.0", "@xterm/xterm": "^5.5.0",
"@xterm/addon-fit": "^0.10.0" "@xterm/addon-fit": "^0.10.0",
"yaml": "^2.6.1"
}, },
"devDependencies": { "devDependencies": {
"@types/react": "^18.3.12", "@types/react": "^18.3.12",
+72 -75
View File
@@ -1,3 +1,7 @@
import { HeaderNavigation, type NavigationPage } from "./HeaderNavigation";
import { SettingsPage } from "./SettingsPage";
import { SetupScreen } from "./SetupScreen";
import { settingsApi } from "./settingsApi";
import { import {
lazy, lazy,
Suspense, Suspense,
@@ -24,11 +28,15 @@ import type {
StartRunRequest, StartRunRequest,
Step, Step,
} from "@shellbook/core"; } from "@shellbook/core";
import { NotebookList } from "./NotebookList";
import { HostKeyConfirmation } from "./HostKeyConfirmation";
import { HostsPage } from "./HostsPage";
import { HttpError } from "./api"; import { HttpError } from "./api";
import type { Api } from "./api"; import type { Api } from "./api";
import { emptySession, eventReducer, stepKey } from "./events"; import { emptySession, eventReducer, stepKey } from "./events";
import { ParamsForm } from "./ParamsForm"; import { ParamsForm } from "./ParamsForm";
import { StepCard } from "./StepCard"; import { StepCard } from "./StepCard";
import { ChatPanel } from "./ChatPanel";
const TerminalSlot = lazy(() => const TerminalSlot = lazy(() =>
import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })), import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })),
); );
@@ -46,7 +54,8 @@ function steps(blocks: Block[]): Step[] {
); );
} }
export function App({ api }: { api: Api }) { export function App({ api }: { api: Api }) {
const [auth, setAuth] = useState<"loading" | "login" | "ready">("loading"); const [auth, setAuth] = useState<"loading" | "login" | "setup" | "ready">("loading");
const [page, setPage] = useState<NavigationPage>("Notebooks");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [list, setList] = useState<NotebookSummary[]>([]); const [list, setList] = useState<NotebookSummary[]>([]);
const [hosts, setHosts] = useState<HostInfo[]>([]); const [hosts, setHosts] = useState<HostInfo[]>([]);
@@ -55,6 +64,7 @@ export function App({ api }: { api: Api }) {
const [values, setValues] = useState<ParamValues>({}); const [values, setValues] = useState<ParamValues>({});
const [edit, setEdit] = useState(false); const [edit, setEdit] = useState(false);
const [terminal, setTerminal] = useState(false); const [terminal, setTerminal] = useState(false);
const [chat, setChat] = useState(false);
const [terminalOpened, setTerminalOpened] = useState(false); const [terminalOpened, setTerminalOpened] = useState(false);
const [conflict, setConflict] = useState(false); const [conflict, setConflict] = useState(false);
const [error, setError] = useState(""); const [error, setError] = useState("");
@@ -103,8 +113,12 @@ export function App({ api }: { api: Api }) {
.me() .me()
.then(() => setAuth("ready")) .then(() => setAuth("ready"))
.catch((e) => { .catch((e) => {
if (e instanceof HttpError && e.status === 401) setAuth("login"); if (e instanceof HttpError && e.status === 401) {
else setError(String(e)); setAuth("login");
void settingsApi.setupStatus()
.then(status => { if (status.required) setAuth("setup"); })
.catch(() => {});
} else setError(String(e));
}); });
}, [api]); }, [api]);
useEffect(() => { useEffect(() => {
@@ -119,7 +133,19 @@ export function App({ api }: { api: Api }) {
}) })
.catch((e) => setError(String(e))); .catch((e) => setError(String(e)));
const close = api.events((event: ServerEvent) => { const close = api.events((event: ServerEvent) => {
if ((event.type === "file.changed" || event.type === "file.deleted") && event.path === "hosts.yaml") {
void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e)));
window.dispatchEvent(new Event("shellbook:hosts-changed")); return;
}
const open = current.current; const open = current.current;
if (event.type === "file.changed" || event.type === "file.deleted") {
void api
.list()
.then((result) => {
if (active) setList(result.notebooks);
})
.catch((e) => setError(String(e)));
}
if (event.type === "file.changed" && event.path === open.doc?.path) { if (event.type === "file.changed" && event.path === open.doc?.path) {
if (open.dirty) setConflict(true); if (open.dirty) setConflict(true);
else void load(event.path); else void load(event.path);
@@ -281,6 +307,7 @@ export function App({ api }: { api: Api }) {
const keyPrompt = Object.values(session.runs).find( const keyPrompt = Object.values(session.runs).find(
(run) => run.status === "hostKey" && requests.current.has(run.runId), (run) => run.status === "hostKey" && requests.current.has(run.runId),
); );
if (auth === "setup") return <SetupScreen onComplete={() => setAuth("ready")} />;
if (auth === "login") if (auth === "login")
return ( return (
<main className="login"> <main className="login">
@@ -319,26 +346,33 @@ export function App({ api }: { api: Api }) {
</main> </main>
); );
return ( return (
<div className={`app ${terminal ? "with-terminal" : ""}`}> <div className={`app ${terminal || chat ? "with-terminal" : ""}`}>
<aside className="sidebar"> <aside className="sidebar">
<h1> <h1>
ShellBook<span>RUNBOOKS</span> ShellBook<span>RUNBOOKS</span>
</h1> </h1>
<nav aria-label="Notebooks"> <NotebookList
{list.map((item) => ( api={api}
<button list={list}
className={path === item.path ? "selected" : ""} path={path}
key={item.path} version={doc?.version}
onClick={() => { canLeave={() => !dirty || window.confirm("Discard unsaved edits?")}
if (!dirty || window.confirm("Discard unsaved edits?")) onSelect={(next) => {
void load(item.path); if (!dirty || window.confirm("Discard unsaved edits?"))
}} void load(next);
> }}
{item.title} onChanged={async (next) => {
<small>{item.path}</small> const result = await api.list();
</button> setList(result.notebooks);
))} if (next) await load(next);
</nav> else {
++loadSequence.current;
setDoc(undefined);
setSource("");
setConflict(false);
}
}}
/>
<small className="connection"> <small className="connection">
{import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""} {import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""}
{connected {connected
@@ -347,7 +381,12 @@ export function App({ api }: { api: Api }) {
</small> </small>
</aside> </aside>
<main> <main>
<HeaderNavigation page={page} onChange={setPage} />
{page === "Settings" && <SettingsPage openTerminal={() => { setTerminalOpened(true); setTerminal(true); }} />}
{page === "Hosts" && <HostsPage onChange={() => { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />}
<div hidden={page !== "Notebooks"}>
<div className="toolbar"> <div className="toolbar">
<button aria-expanded={chat} onClick={() => { setChat(!chat); setTerminal(false); }}>Chat</button>
<span>{doc?.notebook.title ?? "Loading workspace…"}</span> <span>{doc?.notebook.title ?? "Loading workspace…"}</span>
<button onClick={() => setEdit(!edit)}> <button onClick={() => setEdit(!edit)}>
{edit ? "Close editor" : "Edit Markdown"} {edit ? "Close editor" : "Edit Markdown"}
@@ -356,6 +395,7 @@ export function App({ api }: { api: Api }) {
aria-expanded={terminal} aria-expanded={terminal}
onClick={() => { onClick={() => {
setTerminalOpened(true); setTerminalOpened(true);
setChat(false);
setTerminal(!terminal); setTerminal(!terminal);
}} }}
> >
@@ -468,7 +508,11 @@ export function App({ api }: { api: Api }) {
</div> </div>
</> </>
)} )}
</div>
</main> </main>
{chat && <ChatPanel notebookPath={doc?.path} openNotebook={path => {
if (!dirty || window.confirm("Discard unsaved edits?")) void load(path);
}} openTerminal={() => { setChat(false); setTerminalOpened(true); setTerminal(true); }} />}
{terminalOpened && ( {terminalOpened && (
<Suspense fallback={<p>Loading terminal...</p>}> <Suspense fallback={<p>Loading terminal...</p>}>
<TerminalSlot collapsed={!terminal} /> <TerminalSlot collapsed={!terminal} />
@@ -499,62 +543,15 @@ export function App({ api }: { api: Api }) {
</section> </section>
</div> </div>
)} )}
{keyPrompt?.hostKey && ( {keyPrompt?.hostKey && <HostKeyConfirmation
<div className="modal-backdrop"> {...keyPrompt.hostKey}
<section onReject={() => dispatch({ type: "run.error", runId: keyPrompt.runId, message: "Host key rejected" })}
role="dialog" onTrust={() => {
aria-modal="true" const request = requests.current.get(keyPrompt.runId)!;
aria-labelledby="hostkey-title" dispatch({ type: "run.error", runId: keyPrompt.runId, message: "Retrying with accepted host key" });
> void start({ ...request, acceptHostKey: keyPrompt.hostKey!.fingerprint });
<h2 id="hostkey-title"> }}
{keyPrompt.hostKey.changed />}
? "⚠ HOST KEY CHANGED"
: "Unknown SSH host key"}
</h2>
{keyPrompt.hostKey.changed && (
<p className="error">
STOP: a different key is already trusted. This may indicate a
man-in-the-middle attack. Verify the fingerprint independently
before accepting.
</p>
)}
<p>
Verify the key for <strong>{keyPrompt.hostKey.host}</strong>{" "}
through a trusted channel.
</p>
<code>{keyPrompt.hostKey.fingerprint}</code>
<div className="actions">
<button
onClick={() =>
dispatch({
type: "run.error",
runId: keyPrompt.runId,
message: "Host key rejected",
})
}
>
Reject
</button>
<button
onClick={() => {
const request = requests.current.get(keyPrompt.runId)!;
dispatch({
type: "run.error",
runId: keyPrompt.runId,
message: "Retrying with accepted host key",
});
void start({
...request,
acceptHostKey: keyPrompt.hostKey!.fingerprint,
});
}}
>
Trust this fingerprint and retry
</button>
</div>
</section>
</div>
)}
</div> </div>
); );
} }
+170
View File
@@ -0,0 +1,170 @@
import { useState } from "react";
import { parseNotebook, type ParamDef } from "@shellbook/core";
import {
addParameter,
afterSnippet,
notebookSteps,
stepSnippet,
type InsertKind,
} from "./authoring";
export function AuthoringToolbar({
source,
insert,
replace,
}: {
source: string;
insert(text: string): void;
replace(text: string): void;
}) {
const notebook = parseNotebook(source);
const hosts = notebook.params.filter((p) => p.type === "host");
const [target, setTarget] = useState("local");
const [param, setParam] = useState(false);
const [error, setError] = useState("");
const [type, setType] = useState<ParamDef["type"]>("string");
const [after, setAfter] = useState("");
const steps = notebookSteps(notebook.blocks);
return (
<div className="authoring">
<label>
Insert target
<select value={target} onChange={(e) => setTarget(e.target.value)}>
<option value="local">ShellBook server (local)</option>
{hosts.map((p) => (
<option key={p.name} value={p.name}>
Parameter: {p.name}
</option>
))}
</select>
</label>
{(
[
"Check step",
"Run step",
"Artifacts",
"Upload",
"Capture",
] as InsertKind[]
).map((kind) => (
<button
key={kind}
type="button"
onClick={() =>
insert(stepSnippet(source, kind, target === "local", target))
}
>
{kind}
</button>
))}
<button type="button" onClick={() => setParam(!param)}>
Parameter
</button>
<label>
After step
<select value={after} onChange={(e) => setAfter(e.target.value)}>
<option value="">Choose a step</option>
{steps.map((s) => (
<option key={s.attrs.id} value={s.attrs.id}>
{s.attrs.title ?? s.attrs.id}
</option>
))}
</select>
</label>
<button
type="button"
disabled={!steps.some((s) => s.attrs.id === after)}
onClick={() => insert(afterSnippet(after))}
>
Insert after note
</button>
{param && (
<form
onSubmit={(e) => {
e.preventDefault();
const data = new FormData(e.currentTarget);
const def: ParamDef = {
name: String(data.get("name")),
type,
required: data.has("required"),
};
if (data.get("label")) def.label = String(data.get("label"));
if (type !== "secret" && data.get("default"))
def.default = String(data.get("default"));
if (type === "choice")
def.options = String(data.get("options"))
.split("\n")
.map((s) => s.trim())
.filter(Boolean);
try {
replace(addParameter(source, def));
setParam(false);
setError("");
} catch (err) {
setError(String(err));
}
}}
>
<label>
Parameter name
<input name="name" required pattern="[A-Za-z_][A-Za-z0-9_]*" />
</label>
<label>
Type
<select
value={type}
onChange={(e) => setType(e.target.value as ParamDef["type"])}
>
{["host", "name", "path", "string", "choice", "secret"].map(
(t) => (
<option key={t}>{t}</option>
),
)}
</select>
</label>
<label>
<input type="checkbox" name="required" />
Required
</label>
<label>
Label
<input name="label" />
</label>
{type !== "secret" && (
<label>
Default
<input name="default" />
</label>
)}
{type === "choice" && (
<label>
Options (one per line)
<textarea name="options" required />
</label>
)}
<button>Add parameter</button>
</form>
)}
{error && <p role="alert">{error}</p>}
<details>
<summary>Format help</summary>
<p>
Parameters live in YAML frontmatter: type, required, default, label,
options. Use {"{{name}}"} in prose and scripts. Secrets use
environment variables ($NAME), with no default.
</p>
<p>
Steps use sh fences with {'{check host="{{host}}"}'} or{" "}
{"{run on=local confirm}"}. Checks must be read-only. Optional
attributes: id, title, sudo, confirm, timeout (seconds), capture. Run
steps support artifacts="file.txt" and
upload="file.txt:/tmp/file.txt". After notes appear when their
selected step succeeds.
</p>
<p>
Artifact and upload snippets are examples: choose files and commands
appropriate to your runbook before running.
</p>
</details>
</div>
);
}
+98
View File
@@ -0,0 +1,98 @@
import { useEffect, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import type { ChatClientMessage, ChatConversation, ChatEvent } from "@shellbook/core";
import "./chat.css";
export interface ChatSocket {
onopen: ((event: Event) => void) | null; onclose: ((event: CloseEvent) => void) | null; onerror: ((event: Event) => void) | null;
onmessage: ((event: MessageEvent) => void) | null;
send(text: string): void; close(): void;
}
const connectChat = (): ChatSocket => new WebSocket(`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/chat`);
type Message = { role: "user" | "assistant" | "tool"; text: string; path?: string };
/** notebookPath and openNotebook use app paths (relative to notebooks/); the chat wire uses workspace paths. */
export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect = connectChat }: {
notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; connect?: () => ChatSocket;
}) {
const [history, setHistory] = useState<ChatConversation[]>([]);
const [selected, setSelected] = useState("");
const [messages, setMessages] = useState<Message[]>([]);
const cache = useRef(new Map<string, Message[]>());
const selectedRef = useRef("");
const [text, setText] = useState("");
const [allowShell, setAllowShell] = useState(false);
const [busy, setBusy] = useState(false);
const [ready, setReady] = useState(false);
const [error, setError] = useState("");
const [login, setLogin] = useState(false);
const [summary, setSummary] = useState("");
const [attempt, setAttempt] = useState(0);
const socket = useRef<ChatSocket>();
const end = useRef<HTMLDivElement>(null);
useEffect(() => { end.current?.scrollIntoView?.({ block: "nearest" }); }, [messages]);
useEffect(() => {
let alive = true;
let connection: ChatSocket;
try { connection = connect(); socket.current = connection; }
catch { setError("Cannot connect to chat."); return; }
connection.onopen = () => { if (alive) { setReady(true); setError(""); } };
connection.onclose = connection.onerror = () => {
if (alive) { setReady(false); setBusy(false); setError("Chat disconnected. The current turn was stopped. Reconnect to continue."); }
};
connection.onmessage = ({ data }) => {
if (!alive) return;
let event: ChatEvent; try { event = JSON.parse(data); } catch { return; }
if (event.type === "history") setHistory(event.conversations);
if (event.type === "conversation") {
selectedRef.current = event.conversation.id; setSelected(event.conversation.id);
setHistory(previous => [...previous.filter(c => c.id !== event.conversation.id), event.conversation]);
}
if (event.type === "delta") setMessages(previous => {
const last = previous.at(-1);
return last?.role === "assistant" ? [...previous.slice(0, -1), { ...last, text: last.text + event.text }] : [...previous, { role: "assistant", text: event.text }];
});
if (event.type === "tool") setMessages(previous => [...previous, {
role: "tool", text: `${["Edit", "Write", "MultiEdit"].includes(event.name) ? "Editing" : event.name} ${event.path ?? ""}`.trim(), path: event.path,
}]);
if (event.type === "error") { setBusy(false); setError(event.message); setLogin(event.code === "login" || event.code === "missing"); }
if (event.type === "finished") {
setBusy(false); setSummary(event.cancelled ? "Stopped" : `Finished${event.durationMs === undefined ? "" : ` in ${(event.durationMs / 1000).toFixed(1)}s`}${event.costUsd === undefined ? "" : ` · estimated $${event.costUsd.toFixed(4)}`}`);
}
};
return () => { alive = false; connection.close(); };
}, [connect, attempt]);
useEffect(() => { if (selected) cache.current.set(selected, messages); }, [messages, selected]);
function choose(id: string) {
selectedRef.current = id; setSelected(id); setMessages(cache.current.get(id) ?? []);
setError(""); setLogin(false); setSummary(""); setAllowShell(false);
}
function send(message: ChatClientMessage) { try { socket.current?.send(JSON.stringify(message)); } catch { setBusy(false); setError("Cannot send chat message. Reconnect to continue."); } }
return <aside className="chat-panel" aria-label="Chat panel">
<h2>Chat with Claude</h2>
<div className="actions"><button disabled={busy} onClick={() => choose("")}>New conversation</button>
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}</div>
<label>Conversation history<select aria-label="Conversation history" disabled={busy} value={selected} onChange={e => choose(e.target.value)}>
<option value="">New conversation</option>{[...history].reverse().map(c => <option key={c.id} value={c.id}>{c.title}</option>)}
</select></label>
<div className="chat-messages" role="log" aria-label="Chat messages" aria-live="polite">
{!messages.length && <p>{selected ? "Continue this conversation. Earlier messages are retained by the Claude CLI; this view shows messages from this browser session." : "Ask Claude to create or edit a notebook. Do not send secrets."}</p>}
{messages.map((m, i) => <div key={i} className={`chat-message ${m.role}`}>
{m.role === "tool" ? <small>{m.text} {m.path && <button onClick={() => openNotebook(m.path!.replace(/^notebooks\//, ""))}>Open notebook</button>}</small> : <><strong>{m.role === "user" ? "You" : "Claude"}</strong><ReactMarkdown>{m.text}</ReactMarkdown></>}
</div>)}<div ref={end} />
</div>
{error && <p role="alert">{error}</p>}
{login && <button onClick={openTerminal}>Open Terminal — run claude, then /login</button>}
<p role="status">{busy ? "Claude is working…" : summary}</p>
{!messages.length && <div className="actions">{["Create a notebook that…", "Add a check that…"].map(prompt => <button key={prompt} onClick={() => setText(prompt)}>{prompt}</button>)}</div>}
<form onSubmit={e => { e.preventDefault(); if (!ready || busy || !text.trim()) return;
setMessages(previous => [...previous, { role: "user", text }]); setBusy(true); setError(""); setLogin(false); setSummary("");
send({ type: "send", conversationId: selectedRef.current || undefined, message: text, notebookPath: notebookPath && `notebooks/${notebookPath}`, allowShell }); setText("");
}}>
<label>Message<textarea value={text} onChange={e => setText(e.target.value)} maxLength={32000} required rows={3} /></label>
<label className="chat-shell"><input type="checkbox" checked={allowShell} disabled={busy} onChange={e => setAllowShell(e.target.checked)} />Allow Claude to run shell commands on the ShellBook server</label>
<small>Off by default. Enabling this allows commands as the service user, including network access. File tools otherwise stay in the workspace.</small>
<div className="actions"><button disabled={!ready || busy || !text.trim()}>Send</button>{busy && <button type="button" onClick={() => send({ type: "cancel" })}>Stop</button>}</div>
</form>
</aside>;
}
+28 -2
View File
@@ -1,3 +1,4 @@
import { AuthoringToolbar } from "./AuthoringToolbar";
import { useEffect, useRef } from "react"; import { useEffect, useRef } from "react";
import { EditorView } from "@codemirror/view"; import { EditorView } from "@codemirror/view";
import { basicSetup } from "codemirror"; import { basicSetup } from "codemirror";
@@ -10,6 +11,7 @@ export function Editor({
source: string; source: string;
onChange(source: string): void; onChange(source: string): void;
}) { }) {
const editor = useRef<EditorView>();
const root = useRef<HTMLDivElement>(null); const root = useRef<HTMLDivElement>(null);
const change = useRef(onChange); const change = useRef(onChange);
change.current = onChange; change.current = onChange;
@@ -27,9 +29,33 @@ export function Editor({
}), }),
], ],
}); });
return () => view.destroy(); editor.current = view;
return () => {
editor.current = undefined;
view.destroy();
};
// Editor lifetime matches edit mode. Parent remounts after reload. // Editor lifetime matches edit mode. Parent remounts after reload.
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
return <div className="editor" ref={root} />; return (
<>
<AuthoringToolbar
source={source}
insert={(text) => {
const view = editor.current;
if (!view) return;
view.dispatch(view.state.replaceSelection(text));
view.focus();
}}
replace={(text) => {
const view = editor.current;
if (!view) return;
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: text },
});
}}
/>
<div className="editor" ref={root} />
</>
);
} }
+24
View File
@@ -0,0 +1,24 @@
// Feature navigation: add entries here and mount their view in App.
export const navigationItems = ["Notebooks", "Hosts", "Settings"] as const;
export type NavigationPage = (typeof navigationItems)[number];
export function HeaderNavigation({
page,
onChange,
}: {
page: NavigationPage;
onChange: (page: NavigationPage) => void;
}) {
return (
<nav aria-label="Main navigation">
{navigationItems.map((item) => (
<button
key={item}
aria-current={page === item ? "page" : undefined}
onClick={() => onChange(item)}
>
{item}
</button>
))}
</nav>
);
}
+44
View File
@@ -0,0 +1,44 @@
export function HostKeyConfirmation({
host,
fingerprint,
changed,
busy = false,
onReject,
onTrust,
}: {
host: string;
fingerprint: string;
changed: boolean;
busy?: boolean;
onReject: () => void;
onTrust: () => void;
}) {
return (
<div className="modal-backdrop">
<section role="dialog" aria-modal="true" aria-labelledby="hostkey-title">
<h2 id="hostkey-title">
{changed ? "WARNING: HOST KEY CHANGED" : "Unknown SSH host key"}
</h2>
{changed && (
<p className="error">
STOP: a different key is already trusted. This may indicate a
man-in-the-middle attack. Verify the fingerprint independently
before accepting.
</p>
)}
<p>
Verify the key for <strong>{host}</strong> through a trusted channel.
</p>
<code>{fingerprint}</code>
<div className="actions">
<button disabled={busy} onClick={onReject}>
Reject
</button>
<button disabled={busy} onClick={onTrust}>
Trust this fingerprint and retry
</button>
</div>
</section>
</div>
);
}
+469
View File
@@ -0,0 +1,469 @@
import { useCallback, useEffect, useState } from "react";
import type {
HostInfo,
HostInventoryResponse,
HostActionRequest,
HostActionResponse,
HostCredentialInput,
} from "@shellbook/core";
import { json } from "./api";
import "./hosts.css";
import { HostKeyConfirmation } from "./HostKeyConfirmation";
const base = "/host-management";
const url = (name: string) => `${base}/${encodeURIComponent(name)}`;
const empty: HostInfo = {
name: "",
address: "",
user: "root",
port: 22,
tags: [],
};
export function HostsPage({ onChange }: { onChange?: () => void }) {
const [inventory, setInventory] = useState<HostInventoryResponse>();
const [draft, setDraft] = useState<HostInfo>({ ...empty });
const [editVersion, setEditVersion] = useState("");
const [editing, setEditing] = useState<string>();
const [credentialHost, setCredentialHost] = useState<string>();
const [type, setType] = useState<HostCredentialInput["type"]>("shellbook");
const [password, setPassword] = useState("");
const [privateKey, setPrivateKey] = useState("");
const [passphrase, setPassphrase] = useState("");
const [error, setError] = useState("");
const [status, setStatus] = useState("");
const [busy, setBusy] = useState(false);
const [install, setInstall] = useState<{ host: string; script: string }>();
const [trust, setTrust] = useState<{
host: string;
request: HostActionRequest;
key: { fingerprint: string; changed: boolean };
}>();
const load = useCallback(
async () => setInventory(await json<HostInventoryResponse>(base)),
[],
);
useEffect(() => {
void load().catch(() =>
setError("Cannot load hosts or ShellBook public key."),
);
const changed = () => {
void load().catch(() => setError("Cannot reload hosts."));
};
window.addEventListener("shellbook:hosts-changed", changed);
return () => window.removeEventListener("shellbook:hosts-changed", changed);
}, [load]);
async function perform(work: () => Promise<void>) {
setBusy(true);
setError("");
setStatus("");
try {
await work();
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
setError(
(e as { status?: number }).status === 409
? `${message}. Reload hosts before retrying.`
: message,
);
} finally {
setBusy(false);
}
}
async function action(host: string, request: HostActionRequest) {
const response = await json<HostActionResponse>(
`${url(host)}/action`,
"POST",
request,
);
if ("hostKey" in response)
setTrust({ host, request, key: response.hostKey });
else {
setTrust(undefined);
setInstall(undefined);
setStatus(
`${host}: ${response.exitCode === 0 ? "success" : `failed (exit ${response.exitCode})`}`,
);
}
}
return (
<section className="hosts-page" aria-label="Server management">
<h1>Servers and SSH credentials</h1>
{error && <p role="alert">{error}</p>}
{status && <p role="status">{status}</p>}
<button
disabled={busy}
onClick={() =>
void perform(async () => {
await load();
setEditing(undefined);
setDraft({ ...empty });
})
}
>
Reload hosts
</button>
{inventory && (
<>
<h2>ShellBook public key</h2>
<pre>{inventory.publicKey}</pre>
<button
onClick={() =>
void perform(async () => {
await navigator.clipboard.writeText(inventory.publicKey);
setStatus("Public key copied");
})
}
>
Copy public key
</button>
<p>{inventory.certificateSupport.reason}</p>
<div className="host-list">
{inventory.hosts.map((host) => (
<article key={host.name}>
<h2>{host.name}</h2>
<p>
{host.user}@{host.address}:{host.port}
</p>
<p>{host.tags.join(", ")}</p>
<p>
Authentication: {host.credential.type}{" "}
{host.credential.fingerprint}{" "}
{host.credential.setAt && `set ${host.credential.setAt}`}
</p>
<div className="actions">
<button
disabled={busy}
onClick={() => {
setEditing(host.name);
setEditVersion(inventory.version);
setDraft({
name: host.name,
address: host.address,
user: host.user,
port: host.port,
tags: host.tags,
});
}}
>
Edit {host.name}
</button>
<button
disabled={busy}
onClick={() => {
setCredentialHost(host.name);
setType("shellbook");
setPassword("");
setPrivateKey("");
setPassphrase("");
}}
>
SSH credentials for {host.name}
</button>
<button
disabled={busy}
onClick={() =>
void perform(() => action(host.name, { action: "test" }))
}
>
Test connection to {host.name}
</button>
<button
disabled={busy || host.credential.type !== "password"}
onClick={() =>
void perform(async () => {
const { script } = await json<{ script: string }>(
`${url(host.name)}/install-key`,
);
setInstall({ host: host.name, script });
})
}
>
Install ShellBook key on {host.name}
</button>
<button
disabled={busy}
onClick={() => {
if (
window.confirm(
`Forget trusted SSH host key for ${host.name}? The next connection requires verification.`,
)
)
void perform(async () => {
await json(`${url(host.name)}/known-key`, "DELETE");
setStatus("Host key forgotten");
});
}}
>
Forget host key for {host.name}
</button>
<button
disabled={busy}
onClick={() => {
if (
window.confirm(
`Delete ${host.name} and its stored credential?`,
)
)
void perform(async () => {
await json(url(host.name), "DELETE", {
baseVersion: inventory.version,
});
await load();
onChange?.();
});
}}
>
Delete {host.name}
</button>
</div>
</article>
))}
</div>
<h2>{editing ? `Edit ${editing}` : "Add server"}</h2>
<form
onSubmit={(e) => {
e.preventDefault();
void perform(async () => {
await json(
editing ? url(editing) : base,
editing ? "PUT" : "POST",
{
host: draft,
baseVersion: editing ? editVersion : inventory.version,
},
);
setEditing(undefined);
setDraft({ ...empty });
await load();
onChange?.();
});
}}
>
<label>
Name
<input
required
pattern="[A-Za-z0-9._-]+"
value={draft.name}
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
/>
</label>
<label>
Address
<input
required
value={draft.address}
onChange={(e) =>
setDraft({ ...draft, address: e.target.value })
}
/>
</label>
<label>
SSH user
<input
required
value={draft.user}
onChange={(e) => setDraft({ ...draft, user: e.target.value })}
/>
</label>
<label>
Port
<input
required
type="number"
min="1"
max="65535"
value={draft.port}
onChange={(e) =>
setDraft({ ...draft, port: Number(e.target.value) })
}
/>
</label>
<label>
Tags (comma separated)
<input
value={draft.tags.join(",")}
onChange={(e) =>
setDraft({
...draft,
tags: e.target.value
.split(",")
.map((t) => t.trim())
.filter(Boolean),
})
}
/>
</label>
<button disabled={busy}>Save server</button>
<button
type="button"
onClick={() => {
setEditing(undefined);
setDraft({ ...empty });
}}
>
New server
</button>
</form>
</>
)}
{credentialHost && (
<section
role="dialog"
aria-modal="true"
aria-label={`SSH credentials for ${credentialHost}`}
>
<h2>SSH credentials for {credentialHost}</h2>
<p>
Saved secrets cannot be read back. Blank fields do not represent the
existing credential.
</p>
<form
onSubmit={(e) => {
e.preventDefault();
const credential: HostCredentialInput =
type === "password"
? { type, password }
: type === "privateKey"
? { type, privateKey, passphrase }
: { type };
setPassword("");
setPrivateKey("");
setPassphrase("");
void perform(async () => {
await json(
`${url(credentialHost)}/credential`,
"PUT",
credential,
);
setCredentialHost(undefined);
await load();
});
}}
>
<label>
Authentication
<select
value={type}
onChange={(e) => setType(e.target.value as typeof type)}
>
<option value="shellbook">
ShellBook key (remove stored credential)
</option>
<option value="password">Password</option>
<option value="privateKey">Private key</option>
<option disabled>OpenSSH certificate (unavailable)</option>
</select>
</label>
{type === "password" && (
<label>
SSH password
<input
required
type="password"
autoComplete="new-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
)}
{type === "privateKey" && (
<>
<label>
Private key
<textarea
required
value={privateKey}
onChange={(e) => setPrivateKey(e.target.value)}
/>
</label>
<label>
Upload private key
<input
type="file"
onChange={(e) => {
const file = e.target.files?.[0];
if (file)
void perform(async () => {
if (file.size > 65536)
throw new Error("Key exceeds 64 KiB");
setPrivateKey(await file.text());
});
}}
/>
</label>
<label>
Key passphrase (optional)
<input
type="password"
autoComplete="new-password"
value={passphrase}
onChange={(e) => setPassphrase(e.target.value)}
/>
</label>
</>
)}
<button disabled={busy}>Save authentication</button>
<button
type="button"
onClick={() => {
setCredentialHost(undefined);
setPassword("");
setPrivateKey("");
setPassphrase("");
}}
>
Cancel
</button>
</form>
</section>
)}
{install && (
<section
role="dialog"
aria-modal="true"
aria-label="Install ShellBook key"
>
<h2>Install ShellBook key on {install.host}</h2>
<p>
This exact script runs using the stored password. After success,
select ShellBook key in SSH credentials to remove the saved
password.
</p>
<pre>{install.script}</pre>
<button
disabled={busy}
onClick={() =>
void perform(() =>
action(install.host, {
action: "install-key",
script: install.script,
}),
)
}
>
Run displayed script
</button>
<button onClick={() => setInstall(undefined)}>
Cancel installation
</button>
</section>
)}
{trust && (
<HostKeyConfirmation
host={trust.host}
{...trust.key}
busy={busy}
onReject={() => setTrust(undefined)}
onTrust={() =>
void perform(() =>
action(trust.host, {
...trust.request,
acceptHostKey: trust.key.fingerprint,
}),
)
}
/>
)}
</section>
);
}
+214
View File
@@ -0,0 +1,214 @@
import "./notebooks.css";
import { useState } from "react";
import type { NotebookSummary } from "@shellbook/core";
import type { Api } from "./api";
import { newNotebook } from "./authoring";
type Node = { folders: Map<string, Node>; files: NotebookSummary[] };
function tree(list: NotebookSummary[]): Node {
const root: Node = { folders: new Map(), files: [] };
for (const file of list) {
let node = root;
for (const part of file.path.split("/").slice(0, -1)) {
if (!node.folders.has(part))
node.folders.set(part, { folders: new Map(), files: [] });
node = node.folders.get(part)!;
}
node.files.push(file);
}
return root;
}
export function NotebookList({
api,
list,
path,
version,
onSelect,
onChanged,
canLeave,
}: {
api: Api;
list: NotebookSummary[];
path: string;
version?: string;
onSelect(path: string): void;
onChanged(path?: string): Promise<void>;
canLeave(): boolean;
}) {
const [search, setSearch] = useState("");
const [action, setAction] = useState<
"new" | "rename" | "duplicate" | "delete"
>();
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const render = (node: Node) => (
<>
{[...node.folders]
.sort(([a], [b]) => a.localeCompare(b))
.map(([name, child]) => (
<details key={name} open>
<summary>{name}</summary>
{render(child)}
</details>
))}
{node.files.map((item) => (
<button
className={item.path === path ? "selected" : ""}
key={item.path}
onClick={() => onSelect(item.path)}
>
{item.title}
<small>{item.path}</small>
</button>
))}
</>
);
return (
<>
<label>
Search notebooks
<input
type="search"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</label>
<button
onClick={() => {
setAction("new");
setError("");
}}
>
New notebook
</button>
<nav aria-label="Notebooks">
{render(
tree(
list.filter((n) =>
`${n.path} ${n.title}`
.toLowerCase()
.includes(search.toLowerCase()),
),
),
)}
</nav>
{path && (
<div className="actions">
{(["rename", "duplicate", "delete"] as const).map((op) => (
<button
key={op}
onClick={() => {
setAction(op);
setError("");
}}
>
{op === "rename"
? "Rename / move"
: op === "duplicate"
? "Duplicate"
: "Delete"}
</button>
))}
</div>
)}
{action && (
<form
key={`${action}:${path}`}
aria-label="Manage notebook"
onSubmit={async (e) => {
e.preventDefault();
if (busy) return;
const data = new FormData(e.currentTarget);
if (!canLeave()) return;
setBusy(true);
setError("");
try {
let next: string | undefined;
if (action === "new") {
const folder = String(data.get("folder")).trim();
let name = String(data.get("name")).trim();
if (!name.endsWith(".md")) name += ".md";
const result = await api.create(
(folder ? folder + "/" : "") + name,
newNotebook(String(data.get("title"))),
);
next = result.path;
} else {
if (!version)
throw new Error("Reload the notebook before changing it");
if (action === "delete")
await api.deleteNotebook(path, version);
else
next = (
await api.move(
path,
String(data.get("path")).trim(),
version,
action === "duplicate",
)
).path;
}
await onChanged(next);
setAction(undefined);
} catch (err) {
setError(
`${String(err)}. Refresh the list and retry if the notebook changed.`,
);
} finally {
setBusy(false);
}
}}
>
<strong>
{action === "delete"
? `Delete ${path}? This cannot be undone.`
: action === "new"
? "New notebook"
: `${action} ${path}`}
</strong>
{action === "new" ? (
<>
<label>
Name
<input name="name" required />
</label>
<label>
Folder (optional)
<input name="folder" placeholder="operations/linux" />
</label>
<label>
Title
<input name="title" required />
</label>
</>
) : (
action !== "delete" && (
<label>
Destination path
<input
name="path"
defaultValue={
action === "duplicate"
? path.replace(/\.md$/, "-copy.md")
: path
}
required
/>
</label>
)
)}
<button disabled={busy}>
{action === "delete" ? "Confirm delete" : "Apply"}
</button>
<button
type="button"
disabled={busy}
onClick={() => setAction(undefined)}
>
Cancel
</button>
{error && <p role="alert">{error}</p>}
</form>
)}
</>
);
}
+98
View File
@@ -0,0 +1,98 @@
import { useState } from "react";
import type { ChangePasswordRequest, SetupRequest } from "@shellbook/core";
export function PasswordForm({
setup = false,
submit,
}: {
setup?: boolean;
submit: (body: ChangePasswordRequest & SetupRequest) => Promise<void>;
}) {
const [token, setToken] = useState("");
const [currentPassword, setCurrent] = useState("");
const [newPassword, setNew] = useState("");
const [confirmPassword, setConfirm] = useState("");
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
return (
<form
onSubmit={async (event) => {
event.preventDefault();
if (newPassword !== confirmPassword) {
setMessage("Passwords do not match");
return;
}
setBusy(true);
setMessage("");
try {
await submit({
token,
currentPassword,
newPassword,
confirmPassword,
});
setToken("");
setCurrent("");
setNew("");
setConfirm("");
setMessage("Password saved. Other sessions have been signed out.");
} catch {
setMessage(
"Unable to save. Check your credentials and try again; too many attempts require waiting a minute.",
);
} finally {
setBusy(false);
}
}}
>
{setup ? (
<label>
Setup token
<input
required
autoComplete="off"
value={token}
onChange={(e) => setToken(e.target.value)}
/>
</label>
) : (
<label>
Current password
<input
required
type="password"
autoComplete="current-password"
value={currentPassword}
onChange={(e) => setCurrent(e.target.value)}
/>
</label>
)}
<label>
New password
<input
required
type="password"
minLength={12}
autoComplete="new-password"
value={newPassword}
onChange={(e) => setNew(e.target.value)}
/>
</label>
<label>
Confirm password
<input
required
type="password"
minLength={12}
autoComplete="new-password"
value={confirmPassword}
onChange={(e) => setConfirm(e.target.value)}
/>
</label>
<p>Use at least 12 characters (maximum 4096 bytes).</p>
<button disabled={busy}>
{setup ? "Set up ShellBook" : "Change password"}
</button>
{message && <p role="status">{message}</p>}
</form>
);
}
+110
View File
@@ -0,0 +1,110 @@
import { useEffect, useState } from "react";
import type {
ClaudeStatusResponse,
SystemInfoResponse,
SessionSettingsResponse,
} from "@shellbook/core";
import { settingsApi } from "./settingsApi";
import { PasswordForm } from "./PasswordForm";
export function SettingsPage({ openTerminal }: { openTerminal: () => void }) {
const [info, setInfo] = useState<SystemInfoResponse>();
const [claude, setClaude] = useState<ClaudeStatusResponse>();
const [session, setSession] = useState<SessionSettingsResponse>();
const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false);
useEffect(() => {
let active = true;
Promise.all([
settingsApi.system(),
settingsApi.claude(),
settingsApi.session(),
])
.then(([i, c, s]) => {
if (active) {
setInfo(i);
setClaude(c);
setSession(s);
}
})
.catch(() => {
if (active)
setMessage("Unable to load settings. Sign in again or retry.");
});
return () => {
active = false;
};
}, []);
return (
<div className="notebook">
<h1>Settings</h1>
<section>
<h2>Password and sessions</h2>
<PasswordForm submit={settingsApi.password} />
{session && (
<p>
Session lifetime: {session.lifetimeSeconds} seconds (
{session.lifetimeSeconds / 86400} days).
</p>
)}
<button
disabled={busy}
onClick={async () => {
setBusy(true);
try {
await settingsApi.revoke();
setMessage(
"Other sessions signed out. This browser remains signed in.",
);
} catch {
setMessage("Unable to sign out sessions. Try again.");
} finally {
setBusy(false);
}
}}
>
Sign out all sessions
</button>
</section>
<section>
<h2>Claude CLI</h2>
{claude ? (
<>
<p>
{claude.available
? `Available: ${claude.version}`
: "Claude is unavailable on PATH or did not respond."}
</p>
<p>
{claude.loginAppearsPresent
? "Credentials file exists; login may be available."
: "No credentials file found."}
</p>
</>
) : (
<p>Checking CLI...</p>
)}
<button onClick={openTerminal}>Open terminal to log in</button>
<p>
Run <code>claude</code>, then <code>/login</code>. Credentials are
checked for existence only.
</p>
</section>
<section>
<h2>About/System</h2>
{info && (
<dl>
<dt>ShellBook version</dt>
<dd>{info.version}</dd>
<dt>Workspace</dt>
<dd>{info.workspacePath}</dd>
<dt>Data directory</dt>
<dd>{info.dataDirPath}</dd>
<dt>Node version</dt>
<dd>{info.nodeVersion}</dd>
</dl>
)}
</section>
{message && <p role="status">{message}</p>}
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
import { PasswordForm } from "./PasswordForm";
import { settingsApi } from "./settingsApi";
export function SetupScreen({ onComplete }: { onComplete: () => void }) {
return (
<main className="login">
<h1>Set up ShellBook</h1>
<p>
Enter the one-time token from the setup-token file in the server data
directory.
</p>
<PasswordForm
setup
submit={async (body) => {
await settingsApi.setup(body);
onComplete();
}}
/>
</main>
);
}
+38 -4
View File
@@ -9,11 +9,24 @@ import type {
} from "@shellbook/core"; } from "@shellbook/core";
export class HttpError extends Error { export class HttpError extends Error {
constructor(public status: number) { constructor(
super(`Request failed (${status})`); public status: number,
serverMessage?: string,
) {
super(serverMessage || `Request failed (${status})`);
} }
} }
async function json<T>( /** Deliberate errors (4xx, 502, 503) carry a user-facing `message`; unexpected 500s may expose internals. */
async function serverMessage(response: Response): Promise<string | undefined> {
if (response.status === 500) return undefined;
try {
const body = (await response.json()) as { message?: unknown };
return typeof body.message === "string" ? body.message.slice(0, 500) : undefined;
} catch {
return undefined;
}
}
export async function json<T>(
path: string, path: string,
method = "GET", method = "GET",
body?: unknown, body?: unknown,
@@ -24,12 +37,24 @@ async function json<T>(
headers: body === undefined ? {} : { "Content-Type": "application/json" }, headers: body === undefined ? {} : { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body), body: body === undefined ? undefined : JSON.stringify(body),
}); });
if (!response.ok) throw new HttpError(response.status); if (!response.ok)
throw new HttpError(response.status, await serverMessage(response));
return response.status === 204 return response.status === 204
? (undefined as T) ? (undefined as T)
: (response.json() as Promise<T>); : (response.json() as Promise<T>);
} }
export interface Api { export interface Api {
create(
path: string,
source: string,
): Promise<{ path: string; version: string }>;
move(
path: string,
target: string,
baseVersion: string,
duplicate?: boolean,
): Promise<{ path: string; version: string }>;
deleteNotebook(path: string, baseVersion: string): Promise<unknown>;
me(): Promise<unknown>; me(): Promise<unknown>;
login(password: string): Promise<unknown>; login(password: string): Promise<unknown>;
list(): Promise<NotebookListResponse>; list(): Promise<NotebookListResponse>;
@@ -48,6 +73,15 @@ export interface Api {
artifact(runId: string, name: string): string; artifact(runId: string, name: string): string;
} }
export const liveApi: Api = { export const liveApi: Api = {
create: (path, source) => json("/notebooks", "POST", { path, source }),
move: (path, target, baseVersion, duplicate = false) =>
json(
`/notebooks/${encodeURIComponent(path)}/${duplicate ? "duplicate" : "rename"}`,
"POST",
{ path: target, baseVersion },
),
deleteNotebook: (path, baseVersion) =>
json(`/notebooks/${encodeURIComponent(path)}`, "DELETE", { baseVersion }),
me: () => json("/auth/me"), me: () => json("/auth/me"),
login: (password) => json("/auth/login", "POST", { password }), login: (password) => json("/auth/login", "POST", { password }),
list: () => json("/notebooks"), list: () => json("/notebooks"),
+99
View File
@@ -0,0 +1,99 @@
import { isMap, parseDocument } from "yaml";
import {
parseNotebook,
type Block,
type ParamDef,
type Step,
} from "@shellbook/core";
export function notebookSteps(blocks: Block[]): Step[] {
return blocks.flatMap((b) =>
b.type === "step"
? [b.step]
: b.type === "after"
? notebookSteps(b.blocks)
: [],
);
}
const attr = (value: string) =>
'"' +
value
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"')
.replace(/[\r\n]/g, " ") +
'"';
export type InsertKind =
| "Check step"
| "Run step"
| "Artifacts"
| "Upload"
| "Capture";
export function stepSnippet(
source: string,
kind: InsertKind,
local: boolean,
host = "host",
): string {
const ids = new Set(
notebookSteps(parseNotebook(source).blocks).map((s) => s.attrs.id),
);
let n = 1;
while (ids.has(`step-${n}`)) n++;
const check = kind === "Check step" || kind === "Capture";
const extra =
kind === "Artifacts"
? ' artifacts="result.txt"'
: kind === "Upload"
? ' upload="result.txt:/tmp/result.txt"'
: kind === "Capture"
? " capture=result"
: "";
const script =
kind === "Artifacts"
? "printf '%s\\n' 'Example result' > result.txt"
: kind === "Upload"
? "# Use the uploaded /tmp/result.txt here\n:"
: check
? "uname -s"
: "# Replace with your command\n:";
return `\n\n\`\`\`sh {${check ? "check" : "run"} ${local ? "on=local" : `host=${attr(`{{${host}}}`)}`} id=step-${n} title=${attr(kind)}${check ? "" : " confirm"}${extra}}\n${script}\n\`\`\`\n`;
}
export function afterSnippet(id: string): string {
return `\n\n:::after{step=${attr(id)}}\nAdd follow-up instructions here.\n:::\n`;
}
export function addParameter(source: string, def: ParamDef): string {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(def.name))
throw new Error("Invalid parameter name");
const match =
/^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[^\S\r\n]*(?:\r?\n|$)/.exec(
source,
);
const doc = parseDocument(match?.[1] ?? "{}");
if (doc.errors.length || !isMap(doc.contents))
throw new Error("Fix frontmatter YAML first");
if (doc.hasIn(["params", def.name]))
throw new Error("Parameter already exists");
if (doc.has("params") && !isMap(doc.get("params", true)))
throw new Error("params must be a mapping");
if (!doc.has("params")) doc.set("params", doc.createNode({}));
const { name, ...fields } = def;
if (def.type === "secret" && def.default !== undefined)
throw new Error("Secrets cannot have defaults");
doc.setIn(["params", name], doc.createNode(fields));
const next = `---\n${doc.toString()}---\n${match ? source.slice(match[0].length) : source}`;
const errors = parseNotebook(next).diagnostics;
if (errors.length) throw new Error(errors.map((d) => d.message).join("; "));
return next;
}
export function newNotebook(title: string): string {
const doc = parseDocument("{}");
doc.set("title", title.trim() || "New notebook");
doc.set(
"params",
doc.createNode({
host: { type: "host", required: true, label: "Target server" },
}),
);
let source = `---\n${doc.toString()}---\n\n# ${title.replace(/[\r\n]/g, " ").trim() || "New notebook"}\n`;
source += stepSnippet(source, "Check step", false);
return source + stepSnippet(source, "Run step", false);
}
+12
View File
@@ -0,0 +1,12 @@
.chat-panel { position: sticky; top: 0; height: 100vh; min-width: 0; display: flex; flex-direction: column; gap: .6rem; padding: 1rem; border-left: 1px solid #64748b; box-sizing: border-box; }
.chat-panel h2, .chat-panel p { margin: .25rem 0; }
.chat-panel select, .chat-panel textarea { width: 100%; box-sizing: border-box; }
.chat-panel label { display: block; }
.chat-messages { flex: 1; min-height: 120px; overflow-y: auto; overflow-wrap: anywhere; }
.chat-messages pre { overflow-x: auto; }
.chat-message { padding: .6rem 0; border-bottom: 1px solid #64748b55; }
.chat-message.user { opacity: .85; }
.chat-shell { margin-top: .5rem; }
.chat-panel form { flex-shrink: 0; }
@media (max-width: 900px) { .chat-panel { position: static; grid-column: 1 / -1; height: min(800px, 100dvh); } }
@media (max-width: 580px) { .with-terminal { display: block; } .chat-panel { padding: .7rem; } }
+49
View File
@@ -0,0 +1,49 @@
.hosts-page {
padding: 1rem;
max-width: 70rem;
min-width: 0;
}
.hosts-page pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.hosts-page form {
display: flex;
flex-wrap: wrap;
gap: 0.8rem;
align-items: end;
}
.hosts-page label {
display: flex;
flex-direction: column;
gap: 0.3rem;
flex: 1 1 12rem;
min-width: 0;
}
.hosts-page input,
.hosts-page textarea,
.hosts-page select {
width: 100%;
box-sizing: border-box;
}
.hosts-page article,
.hosts-page [role="dialog"] {
border: 1px solid #777;
padding: 1rem;
margin-block: 1rem;
overflow-wrap: anywhere;
}
.hosts-page .actions {
flex-wrap: wrap;
}
.hosts-page button {
white-space: normal;
}
@media (max-width: 600px) {
.app:has(.hosts-page) {
display: block;
}
.app:has(.hosts-page) .sidebar {
width: auto;
}
}
+9
View File
@@ -31,6 +31,15 @@ const artifactUrl = URL.createObjectURL(
}), }),
); );
export const mockApi: Api = { export const mockApi: Api = {
create: async () => {
throw new Error("Notebook management requires a live workspace");
},
move: async () => {
throw new Error("Notebook management requires a live workspace");
},
deleteNotebook: async () => {
throw new Error("Notebook management requires a live workspace");
},
me: async () => ({ authenticated: true }), me: async () => ({ authenticated: true }),
login: async () => undefined, login: async () => undefined,
list: async () => ({ list: async () => ({
+34
View File
@@ -0,0 +1,34 @@
.authoring {
display: flex;
align-items: end;
flex-wrap: wrap;
gap: 0.5rem;
margin: 0.75rem 0;
}
.authoring label,
.sidebar form label {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.authoring form,
.authoring details {
flex-basis: 100%;
}
.sidebar form {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-top: 1rem;
}
.sidebar input {
min-width: 0;
max-width: 100%;
}
.sidebar nav details {
margin-left: 0.5rem;
}
.sidebar nav summary {
cursor: pointer;
padding: 0.5rem 0;
}
+31
View File
@@ -0,0 +1,31 @@
import type {
SetupStatusResponse,
SetupRequest,
ChangePasswordRequest,
SessionSettingsResponse,
ClaudeStatusResponse,
SystemInfoResponse,
} from "@shellbook/core";
import { HttpError } from "./api";
async function request<T>(path: string, body?: unknown): Promise<T> {
const response = await fetch(`/api${path}`, {
method: body === undefined ? "GET" : "POST",
credentials: "same-origin",
headers: body === undefined ? {} : { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!response.ok) throw new HttpError(response.status);
return response.status === 204
? (undefined as T)
: (response.json() as Promise<T>);
}
export const settingsApi = {
setupStatus: () => request<SetupStatusResponse>("/auth/setup"),
setup: (body: SetupRequest) => request<void>("/auth/setup", body),
password: (body: ChangePasswordRequest) =>
request<void>("/settings/password", body),
revoke: () => request<void>("/settings/sessions/revoke", {}),
session: () => request<SessionSettingsResponse>("/settings/session"),
claude: () => request<ClaudeStatusResponse>("/settings/claude"),
system: () => request<SystemInfoResponse>("/settings/system"),
};
+18
View File
@@ -0,0 +1,18 @@
import { afterEach, expect, it, vi } from "vitest";
import { HttpError, json } from "../api";
afterEach(() => vi.unstubAllGlobals());
it("keeps the server's error message and status", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ statusCode: 502, error: "Bad Gateway", message: "SSH authentication failed: check the user and the saved password or key" }), { status: 502, headers: { "Content-Type": "application/json" } })));
const error = (await json("/x").catch((e: HttpError) => e)) as HttpError;
expect(error).toBeInstanceOf(HttpError);
expect(error.status).toBe(502);
expect(error.message).toBe("SSH authentication failed: check the user and the saved password or key");
});
it("falls back to the status when the body is not JSON", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response("<html>", { status: 500 })));
expect(((await json("/x").catch((e: HttpError) => e)) as HttpError).message).toBe("Request failed (500)");
});
it("does not surface messages of unexpected server errors", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ statusCode: 500, message: "EACCES: permission denied, open '/var/lib/shellbook/x'" }), { status: 500 })));
expect(((await json("/x").catch((e: HttpError) => e)) as HttpError).message).toBe("Request failed (500)");
});
+9
View File
@@ -33,6 +33,15 @@ function harness() {
let receive: (event: ServerEvent) => void = () => {}; let receive: (event: ServerEvent) => void = () => {};
let id = 0; let id = 0;
const api: Api = { const api: Api = {
create: async () => {
throw new Error("Notebook management requires a live workspace");
},
move: async () => {
throw new Error("Notebook management requires a live workspace");
},
deleteNotebook: async () => {
throw new Error("Notebook management requires a live workspace");
},
me: vi.fn().mockResolvedValue({}), me: vi.fn().mockResolvedValue({}),
login: vi.fn().mockResolvedValue(undefined), login: vi.fn().mockResolvedValue(undefined),
list: vi.fn().mockResolvedValue({ list: vi.fn().mockResolvedValue({
+80
View File
@@ -0,0 +1,80 @@
import { expect, it } from "vitest";
import { parseNotebook } from "@shellbook/core";
import { parse } from "yaml";
import {
addParameter,
afterSnippet,
newNotebook,
notebookSteps,
stepSnippet,
type InsertKind,
} from "../authoring";
it.each([
"Check step",
"Run step",
"Artifacts",
"Upload",
"Capture",
] as InsertKind[])(
"generates valid %s fences for both targets and unique ids",
(kind) => {
for (const local of [true, false]) {
let source = newNotebook('Title: "quoted"');
source += stepSnippet(source, kind, local);
source += stepSnippet(source, kind, local);
source += afterSnippet(
notebookSteps(parseNotebook(source).blocks)[0]!.attrs.id,
);
expect(parseNotebook(source).diagnostics).toEqual([]);
expect(notebookSteps(parseNotebook(source).blocks)).toHaveLength(4);
}
},
);
it("preserves other YAML, comments, body and existing params", () => {
const source =
"---\n# keep comment\ntitle: Original\ncustom: {nested: [one, two]}\nparams:\n host: {type: host}\n---\n\n# Body\n";
const next = addParameter(source, {
name: "mode",
type: "choice",
required: true,
options: ["a", "b"],
default: "a",
label: "Mode",
});
expect(parseNotebook(next).diagnostics).toEqual([]);
expect(next).toContain("# keep comment");
expect(next).toContain("\n\n# Body\n");
const yaml = parse(next.split("---")[1]!);
expect(yaml.custom).toEqual({ nested: ["one", "two"] });
expect(yaml.params.host).toEqual({ type: "host" });
expect(yaml.params.mode.options).toEqual(["a", "b"]);
expect(() =>
addParameter(next, { name: "host", type: "host", required: true }),
).toThrow("already exists");
});
it("adds frontmatter when absent and rejects invalid YAML or secret defaults", () => {
expect(
parseNotebook(
addParameter("# Title\n", {
name: "token",
type: "secret",
required: true,
}),
).diagnostics,
).toEqual([]);
expect(() =>
addParameter("---\nx: [\n---\n", {
name: "a",
type: "string",
required: false,
}),
).toThrow();
expect(() =>
addParameter("# Title", {
name: "token",
type: "secret",
required: true,
default: "bad",
}),
).toThrow();
});
+49
View File
@@ -0,0 +1,49 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import { ChatPanel, type ChatSocket } from "../ChatPanel";
import type { ChatEvent } from "@shellbook/core";
function setup() {
const socket: ChatSocket = { onopen: null, onclose: null, onerror: null, onmessage: null, send: vi.fn(), close: vi.fn() };
const openNotebook = vi.fn(), openTerminal = vi.fn();
const view = render(<ChatPanel notebookPath="setup/current.md" connect={() => socket} openNotebook={openNotebook} openTerminal={openTerminal} />);
act(() => socket.onopen?.(new Event("open")));
const emit = (event: ChatEvent) => act(() => socket.onmessage?.({ data: JSON.stringify(event) } as MessageEvent));
return { socket, emit, openNotebook, openTerminal, ...view };
}
it("sends notebook context, defaults shell off, streams Markdown, opens edited notebooks and stops", () => {
const { socket, emit, openNotebook } = setup();
fireEvent.change(screen.getByLabelText("Message"), { target: { value: "Create nginx" } });
fireEvent.click(screen.getByRole("button", { name: "Send" }));
expect(socket.send).toHaveBeenCalledWith(JSON.stringify({ type: "send", message: "Create nginx", notebookPath: "notebooks/setup/current.md", allowShell: false }));
emit({ type: "delta", text: "Hello **" }); emit({ type: "delta", text: "world**" });
expect(screen.getByText("world").tagName).toBe("STRONG");
emit({ type: "tool", name: "Edit", path: "notebooks/nginx.md" });
fireEvent.click(screen.getByText("Open notebook")); expect(openNotebook).toHaveBeenCalledWith("nginx.md");
fireEvent.click(screen.getByText("Stop")); expect(socket.send).toHaveBeenLastCalledWith('{"type":"cancel"}');
emit({ type: "finished", durationMs: 1000, costUsd: .01 }); expect(screen.getByRole("status")).toHaveTextContent("Finished in 1.0s");
});
it("offers terminal login recovery and closes the socket on unmount", () => {
const { emit, openTerminal, unmount, socket } = setup();
emit({ type: "error", code: "login", message: "Please log in" });
fireEvent.click(screen.getByRole("button", { name: /Open Terminal/ })); expect(openTerminal).toHaveBeenCalledOnce();
expect(screen.getByRole("alert")).toHaveTextContent("Please log in");
unmount(); expect(socket.close).toHaveBeenCalledOnce();
});
it("resumes history, enables shell explicitly and resets it for new conversations", () => {
const { emit, socket } = setup();
emit({ type: "history", conversations: [{ id: "saved", title: "Earlier notebook", createdAt: "now", updatedAt: "now" }] });
fireEvent.change(screen.getByLabelText("Conversation history"), { target: { value: "saved" } });
fireEvent.click(screen.getByLabelText(/Allow Claude/));
fireEvent.click(screen.getByText("Add a check that…"));
fireEvent.click(screen.getByRole("button", { name: "Send" }));
expect(JSON.parse((socket.send as ReturnType<typeof vi.fn>).mock.calls[0]![0])).toMatchObject({ conversationId: "saved", allowShell: true });
expect(screen.getByText("New conversation", { selector: "button" })).toBeDisabled();
emit({ type: "finished" }); fireEvent.click(screen.getByText("New conversation", { selector: "button" }));
expect(screen.getByLabelText(/Allow Claude/)).not.toBeChecked();
});
it("handles a disconnect and disables sending", () => {
const { socket } = setup(); act(() => socket.onclose?.(new CloseEvent("close")));
expect(screen.getByRole("alert")).toHaveTextContent("disconnected");
expect(screen.getByRole("button", { name: "Reconnect chat" })).toBeInTheDocument();
});
+130
View File
@@ -0,0 +1,130 @@
import { afterEach, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { HostsPage } from "../HostsPage";
import { json } from "../api";
vi.mock("../api", () => ({ json: vi.fn() }));
const inventory = {
hosts: [
{
name: "demo",
address: "example.org",
user: "ops",
port: 22,
tags: [],
credential: { type: "password" },
},
],
version: "v1",
publicKey: "ssh-ed25519 AAA",
certificateSupport: {
available: false,
reason: "Certificates unavailable in ssh2",
},
};
afterEach(() => vi.resetAllMocks());
it("adds hosts with accessible fields and optimistic version", async () => {
vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />);
await screen.findByText("demo");
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "new" } });
fireEvent.change(screen.getByLabelText("Address"), {
target: { value: "::1" },
});
fireEvent.click(screen.getByText("Save server"));
await waitFor(() =>
expect(json).toHaveBeenCalledWith("/host-management", "POST", {
baseVersion: "v1",
host: { name: "new", address: "::1", user: "root", port: 22, tags: [] },
}),
);
});
it("sends credentials once and clears password fields", async () => {
vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />);
await screen.findByText("demo");
fireEvent.click(screen.getByText("SSH credentials for demo"));
fireEvent.change(screen.getByLabelText("Authentication"), {
target: { value: "password" },
});
fireEvent.change(screen.getByLabelText("SSH password"), {
target: { value: "never-read-back" },
});
fireEvent.click(screen.getByText("Save authentication"));
await waitFor(() =>
expect(json).toHaveBeenCalledWith(
"/host-management/demo/credential",
"PUT",
{ type: "password", password: "never-read-back" },
),
);
await waitFor(() =>
expect(screen.queryByLabelText("SSH password")).not.toBeInTheDocument(),
);
expect(document.body.textContent).not.toContain("never-read-back");
});
it("requires fingerprint confirmation and resends the displayed installation script", async () => {
vi.mocked(json).mockImplementation(async (url, method, body) => {
if (url.endsWith("/install-key")) return { script: "literal script" };
if (url.endsWith("/action"))
return (body as { acceptHostKey?: string }).acceptHostKey
? { exitCode: 0 }
: {
hostKey: {
fingerprint: "SHA256:test",
changed: true,
host: "demo",
},
};
return inventory;
});
render(<HostsPage />);
await screen.findByText("demo");
fireEvent.click(screen.getByText("Install ShellBook key on demo"));
await screen.findByText("literal script");
expect(json).not.toHaveBeenCalledWith(
"/host-management/demo/action",
expect.anything(),
expect.anything(),
);
fireEvent.click(screen.getByText("Run displayed script"));
await screen.findByText("WARNING: HOST KEY CHANGED");
fireEvent.click(screen.getByText("Trust this fingerprint and retry"));
await screen.findByText("demo: success");
expect(json).toHaveBeenLastCalledWith(
"/host-management/demo/action",
"POST",
{
action: "install-key",
script: "literal script",
acceptHostKey: "SHA256:test",
},
);
});
it("loads external changes without silently changing the version of an open edit", async () => {
vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />);
await screen.findByText("demo");
fireEvent.click(screen.getByText("Edit demo"));
vi.mocked(json).mockResolvedValue({ ...inventory, version: "v2" });
window.dispatchEvent(new Event("shellbook:hosts-changed"));
await waitFor(() => expect(json).toHaveBeenCalledTimes(2));
fireEvent.click(screen.getByText("Save server"));
await waitFor(() =>
expect(json).toHaveBeenCalledWith(
"/host-management/demo",
"PUT",
expect.objectContaining({ baseVersion: "v1" }),
),
);
});
it("shows the server's reason for a failed connection test without a conflict hint", async () => {
vi.mocked(json).mockImplementation(async (url) => {
if (url.endsWith("/action")) throw Object.assign(new Error("SSH authentication failed: check the user and the saved password or key"), { status: 502 });
return inventory;
});
render(<HostsPage />);
await screen.findByText("demo");
fireEvent.click(screen.getByText("Test connection to demo"));
const alert = await screen.findByText(/SSH authentication failed/);
expect(alert.textContent).toBe("SSH authentication failed: check the user and the saved password or key");
});
@@ -0,0 +1,90 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import { parseNotebook } from "@shellbook/core";
import { AuthoringToolbar } from "../AuthoringToolbar";
import { NotebookList } from "../NotebookList";
import { newNotebook } from "../authoring";
import type { Api } from "../api";
it("inserts snippets and adds parameters through forms", () => {
const insert = vi.fn(),
replace = vi.fn();
render(
<AuthoringToolbar
source={newNotebook("Example")}
insert={insert}
replace={replace}
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Run step" }));
expect(insert.mock.calls[0]![0]).toContain("on=local");
fireEvent.click(screen.getByRole("button", { name: "Parameter" }));
fireEvent.change(screen.getByLabelText("Parameter name"), {
target: { value: "package" },
});
fireEvent.click(screen.getByRole("button", { name: "Add parameter" }));
expect(
parseNotebook(replace.mock.calls[0]![0]).params.some(
(p) => p.name === "package",
),
).toBe(true);
});
it("shows a folder tree, filters, creates and navigates", async () => {
const create = vi
.fn()
.mockResolvedValue({ path: "ops/new.md", version: "1" });
const changed = vi.fn().mockResolvedValue(undefined);
render(
<NotebookList
api={{ create } as unknown as Api}
list={[
{ path: "ops/a.md", title: "Alpha" },
{ path: "b.md", title: "Beta" },
]}
path=""
onSelect={vi.fn()}
onChanged={changed}
canLeave={() => true}
/>,
);
expect(screen.getByText("ops")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Search notebooks"), {
target: { value: "Alpha" },
});
expect(screen.queryByText("Beta")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "New notebook" }));
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "new" } });
fireEvent.change(screen.getByLabelText("Folder (optional)"), {
target: { value: "ops" },
});
fireEvent.change(screen.getByLabelText("Title"), {
target: { value: "New" },
});
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
await waitFor(() => expect(changed).toHaveBeenCalledWith("ops/new.md"));
expect(create.mock.calls[0]![0]).toBe("ops/new.md");
expect(parseNotebook(create.mock.calls[0]![1]).diagnostics).toEqual([]);
});
it("requires explicit delete confirmation and uses the displayed version", async () => {
const remove = vi.fn().mockResolvedValue({ deleted: true });
const changed = vi.fn().mockResolvedValue(undefined);
render(
<NotebookList
api={
{
notebook: async () => ({ version: "latest" }),
deleteNotebook: remove,
} as unknown as Api
}
list={[]}
path="a.md"
version="latest"
onSelect={vi.fn()}
onChanged={changed}
canLeave={() => true}
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
expect(remove).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Confirm delete" }));
await waitFor(() => expect(remove).toHaveBeenCalledWith("a.md", "latest"));
});
+91
View File
@@ -0,0 +1,91 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { PasswordForm } from "../PasswordForm";
import { SetupScreen } from "../SetupScreen";
import { SettingsPage } from "../SettingsPage";
import { HeaderNavigation } from "../HeaderNavigation";
import { settingsApi } from "../settingsApi";
afterEach(() => vi.restoreAllMocks());
function fill(label: string, value: string) {
fireEvent.change(screen.getByLabelText(label), { target: { value } });
}
it("validates confirmation and clears credentials after setup", async () => {
const submit = vi.fn().mockResolvedValue(undefined);
render(<PasswordForm setup submit={submit} />);
fill("Setup token", "token");
fill("New password", "long password here");
fill("Confirm password", "wrong password here");
fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" }));
expect(await screen.findByText("Passwords do not match")).toBeInTheDocument();
expect(submit).not.toHaveBeenCalled();
fill("Confirm password", "long password here");
fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" }));
await waitFor(() =>
expect(submit).toHaveBeenCalledWith({
token: "token",
currentPassword: "",
newPassword: "long password here",
confirmPassword: "long password here",
}),
);
await waitFor(() =>
expect(screen.getByLabelText("New password")).toHaveValue(""),
);
});
it("submits setup and enters the app", async () => {
vi.spyOn(settingsApi, "setup").mockResolvedValue();
const done = vi.fn();
render(<SetupScreen onComplete={done} />);
fill("Setup token", "token");
fill("New password", "long password here");
fill("Confirm password", "long password here");
fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" }));
await waitFor(() => expect(done).toHaveBeenCalledOnce());
});
it("shows password failure and preserves the form for retry", async () => {
render(
<PasswordForm submit={vi.fn().mockRejectedValue(new Error("invalid"))} />,
);
fill("Current password", "wrong");
fill("New password", "long password here");
fill("Confirm password", "long password here");
fireEvent.click(screen.getByRole("button", { name: "Change password" }));
expect(await screen.findByRole("status")).toHaveTextContent("Unable to save");
});
it("renders system/session/Claude information and opens the terminal", async () => {
vi.spyOn(settingsApi, "system").mockResolvedValue({
version: "1.2",
workspacePath: "/workspace",
dataDirPath: "/data",
nodeVersion: "v22",
});
vi.spyOn(settingsApi, "session").mockResolvedValue({
lifetimeSeconds: 86400,
});
vi.spyOn(settingsApi, "claude").mockResolvedValue({
available: true,
version: "Claude 1",
loginAppearsPresent: true,
});
const revoke = vi.spyOn(settingsApi, "revoke").mockResolvedValue();
const open = vi.fn();
render(<SettingsPage openTerminal={open} />);
expect(await screen.findByText("/workspace")).toBeInTheDocument();
expect(screen.getByText(/86400 seconds/)).toBeInTheDocument();
expect(screen.getByText("Available: Claude 1")).toBeInTheDocument();
fireEvent.click(screen.getByText("Open terminal to log in"));
expect(open).toHaveBeenCalledOnce();
fireEvent.click(screen.getByText("Sign out all sessions"));
await waitFor(() => expect(revoke).toHaveBeenCalledOnce());
expect(await screen.findByRole("status")).toHaveTextContent(
"This browser remains signed in",
);
});
it("provides the shared feature navigation", () => {
const change = vi.fn();
render(<HeaderNavigation page="Notebooks" onChange={change} />);
fireEvent.click(screen.getByText("Settings"));
expect(change).toHaveBeenCalledWith("Settings");
expect(screen.getByText("Hosts")).toBeInTheDocument();
expect(screen.getByText("Notebooks")).toHaveAttribute("aria-current", "page");
});
+12 -5
View File
@@ -15,9 +15,11 @@ LAN/Tailscale addresses. No password is set initially: API access fails closed.
`SHELLBOOK_PORT`, `SHELLBOOK_TRUSTED_PROXIES` (comma-separated proxy IPs), `SHELLBOOK_PORT`, `SHELLBOOK_TRUSTED_PROXIES` (comma-separated proxy IPs),
and `TS_AUTHKEY` in the host environment. Auth keys are transferred in a and `TS_AUTHKEY` in the host environment. Auth keys are transferred in a
mode-0600 temporary file and removed, never stored in the service env. mode-0600 temporary file and removed, never stored in the service env.
3. In the CT run the printed password command. It also accepts one password 3. Open ShellBook in your browser. In the CT run `cat /var/lib/shellbook/setup-token`
line on stdin; do not pass passwords as arguments. Source-checkout command: and enter the token with a new password (at least 12 characters) in the setup screen.
`SHELLBOOK_DATA_DIR=/var/lib/shellbook pnpm --filter @shellbook/server set-password`. This token is private, survives restart, and is deleted after setup. It is never logged.
Alternative password CLI: `SHELLBOOK_DATA_DIR=/var/lib/shellbook pnpm --filter @shellbook/server set-password`
from the checkout (hidden prompt or one password line on stdin; never arguments).
4. Run `claude` as shellbook and use `/login`. Authorize 4. Run `claude` as shellbook and use `/login`. Authorize
`/home/shellbook/.ssh/id_ed25519.pub` on managed hosts. The service user has `/home/shellbook/.ssh/id_ed25519.pub` on managed hosts. The service user has
no sudo access. Initialize notebooks manually if templates were absent. no sudo access. Initialize notebooks manually if templates were absent.
@@ -36,8 +38,13 @@ leaves the running service in place. Check `journalctl -u shellbook`.
Configuration is `/etc/shellbook/env`; data is `/var/lib/shellbook` (back it up Configuration is `/etc/shellbook/env`; data is `/var/lib/shellbook` (back it up
along with workspace and service-user home). `SHELLBOOK_SESSION_SECONDS` defaults along with workspace and service-user home). `SHELLBOOK_SESSION_SECONDS` defaults
to 2592000 (30 days). Cookies survive restart. Logout clears the browser cookie; to 2592000 (30 days). Cookies survive restart. Logout clears the browser cookie;
password changes do not revoke existing cookies. For emergency revocation stop Settings supports changing the password and signing out all sessions; both revoke
the service, delete `session-secret` from the data directory and start it again. older cookies and close active WebSockets, while the current browser receives a fresh
cookie. CLI password changes invalidate cookies on their next request. For emergency
revocation stop the service, delete `session-secret`, and restart it.
Settings also shows paths, versions, and Claude CLI status, and opens the terminal
for `claude` then `/login` as the service user. A credentials file's existence is only
a hint, not proof that a login is valid.
Forward auth is off by default. To enable it set Forward auth is off by default. To enable it set
`SHELLBOOK_FORWARD_AUTH_HEADER=Remote-User` and trusted proxy IPs. The header is `SHELLBOOK_FORWARD_AUTH_HEADER=Remote-User` and trusted proxy IPs. The header is
+3 -1
View File
@@ -122,7 +122,9 @@ systemctl enable shellbook
systemctl restart shellbook systemctl restart shellbook
cat <<'EOF' cat <<'EOF'
Next steps: Next steps:
1. Set the password (hidden prompt): 1. Open ShellBook in the browser and enter the setup token shown by:
cat /var/lib/shellbook/setup-token
Alternative password CLI (hidden prompt):
runuser -u shellbook -- env SHELLBOOK_DATA_DIR=/var/lib/shellbook node /opt/shellbook/apps/server/dist/cli/set-password.js runuser -u shellbook -- env SHELLBOOK_DATA_DIR=/var/lib/shellbook node /opt/shellbook/apps/server/dist/cli/set-password.js
2. Log into Claude as the service user: 2. Log into Claude as the service user:
runuser -l shellbook -c '/home/shellbook/.local/bin/claude' runuser -l shellbook -c '/home/shellbook/.local/bin/claude'
+89 -14
View File
@@ -5,7 +5,7 @@ A notebook is a Markdown file: prose plus shell blocks. The shell is the primary
artifact — always shown literally, with parameter values filled in, copyable into artifact — always shown literally, with parameter values filled in, copyable into
any terminal. ShellBook adds buttons around it: run on a host over SSH, check a any terminal. ShellBook adds buttons around it: run on a host over SSH, check a
condition, download a produced file. Claude Code (the real CLI, subscription condition, download a produced file. Claude Code (the real CLI, subscription
login) runs in a built-in terminal and edits the notebooks. login) runs behind chat or in a built-in terminal and edits the notebooks.
## 1. Goals ## 1. Goals
@@ -28,7 +28,7 @@ programs inside run blocks (use the terminal panel for those).
- **Workspace**: a git repo with the user's data, separate from the app code: - **Workspace**: a git repo with the user's data, separate from the app code:
`notebooks/*.md`, `hosts.yaml`, `CLAUDE.md` (format guide for Claude, shipped by ShellBook). `notebooks/*.md`, `hosts.yaml`, `CLAUDE.md` (format guide for Claude, shipped by ShellBook).
- **Host**: an entry in `hosts.yaml` (`name`, `address`, `user`, `port`, optional `tags`). - **Host**: an entry in `hosts.yaml` (`name`, `address`, `user`, `port`, optional `tags`).
ShellBook connects with its own SSH key. Authentication is chosen per host in the Servers & SSH page (see ?4.1).
- **Step**: a fenced block with a ShellBook attribute set. Kinds: `run`, `check`. - **Step**: a fenced block with a ShellBook attribute set. Kinds: `run`, `check`.
- **Run record**: one execution of a step (host, rendered script, output, exit code, - **Run record**: one execution of a step (host, rendered script, output, exit code,
artifacts, timestamp). Appended to the audit log. artifacts, timestamp). Appended to the audit log.
@@ -127,12 +127,46 @@ only, then removed.
## 4. Execution ## 4. Execution
- Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY. - Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY.
- SSH via `ssh2`, ShellBook's own key, **strict host key checking**. Unknown host key → - SSH via `ssh2`, per-host authentication, **strict host key checking**. Unknown host key →
UI shows the fingerprint and asks once (TOFU), then stored in the workspace's `known_hosts`. UI shows the fingerprint and asks once (TOFU), then stored in the workspace's `known_hosts`.
- Output is streamed to the browser over WebSocket (stdout/stderr interleaved, with exit code). - Output is streamed to the browser over WebSocket (stdout/stderr interleaved, with exit code).
- Every run is appended to `data/audit.jsonl`: time, notebook, step id, host, rendered script, exit code, duration. Secrets never appear. - Every run is appended to `data/audit.jsonl`: time, notebook, step id, host, rendered script, exit code, duration. Secrets never appear.
- One step per host at a time (queue); different hosts in parallel. - One step per host at a time (queue); different hosts in parallel.
### 4.1 Hosts and SSH credentials
The Servers & SSH page manages host name, address, user, port and tags without YAML
editing. Changes preserve YAML comments/order where practical and use an opaque
inventory version; stale writes return 409. Host renames migrate stored credentials;
notebook host references remain literal and must be updated by the user. The file
watcher publishes `file.changed` / `file.deleted` with path `hosts.yaml`.
Per-host authentication is ShellBook key (default), password (including non-echoed
keyboard-interactive password prompts), or private key with optional passphrase.
Paste or upload the key from the browser. ssh2 1.17.0 does not expose client user
certificate pairing; the UI explicitly disables OpenSSH certificates. All remote
execution, checks, uploads and artifact downloads use the same authenticated client.
Strict host key checks and explicit TOFU acceptance remain mandatory.
Passwords, private keys and passphrases are stored only in the data directory,
AES-256-GCM encrypted with random 96-bit nonces and host-name AAD. A random 256-bit
key file and credential files have POSIX mode 0600; ciphertext updates use atomic
rename. Keep dataDir outside the workspace repository. APIs never return stored
secrets: only type, key fingerprint (when applicable), and set-at time. Selecting
the default or deleting a host deletes its credential. Credential values join the
existing streaming/audit redaction list; host actions discard remote output and
return only an exit status or a TOFU fingerprint challenge.
The page shows the ShellBook public key with Copy, Test connection (`true`),
Install ShellBook key, and Forget host key. Installation requires the stored
password and previews the literal script; the server rejects a mismatched preview
before connecting. It appends the public key idempotently to the remote user's
`~/.ssh/authorized_keys`, with all quoting through core `shellQuote`. The password
remains selected until the user chooses ShellBook key after successful installation.
Forgetting a host key requires UI confirmation and removes only that endpoint,
preserving other aliases. All management routes use the existing session and origin
checks and responses disable caching.
## 5. UI ## 5. UI
- **Notebook list** (left), **notebook view** (center), **AI/terminal panel** (right, collapsible). - **Notebook list** (left), **notebook view** (center), **AI/terminal panel** (right, collapsible).
@@ -143,23 +177,64 @@ only, then removed.
- Edit mode: raw Markdown in CodeMirror with live preview. Files changed on disk - Edit mode: raw Markdown in CodeMirror with live preview. Files changed on disk
(by Claude or git pull) reload live. (by Claude or git pull) reload live.
- Notebook management: searchable folder tree; create with name/folder/title and a
valid starter, rename/move, duplicate, and explicitly confirmed delete. Paths are
relative to `notebooks/`; folders are created as needed and pruned when empty.
- Editor toolbar inserts checks, runs, artifact downloads, uploads, captures and
after-step notes at the cursor. A parameter form edits YAML frontmatter through
a YAML document parser; format help explains syntax. Targets are local or host
parameters. Examples must be reviewed before execution.
- Mutations use optimistic versions; occupied destinations or stale versions return
409. Atomic file publication and recursive watcher events refresh all tabs. An
external rename/delete retains the old open draft with a notice and refreshes
the tree; users can select the new path. Unsaved navigation requires confirmation.
## 6. AI: Claude Code ## 6. AI: Claude Code
- The right panel is a real terminal (xterm.js ↔ node-pty) running `claude` in the - The right panel offers chat and a real terminal. Both use the real `claude`
workspace, inside `tmux` so the session survives closed tabs and app restarts. CLI with the user's own subscription login; no API key or embedded SDK.
This is the genuine CLI with the user's own subscription login — no API key, no SDK. - Chat runs one headless CLI process per turn (`-p`, stream-json stdin/stdout),
- The workspace ships a `CLAUDE.md` describing this notebook format, so Claude writes in the workspace, with explicit `--resume` of the CLI session ID. A dedicated,
shell-first notebooks (literal commands, no wrapper code). authenticated same-origin `/api/chat` WebSocket streams text deltas, compact
- Live reload (§5) makes Claude's edits appear immediately. tool summaries, completion metadata and safe errors. Disconnect/Stop/timeout
- Later option: `ANTHROPIC_BASE_URL` / token for a custom endpoint, set in the terminate the process; only one active turn per conversation is allowed.
panel's environment. - File tools are restricted to workspace working directories using CLI restricted
mode (Claude Code 2.1.248+). Available tools are Read, Glob, Grep, Edit, Write,
MultiEdit; Bash is added only by the off-by-default shell-command toggle. Web
and MCP tools are unavailable. Never use bypassPermissions.
- The data directory persists conversation titles (first message), session IDs
and timestamps, not messages or tool contents. The CLI keeps its own session
transcripts. Never send secrets in chat. History resumes CLI context; the web
view retains messages only for the lifetime of the mounted panel.
- The terminal (xterm.js and node-pty) uses tmux, so interactive sessions survive
closed tabs and app restarts. Missing CLI/login errors offer this panel with
instructions to run `claude`, then `/login`.
- The workspace ships a `CLAUDE.md` describing the notebook format. The chat
appends ShellBook context and the open notebook path to the system prompt.
Live reload (section 5) makes actual notebook edits appear immediately.
- Details, resource limits and verified CLI flags: `apps/server/src/chat/README.md`.
## 7. Security ## 7. Security
- The app can run commands on every host → treat access as root-equivalent. - The app can run commands on every host → treat access as root-equivalent.
- Built-in login: one password (scrypt hash in config), session cookie signed with a - Built-in login: one scrypt password hash in `auth.json`; session cookies are HMAC
secret persisted on disk → **logins survive restarts**. Optional: trust a signed with a persisted mode-0600 secret and bound to the current password hash.
forward-auth header from Traefik instead. Logins survive restarts; changing the password invalidates other cookies.
- First run creates a random mode-0600 `setup-token` in the data directory. Only its
path is logged. Public GET `/api/auth/setup` reports whether setup is needed;
POST requires the token (constant-time comparison), matching passwords of at
least 12 characters (maximum 4096 bytes), and consumes the token once. Configured
instances reject setup with 409. Setup and login share a per-IP rate limit.
- Settings changes require the current password, or atomically rotate the signing
secret to sign out all sessions. Both issue a fresh cookie to the current browser
and close existing WebSockets; future connections must authenticate again.
Forward-auth identities remain governed by the upstream proxy.
- Every API route is authenticated except exact health, login, and setup paths;
the origin check also covers those exceptions and WebSocket upgrades.
Optional forward-auth headers are accepted only from configured trusted peers.
- Claude status executes only `claude --version` with argv, timeout, and output limit.
Login status checks only the existence of `~/.claude/.credentials.json` under the
service user home; credential contents are never read or returned.
- Listens on `127.0.0.1` or LAN; intended behind Traefik + firewall (LAN/Tailscale only). - Listens on `127.0.0.1` or LAN; intended behind Traefik + firewall (LAN/Tailscale only).
- Terminal panel = shell as the service user: same trust level as the app itself. - Terminal panel = shell as the service user: same trust level as the app itself.
- No secrets in notebooks, audit log or artifacts metadata. - No secrets in notebooks, audit log or artifacts metadata.
+74
View File
@@ -126,3 +126,77 @@ export type ServerEvent =
export type TerminalClientMessage = export type TerminalClientMessage =
| { type: "input"; data: string } | { type: "input"; data: string }
| { type: "resize"; cols: number; rows: number }; | { type: "resize"; cols: number; rows: number };
// Settings and first-run setup (#10). Only GET/POST /auth/setup is public.
export interface SetupStatusResponse { required: boolean }
export interface NewPasswordRequest { newPassword: string; confirmPassword: string }
export interface SetupRequest extends NewPasswordRequest { token: string }
export interface ChangePasswordRequest extends NewPasswordRequest { currentPassword: string }
export interface SessionSettingsResponse { lifetimeSeconds: number }
export interface ClaudeStatusResponse { available: boolean; version: string | null; loginAppearsPresent: boolean }
export interface SystemInfoResponse { version: string; workspacePath: string; dataDirPath: string; nodeVersion: string }
// ---- notebook management (#9) ------------------------------------------------
// Paths are relative to notebooks/. Mutations return 409 on stale versions or occupied targets.
// POST /api/notebooks
export interface CreateNotebookRequest { path: string; source: string }
// POST /api/notebooks/:path/rename or /duplicate
export interface MoveNotebookRequest { path: string; baseVersion: string }
// DELETE /api/notebooks/:path
export interface DeleteNotebookRequest { baseVersion: string }
export interface NotebookMutationResponse { path: string; version: string }
export interface DeleteNotebookResponse { deleted: boolean }
// Chat: JSON WebSocket frames on /api/chat (separate from run events).
export interface ChatConversation {
id: string;
title: string;
sessionId?: string;
createdAt: string;
updatedAt: string;
}
export type ChatClientMessage =
| { type: "send"; conversationId?: string; message: string; notebookPath?: string; allowShell: boolean }
| { type: "cancel" };
export type ChatEvent =
| { type: "history"; conversations: ChatConversation[] }
| { type: "conversation"; conversation: ChatConversation }
| { type: "delta"; text: string }
| { type: "tool"; name: string; path?: string }
| { type: "finished"; cancelled?: boolean; costUsd?: number; durationMs?: number }
| { type: "error"; code: "login" | "missing" | "cli" | "busy" | "invalid" | "limit" | "timeout"; message: string };
// ---- host management (#7) ----------------------------------------------------
export type HostCredentialInput =
| { type: "shellbook" }
| { type: "password"; password: string }
| { type: "privateKey"; privateKey: string; passphrase?: string };
export interface HostCredentialMetadata {
type: "shellbook" | "password" | "privateKey";
fingerprint?: string;
setAt?: string;
}
// GET /api/host-management
export interface HostInventoryResponse {
hosts: (HostInfo & { credential: HostCredentialMetadata })[];
version: string;
publicKey: string;
certificateSupport: { available: false; reason: string };
}
// POST /api/host-management; PUT /api/host-management/:name
export interface SaveHostRequest { host: HostInfo; baseVersion: string }
// DELETE /api/host-management/:name {baseVersion}; returns {version}.
// PUT /api/host-management/:name/credential (write-only); returns metadata.
// DELETE /api/host-management/:name/credential -> ShellBook key default.
// GET /api/host-management/:name/install-key -> {script}.
// POST /api/host-management/:name/action -> HostActionResponse.
export interface HostActionRequest {
action: "test" | "install-key";
acceptHostKey?: string;
/** Required for install-key; must match the current displayed script. */
script?: string;
}
export type HostActionResponse =
| { exitCode: number }
| { hostKey: { host: string; fingerprint: string; changed: boolean } };
// DELETE /api/host-management/:name/known-key -> 204 (explicit UI confirmation).
+3
View File
@@ -90,6 +90,9 @@ importers:
react-markdown: react-markdown:
specifier: ^9.0.1 specifier: ^9.0.1
version: 9.1.0(@types/[email protected])([email protected]) version: 9.1.0(@types/[email protected])([email protected])
yaml:
specifier: ^2.6.1
version: 2.9.1
devDependencies: devDependencies:
'@testing-library/jest-dom': '@testing-library/jest-dom':
specifier: ^6.6.3 specifier: ^6.6.3
+3 -2
View File
@@ -2,8 +2,9 @@
This repository is the user's workspace. Write runbooks as ordinary Markdown in 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 `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 workspace is available through ShellBook chat (the real `claude -p` CLI) or a real
the user's CLI login. Do not add API clients, subscription tokens, or chat wrappers. shell in a persistent tmux session. Both use the user's CLI login. Follow this
format when creating or editing notebooks. Do not add API clients or subscription tokens.
## Style and safety ## Style and safety