From 4d9a6326256fc72d816d2683a922883afd5f02ee Mon Sep 17 00:00:00 2001
From: Florian Schmidt
Date: Mon, 16 Nov 2026 10:19:52 +0100
Subject: [PATCH] feat(hosts): manage servers and encrypted SSH credentials in
UI (#7)
---
.agents/mind/architecture.md | 2 +
.agents/mind/index.md | 2 +-
README.md | 30 +-
apps/server/src/app.ts | 2 +
apps/server/src/hosts/credentials.ts | 195 +++++++++++
apps/server/src/hosts/index.ts | 230 +++++++++++++
apps/server/src/hosts/validation.ts | 34 ++
apps/server/src/runs/index.ts | 8 +-
apps/server/src/ssh/index.ts | 32 +-
apps/server/src/watch/index.ts | 6 +-
apps/server/src/workspace/index.ts | 20 +-
apps/server/test/hosts.test.ts | 456 ++++++++++++++++++++++++++
apps/server/test/ssh-fixture.ts | 4 +-
apps/server/test/watch.test.ts | 13 +
apps/web/src/App.tsx | 75 ++---
apps/web/src/HostKeyConfirmation.tsx | 44 +++
apps/web/src/HostsPage.tsx | 464 +++++++++++++++++++++++++++
apps/web/src/api.ts | 2 +-
apps/web/src/hosts.css | 49 +++
apps/web/src/tests/hosts.test.tsx | 119 +++++++
docs/spec.md | 38 ++-
packages/core/src/protocol.ts | 35 ++
22 files changed, 1779 insertions(+), 81 deletions(-)
create mode 100644 apps/server/src/hosts/credentials.ts
create mode 100644 apps/server/src/hosts/index.ts
create mode 100644 apps/server/src/hosts/validation.ts
create mode 100644 apps/server/test/hosts.test.ts
create mode 100644 apps/web/src/HostKeyConfirmation.tsx
create mode 100644 apps/web/src/HostsPage.tsx
create mode 100644 apps/web/src/hosts.css
create mode 100644 apps/web/src/tests/hosts.test.tsx
diff --git a/.agents/mind/architecture.md b/.agents/mind/architecture.md
index 5e64da4..44c330f 100644
--- a/.agents/mind/architecture.md
+++ b/.agents/mind/architecture.md
@@ -8,4 +8,6 @@
- [2026-11-16] **Secrets on SSH:** exported via `export NAME=` 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] **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
diff --git a/.agents/mind/index.md b/.agents/mind/index.md
index 358f0fd..5a30581 100644
--- a/.agents/mind/index.md
+++ b/.agents/mind/index.md
@@ -14,7 +14,7 @@
- Notebooks stay plain, readable Markdown.
## 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
- `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)
diff --git a/README.md b/README.md
index 53419e2..cbeefad 100644
--- a/README.md
+++ b/README.md
@@ -8,4 +8,32 @@ Notebook-style runbooks for Linux servers.
- 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.
-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.
diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts
index ed3ac60..4a95611 100644
--- a/apps/server/src/app.ts
+++ b/apps/server/src/app.ts
@@ -1,3 +1,4 @@
+import { hostsPlugin } from "./hosts";
import Fastify, { type FastifyInstance } from "fastify";
import websocket from "@fastify/websocket";
import { loadConfig, type ServerConfig } from "./config";
@@ -39,6 +40,7 @@ export async function buildApp(options: AppOptions = {}): Promise;
+ 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 {
+ 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 {
+ 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 ?? "",
+ ];
+}
diff --git a/apps/server/src/hosts/index.ts b/apps/server/src/hosts/index.ts
new file mode 100644
index 0000000..791adaa
--- /dev/null
+++ b/apps/server/src/hosts/index.ts
@@ -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 } 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, "SSH connection or action failed");
+ } finally {
+ client?.end();
+ }
+ },
+ );
+}
diff --git a/apps/server/src/hosts/validation.ts b/apps/server/src/hosts/validation.ts
new file mode 100644
index 0000000..e1d4101
--- /dev/null
+++ b/apps/server/src/hosts/validation.ts
@@ -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 };
+}
diff --git a/apps/server/src/runs/index.ts b/apps/server/src/runs/index.ts
index c9f20fd..50b7fba 100644
--- a/apps/server/src/runs/index.ts
+++ b/apps/server/src/runs/index.ts
@@ -1,3 +1,4 @@
+import { CredentialStore, credentialSecrets } from "../hosts/credentials";
import { randomUUID } from "node:crypto";
import { appendFile, mkdir, copyFile, stat, rm } from "node:fs/promises";
import path from "node:path";
@@ -38,9 +39,10 @@ export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: Host
/** Streaming redaction retains possible secret prefixes across chunks. */
export function redactor(secrets: string[], output: (data: string) => void) {
- const values = secrets.filter(Boolean).sort((a, b) => b.length - a.length);
let pending = "";
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 = "";
while (pending) {
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 artifactDir = path.join(root, "artifacts");
const secrets = Object.values(env).filter(Boolean);
+ let credential: Awaited>;
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 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);
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(artifactDir, { mode: 0o700 });
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;
if (!rendered.local) {
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";
let directory = "";
const code = await exec(client, "mktemp -d", "", timeout, (stream, data) => { if (stream === "stdout") directory += data; });
diff --git a/apps/server/src/ssh/index.ts b/apps/server/src/ssh/index.ts
index 10b07a4..6537369 100644
--- a/apps/server/src/ssh/index.ts
+++ b/apps/server/src/ssh/index.ts
@@ -7,6 +7,7 @@ import { StringDecoder } from "node:string_decoder";
import { shellQuote, type HostInfo } from "@shellbook/core";
import type { ServerConfig } from "../config";
import { SerialQueue } from "../workspace";
+import { CredentialStore, type StoredCredential } from "../hosts/credentials";
export type Output = (stream: "stdout" | "stderr", data: string) => void;
export class HostKeyError extends Error {
@@ -15,9 +16,12 @@ export class HostKeyError extends Error {
const keyWrites = new SerialQueue();
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 {
+export async function connect(config: ServerConfig, host: HostInfo, accepted?: string, credential?: StoredCredential | null): Promise {
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.
return keyWrites.run(file, async () => {
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.on("error", err => reject(failure ?? err));
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) {
const encoded = key.toString("base64");
if (matches.some(line => line.split(/\s+/)[2] === encoded)) return true;
@@ -136,3 +147,18 @@ export function sftpRequest(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 });
+ });
+}
diff --git a/apps/server/src/watch/index.ts b/apps/server/src/watch/index.ts
index 54eed06..f84d364 100644
--- a/apps/server/src/watch/index.ts
+++ b/apps/server/src/watch/index.ts
@@ -22,7 +22,7 @@ export function createNotebookWatcher(workspaceDir: string, options: {
const listeners = new Set<(event: NotebookFileEvent) => void>();
const pending = new Map>();
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((resolveReady, reject) => {
watcher.once("ready", resolveReady);
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.
void ready.catch(() => {});
const schedule = (type: NotebookFileEvent["type"], file: string) => {
- const path = relative(root, file).split(sep).join("/");
- if (closed || !path.endsWith(".md") || path.startsWith("../") || isAbsolute(path)) return;
+ const path = resolve(file) === resolve(workspaceDir, "hosts.yaml") ? "hosts.yaml" : relative(root, file).split(sep).join("/");
+ if (closed || (!path.endsWith(".md") && path !== "hosts.yaml") || path.startsWith("../") || isAbsolute(path)) return;
clearTimeout(pending.get(path));
pending.set(path, setTimeout(() => {
pending.delete(path);
diff --git a/apps/server/src/workspace/index.ts b/apps/server/src/workspace/index.ts
index 4e5d922..1b43bb4 100644
--- a/apps/server/src/workspace/index.ts
+++ b/apps/server/src/workspace/index.ts
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
import { readFile, writeFile, readdir, realpath, lstat } from "node:fs/promises";
import path from "node:path";
import { parse } from "yaml";
+import { validateHost } from "../hosts/validation";
import { parseNotebook, type HostInfo } from "@shellbook/core";
import type { FastifyInstance } from "fastify";
import type { ServerConfig } from "../config";
@@ -40,20 +41,19 @@ export async function readNotebook(config: ServerConfig, name: string) {
}
export async function readHosts(config: ServerConfig): Promise {
- 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;
if (!Array.isArray(entries)) throw httpError(400, "hosts.yaml must contain a host list");
const names = new Set();
return entries.map((entry: Record) => {
- if (!entry || typeof entry !== "object") throw httpError(400, "Invalid host");
- const { name, address, user, port = 22, tags = [] } = entry;
- if (typeof name !== "string" || !/^[A-Za-z0-9._-]+$/.test(name) || names.has(name) ||
- typeof address !== "string" || !address || /[\s\x00]/.test(address) ||
- 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[] };
+ const host = validateHost(entry);
+ if (names.has(host.name)) throw httpError(400, "Duplicate host name");
+ names.add(host.name);
+ return host;
});
}
diff --git a/apps/server/test/hosts.test.ts b/apps/server/test/hosts.test.ts
new file mode 100644
index 0000000..d90473c
--- /dev/null
+++ b/apps/server/test/hosts.test.ts
@@ -0,0 +1,456 @@
+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)[] = [];
+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");
+});
diff --git a/apps/server/test/ssh-fixture.ts b/apps/server/test/ssh-fixture.ts
index 00f6571..af4ab8e 100644
--- a/apps/server/test/ssh-fixture.ts
+++ b/apps/server/test/ssh-fixture.ts
@@ -3,7 +3,7 @@ import { Server, utils, type Connection } from "ssh2";
import type { HostInfo } from "@shellbook/core";
import type { ServerConfig } from "../src/config";
import { fingerprint } from "../src/ssh";
-export async function createSshFixture(config: ServerConfig, cleanup: (() => Promise)[], authenticate = true) {
+export async function createSshFixture(config: ServerConfig, cleanup: (() => Promise)[], authenticate: boolean | ((ctx: import("ssh2").AuthContext) => void) = true) {
const key = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString();
const parsed = utils.parseKey(key);
if (parsed instanceof Error) throw parsed;
@@ -15,7 +15,7 @@ export async function createSshFixture(config: ServerConfig, cleanup: (() => Pro
clients.add(client);
client.on("error", () => {});
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 => {
const session = accept();
session.on("exec", (acceptExec, _reject, info) => {
diff --git a/apps/server/test/watch.test.ts b/apps/server/test/watch.test.ts
index 267a929..5633b30 100644
--- a/apps/server/test/watch.test.ts
+++ b/apps/server/test/watch.test.ts
@@ -44,3 +44,16 @@ it("starts before notebooks exists and cancels pending notifications on close",
await new Promise((r) => setTimeout(r, 600)); expect(listener).not.toHaveBeenCalled();
} 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 }); }
+});
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx
index d8fd693..d35bb5a 100644
--- a/apps/web/src/App.tsx
+++ b/apps/web/src/App.tsx
@@ -24,6 +24,8 @@ import type {
StartRunRequest,
Step,
} from "@shellbook/core";
+import { HostKeyConfirmation } from "./HostKeyConfirmation";
+import { HostsPage } from "./HostsPage";
import { HttpError } from "./api";
import type { Api } from "./api";
import { emptySession, eventReducer, stepKey } from "./events";
@@ -46,6 +48,7 @@ function steps(blocks: Block[]): Step[] {
);
}
export function App({ api }: { api: Api }) {
+ const [hostsPage, setHostsPage] = useState(false);
const [auth, setAuth] = useState<"loading" | "login" | "ready">("loading");
const [password, setPassword] = useState("");
const [list, setList] = useState([]);
@@ -119,6 +122,10 @@ export function App({ api }: { api: Api }) {
})
.catch((e) => setError(String(e)));
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;
if (event.type === "file.changed" && event.path === open.doc?.path) {
if (open.dirty) setConflict(true);
@@ -324,6 +331,7 @@ export function App({ api }: { api: Api }) {
ShellBookRUNBOOKS
+
}>
@@ -499,62 +509,15 @@ export function App({ api }: { api: Api }) {
)}
- {keyPrompt?.hostKey && (
-
-
-
- {keyPrompt.hostKey.changed
- ? "⚠ HOST KEY CHANGED"
- : "Unknown SSH host key"}
-
- {keyPrompt.hostKey.changed && (
-
- STOP: a different key is already trusted. This may indicate a
- man-in-the-middle attack. Verify the fingerprint independently
- before accepting.
-
- )}
-
- Verify the key for {keyPrompt.hostKey.host}{" "}
- through a trusted channel.
-
- {keyPrompt.hostKey.fingerprint}
-
-
- dispatch({
- type: "run.error",
- runId: keyPrompt.runId,
- message: "Host key rejected",
- })
- }
- >
- Reject
-
- {
- 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
-
-
-
-
- )}
+ {keyPrompt?.hostKey && dispatch({ type: "run.error", runId: keyPrompt.runId, message: "Host key rejected" })}
+ onTrust={() => {
+ 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 });
+ }}
+ />}
);
}
diff --git a/apps/web/src/HostKeyConfirmation.tsx b/apps/web/src/HostKeyConfirmation.tsx
new file mode 100644
index 0000000..88477a1
--- /dev/null
+++ b/apps/web/src/HostKeyConfirmation.tsx
@@ -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 (
+
+
+
+ {changed ? "WARNING: HOST KEY CHANGED" : "Unknown SSH host key"}
+
+ {changed && (
+
+ STOP: a different key is already trusted. This may indicate a
+ man-in-the-middle attack. Verify the fingerprint independently
+ before accepting.
+
+ )}
+
+ Verify the key for {host} through a trusted channel.
+
+ {fingerprint}
+
+
+ Reject
+
+
+ Trust this fingerprint and retry
+
+
+
+
+ );
+}
diff --git a/apps/web/src/HostsPage.tsx b/apps/web/src/HostsPage.tsx
new file mode 100644
index 0000000..545f34e
--- /dev/null
+++ b/apps/web/src/HostsPage.tsx
@@ -0,0 +1,464 @@
+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();
+ const [draft, setDraft] = useState({ ...empty });
+ const [editVersion, setEditVersion] = useState("");
+ const [editing, setEditing] = useState();
+ const [credentialHost, setCredentialHost] = useState();
+ const [type, setType] = useState("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(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) {
+ setBusy(true);
+ setError("");
+ setStatus("");
+ try {
+ await work();
+ } catch (e) {
+ setError(`${String(e)}. Reload hosts after a conflict before retrying.`);
+ } finally {
+ setBusy(false);
+ }
+ }
+ async function action(host: string, request: HostActionRequest) {
+ const response = await json(
+ `${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 (
+
+ Servers and SSH credentials
+ {error && {error}
}
+ {status && {status}
}
+
+ void perform(async () => {
+ await load();
+ setEditing(undefined);
+ setDraft({ ...empty });
+ })
+ }
+ >
+ Reload hosts
+
+ {inventory && (
+ <>
+ ShellBook public key
+ {inventory.publicKey}
+
+ void perform(async () => {
+ await navigator.clipboard.writeText(inventory.publicKey);
+ setStatus("Public key copied");
+ })
+ }
+ >
+ Copy public key
+
+ {inventory.certificateSupport.reason}
+
+ {inventory.hosts.map((host) => (
+
+ {host.name}
+
+ {host.user}@{host.address}:{host.port}
+
+ {host.tags.join(", ")}
+
+ Authentication: {host.credential.type}{" "}
+ {host.credential.fingerprint}{" "}
+ {host.credential.setAt && `set ${host.credential.setAt}`}
+
+
+ {
+ 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}
+
+ {
+ setCredentialHost(host.name);
+ setType("shellbook");
+ setPassword("");
+ setPrivateKey("");
+ setPassphrase("");
+ }}
+ >
+ SSH credentials for {host.name}
+
+
+ void perform(() => action(host.name, { action: "test" }))
+ }
+ >
+ Test connection to {host.name}
+
+
+ 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}
+
+ {
+ 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}
+
+ {
+ 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}
+
+
+
+ ))}
+
+ {editing ? `Edit ${editing}` : "Add server"}
+
+ >
+ )}
+ {credentialHost && (
+
+ SSH credentials for {credentialHost}
+
+ Saved secrets cannot be read back. Blank fields do not represent the
+ existing credential.
+
+
+
+ )}
+ {install && (
+
+ Install ShellBook key on {install.host}
+
+ This exact script runs using the stored password. After success,
+ select ShellBook key in SSH credentials to remove the saved
+ password.
+
+ {install.script}
+
+ void perform(() =>
+ action(install.host, {
+ action: "install-key",
+ script: install.script,
+ }),
+ )
+ }
+ >
+ Run displayed script
+
+ setInstall(undefined)}>
+ Cancel installation
+
+
+ )}
+ {trust && (
+ setTrust(undefined)}
+ onTrust={() =>
+ void perform(() =>
+ action(trust.host, {
+ ...trust.request,
+ acceptHostKey: trust.key.fingerprint,
+ }),
+ )
+ }
+ />
+ )}
+
+ );
+}
diff --git a/apps/web/src/api.ts b/apps/web/src/api.ts
index 0050c25..ccc251c 100644
--- a/apps/web/src/api.ts
+++ b/apps/web/src/api.ts
@@ -13,7 +13,7 @@ export class HttpError extends Error {
super(`Request failed (${status})`);
}
}
-async function json(
+export async function json(
path: string,
method = "GET",
body?: unknown,
diff --git a/apps/web/src/hosts.css b/apps/web/src/hosts.css
new file mode 100644
index 0000000..5e68383
--- /dev/null
+++ b/apps/web/src/hosts.css
@@ -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;
+ }
+}
diff --git a/apps/web/src/tests/hosts.test.tsx b/apps/web/src/tests/hosts.test.tsx
new file mode 100644
index 0000000..f96b769
--- /dev/null
+++ b/apps/web/src/tests/hosts.test.tsx
@@ -0,0 +1,119 @@
+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();
+ 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();
+ 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();
+ 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();
+ 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" }),
+ ),
+ );
+});
diff --git a/docs/spec.md b/docs/spec.md
index 3c0ef21..794ea65 100644
--- a/docs/spec.md
+++ b/docs/spec.md
@@ -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:
`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`).
- 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`.
- **Run record**: one execution of a step (host, rendered script, output, exit code,
artifacts, timestamp). Appended to the audit log.
@@ -127,12 +127,46 @@ only, then removed.
## 4. Execution
- 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`.
- 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.
- 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
- **Notebook list** (left), **notebook view** (center), **AI/terminal panel** (right, collapsible).
diff --git a/packages/core/src/protocol.ts b/packages/core/src/protocol.ts
index c32a806..50d08c4 100644
--- a/packages/core/src/protocol.ts
+++ b/packages/core/src/protocol.ts
@@ -126,3 +126,38 @@ export type ServerEvent =
export type TerminalClientMessage =
| { type: "input"; data: string }
| { type: "resize"; cols: number; rows: number };
+
+// ---- 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).