feat(hosts): manage servers and encrypted SSH credentials in UI (#7)

This commit is contained in:
Florian Schmidt
2026-11-16 10:19:52 +01:00
parent 4fe7e4e376
commit 4d9a632625
22 changed files with 1779 additions and 81 deletions
+2
View File
@@ -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<FastifyInstanc
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
await app.register(websocket);
await app.register(workspacePlugin, { config });
await app.register(hostsPlugin, { config });
await app.register(runsPlugin, { config, hub });
await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir });
+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 } 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();
}
},
);
}
+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 };
}
+6 -2
View File
@@ -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<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; };
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; });
+29 -3
View File
@@ -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<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 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<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 });
});
}
+3 -3
View File
@@ -22,7 +22,7 @@ export function createNotebookWatcher(workspaceDir: string, options: {
const listeners = new Set<(event: NotebookFileEvent) => void>();
const pending = new Map<string, ReturnType<typeof setTimeout>>();
let closed = false;
const watcher = watch(root, { ignoreInitial: true, followSymlinks: false, atomic: true });
const watcher = watch([root, resolve(workspaceDir, "hosts.yaml")], { ignoreInitial: true, followSymlinks: false, atomic: true });
const ready = new Promise<void>((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);
+10 -10
View File
@@ -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<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;
if (!Array.isArray(entries)) throw httpError(400, "hosts.yaml must contain a host list");
const names = new Set<string>();
return entries.map((entry: Record<string, unknown>) => {
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;
});
}