Compare commits

...
3 Commits
Author SHA1 Message Date
Florian Schmidt 54115289cc feat(deploy): bring new notebook templates into existing workspaces (#11)
Each shipped template is offered once (recorded in
/etc/shellbook/templates-offered) and copied as the service user only
when the file does not exist, so updates add new templates without
overwriting files or restoring deleted ones.
2026-11-16 11:42:13 +01:00
Florian Schmidt 85afd105f7 feat(templates): LXC container and chained web server notebooks (#11)
infra/lxc-container.md creates an unprivileged container on a Proxmox
host with ShellBook's key, waits for its address and adds it to Hosts.
services/web-server.md installs nginx on an existing host or on a new
container through ::use. Document chaining in the spec (3.6) and in the
workspace format guide.
2026-11-16 11:42:12 +01:00
Florian Schmidt 845d6c828e feat: chained notebooks with when sections and host blocks (#11)
A notebook can include another one and continue with what it produced:

- core: parse :::when{param=a,b}, ::use{notebook= as= with=} and
  ::host{name= address= user= port= capture=}; composeNotebook namespaces
  an included notebook's params, steps, captures and templates by alias
  (cycles, missing files, depth > 4 and child errors are reported on the
  use line). Defaults may reference captures and builtins
  ({{shellbook.public_key}}); required params and secrets gate only steps
  of their own scope; secretEnv passes a scope's secrets under local names.
- protocol: NotebookResponse gains includes and builtins.
- server: compose includes on load, inject builtins (client values are
  ignored), refuse steps in inactive when sections.
- web: render when/use/host blocks, group included params in the form,
  add a created machine to Hosts and capture its name, reload when an
  included notebook changes, run all checks only for active steps,
  authoring snippets for when, use and host.
2026-11-16 11:42:12 +01:00
30 changed files with 1653 additions and 138 deletions
+4 -3
View File
@@ -1,5 +1,5 @@
import { registerSettings } from "./settings";
import { hostsPlugin } from "./hosts";
import { builtinValues, hostsPlugin } from "./hosts";
import Fastify, { type FastifyInstance } from "fastify";
import websocket from "@fastify/websocket";
import { loadConfig, type ServerConfig } from "./config";
@@ -42,9 +42,10 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
await registerSettings(app, config);
await app.register(websocket);
await app.register(workspacePlugin, { config });
const builtins = () => builtinValues(config);
await app.register(workspacePlugin, { config, builtins });
await app.register(hostsPlugin, { config });
await app.register(runsPlugin, { config, hub });
await app.register(runsPlugin, { config, hub, builtins });
await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir });
await app.register(chatPlugin, { config });
+5
View File
@@ -43,6 +43,11 @@ export async function shellbookPublicKey(config: ServerConfig) {
throw httpError(503, "ShellBook key unavailable");
return `${parsed.type} ${parsed.getPublicSSH().toString("base64")}`;
}
/** Runtime values every notebook can reference ({{shellbook.public_key}}); empty when the key is unavailable. */
export async function builtinValues(config: ServerConfig): Promise<Record<string, string>> {
try { return { "shellbook.public_key": await shellbookPublicKey(config) }; }
catch { return {}; }
}
export async function hostsPlugin(
app: FastifyInstance,
{ config }: { config: ServerConfig },
+20 -17
View File
@@ -3,38 +3,41 @@ import { randomUUID } from "node:crypto";
import { appendFile, mkdir, copyFile, stat, rm } from "node:fs/promises";
import path from "node:path";
import { createReadStream } from "node:fs";
import { parseNotebook, resolveParams, renderStep, secretEnv, shellQuote, type Block, type Step, type Notebook, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core";
import { blockActive, findStep, isBuiltin, resolveParams, renderStep, secretEnv, shellQuote, type Step, type Notebook, type ParamValues, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core";
import type { FastifyInstance } from "fastify";
import type { Client } from "ssh2";
import type { ServerConfig } from "../config";
import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace";
import { readHosts, loadNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace";
import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, sshFailure, type Output } from "../ssh";
import { EventsHub } from "./events";
import { runRoot, artifactFile, persistArtifacts, isSensitive, claimArtifact, sweepRuns } from "./artifacts";
export { EventsHub } from "./events";
export function findStep(blocks: Block[], id: string): Step | undefined {
for (const block of blocks) {
if (block.type === "step" && block.step.attrs.id === id) return block.step;
if (block.type === "after") { const found = findStep(block.blocks, id); if (found) return found; }
}
}
export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: HostInfo[]) {
/** `notebook` is the composed notebook (see loadNotebook); builtins come from the server only. */
export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: HostInfo[], builtins: ParamValues = {}) {
if (notebook.diagnostics.some(d => d.severity === "error")) throw httpError(400, "Notebook has errors");
const step = findStep(notebook.blocks, req.stepId);
if (!step) throw httpError(404, "Step not found");
const names = hosts.map(h => h.name);
const resolved = resolveParams(notebook, req.params, names);
if (Object.keys(resolved.errors).length) throw httpError(400, "Parameters are missing or invalid");
const rendered = renderStep(notebook, step, resolved.values, req.runtime, names);
// A client cannot supply or override builtins.
const runtime: ParamValues = Object.assign(Object.create(null) as ParamValues,
Object.fromEntries(Object.entries(req.runtime).filter(([name]) => !isBuiltin(name))), builtins);
const resolved = resolveParams(notebook, req.params, names, runtime);
// Only parameters of the step's own scope gate it (an included notebook's form does not block the parent).
// Same rule as core's renderStep: required params and secrets of the step's scope gate it;
// other params only matter when the step references them (checked by renderStep below).
const scope = step.attrs.scope ?? "";
const gating = notebook.params.filter(def => (def.scope ?? "") === scope && (def.required || def.type === "secret"));
if (gating.some(def => Object.hasOwn(resolved.errors, def.name))) throw httpError(400, "Parameters are missing or invalid");
if (!blockActive(notebook, step.attrs.id, resolved.values)) throw httpError(400, "Step is not part of the selected options");
const rendered = renderStep(notebook, step, resolved.values, runtime, names);
if (rendered.missing.length || Object.keys(rendered.invalid).length) throw httpError(400, "Step parameters are missing or invalid");
const host = hosts.find(h => h.name === rendered.host);
if (!rendered.local && !host) throw httpError(400, "Unknown target host");
for (const name of rendered.artifacts) safeRelative(name);
if (rendered.kind === "check" && (rendered.uploads.length || rendered.artifacts.length)) throw httpError(400, "Checks cannot upload or collect artifacts");
if (!Number.isFinite(step.attrs.timeoutSec) || step.attrs.timeoutSec <= 0) throw httpError(400, "Invalid timeout");
return { step, rendered, host, env: secretEnv(notebook, resolved.values) };
return { step, rendered, host, env: secretEnv(notebook, resolved.values, step.attrs.scope) };
}
/** Streaming redaction retains possible secret prefixes across chunks. */
@@ -179,7 +182,7 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
function stringMap(value: unknown): value is Record<string, string> {
return !!value && typeof value === "object" && !Array.isArray(value) && Object.values(value).every(v => typeof v === "string");
}
export async function runsPlugin(app: FastifyInstance, { config, hub }: { config: ServerConfig; hub: EventsHub }) {
export async function runsPlugin(app: FastifyInstance, { config, hub, builtins = async () => ({}) }: { config: ServerConfig; hub: EventsHub; builtins?: () => Promise<ParamValues> }) {
const queue = new SerialQueue();
const active = new Set<string>();
const downloads = new Set<Promise<void>>();
@@ -197,8 +200,8 @@ export async function runsPlugin(app: FastifyInstance, { config, hub }: { config
app.post<{ Body: StartRunRequest }>("/api/runs", async (req, reply) => {
const body = req.body;
if (!body || typeof body.notebookPath !== "string" || typeof body.stepId !== "string" || !stringMap(body.params) || !stringMap(body.runtime) || !stringMap(body.artifactSources) || (body.acceptHostKey !== undefined && typeof body.acceptHostKey !== "string")) throw httpError(400, "Invalid run request");
const { source } = await readNotebook(config, body.notebookPath);
const prepared = prepareRun(parseNotebook(source), body, await readHosts(config));
const { notebook } = await loadNotebook(config, body.notebookPath);
const prepared = prepareRun(notebook, body, await readHosts(config), await builtins());
const runId = randomUUID();
active.add(runId);
// Queue immediately; defer the work to allow the HTTP response to reach the subscriber.
+33 -4
View File
@@ -4,7 +4,7 @@ import { readFile, 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 { composeNotebook, notebookIncludes, parseNotebook, type HostInfo, type Notebook, type ParamValues } from "@shellbook/core";
import type { FastifyInstance } from "fastify";
import type { ServerConfig } from "../config";
@@ -43,6 +43,29 @@ export async function readNotebook(config: ServerConfig, name: string) {
return { file, source: await readFile(file, "utf8") };
}
/** Upper bound on notebook files read for one composition (includes of includes). */
const MAX_INCLUDE_FILES = 32;
/**
* Read a notebook and compose its `::use` includes. Included files go through the same
* workspace path rules; unreadable ones become "not found" diagnostics on the use line.
*/
export async function loadNotebook(config: ServerConfig, name: string) {
const { file, source } = await readNotebook(config, name);
const root = parseNotebook(source);
const parsed = new Map<string, Notebook | undefined>([[name, root]]);
const queue = notebookIncludes(root);
while (queue.length && parsed.size < MAX_INCLUDE_FILES) {
const next = queue.shift()!;
if (parsed.has(next)) continue;
const included = await readNotebook(config, next).then(r => parseNotebook(r.source), () => undefined);
parsed.set(next, included);
if (included) queue.push(...notebookIncludes(included));
}
const notebook = composeNotebook(name, root, include => parsed.get(include));
return { file, source, notebook, includes: [...parsed.keys()].filter(include => include !== name) };
}
export async function readHosts(config: ServerConfig): Promise<HostInfo[]> {
return parseHosts(await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8"));
}
@@ -72,7 +95,13 @@ export class SerialQueue {
async idle() { await Promise.allSettled(this.tails.values()); }
}
export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) {
export interface WorkspaceOptions {
config: ServerConfig;
/** Server-provided runtime values such as shellbook.public_key. */
builtins?: () => Promise<ParamValues>;
}
export async function workspacePlugin(app: FastifyInstance, { config, builtins = async () => ({}) }: WorkspaceOptions) {
const saves = new SerialQueue();
notebookManagement(app, config, saves);
app.get("/api/hosts", async () => ({ hosts: await readHosts(config) }));
@@ -93,8 +122,8 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config
return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) };
});
app.get<{ Params: { path: string } }>("/api/notebooks/:path", async req => {
const { source } = await readNotebook(config, req.params.path);
return { path: req.params.path, source, notebook: parseNotebook(source), version: version(source) };
const { source, notebook, includes } = await loadNotebook(config, req.params.path);
return { path: req.params.path, source, notebook, includes, builtins: await builtins(), version: version(source) };
});
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");
+159
View File
@@ -0,0 +1,159 @@
import { afterEach, describe, expect, it } from "vitest";
import { cp, mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { generateKeyPairSync } from "node:crypto";
import type { HostInfo, NotebookResponse, StartRunRequest } from "@shellbook/core";
import { findStep } from "@shellbook/core";
import { buildApp } from "../src/app";
import { loadConfig, type ServerConfig } from "../src/config";
import { prepareRun } from "../src/runs";
import { loadNotebook } from "../src/workspace";
const lxc = `---
title: LXC container
params:
proxmox: {type: host, required: true}
hostname: {type: name, required: true}
ROOTPW: {type: secret}
---
\`\`\`sh {run host="{{proxmox}}" id=create capture=address}
pct create --hostname {{hostname}} --key {{shellbook.public_key}} --pw "$ROOTPW"
\`\`\`
::host{name="{{hostname}}" address="{{address}}" capture=host}
`;
const service = `---
title: Web server
params:
target: {type: choice, options: [existing, lxc], default: lxc}
host: {type: host, required: true, default: "{{ct.host}}"}
TOKEN: {type: secret}
---
:::when{target=lxc}
::use{notebook="infra/lxc.md" as=ct with="hostname=web-ct"}
:::
\`\`\`sh {run host="{{host}}" id=install}
apt-get install -y nginx
\`\`\`
`;
const hosts: HostInfo[] = ["pve", "web-ct", "existing"].map(name => ({ name, address: "127.0.0.1", user: "root", port: 22, tags: [] }));
const cleanup: (() => Promise<unknown>)[] = [];
afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); });
async function fixture(files: Record<string, string> = { "infra/lxc.md": lxc, "services/web.md": service }) {
const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-chain-"));
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(path.join(config.workspaceDir, "notebooks"), { recursive: true });
for (const [name, source] of Object.entries(files)) {
await mkdir(path.dirname(path.join(config.workspaceDir, "notebooks", name)), { recursive: true });
await writeFile(path.join(config.workspaceDir, "notebooks", name), source);
}
await writeFile(path.join(config.workspaceDir, "hosts.yaml"), "- name: pve\n address: 127.0.0.1\n user: root\n");
await writeFile(config.sshKeyPath, generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString());
return config;
}
async function app(config: ServerConfig) {
const instance = await buildApp({ config, auth: false });
cleanup.push(() => instance.close());
return instance;
}
const request = (stepId: string, params: Record<string, string>, runtime: Record<string, string> = {}): StartRunRequest =>
({ notebookPath: "services/web.md", stepId, params, runtime, artifactSources: {} });
describe("chained notebooks on the server", () => {
it("returns the composed notebook with its includes and builtins", async () => {
const config = await fixture();
const res = await (await app(config)).inject("/api/notebooks/services%2Fweb.md");
expect(res.statusCode).toBe(200);
const body = res.json() as NotebookResponse;
expect(body.source).toBe(service);
expect(body.includes).toEqual(["infra/lxc.md"]);
expect(body.builtins["shellbook.public_key"]).toMatch(/^ssh-rsa AAAA/);
expect(body.notebook.diagnostics).toEqual([]);
expect(body.notebook.params.map(p => p.name)).toContain("ct.hostname");
expect(findStep(body.notebook.blocks, "ct.create")?.attrs.scope).toBe("ct");
});
it("reports a missing or unreadable include on the use line and refuses runs", async () => {
const config = await fixture({ "web.md": '::use{notebook="../escape.md" as=x}\n::use{notebook="gone.md" as=y}\n' });
const { notebook, includes } = await loadNotebook(config, "web.md");
expect(includes).toEqual(["gone.md"]);
expect(notebook.diagnostics.map(d => [d.line, d.message])).toEqual([
[1, 'use requires notebook="dir/name.md" (relative to notebooks/)'],
[2, "Included notebook not found: gone.md"],
]);
const res = await (await app(config)).inject({ method: "POST", url: "/api/runs", payload: { ...request("x", {}), notebookPath: "web.md" } });
expect(res.statusCode).toBe(400);
expect(res.json().message).toBe("Notebook has errors");
});
it("gates by scope, refuses inactive when sections and injects server builtins only", async () => {
const config = await fixture();
const { notebook } = await loadNotebook(config, "services/web.md");
const builtins = { "shellbook.public_key": "ssh-ed25519 SERVER" };
const values = { target: "lxc", "ct.proxmox": "pve", "ct.ROOTPW": "root-pw", TOKEN: "token" };
// The parent's host is still pending (captured later), which must not block the container step.
const prepared = prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, builtins);
expect(prepared.rendered.script).toBe("pct create --hostname web-ct --key 'ssh-ed25519 SERVER' --pw \"$ROOTPW\"\n");
expect(prepared.host?.name).toBe("pve");
expect(prepared.env).toEqual({ ROOTPW: "root-pw" });
expect(() => prepareRun(notebook, request("install", values), hosts, builtins)).toThrow("Parameters are missing or invalid");
const parent = prepareRun(notebook, request("install", values, { "ct.host": "web-ct" }), hosts, builtins);
expect(parent.host?.name).toBe("web-ct");
expect(parent.env).toEqual({ TOKEN: "token" });
// Container steps are refused when "existing host" is selected; the included form gates its own steps.
expect(() => prepareRun(notebook, request("ct.create", { ...values, target: "existing" }), hosts, builtins)).toThrow("Step is not part of the selected options");
expect(() => prepareRun(notebook, request("ct.create", { target: "lxc" }), hosts, builtins)).toThrow("Parameters are missing or invalid");
// Without a server key the builtin stays missing even if a client sends one.
expect(() => prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, {})).toThrow("Step parameters are missing or invalid");
});
it("lets an optional parameter wait for a capture without blocking the step that captures it", async () => {
const config = await fixture({ "next.md": `---
params:
proxmox: {type: host, required: true}
ctid: {type: name, default: "{{nextid}}"}
---
\`\`\`sh {check host="{{proxmox}}" id=next capture=nextid}
pvesh get /cluster/nextid
\`\`\`
\`\`\`sh {run host="{{proxmox}}" id=create}
pct create {{ctid}}
\`\`\`
` });
const { notebook } = await loadNotebook(config, "next.md");
const run = (stepId: string, runtime: Record<string, string> = {}) =>
prepareRun(notebook, { notebookPath: "next.md", stepId, params: { proxmox: "pve" }, runtime, artifactSources: {} }, hosts);
expect(run("next").rendered.script).toBe("pvesh get /cluster/nextid\n");
expect(() => run("create")).toThrow("Step parameters are missing or invalid");
expect(run("create", { nextid: "105" }).rendered.script).toBe("pct create 105\n");
});
it("ships template notebooks that compose without diagnostics", async () => {
const config = await fixture({});
await cp(path.resolve(__dirname, "../../../templates/workspace/notebooks"), path.join(config.workspaceDir, "notebooks"), { recursive: true });
const names = ["base-hardening-checks.md", "install-package.md", "ssh-key.md", "infra/lxc-container.md", "services/web-server.md"];
for (const name of names) expect((await loadNotebook(config, name)).notebook.diagnostics, name).toEqual([]);
const { notebook, includes } = await loadNotebook(config, "services/web-server.md");
expect(includes).toEqual(["infra/lxc-container.md"]);
const values = { target: "lxc", server_name: "web", "ct.proxmox": "pve", "ct.net": "ip=10.0.30.160/24,gw=10.0.30.1" };
const runtime = { "ct.nextid": "105", "ct.template": "local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst" };
const prepared = prepareRun(notebook, request("ct.create", values, runtime), hosts, { "shellbook.public_key": "ssh-ed25519 AAAAKEY shellbook" });
expect(prepared.rendered.script).toContain("printf '%s\\n' 'ssh-ed25519 AAAAKEY shellbook' > \"$keys\"");
expect(prepared.rendered.script).toContain("pct create 105 local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst \\\n --hostname web \\");
expect(prepared.rendered.script).toContain("--net0 name=eth0,bridge=vmbr0,'ip=10.0.30.160/24,gw=10.0.30.1'");
expect(() => prepareRun(notebook, request("install", { ...values, target: "existing" }), hosts, {})).toThrow("Parameters are missing or invalid");
expect(prepareRun(notebook, request("install", { target: "existing", host: "existing" }), hosts, {}).host?.name).toBe("existing");
});
it("refuses an inactive step over HTTP", async () => {
const config = await fixture();
const res = await (await app(config)).inject({ method: "POST", url: "/api/runs", payload: request("ct.create", { target: "existing", "ct.proxmox": "pve" }) });
expect(res.statusCode).toBe(400);
expect(res.json().message).toBe("Step is not part of the selected options");
});
});
+7 -2
View File
@@ -13,7 +13,9 @@ import { SerialQueue, safeRelative } from "../src/workspace";
import { connect, exec, fingerprint, HostKeyError, localExec, scriptInput } from "../src/ssh";
import { executeRun, EventsHub, prepareRun, redactor } from "../src/runs";
vi.mock("@shellbook/core", () => ({
vi.mock("@shellbook/core", async importOriginal => ({
// Composition helpers stay real; parsing and rendering are stubbed per test.
...pick(await importOriginal<typeof import("@shellbook/core")>(), "composeNotebook", "notebookIncludes", "findStep", "blockActive", "isBuiltin"),
parseNotebook: vi.fn((source: string) => ({ title: source.split("\n")[0], params: [], blocks: [], diagnostics: [] })),
shellQuote: (value: string) => /^[A-Za-z0-9._/@:=+-]+$/.test(value) ? value : "'" + value.replaceAll("'", "'\\''") + "'",
resolveParams: vi.fn((_notebook: Notebook, values: Record<string, string>) => ({ values, errors: {} })),
@@ -21,6 +23,9 @@ vi.mock("@shellbook/core", () => ({
secretEnv: vi.fn(() => ({})),
}));
function pick<T extends object, K extends keyof T>(object: T, ...keys: K[]) {
return Object.fromEntries(keys.map(key => [key, object[key]])) as Pick<T, K>;
}
const cleanup: (() => Promise<unknown>)[] = [];
afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); vi.clearAllMocks(); });
async function fixture() {
@@ -175,7 +180,7 @@ describe("pipeline helpers", () => {
expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: -1 });
});
it("refuses missing or invalid parameters before execution", () => {
const notebook: Notebook = { title: "Test", params: [], blocks: [{ type: "step", step: step() }], diagnostics: [] };
const notebook: Notebook = { title: "Test", params: [{ name: "required", type: "string", required: true }], blocks: [{ type: "step", step: step() }], diagnostics: [] };
vi.mocked(resolveParams).mockReturnValueOnce({ values: {}, errors: { required: "missing" } });
expect(() => prepareRun(notebook, request(), [])).toThrow("Parameters are missing or invalid");
vi.mocked(renderStep).mockReturnValueOnce({ ...rendered(), missing: ["required"] });
+98 -24
View File
@@ -13,10 +13,14 @@ import {
} from "react";
import ReactMarkdown from "react-markdown";
import {
blockActive,
notebookIncludes,
parseNotebook,
renderHost,
renderStep,
renderText,
resolveParams,
scopeActive,
} from "@shellbook/core";
import type {
Block,
@@ -34,7 +38,8 @@ import { HostsPage } from "./HostsPage";
import { HttpError } from "./api";
import type { Api } from "./api";
import { emptySession, eventReducer, stepKey } from "./events";
import { ParamsForm } from "./ParamsForm";
import { ParamsForm, type ParamGroup } from "./ParamsForm";
import { HostBlockCard } from "./HostBlockCard";
import { StepCard } from "./StepCard";
import { ChatPanel } from "./ChatPanel";
const TerminalSlot = lazy(() =>
@@ -48,8 +53,18 @@ function steps(blocks: Block[]): Step[] {
return blocks.flatMap((block) =>
block.type === "step"
? [block.step]
: block.type === "after"
? steps(block.blocks)
: block.type === "markdown" || block.type === "host"
? []
: steps(block.blocks),
);
}
/** Included notebooks (`::use`, nested too) as parameter groups. */
function includedGroups(blocks: Block[]): ParamGroup[] {
return blocks.flatMap((block): ParamGroup[] =>
block.type === "use"
? [{ scope: block.scope, title: `${block.title ?? block.path} (${block.scope})` }, ...includedGroups(block.blocks)]
: block.type === "after" || block.type === "when"
? includedGroups(block.blocks)
: [],
);
}
@@ -146,7 +161,10 @@ export function App({ api }: { api: Api }) {
})
.catch((e) => setError(String(e)));
}
if (event.type === "file.changed" && event.path === open.doc?.path) {
// A changed included notebook changes the composed one; a draft keeps its own copy.
if (event.type === "file.changed" && event.path !== open.doc?.path && open.doc?.includes.includes(event.path)) {
if (!open.dirty) void load(open.doc.path);
} else if (event.type === "file.changed" && event.path === open.doc?.path) {
if (open.dirty) setConflict(true);
else void load(event.path);
} else if (
@@ -173,20 +191,31 @@ export function App({ api }: { api: Api }) {
return () => window.removeEventListener("beforeunload", guard);
}, [dirty]);
// The saved notebook comes composed from the server; a draft shows its includes after saving.
const notebook = doc
? edit
? edit && source !== doc.source
? parseNotebook(source)
: doc.notebook
: undefined;
const resolved = notebook
? resolveParams(
notebook,
values,
hosts.map((h) => h.name),
)
: { values: {}, errors: {} };
const path = doc?.path ?? "";
const runtime = session.runtime[path] ?? {};
const hostNames = hosts.map((h) => h.name);
const sessionRuntime = session.runtime[path] ?? {};
// Builtins ({{shellbook.public_key}}) come from the server, which also sets them on runs.
const runtime = { ...sessionRuntime, ...doc?.builtins };
const resolved = notebook
? resolveParams(notebook, values, hostNames, runtime)
: { values: {}, errors: {} };
const active = (id: string) => !!notebook && blockActive(notebook, id, resolved.values);
const groups = notebook
? includedGroups(notebook.blocks).filter((group) => scopeActive(notebook, group.scope, resolved.values))
: [];
const activeChecks = notebook
? steps(notebook.blocks).filter((s) => s.kind === "check" && active(s.attrs.id))
: [];
const runnable = (step: Step) => {
const rendered = renderStep(notebook!, step, resolved.values, runtime, hostNames);
return !rendered.missing.length && !Object.keys(rendered.invalid).length;
};
const runFor = (id: string) =>
session.runs[session.latest[stepKey(path, id)] ?? ""];
async function start(request: StartRunRequest) {
@@ -207,13 +236,13 @@ export function App({ api }: { api: Api }) {
}
}
function requestRun(step: Step) {
if (!notebook || !doc || dirty) return;
if (!notebook || !doc || dirty || !active(step.attrs.id)) return;
const rendered = renderStep(
notebook,
step,
resolved.values,
runtime,
hosts.map((h) => h.name),
hostNames,
);
if (
rendered.missing.length ||
@@ -225,7 +254,7 @@ export function App({ api }: { api: Api }) {
notebookPath: path,
stepId: step.attrs.id,
params: { ...resolved.values },
runtime: { ...runtime },
runtime: { ...sessionRuntime },
artifactSources: { ...session.artifactSources[path] },
};
const host = hosts.find((h) => h.name === rendered.host);
@@ -251,6 +280,49 @@ export function App({ api }: { api: Api }) {
</ReactMarkdown>
</div>
);
if (block.type === "when")
return block.values.includes(resolved.values[block.param] ?? "") ? (
<div className="when" key={i}>
{blocks(block.blocks)}
</div>
) : null;
if (block.type === "use")
return (
<details className="included" open key={i}>
<summary>
{block.title ?? block.path}
<small>
{block.path} · as {block.scope}
</small>
</summary>
{block.blocks.length ? (
blocks(block.blocks)
) : (
<p className="muted">Save the notebook to load {block.path}.</p>
)}
</details>
);
if (block.type === "host") {
const rendered = renderHost(notebook, block, resolved.values, runtime, hostNames);
const capture = (name: string) => {
if (block.capture) dispatch({ type: "runtime.set", notebookPath: path, name: block.capture, value: name });
};
return (
<HostBlockCard
key={block.id}
rendered={rendered}
existing={hosts.find((h) => h.name === rendered.name)}
captured={block.capture ? runtime[block.capture] : undefined}
onUse={capture}
onAdd={async (host) => {
await api.addHost(host);
setHosts((await api.hosts()).hosts);
window.dispatchEvent(new Event("shellbook:hosts-changed"));
capture(host.name);
}}
/>
);
}
if (block.type === "after") {
const run = runFor(block.stepId);
return run &&
@@ -265,7 +337,7 @@ export function App({ api }: { api: Api }) {
block.step,
resolved.values,
runtime,
hosts.map((h) => h.name),
hostNames,
);
return (
<StepCard
@@ -292,13 +364,16 @@ export function App({ api }: { api: Api }) {
if (!doc) return;
try {
const saved = await api.save(path, source, doc.version);
const parsed = parseNotebook(source);
setDoc({
...doc,
source,
notebook: parseNotebook(source),
notebook: parsed,
version: saved.version,
});
setConflict(false);
// Includes are composed on the server: reload to show them.
if (notebookIncludes(parsed).length || doc.includes.length) await load(path);
} catch (e) {
if (e instanceof HttpError && e.status === 409) setConflict(true);
else setError(String(e));
@@ -428,6 +503,7 @@ export function App({ api }: { api: Api }) {
values={resolved.values}
errors={resolved.errors}
hosts={hosts}
groups={groups}
onChange={(name, value) =>
setValues((previous) => ({ ...previous, [name]: value }))
}
@@ -472,7 +548,8 @@ export function App({ api }: { api: Api }) {
disabled={
!connected ||
dirty ||
Object.keys(resolved.errors).length > 0 ||
activeChecks.length === 0 ||
!activeChecks.every(runnable) ||
steps(notebook.blocks).some(
(s) =>
runFor(s.attrs.id)?.status === "running" ||
@@ -480,11 +557,8 @@ export function App({ api }: { api: Api }) {
)
}
onClick={() => {
const checks = steps(notebook.blocks).filter(
(s) => s.kind === "check",
);
setCheckIds(checks.map((s) => s.attrs.id));
checks.forEach(requestRun);
setCheckIds(activeChecks.map((s) => s.attrs.id));
activeChecks.forEach(requestRun);
}}
>
Run all checks
+67
View File
@@ -3,8 +3,11 @@ import { parseNotebook, type ParamDef } from "@shellbook/core";
import {
addParameter,
afterSnippet,
hostSnippet,
notebookSteps,
stepSnippet,
useSnippet,
whenSnippet,
type InsertKind,
} from "./authoring";
export function AuthoringToolbar({
@@ -23,7 +26,13 @@ export function AuthoringToolbar({
const [error, setError] = useState("");
const [type, setType] = useState<ParamDef["type"]>("string");
const [after, setAfter] = useState("");
const [when, setWhen] = useState("");
const [include, setInclude] = useState(false);
const steps = notebookSteps(notebook.blocks);
const choices = notebook.params.flatMap((p) =>
p.type === "choice" ? (p.options ?? []).map((o) => ({ param: p.name, option: o })) : [],
);
const selected = choices.find((c) => JSON.stringify([c.param, c.option]) === when);
return (
<div className="authoring">
<label>
@@ -77,6 +86,56 @@ export function AuthoringToolbar({
>
Insert after note
</button>
<label>
Show when
<select value={when} onChange={(e) => setWhen(e.target.value)}>
<option value="">Choose an option</option>
{choices.map((c) => (
<option key={JSON.stringify([c.param, c.option])} value={JSON.stringify([c.param, c.option])}>
{c.param} = {c.option}
</option>
))}
</select>
</label>
<button
type="button"
disabled={!selected}
onClick={() => selected && insert(whenSnippet(selected.param, selected.option))}
>
Insert when section
</button>
<button type="button" onClick={() => setInclude(!include)}>
Use notebook
</button>
<button type="button" onClick={() => insert(hostSnippet())}>
Add host
</button>
{include && (
<form
aria-label="Use notebook"
onSubmit={(e) => {
e.preventDefault();
const data = new FormData(e.currentTarget);
try {
insert(useSnippet(String(data.get("path")), String(data.get("alias"))));
setInclude(false);
setError("");
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
}}
>
<label>
Notebook path
<input name="path" required placeholder="infra/lxc-container.md" />
</label>
<label>
Alias
<input name="alias" required pattern="[A-Za-z_][A-Za-z0-9_]*" placeholder="ct" />
</label>
<button>Insert include</button>
</form>
)}
{param && (
<form
onSubmit={(e) => {
@@ -160,6 +219,14 @@ export function AuthoringToolbar({
upload="file.txt:/tmp/file.txt". After notes appear when their
selected step succeeds.
</p>
<p>
Chaining: {'::use{notebook="infra/lxc-container.md" as=ct with="hostname={{name}}"}'}{" "}
includes another notebook; its parameters appear as ct.name and its
captures as {"{{ct.address}}"}. {":::when{target=lxc}"} … {":::"} shows a
section only for that choice. {'::host{name="{{hostname}}" address="{{address}}" capture=host}'}{" "}
adds a created machine to Hosts. {"{{shellbook.public_key}}"} is
ShellBook's SSH public key.
</p>
<p>
Artifact and upload snippets are examples: choose files and commands
appropriate to your runbook before running.
+99
View File
@@ -0,0 +1,99 @@
import { useState } from "react";
import type { HostInfo, RenderedHost } from "@shellbook/core";
/**
* A notebook's `::host` block: adds the machine a notebook created (e.g. an LXC container)
* to Hosts, so later steps can target it. Never overwrites a different existing host.
*/
export function HostBlockCard({
rendered,
existing,
captured,
onAdd,
onUse,
}: {
rendered: RenderedHost;
/** Host with the same name already in Hosts. */
existing?: HostInfo;
/** Runtime value of the block's capture, if any. */
captured?: string;
onAdd(host: HostInfo): Promise<void>;
onUse(name: string): void;
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const problems = Object.entries(rendered.invalid);
const ready = !rendered.missing.length && !problems.length;
const same =
!!existing &&
existing.address === rendered.address &&
existing.user === rendered.user &&
existing.port === rendered.port;
async function add() {
setBusy(true);
setError("");
try {
await onAdd({
name: rendered.name,
address: rendered.address,
user: rendered.user,
port: rendered.port,
tags: [],
});
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
}
return (
<article className="step host-block" aria-label={`Add host ${rendered.name}`}>
<header>
<strong>Add to Hosts</strong>
<code>
{rendered.user}@{rendered.address}:{rendered.port}
</code>
<span>as {rendered.name}</span>
</header>
{rendered.missing.length > 0 && (
<p className="muted">
Available after: {rendered.missing.join(", ")}
</p>
)}
{problems.map(([field, message]) => (
<p className="error" key={field}>
{message}
</p>
))}
{ready &&
(existing ? (
same ? (
captured === existing.name ? (
<p role="status">✓ {existing.name} is in Hosts</p>
) : (
<button onClick={() => onUse(existing.name)}>
Use existing host {existing.name}
</button>
)
) : (
<p className="error" role="alert">
A different host named {rendered.name} already exists. Choose
another name or change it under Hosts.
</p>
)
) : (
<button className="primary" disabled={busy} onClick={() => void add()}>
{busy ? "Adding…" : "Add to Hosts"}
</button>
))}
{error && (
<p className="error" role="alert">
{error}
</p>
)}
<p className="muted">
The first connection asks you to confirm the new server's host key.
</p>
</article>
);
}
+65 -45
View File
@@ -1,68 +1,88 @@
import type { HostInfo, Notebook, ParamValues } from "@shellbook/core";
import type { HostInfo, Notebook, ParamDef, ParamValues } from "@shellbook/core";
/** An included notebook (`::use`) whose parameters the form shows as a group. */
export interface ParamGroup {
scope: string;
title: string;
}
export function ParamsForm({
notebook,
values,
errors,
hosts,
groups = [],
onChange,
}: {
notebook: Notebook;
values: ParamValues;
errors: Record<string, string>;
hosts: HostInfo[];
/** Active included notebooks; parameters of inactive ones are hidden. */
groups?: ParamGroup[];
onChange(name: string, value: string): void;
}) {
const field = (param: ParamDef) => {
const id = `param-${param.name}`;
const local = param.scope ? param.name.slice(param.scope.length + 1) : param.name;
const common = {
id,
required: param.required,
value: values[param.name] ?? "",
"aria-labelledby": `${id}-label`,
"aria-invalid": !!errors[param.name],
"aria-describedby": errors[param.name] ? `${id}-error` : undefined,
onChange: (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => onChange(param.name, e.target.value),
};
return (
<label key={param.name} htmlFor={id}>
<span id={`${id}-label`}>
{param.label ?? local}
{param.required && <b title="Required"> *</b>}
</span>
{param.type === "host" || param.type === "choice" ? (
<select {...common}>
<option value="">Select…</option>
{(param.type === "host"
? hosts.map((h) => h.name)
: (param.options ?? [])
).map((option) => (
<option key={option}>{option}</option>
))}
</select>
) : (
<input
{...common}
type={param.type === "secret" ? "password" : "text"}
autoComplete={param.type === "secret" ? "new-password" : "off"}
spellCheck={false}
/>
)}
{errors[param.name] && (
<small id={`${id}-error`} className="error">
{errors[param.name]}
</small>
)}
</label>
);
};
return (
<form
className="params"
aria-label="Notebook parameters"
onSubmit={(e) => e.preventDefault()}
>
{notebook.params.map((param) => {
const id = `param-${param.name}`;
const common = {
id,
required: param.required,
value: values[param.name] ?? "",
"aria-labelledby": `${id}-label`,
"aria-invalid": !!errors[param.name],
"aria-describedby": errors[param.name] ? `${id}-error` : undefined,
onChange: (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => onChange(param.name, e.target.value),
};
return (
<label key={param.name} htmlFor={id}>
<span id={`${id}-label`}>
{param.label ?? param.name}
{param.required && <b title="Required"> *</b>}
</span>
{param.type === "host" || param.type === "choice" ? (
<select {...common}>
<option value="">Select…</option>
{(param.type === "host"
? hosts.map((h) => h.name)
: (param.options ?? [])
).map((option) => (
<option key={option}>{option}</option>
))}
</select>
) : (
<input
{...common}
type={param.type === "secret" ? "password" : "text"}
autoComplete={param.type === "secret" ? "new-password" : "off"}
spellCheck={false}
/>
)}
{errors[param.name] && (
<small id={`${id}-error`} className="error">
{errors[param.name]}
</small>
)}
</label>
);
{notebook.params.filter((param) => !param.scope).map(field)}
{groups.map((group) => {
const params = notebook.params.filter((param) => param.scope === group.scope);
return params.length ? (
<fieldset key={group.scope}>
<legend>{group.title}</legend>
{params.map(field)}
</fieldset>
) : null;
})}
</form>
);
+10
View File
@@ -1,4 +1,7 @@
import type {
HostInfo,
HostInventoryResponse,
SaveHostRequest,
NotebookListResponse,
HostsResponse,
NotebookResponse,
@@ -66,6 +69,8 @@ export interface Api {
baseVersion: string,
): Promise<SaveNotebookResponse>;
run(request: StartRunRequest): Promise<StartRunResponse>;
/** Add a host to the inventory (a notebook's `::host` block); 409 if the name is taken. */
addHost(host: HostInfo): Promise<void>;
events(
receive: (event: ServerEvent) => void,
connection: (connected: boolean) => void,
@@ -93,6 +98,11 @@ export const liveApi: Api = {
baseVersion,
}),
run: (request) => json("/runs", "POST", request),
async addHost(host) {
const { version } = await json<HostInventoryResponse>("/host-management");
const request: SaveHostRequest = { host, baseVersion: version };
await json("/host-management", "POST", request);
},
artifact: (id, name) =>
`/api/runs/${encodeURIComponent(id)}/artifacts/${encodeURIComponent(name)}`,
events(receive, connection) {
+19 -3
View File
@@ -1,5 +1,6 @@
import { isMap, parseDocument } from "yaml";
import {
includePath,
parseNotebook,
type Block,
type ParamDef,
@@ -9,9 +10,9 @@ export function notebookSteps(blocks: Block[]): Step[] {
return blocks.flatMap((b) =>
b.type === "step"
? [b.step]
: b.type === "after"
? notebookSteps(b.blocks)
: [],
: b.type === "markdown" || b.type === "host"
? []
: notebookSteps(b.blocks),
);
}
const attr = (value: string) =>
@@ -60,6 +61,21 @@ export function stepSnippet(
export function afterSnippet(id: string): string {
return `\n\n:::after{step=${attr(id)}}\nAdd follow-up instructions here.\n:::\n`;
}
/** A section shown (and runnable) only while a choice parameter has this value. */
export function whenSnippet(param: string, value: string): string {
return `\n\n:::when{${param}=${attr(value)}}\nShown only when ${param} is ${value.replace(/[\r\n]/g, " ")}.\n:::\n`;
}
/** Include another notebook; its parameters and steps are namespaced as alias.name. */
export function useSnippet(path: string, alias: string): string {
if (!includePath(path)) throw new Error("Notebook path must be dir/name.md relative to notebooks/");
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(alias) || alias === "shellbook")
throw new Error("Alias must use letters, digits or _ (not shellbook)");
return `\n\n::use{notebook=${attr(path)} as=${alias}}\n`;
}
/** Add the machine a notebook created to Hosts; replace the example templates. */
export function hostSnippet(): string {
return '\n\n::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}\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");
+14 -1
View File
@@ -41,10 +41,23 @@ export type Action =
state: DownloadState;
}
| ServerEvent
| { type: "requested"; runId: string; request: StartRunRequest };
| { type: "requested"; runId: string; request: StartRunRequest }
/** A runtime value set in the browser, e.g. by a `::host` block's capture. */
| { type: "runtime.set"; notebookPath: string; name: string; value: string };
export function eventReducer(state: Session, event: Action): Session {
if (event.type === "file.changed" || event.type === "file.deleted")
return state;
if (event.type === "runtime.set")
return {
...state,
runtime: {
...state.runtime,
[event.notebookPath]: {
...state.runtime[event.notebookPath],
[event.name]: event.value,
},
},
};
if (event.type === "requested" || event.type === "run.started") {
const info = event.type === "requested" ? event.request : event;
const previous = state.runs[event.runId];
+12 -8
View File
@@ -1,7 +1,7 @@
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
import type { Api } from "../api";
import { HttpError } from "../api";
import { parseNotebook, renderStep } from "@shellbook/core";
import { findStep, parseNotebook, renderStep } from "@shellbook/core";
import initial from "./ssh-key.md?raw";
let source = initial;
let version = 1;
@@ -50,8 +50,14 @@ export const mockApi: Api = {
path,
source,
notebook: parseNotebook(source),
includes: [],
builtins: { "shellbook.public_key": "ssh-ed25519 AAAADEMO shellbook" },
version: String(version),
}),
addHost: async (host) => {
if (hosts.some((h) => h.name === host.name)) throw new HttpError(409, "Host already exists");
hosts.push({ ...host });
},
save: async (_path, next, base) => {
if (base !== String(version)) throw new HttpError(409);
source = next;
@@ -68,13 +74,11 @@ export const mockApi: Api = {
artifact: () => artifactUrl,
run: async (request: StartRunRequest) => {
const notebook = parseNotebook(source);
const block = notebook.blocks.find(
(b) => b.type === "step" && b.step.attrs.id === request.stepId,
);
if (!block || block.type !== "step") throw new Error("Unknown demo step");
const step = findStep(notebook.blocks, request.stepId);
if (!step) throw new Error("Unknown demo step");
const rendered = renderStep(
notebook,
block.step,
step,
request.params,
request.runtime,
hosts.map((h) => h.name),
@@ -125,8 +129,8 @@ export const mockApi: Api = {
request.stepId === "keygen"
? rendered.artifacts.filter((name) => !name.endsWith(".pub"))
: [],
captured: block.step.attrs.capture
? { name: block.step.attrs.capture, value: "demo-value" }
captured: step.attrs.capture
? { name: step.attrs.capture, value: "demo-value" }
: undefined,
});
}, 850);
+42
View File
@@ -152,6 +152,25 @@ main {
.params b {
color: var(--accent);
}
.params {
max-height: 40vh;
overflow-y: auto;
}
.params fieldset {
flex-basis: 100%;
display: flex;
flex-wrap: wrap;
gap: 12px;
margin: 0;
border: 1px solid var(--line);
border-radius: 6px;
padding: 8px 12px 12px;
}
.params legend {
font-size: 12px;
color: var(--muted);
padding: 0 4px;
}
.notebook {
max-width: 1100px;
margin: auto;
@@ -279,6 +298,29 @@ a {
border-left: 3px solid var(--accent);
padding-left: 18px;
}
/* Chained notebooks (::use): the included notebook, collapsible. */
.included {
border: 1px dashed var(--line);
border-radius: 7px;
padding: 4px 18px;
margin: 20px 0;
}
.included > summary {
cursor: pointer;
padding: 10px 0;
font-weight: 600;
}
.included > summary small {
font-weight: normal;
color: var(--muted);
margin-left: 8px;
}
.host-block > p {
margin: 10px 16px;
}
.host-block > button {
margin: 10px 16px;
}
.banner {
padding: 14px 24px;
background: var(--panel);
+7
View File
@@ -62,9 +62,12 @@ function harness() {
path: "ssh-key.md",
source,
notebook: parseNotebook(source),
includes: [],
builtins: {},
version: "1",
}),
save: vi.fn().mockResolvedValue({ version: "2" }),
addHost: vi.fn().mockResolvedValue(undefined),
run: vi.fn(async (_request: StartRunRequest) => ({ runId: String(++id) })),
events: (callback, connected) => {
receive = callback;
@@ -215,6 +218,8 @@ it("retains edits made while a file reload is in flight", async () => {
path: "ssh-key.md",
source,
notebook: parseNotebook(source),
includes: [],
builtins: {},
version: "2",
}),
);
@@ -247,6 +252,8 @@ Key generation failed. Retry safely.
path: "ssh-key.md",
source: captureSource,
notebook: parseNotebook(captureSource),
includes: [],
builtins: {},
version: "1",
});
await ready(api);
+11
View File
@@ -78,3 +78,14 @@ it("adds frontmatter when absent and rejects invalid YAML or secret defaults", (
}),
).toThrow();
});
it("generates valid chaining snippets", async () => {
const { whenSnippet, useSnippet, hostSnippet } = await import("../authoring");
const base = "---\nparams:\n target: {type: choice, options: [existing, lxc]}\n hostname: {type: name}\n address: {type: string}\n---\n";
const source = base + whenSnippet("target", "lxc") + useSnippet("infra/lxc-container.md", "ct") + hostSnippet();
const notebook = parseNotebook(source);
expect(notebook.diagnostics).toEqual([]);
expect(notebook.blocks.map((b) => b.type).filter((t) => t !== "markdown")).toEqual(["when", "use", "host"]);
expect(() => useSnippet("../x.md", "ct")).toThrow("dir/name.md");
expect(() => useSnippet("x.md", "shellbook")).toThrow("Alias");
});
+106
View File
@@ -0,0 +1,106 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { expect, it, vi } from "vitest";
vi.mock("../Editor", () => ({ Editor: () => null }));
import { App } from "../App";
import type { Api } from "../api";
import type { HostInfo, ServerEvent, StartRunRequest } from "@shellbook/core";
import { composeNotebook, parseNotebook } from "@shellbook/core";
const lxc = `---
title: LXC container
params:
proxmox: {type: host, required: true}
hostname: {type: name, required: true}
---
\`\`\`sh {run host="{{proxmox}}" id=create title="Create container" capture=address}
pct create --hostname {{hostname}} --key {{shellbook.public_key}}
\`\`\`
::host{name="{{hostname}}" address="{{address}}" capture=host}
`;
const service = `---
title: Web server
params:
target: {type: choice, options: [existing, lxc], default: existing}
host: {type: host, required: true, default: "{{ct.host}}"}
---
:::when{target=lxc}
::use{notebook="infra/lxc.md" as=ct with="hostname=web-ct"}
:::
\`\`\`sh {check host="{{host}}" id=installed title="Is nginx installed"}
command -v nginx
\`\`\`
`;
const files: Record<string, string> = { "infra/lxc.md": lxc };
const composed = composeNotebook("web.md", parseNotebook(service), p => files[p] === undefined ? undefined : parseNotebook(files[p]!));
function harness() {
let receive: (event: ServerEvent) => void = () => {};
const hosts: HostInfo[] = [{ name: "pve", address: "10.0.0.2", user: "root", port: 22, tags: [] }];
const api: Api = {
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
me: vi.fn().mockResolvedValue({}),
login: vi.fn(),
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "web.md", title: "Web server" }] }),
hosts: vi.fn(async () => ({ hosts: [...hosts] })),
notebook: vi.fn().mockResolvedValue({
path: "web.md", source: service, notebook: composed, includes: ["infra/lxc.md"],
builtins: { "shellbook.public_key": "ssh-ed25519 AAAA shellbook" }, version: "1",
}),
save: vi.fn(),
run: vi.fn(async (_request: StartRunRequest) => ({ runId: "1" })),
addHost: vi.fn(async (host: HostInfo) => { hosts.push(host); }),
events: (callback, connected) => { receive = callback; connected(true); return () => {}; },
artifact: () => "/download",
};
return { api, emit: (event: ServerEvent) => act(() => receive(event)) };
}
it("shows the included notebook and its parameters only for the selected option", async () => {
const { api } = harness();
render(<App api={api} />);
const target = await screen.findByLabelText("target");
expect(screen.queryByRole("article", { name: "Create container" })).not.toBeInTheDocument();
expect(screen.queryByRole("group", { name: "LXC container (ct)" })).not.toBeInTheDocument();
fireEvent.change(target, { target: { value: "lxc" } });
const group = screen.getByRole("group", { name: "LXC container (ct)" });
expect(within(group).getByLabelText("hostname *")).toHaveValue("web-ct");
fireEvent.change(within(group).getByLabelText("proxmox *"), { target: { value: "pve" } });
const create = screen.getByRole("article", { name: "Create container" });
expect(create).toHaveTextContent("pct create --hostname web-ct --key 'ssh-ed25519 AAAA shellbook'");
// The parent's host waits for the container; the parent's checks cannot run yet.
expect(screen.getByText("Available after the step that sets ct.host")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Run all checks" })).toBeDisabled();
});
it("adds the created container to Hosts and feeds it into the parent's steps", async () => {
const { api, emit } = harness();
render(<App api={api} />);
fireEvent.change(await screen.findByLabelText("target"), { target: { value: "lxc" } });
fireEvent.change(screen.getByLabelText("proxmox *"), { target: { value: "pve" } });
const card = screen.getByRole("article", { name: "Add host web-ct" });
expect(card).toHaveTextContent("Available after: ct.address");
fireEvent.click(within(screen.getByRole("article", { name: "Create container" })).getByRole("button", { name: "Run" }));
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(1));
const request = vi.mocked(api.run).mock.calls[0]![0];
expect(request).toMatchObject({ stepId: "ct.create", params: { target: "lxc", "ct.proxmox": "pve", "ct.hostname": "web-ct" } });
// Builtins are the server's; the client never sends them.
expect(request.runtime).toEqual({});
emit({ type: "run.finished", runId: "1", exitCode: 0, durationMs: 5, artifacts: [], captured: { name: "ct.address", value: "10.0.30.160" } });
fireEvent.click(within(card).getByRole("button", { name: "Add to Hosts" }));
await waitFor(() => expect(api.addHost).toHaveBeenCalledWith({ name: "web-ct", address: "10.0.30.160", user: "root", port: 22, tags: [] }));
expect(await within(card).findByRole("status")).toHaveTextContent("web-ct is in Hosts");
expect(screen.getByLabelText("host *")).toHaveValue("web-ct");
expect(screen.getByRole("article", { name: "Is nginx installed" })).toHaveTextContent("web-ct");
expect(screen.getByRole("button", { name: "Run all checks" })).toBeEnabled();
});
it("reloads when an included notebook changes", async () => {
const { api, emit } = harness();
render(<App api={api} />);
await screen.findByLabelText("target");
expect(api.notebook).toHaveBeenCalledTimes(1);
emit({ type: "file.changed", path: "infra/lxc.md" });
await waitFor(() => expect(api.notebook).toHaveBeenCalledTimes(2));
});
+16
View File
@@ -59,6 +59,22 @@ if [[ -z $(find "$workspace" -mindepth 1 -maxdepth 1 -print -quit) ]]; then
chown -R shellbook:shellbook "$workspace"
runuser -u shellbook -- git -C "$workspace" init
fi
# Offer each shipped notebook template once: updates bring new templates into existing
# workspaces, but never overwrite files or bring back ones the user deleted. The copy runs
# as the service user, so links inside the workspace cannot redirect a root write.
offer_templates() { # <templates dir> <workspace> <offered list>
local file rel
touch "$3"
[[ -d $1/notebooks ]] || return 0
while IFS= read -r -d '' file; do
rel=${file#"$1"/}
grep -qxF -- "$rel" "$3" && continue
runuser -u shellbook -- bash -c 'test -e "$2" || test -L "$2" || install -D -m 644 "$1" "$2"' _ "$file" "$2/$rel"
printf '%s\n' "$rel" >> "$3"
done < <(find "$1/notebooks" -type f -name '*.md' -print0 | sort -z)
}
install -d -m 0750 /etc/shellbook
offer_templates /opt/shellbook/templates/workspace "$workspace" /etc/shellbook/templates-offered
if [[ ! -f /home/shellbook/.ssh/id_ed25519 ]]; then
runuser -u shellbook -- ssh-keygen -q -t ed25519 -N '' -f /home/shellbook/.ssh/id_ed25519 -C shellbook
fi
+18 -1
View File
@@ -20,4 +20,21 @@ grep -q 'git_app pull --ff-only' "$dir/install.sh" || { echo 'install.sh: existi
# Nothing may remain in the CT's /root after the Proxmox install.
grep -q 'rm -f /root/shellbook-install.env /root/shellbook-install.sh' "$dir/proxmox/create-ct.sh" \
|| { echo 'create-ct.sh: installer files left in the CT' >&2; exit 1; }
printf '8 install script checks passed\n'
# Templates: new ones reach existing workspaces once; existing and deleted files stay as they are.
offer=$(sed -n '/^offer_templates() {/,/^}$/p' "$dir/install.sh")
[[ -n $offer ]] || { echo 'install.sh: offer_templates missing' >&2; exit 1; }
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
(
runuser() { shift 3; "$@"; } # stub: run as the current user
eval "$offer"
mkdir -p "$tmp/t/notebooks/infra" "$tmp/w/notebooks"
printf 'new\n' > "$tmp/t/notebooks/infra/lxc.md"; printf 'shipped\n' > "$tmp/t/notebooks/a.md"
printf 'mine\n' > "$tmp/w/notebooks/a.md"
offer_templates "$tmp/t" "$tmp/w" "$tmp/offered"
[[ $(cat "$tmp/w/notebooks/a.md") == mine && $(cat "$tmp/w/notebooks/infra/lxc.md") == new ]] || { echo 'offer_templates: wrong copy' >&2; exit 1; }
rm "$tmp/w/notebooks/infra/lxc.md"
offer_templates "$tmp/t" "$tmp/w" "$tmp/offered"
[[ ! -e $tmp/w/notebooks/infra/lxc.md ]] || { echo 'offer_templates: deleted template came back' >&2; exit 1; }
[[ $(sort "$tmp/offered" | tr '\n' ' ') == 'notebooks/a.md notebooks/infra/lxc.md ' ]] || { echo 'offer_templates: wrong list' >&2; exit 1; }
)
printf '9 install script checks passed\n'
+39
View File
@@ -118,12 +118,51 @@ Info string: `sh {<kind> key=value key="value with spaces" flag}`. Language `sh`
`:::after{step=<id>}` … `:::` — rendered only after that step succeeded in the
current session. `:::after{step=<id> failed}` for the failure case. (remark-directive syntax.)
`:::when{param=a,b}` … `:::` — shown, and its steps runnable, only while the `choice` (or
other non-secret) parameter has one of the listed values. The server refuses to run a
step inside an inactive section. Values must be options of a `choice` parameter.
### 3.5 Artifacts
Each `on=local` run gets a fresh workdir under `data/runs/<run-id>/`. Artifacts are kept
for 24 h (configurable), then deleted. Private keys are flagged sensitive: one download
only, then removed.
### 3.6 Chained notebooks
A notebook can include another one and continue with what it produced, e.g. a service
notebook that first creates an LXC container:
```markdown
:::when{target=lxc}
::use{notebook="infra/lxc-container.md" as=ct with="hostname={{server_name}}"}
:::
```
- `::use{notebook="dir/name.md" as=alias with="p={{x}}, q=1"}` — path relative to
`notebooks/`, no `..`. The server composes the notebook (core `composeNotebook`):
the included params, step ids, captures and templates are namespaced by the alias
(`ct.hostname`, `ct.create`, `{{ct.address}}`) and shown inline as a collapsible
section with its own parameter group. Nested includes chain aliases (`svc.ct.x`); at
most 4 levels. Missing files, cycles and errors inside the included notebook are
errors on the `::use` line. The UI reloads when an included file changes.
- `with` sets defaults of the included params, written in the including notebook's
namespace. Secrets cannot be bound; they are entered in the form and passed only to
steps of their own notebook, under their local name (`$ROOTPW`).
- Required params gate only steps of their own notebook (scope); a step also needs every
value it references.
- Non-secret defaults may reference captures and builtins (`default: "{{ct.host}}"`). Until
the value exists the field shows "Available after the step that sets ct.host". A
required param that waits for a capture of its own notebook would block the step
producing it; make such params optional.
- `::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}` adds
the machine to Hosts (same validation as the Hosts page; never overwrites a different
host with that name). `capture` stores the host name as a runtime value so later
steps can target it. The first SSH connection still requires host key confirmation.
- Builtins are server-provided runtime values, never namespaced:
`{{shellbook.public_key}}` is ShellBook's SSH public key. The server sets them on every
run; client-sent values are ignored.
## 4. Execution
- Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY.
+191
View File
@@ -0,0 +1,191 @@
// Chained notebooks (`::use`): pure composition. The server loads the files; core only
// namespaces and merges them, so display and execution keep using one notebook model.
import type { Block, Diagnostic, Notebook, ParamDef, ParamValues, Step } from "./types";
import { includePath } from "./parser";
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
/** Maximum `::use` nesting (root -> a -> b -> c -> d). */
export const MAX_INCLUDE_DEPTH = 4;
/** Runtime names provided by the server, never namespaced: {{shellbook.public_key}}. */
export const isBuiltin = (name: string) => name.startsWith("shellbook.");
/** Workspace paths a notebook includes directly, in document order. Invalid paths never reach I/O. */
export function notebookIncludes(notebook: Notebook): string[] {
const paths: string[] = [];
const walk = (blocks: Block[]) => {
for (const block of blocks) {
if (block.type === "use" && !block.blocks.length) { if (includePath(block.path)) paths.push(block.path); }
else if (block.type === "after" || block.type === "when" || block.type === "use") walk(block.blocks);
}
};
walk(notebook.blocks);
return [...new Set(paths)];
}
const qualify = (alias: string, name: string) => `${alias}.${name}`;
const rewrite = (text: string, alias: string) =>
text.replace(template, (match, name: string) => isBuiltin(name) ? match : `{{${qualify(alias, name)}}}`);
const scoped = (alias: string, scope?: string) => scope ? qualify(alias, scope) : alias;
function prefixStep(step: Step, alias: string): Step {
const a = step.attrs;
return {
...step,
script: rewrite(step.script, alias),
attrs: {
...a,
id: qualify(alias, a.id),
host: a.host === undefined ? undefined : rewrite(a.host, alias),
capture: a.capture === undefined ? undefined : qualify(alias, a.capture),
artifacts: a.artifacts.map(x => rewrite(x, alias)),
uploads: a.uploads.map(u => ({ src: rewrite(u.src, alias), dst: rewrite(u.dst, alias) })),
scope: scoped(alias, a.scope),
},
};
}
/** Namespace a composed notebook's blocks under alias (names, ids, templates, scopes). */
function prefixBlocks(blocks: Block[], alias: string): Block[] {
return blocks.map((block): Block => {
switch (block.type) {
case "markdown": return { ...block, text: rewrite(block.text, alias) };
case "step": return { type: "step", step: prefixStep(block.step, alias) };
case "after": return { ...block, stepId: qualify(alias, block.stepId), blocks: prefixBlocks(block.blocks, alias) };
case "when": return { ...block, param: qualify(alias, block.param), blocks: prefixBlocks(block.blocks, alias) };
case "use": return { ...block, scope: qualify(alias, block.scope), bindings: {}, blocks: prefixBlocks(block.blocks, alias) };
case "host": return {
...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope),
name: rewrite(block.name, alias), address: rewrite(block.address, alias),
user: rewrite(block.user, alias), port: rewrite(block.port, alias),
capture: block.capture === undefined ? undefined : qualify(alias, block.capture),
};
}
});
}
function prefixParam(def: ParamDef, alias: string): ParamDef {
return {
...def,
name: qualify(alias, def.name),
default: def.default === undefined ? undefined : rewrite(def.default, alias),
scope: scoped(alias, def.scope),
};
}
/** Every step and host id in composed blocks (for duplicate detection). */
function blockIds(blocks: Block[], into: string[] = []): string[] {
for (const block of blocks) {
if (block.type === "step") into.push(block.step.attrs.id);
else if (block.type === "host") into.push(block.id);
else if (block.type !== "markdown") blockIds(block.blocks, into);
}
return into;
}
/**
* Resolve `::use` blocks: the included notebook's params, steps, captures and ids are
* namespaced by its alias ("ct.hostname") and merged into one notebook. `with` bindings
* become the included params' defaults in the including notebook's namespace.
* Missing files, cycles, nesting deeper than MAX_INCLUDE_DEPTH and errors inside an
* included notebook become error diagnostics on the `::use` line.
*/
export function composeNotebook(path: string, notebook: Notebook, load: (path: string) => Notebook | undefined): Notebook {
return compose(path, notebook, load, [path]);
}
function compose(path: string, notebook: Notebook, load: (path: string) => Notebook | undefined, stack: string[]): Notebook {
const diagnostics: Diagnostic[] = [...notebook.diagnostics];
const params: ParamDef[] = [...notebook.params];
const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line });
const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => {
if (block.type === "after" || block.type === "when") return { ...block, blocks: resolve(block.blocks) };
if (block.type !== "use") return block;
const line = block.range.startLine;
// The parser already reported an invalid path; never hand it to the loader.
if (!includePath(block.path)) return block;
if (stack.includes(block.path)) { fail(`Notebook include cycle: ${[...stack, block.path].join(" -> ")}`, line); return block; }
if (stack.length > MAX_INCLUDE_DEPTH) { fail(`Notebook includes are nested deeper than ${MAX_INCLUDE_DEPTH}`, line); return block; }
const loaded = load(block.path);
if (!loaded) { fail(`Included notebook not found: ${block.path}`, line); return block; }
const child = compose(block.path, loaded, load, [...stack, block.path]);
for (const d of child.diagnostics) if (d.severity === "error") fail(`${block.path}${d.line ? `:${d.line}` : ""}: ${d.message}`, line);
const alias = block.scope;
for (const [name, value] of Object.entries(block.bindings)) {
const def = child.params.find(p => p.name === name && !p.scope);
if (!def) fail(`with binds unknown parameter of ${block.path}: ${name}`, line);
else if (def.type === "secret") fail(`with cannot bind secret ${name}; enter it in the form`, line);
}
for (const def of child.params) {
const prefixed = prefixParam(def, alias);
// Bindings are templates in the including notebook's namespace: not rewritten.
if (!def.scope && def.type !== "secret" && Object.hasOwn(block.bindings, def.name)) prefixed.default = block.bindings[def.name];
params.push(prefixed);
}
return { ...block, title: child.title, bindings: { ...block.bindings }, blocks: prefixBlocks(child.blocks, alias) };
});
const blocks = resolve(notebook.blocks);
const seen = new Set<string>();
for (const id of blockIds(blocks)) {
if (seen.has(id) && id.includes(".")) fail(`Duplicate step id after including notebooks: ${id}`, 1);
seen.add(id);
}
return { ...notebook, params, blocks, diagnostics };
}
/** Find a step anywhere in the block tree (after, when and use containers). */
export function findStep(blocks: Block[], id: string): Step | undefined {
for (const block of blocks) {
if (block.type === "step" && block.step.attrs.id === id) return block.step;
if (block.type === "after" || block.type === "when" || block.type === "use") {
const found = findStep(block.blocks, id);
if (found) return found;
}
}
}
/**
* Whether a step or host block is shown and runnable: every enclosing `:::when` must match
* the resolved parameter values. `:::after` only gates display, not execution.
*/
export function blockActive(notebook: Notebook, id: string, values: ParamValues): boolean {
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
for (const block of blocks) {
if (block.type === "step" && block.step.attrs.id === id) return active;
if (block.type === "host" && block.id === id) return active;
if (block.type === "when") {
const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? ""));
if (found !== undefined) return found;
} else if (block.type === "after" || block.type === "use") {
const found = walk(block.blocks, active);
if (found !== undefined) return found;
}
}
return undefined;
};
return walk(notebook.blocks, true) ?? false;
}
/** Whether an included notebook's scope ("ct", "svc.ct") is active, i.e. its `::use` lies in matching `:::when` sections. The root scope ("") always is. */
export function scopeActive(notebook: Notebook, scope: string, values: ParamValues): boolean {
if (!scope) return true;
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
for (const block of blocks) {
if (block.type === "use" && block.scope === scope) return active;
if (block.type === "markdown" || block.type === "step" || block.type === "host") continue;
const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? "")));
if (found !== undefined) return found;
}
return undefined;
};
return walk(notebook.blocks, true) ?? false;
}
/** Runtime names that steps or host blocks of the notebook set (`capture=`). */
export function captureNames(blocks: Block[], into = new Set<string>()): Set<string> {
for (const block of blocks) {
if (block.type === "step" && block.step.attrs.capture) into.add(block.step.attrs.capture);
else if (block.type === "host" && block.capture) into.add(block.capture);
else if (block.type !== "markdown" && block.type !== "step" && block.type !== "host") captureNames(block.blocks, into);
}
return into;
}
+82 -27
View File
@@ -1,8 +1,10 @@
// Public API of @shellbook/core. Pure functions, no I/O.
import type { Notebook, ParamValues, RenderedStep, Step } from "./types";
import type { Block, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types";
import { captureNames, isBuiltin } from "./compose";
export type * from "./types";
export type * from "./protocol";
export { parseNotebook } from "./parser";
export { parseNotebook, includePath } from "./parser";
export { composeNotebook, notebookIncludes, findStep, blockActive, scopeActive, captureNames, isBuiltin, MAX_INCLUDE_DEPTH } from "./compose";
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
const own = (object: object, key: string) => Object.hasOwn(object, key);
@@ -17,15 +19,20 @@ export function shellQuote(value: string): string {
return /^[A-Za-z0-9._/@:=+\-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
}
/** Resolve defaults ({{other}} references) and validate all params by type. */
/**
* Resolve defaults ({{other}} references) and validate all params by type. Defaults may
* also reference runtime values (captures such as {{ct.host}}, builtins {{shellbook.*}}).
*/
export function resolveParams(
notebook: Notebook,
values: ParamValues,
hostNames: readonly string[],
runtime: ParamValues = {},
): { values: ParamValues; errors: Record<string, string> } {
const effective = dictionary();
const errors = dictionary();
const defs = new Map(notebook.params.map(def => [def.name, def]));
const captures = captureNames(notebook.blocks);
const active = new Set<string>();
const resolve = (name: string): string => {
if (own(effective, name)) return effective[name]!;
@@ -34,9 +41,14 @@ export function resolveParams(
if (active.has(name)) { errors[name] = "Cyclic parameter default"; return ""; }
active.add(name);
let value = own(values, name) ? values[name] ?? "" : "";
let pending = false;
if (!value && def.type !== "secret" && def.default !== undefined) {
value = def.default.replace(template, (match, ref: string) => {
const other = defs.get(ref);
if (!other && (captures.has(ref) || isBuiltin(ref))) {
if (own(runtime, ref) && runtime[ref]) return runtime[ref]!;
errors[name] = `Available after the step that sets ${ref}`; pending = true; return match;
}
if (!other) { errors[name] = `Unknown default reference: ${ref}`; return match; }
if (other.type === "secret") { errors[name] = "Defaults cannot reference secrets"; return match; }
const resolved = resolve(ref);
@@ -46,6 +58,8 @@ export function resolveParams(
});
}
active.delete(name);
// A default still waiting for a captured value is empty, not its literal template.
if (pending) value = "";
effective[name] = value;
if (!value) {
if (def.required) errors[name] ??= "Required parameter is missing";
@@ -63,6 +77,42 @@ export function resolveParams(
return { values: effective, errors };
}
/**
* Shared template substitution for steps and host blocks. Required params gate only
* blocks of their own scope: an included notebook's form does not block the parent.
*/
function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) {
const resolved = resolveParams(notebook, values, hostNames, runtime);
const captures = captureNames(notebook.blocks);
const defs = new Map(notebook.params.map(def => [def.name, def]));
const invalid = dictionary();
const missing = new Set<string>();
for (const def of notebook.params) {
if ((def.scope ?? "") !== (scope ?? "")) continue;
if (def.required && !resolved.values[def.name]) missing.add(def.name);
if ((def.required || def.type === "secret") && resolved.values[def.name]
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
}
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
const def = defs.get(name);
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
if (!def && !own(runtime, name)) {
// A capture that has not run yet (or a builtin) is pending, not a typo.
if (captures.has(name) || isBuiltin(name)) missing.add(name);
else invalid[name] = "Unknown parameter or runtime value";
return match;
}
const value = def ? resolved.values[name] : runtime[name];
if (def && own(resolved.errors, name)) invalid[name] = resolved.errors[name]!;
if (!value) { missing.add(name); return match; }
if (value.includes("\0")) { invalid[name] = "Value cannot contain NUL"; return match; }
// Never interpolate values with validation errors into scripts or metadata.
if (own(invalid, name)) return match;
return script ? shellQuote(value) : value;
});
return { substitute, invalid, missing };
}
/**
* The single script substitution path: display and execution consume this result.
* Attributes use raw substitution and separate validation; secrets are env-only.
@@ -74,27 +124,7 @@ export function renderStep(
runtime: ParamValues,
hostNames: readonly string[],
): RenderedStep {
const resolved = resolveParams(notebook, values, hostNames);
const defs = new Map(notebook.params.map(def => [def.name, def]));
const invalid = dictionary();
const missing = new Set<string>();
for (const def of notebook.params) {
if (def.required && !resolved.values[def.name]) missing.add(def.name);
if ((def.required || def.type === "secret") && resolved.values[def.name]
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
}
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
const def = defs.get(name);
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
if (!def && !own(runtime, name)) { invalid[name] = "Unknown parameter or runtime value"; return match; }
const value = def ? resolved.values[name] : runtime[name];
if (def && own(resolved.errors, name)) invalid[name] = resolved.errors[name]!;
if (!value) { missing.add(name); return match; }
if (value.includes("\0")) { invalid[name] = "Value cannot contain NUL"; return match; }
// Never interpolate values with validation errors into scripts or metadata.
if (own(invalid, name)) return match;
return script ? shellQuote(value) : value;
});
const { substitute, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames);
const script = substitute(step.script, true);
const host = step.attrs.local || step.attrs.host === undefined ? undefined : substitute(step.attrs.host, false);
if (!step.attrs.local && (!host || !hostNames.includes(host))) invalid.host ??= "Unknown or missing target host";
@@ -113,15 +143,40 @@ export function renderStep(
return { stepId: step.attrs.id, kind: step.kind, host, local: step.attrs.local, script, artifacts, uploads, missing: [...missing], invalid };
}
/** Resolve a `::host` block with the same rules as hosts.yaml entries. */
export function renderHost(
notebook: Notebook,
block: Extract<Block, { type: "host" }>,
values: ParamValues,
runtime: ParamValues,
hostNames: readonly string[],
): RenderedHost {
const { substitute, invalid, missing } = substitution(notebook, block.scope, values, runtime, hostNames);
const name = substitute(block.name, false), address = substitute(block.address, false);
const user = substitute(block.user, false), portText = substitute(block.port, false);
const port = Number(portText);
if (!/^[A-Za-z0-9._-]+$/.test(name)) invalid.name ??= "Host name may only contain letters, digits, ., _ or -";
if (!address || /[\s\0]/.test(address)) invalid.address ??= "Address cannot be empty or contain whitespace";
if (!/^[A-Za-z0-9._-]+$/.test(user)) invalid.user ??= "User may only contain letters, digits, ., _ or -";
if (!Number.isInteger(port) || port < 1 || port > 65535) invalid.port ??= "Port must be 1-65535";
return { id: block.id, name, address, user, port, missing: [...missing], invalid };
}
/** Substitute prose without quoting; secrets always appear masked. */
export function renderText(text: string, values: ParamValues, notebook: Notebook): string {
const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name));
return text.replace(template, (match, name: string) => secrets.has(name) ? "••••" : own(values, name) ? values[name]! : match);
}
/** Env vars for a run: every secret param under its exact name. Server-side only. */
export function secretEnv(notebook: Notebook, values: ParamValues): Record<string, string> {
/**
* Env vars for a run: the secrets of the step's scope under their local name
* (an included notebook's `ct.TOKEN` is `$TOKEN` in its own steps). Server-side only.
*/
export function secretEnv(notebook: Notebook, values: ParamValues, scope?: string): Record<string, string> {
const env = dictionary();
for (const def of notebook.params) if (def.type === "secret" && own(values, def.name)) env[def.name] = values[def.name]!;
for (const def of notebook.params) {
if (def.type !== "secret" || (def.scope ?? "") !== (scope ?? "") || !own(values, def.name)) continue;
env[def.scope ? def.name.slice(def.scope.length + 1) : def.name] = values[def.name]!;
}
return env;
}
+72 -2
View File
@@ -3,6 +3,10 @@ import type { Block, Notebook, ParamDef, Step, StepAttrs } from "./types";
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
const paramTypes = new Set(["host", "name", "path", "string", "choice", "secret"]);
const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** Workspace notebook path relative to notebooks/: forward slashes, no `..`, Markdown only. */
export const includePath = (value: string) =>
/^[^\\\0\r\n:]+\.md$/.test(value) && value.split("/").every(part => part && part !== "." && part !== "..");
/** Small attribute scanner: quoted values may contain whitespace, braces and escaped quotes. */
function attributes(text: string, error: (message: string) => void): Map<string, (string | true)[]> {
@@ -90,7 +94,9 @@ export function parseNotebook(source: string): Notebook {
}
const ids = new Set<string>();
const afterRefs: { id: string; line: number }[] = [];
const aliases = new Set<string>();
let stepNumber = 0;
let hostNumber = 0;
let heading: string | undefined;
let i = start;
const parseBlocks = (nested: boolean, depth = 0): Block[] => {
@@ -118,6 +124,70 @@ export function parseNotebook(source: string): Notebook {
blocks.push({ type: "after", stepId: id, onFailure: attrs.has("failed"), blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue;
}
const when = /^\s{0,3}:::when\{(.*)\}\s*$/.exec(line);
if (when && depth < 100) {
flush(); const begin = i++;
const attrs = attributes(when[1]!, m => error(m, begin + 1));
const [param, raw] = [...attrs][0] ?? [];
const value = raw?.[0];
if (attrs.size !== 1 || typeof value !== "string") error("when requires exactly one param=value[,value]", begin + 1);
const values = typeof value === "string" ? value.split(",").map(v => v.trim()).filter(Boolean) : [];
const def = notebook.params.find(p => p.name === param);
if (param && !def) error(`when references unknown parameter: ${param}`, begin + 1);
else if (def?.type === "secret") error("when cannot test a secret", begin + 1);
else if (def?.options) for (const v of values) if (!def.options.includes(v)) error(`when value is not an option of ${param}: ${v}`, begin + 1);
const children = parseBlocks(true, depth + 1);
if (i === lines.length) error("Unclosed when container", begin + 1);
else i++;
blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue;
}
const leaf = /^\s{0,3}::(use|host)\{(.*)\}\s*$/.exec(line);
if (leaf) {
flush();
const lineNo = i + 1;
const attrs = attributes(leaf[2]!, m => error(m, lineNo));
const get = (key: string): string | undefined => {
const v = attrs.get(key);
if (v && (v.length > 1 || v[0] === true)) error(`${key} requires one value`, lineNo);
return typeof v?.[0] === "string" ? v[0] : undefined;
};
const range = { startLine: lineNo, endLine: lineNo };
if (leaf[1] === "use") {
for (const key of attrs.keys()) if (!["notebook", "as", "with"].includes(key)) error(`Unknown use attribute: ${key}`, lineNo);
const path = get("notebook") ?? "";
const alias = get("as") ?? "";
if (!includePath(path)) error('use requires notebook="dir/name.md" (relative to notebooks/)', lineNo);
if (!identifier.test(alias) || alias === "shellbook") error("use requires as=alias (letters, digits, _; not shellbook)", lineNo);
else if (aliases.has(alias)) error(`Duplicate use alias: ${alias}`, lineNo);
aliases.add(alias);
const bindings = Object.create(null) as Record<string, string>;
for (const value of attrs.get("with") ?? []) {
if (value === true) { error("with requires name=value pairs", lineNo); continue; }
// Values may contain commas; a new binding starts only at ",name=".
for (const pair of value.split(/,(?=\s*[A-Za-z_][A-Za-z0-9_]*\s*=)/)) {
const eq = pair.indexOf("=");
const name = pair.slice(0, Math.max(eq, 0)).trim();
if (eq <= 0 || !identifier.test(name)) error("with requires name=value pairs", lineNo);
else if (Object.hasOwn(bindings, name)) error(`Duplicate with binding: ${name}`, lineNo);
else bindings[name] = pair.slice(eq + 1).trim();
}
}
blocks.push({ type: "use", scope: alias, path, bindings, blocks: [], range });
} else {
hostNumber++;
for (const key of attrs.keys()) if (!["id", "name", "address", "user", "port", "capture"].includes(key)) error(`Unknown host attribute: ${key}`, lineNo);
const id = get("id") || `host-${hostNumber}`;
if (ids.has(id)) error(`Duplicate step id: ${id}`, lineNo);
ids.add(id);
const name = get("name"), address = get("address");
if (!name || !address) error("host requires name and address", lineNo);
const capture = get("capture");
if (capture !== undefined && !identifier.test(capture)) error("Invalid capture name", lineNo);
blocks.push({ type: "host", id, name: name ?? "", address: address ?? "", user: get("user") ?? "root", port: get("port") ?? "22", capture, range });
}
i++; markdownStart = i; continue;
}
const fence = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
if (fence) {
const begin = i;
@@ -166,7 +236,7 @@ export function parseNotebook(source: string): Notebook {
}
if (kind === "check" && (attrs.has("artifacts") || attrs.has("upload"))) error("Checks cannot declare artifacts or uploads", begin + 1);
const capture = get("capture");
if (capture && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(capture)) error("Invalid capture name", begin + 1);
if (capture && !identifier.test(capture)) error("Invalid capture name", begin + 1);
const step: Step = {
kind,
lang: match[1]!,
@@ -186,7 +256,7 @@ export function parseNotebook(source: string): Notebook {
i = end < lines.length ? end + 1 : end; markdownStart = i; continue;
}
heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1];
if (/^\s*:::/.test(line)) error("Malformed or unexpected directive", i + 1);
if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host)\b/.test(line)) error("Malformed or unexpected directive", i + 1);
i++;
}
flush(); return blocks;
+9
View File
@@ -35,8 +35,17 @@ export interface NotebookListResponse {
// GET /api/notebooks/:path (path URL-encoded)
export interface NotebookResponse {
path: string;
/** The notebook's own Markdown (what the editor saves). */
source: string;
/** Parsed and composed: `::use` blocks contain the included notebooks (namespaced). */
notebook: Notebook;
/** Workspace paths of all included notebooks (reload when one of them changes). */
includes: string[];
/**
* Server-provided runtime values, e.g. "shellbook.public_key". The server sets them on
* every run itself; clients merge them into the runtime they render with.
*/
builtins: ParamValues;
/** Opaque version for optimistic concurrency on save. */
version: string;
}
+57
View File
@@ -13,6 +13,11 @@ export interface ParamDef {
label?: string;
/** Only for type "choice". */
options?: string[];
/**
* Set for params of an included notebook (`::use`): the alias path ("ct", "ct.base").
* The name is then prefixed ("ct.hostname"); a secret's env var keeps the local name.
*/
scope?: string;
}
/** Param name -> current value. Missing key or "" means "not filled". */
@@ -44,6 +49,8 @@ export interface StepAttrs {
artifacts: string[];
uploads: Upload[];
timeoutSec: number;
/** Alias path when the step comes from an included notebook (see ParamDef.scope). */
scope?: string;
}
/** 1-based, inclusive line range in the notebook source. */
@@ -72,8 +79,58 @@ export type Block =
onFailure: boolean;
blocks: Block[];
range: SourceRange;
}
| {
/** `:::when{param=a,b}` — shown, and its steps runnable, only while param is one of values. */
type: "when";
param: string;
values: string[];
blocks: Block[];
range: SourceRange;
}
| {
/**
* `::use{notebook="dir/x.md" as=alias with="p={{v}}"}` — another workspace notebook inline.
* As parsed, `blocks` is empty; composeNotebook fills it with the namespaced content.
*/
type: "use";
/** Alias path ("ct"; "ct.base" for nested includes). */
scope: string;
/** Workspace notebook path relative to notebooks/. */
path: string;
/** Included notebook's title (set by composeNotebook). */
title?: string;
/** Local param name of the included notebook -> default template in the including notebook. */
bindings: Record<string, string>;
blocks: Block[];
range: SourceRange;
}
| {
/** `::host{name= address= user= port= capture=}` — add a machine to Hosts from the notebook. */
type: "host";
id: string;
scope?: string;
/** Templates, resolved like step attributes. */
name: string;
address: string;
user: string;
port: string;
/** Runtime value set to the host name once it is in Hosts. */
capture?: string;
range: SourceRange;
};
/** A `::host` block with all templates resolved. */
export interface RenderedHost {
id: string;
name: string;
address: string;
user: string;
port: number;
missing: string[];
invalid: Record<string, string>;
}
export interface Diagnostic {
severity: "error" | "warning";
message: string;
+218
View File
@@ -0,0 +1,218 @@
import { describe, expect, it } from "vitest";
import {
blockActive, scopeActive, composeNotebook, findStep, notebookIncludes, parseNotebook, renderHost,
renderStep, resolveParams, secretEnv, type Block, type Notebook,
} from "../src/index";
const lxc = `---
title: LXC container
params:
proxmox: {type: host, required: true}
hostname: {type: name, required: true}
memory: {type: name, default: "2048"}
ROOTPW: {type: secret}
---
# LXC
Creates {{hostname}}.
\`\`\`sh {run host="{{proxmox}}" id=create capture=address}
pct create --hostname {{hostname}} --memory {{memory}} --key {{shellbook.public_key}} --pw "$ROOTPW"
\`\`\`
:::after{step=create}
Created {{address}}.
:::
::host{name="{{hostname}}" address="{{address}}" capture=host}
`;
const service = `---
title: Web server
params:
target: {type: choice, options: [existing, lxc], default: lxc}
service: {type: name, default: web}
host: {type: host, required: true, default: "{{ct.host}}"}
TOKEN: {type: secret}
---
:::when{target=lxc}
::use{notebook="infra/lxc.md" as=ct with="hostname={{service}}-ct, memory=512"}
:::
\`\`\`sh {run host="{{host}}" id=install}
apt-get install -y nginx
\`\`\`
`;
const files: Record<string, string> = { "infra/lxc.md": lxc, "services/web.md": service };
const load = (path: string) => files[path] === undefined ? undefined : parseNotebook(files[path]!);
const composed = () => composeNotebook("services/web.md", parseNotebook(service), load);
function all(blocks: Block[]): Block[] {
return blocks.flatMap(b => b.type === "markdown" || b.type === "step" || b.type === "host" ? [b] : [b, ...all(b.blocks)]);
}
const hosts = ["pve", "web-ct", "existing"];
describe("directives", () => {
it("parses when, use and host blocks", () => {
const n = parseNotebook(service);
expect(n.diagnostics).toEqual([]);
const when = n.blocks.find(b => b.type === "when");
expect(when).toMatchObject({ type: "when", param: "target", values: ["lxc"] });
expect(when?.type === "when" && when.blocks.find(b => b.type === "use")).toMatchObject({
type: "use", scope: "ct", path: "infra/lxc.md", bindings: { hostname: "{{service}}-ct", memory: "512" }, blocks: [],
});
expect(notebookIncludes(n)).toEqual(["infra/lxc.md"]);
const host = parseNotebook(lxc).blocks.find(b => b.type === "host");
expect(host).toMatchObject({ id: "host-1", name: "{{hostname}}", address: "{{address}}", user: "root", port: "22", capture: "host" });
});
it("reports malformed directives", () => {
const bad = parseNotebook(`---
params:
mode: {type: choice, options: [a, b]}
pw: {type: secret}
---
:::when{mode=c}
:::
:::when{nope=a}
:::
:::when{pw=x}
:::
::use{notebook="../x.md" as=1x}
::use{notebook="a.md" as=shellbook}
::use{notebook="a.md" as=a with="x"}
::use{notebook="a.md" as=a}
::host{name=x}
::host{name=x address=y capture=bad-name extra=1}
::use{broken
`);
// Invalid include paths are reported but never handed to the loader.
expect(notebookIncludes(bad)).toEqual(["a.md"]);
const loaded: string[] = [];
composeNotebook("bad.md", bad, p => { loaded.push(p); return undefined; });
expect(loaded).not.toContain("../x.md");
const messages = bad.diagnostics.map(d => d.message);
expect(messages).toEqual(expect.arrayContaining([
"when value is not an option of mode: c",
"when references unknown parameter: nope",
"when cannot test a secret",
'use requires notebook="dir/name.md" (relative to notebooks/)',
"use requires as=alias (letters, digits, _; not shellbook)",
"with requires name=value pairs",
"Duplicate use alias: a",
"host requires name and address",
"Invalid capture name",
"Unknown host attribute: extra",
"Malformed or unexpected directive",
]));
});
});
describe("composeNotebook", () => {
it("namespaces the included notebook and applies with bindings", () => {
const n = composed();
expect(n.diagnostics).toEqual([]);
expect(n.params.map(p => [p.name, p.scope, p.default])).toEqual([
["target", undefined, "lxc"], ["service", undefined, "web"], ["host", undefined, "{{ct.host}}"], ["TOKEN", undefined, undefined],
["ct.proxmox", "ct", undefined], ["ct.hostname", "ct", "{{service}}-ct"], ["ct.memory", "ct", "512"], ["ct.ROOTPW", "ct", undefined],
]);
const create = findStep(n.blocks, "ct.create")!;
expect(create.attrs).toMatchObject({ host: "{{ct.proxmox}}", capture: "ct.address", scope: "ct" });
expect(create.script).toBe('pct create --hostname {{ct.hostname}} --memory {{ct.memory}} --key {{shellbook.public_key}} --pw "$ROOTPW"\n');
const blocks = all(n.blocks);
expect(blocks.find(b => b.type === "after")).toMatchObject({ stepId: "ct.create" });
expect(blocks.find(b => b.type === "host")).toMatchObject({ id: "ct.host-1", scope: "ct", name: "{{ct.hostname}}", capture: "ct.host" });
expect(blocks.find(b => b.type === "use")).toMatchObject({ title: "LXC container", scope: "ct" });
expect(blocks.some(b => b.type === "markdown" && b.text.includes("Creates {{ct.hostname}}."))).toBe(true);
});
it("namespaces nested includes by alias path", () => {
const nested = { ...files, "outer.md": '::use{notebook="services/web.md" as=svc}\n' };
const n = composeNotebook("outer.md", parseNotebook(nested["outer.md"]), p => nested[p as keyof typeof nested] === undefined ? undefined : parseNotebook(nested[p as keyof typeof nested]!));
expect(n.diagnostics).toEqual([]);
expect(n.params.find(p => p.name === "svc.ct.hostname")).toMatchObject({ scope: "svc.ct", default: "{{svc.service}}-ct" });
expect(n.params.find(p => p.name === "svc.host")).toMatchObject({ scope: "svc", default: "{{svc.ct.host}}" });
expect(findStep(n.blocks, "svc.ct.create")?.attrs.scope).toBe("svc.ct");
});
it("reports missing files, cycles, depth, child errors and bad bindings on the use line", () => {
const cases: Record<string, string> = {
"a.md": '\n::use{notebook="b.md" as=b}\n',
"b.md": '::use{notebook="a.md" as=a}\n',
"missing.md": '::use{notebook="nowhere.md" as=x}\n',
"broken.md": '::use{notebook="bad.md" as=x}\n',
"bad.md": "```sh {run bogus}\nx\n```\n",
"bind.md": '::use{notebook="infra/lxc.md" as=x with="nope=1,ROOTPW=2"}\n',
"d0.md": '::use{notebook="d1.md" as=a}\n', "d1.md": '::use{notebook="d2.md" as=a}\n', "d2.md": '::use{notebook="d3.md" as=a}\n',
"d3.md": '::use{notebook="d4.md" as=a}\n', "d4.md": '::use{notebook="d5.md" as=a}\n', "d5.md": "# deep\n",
...files,
};
const get = (p: string) => cases[p] === undefined ? undefined : parseNotebook(cases[p]!);
const errors = (p: string) => composeNotebook(p, get(p)!, get).diagnostics;
expect(errors("a.md")).toEqual([expect.objectContaining({ line: 2, message: expect.stringContaining("Notebook include cycle: a.md -> b.md -> a.md") })]);
expect(errors("missing.md")).toEqual([{ severity: "error", line: 1, message: "Included notebook not found: nowhere.md" }]);
expect(errors("broken.md")[0]?.message).toBe("bad.md:1: Unknown attribute: bogus");
expect(errors("bind.md").map(d => d.message)).toEqual([
"with binds unknown parameter of infra/lxc.md: nope", "with cannot bind secret ROOTPW; enter it in the form",
]);
expect(errors("d0.md").map(d => d.message).join()).toContain("nested deeper than 4");
});
});
describe("rendering chained notebooks", () => {
const values = { target: "lxc", "ct.proxmox": "pve", "ct.ROOTPW": "pw-secret", TOKEN: "tok" };
const runtime = { "shellbook.public_key": "ssh-ed25519 AAAA shellbook" };
it("renders included steps with bindings, builtins and shell quoting", () => {
const n = composed();
const r = renderStep(n, findStep(n.blocks, "ct.create")!, resolveParams(n, values, hosts, runtime).values, runtime, hosts);
expect(r).toMatchObject({ host: "pve", missing: [], invalid: {} });
expect(r.script).toBe("pct create --hostname web-ct --memory 512 --key 'ssh-ed25519 AAAA shellbook' --pw \"$ROOTPW\"\n");
});
it("gates required params per scope and resolves defaults from captures", () => {
const n = composed();
const before = resolveParams(n, values, hosts, runtime);
expect(before.errors.host).toBe("Available after the step that sets ct.host");
// The parent's missing host does not block the included notebook's steps ...
expect(renderStep(n, findStep(n.blocks, "ct.create")!, before.values, runtime, hosts).missing).toEqual([]);
// ... but blocks the parent's own steps until the container is in Hosts.
expect(renderStep(n, findStep(n.blocks, "install")!, before.values, runtime, hosts).missing).toContain("host");
const after = resolveParams(n, values, hosts, { ...runtime, "ct.host": "web-ct" });
expect(after.values.host).toBe("web-ct");
expect(renderStep(n, findStep(n.blocks, "install")!, after.values, { "ct.host": "web-ct" }, hosts)).toMatchObject({ host: "web-ct", missing: [], invalid: {} });
// An included required param blocks only its own scope.
const empty = resolveParams(n, { target: "lxc" }, hosts, runtime).values;
expect(renderStep(n, findStep(n.blocks, "ct.create")!, empty, runtime, hosts).missing).toContain("ct.proxmox");
expect(renderStep(n, findStep(n.blocks, "install")!, { ...empty, host: "existing" }, runtime, hosts).missing).toEqual([]);
});
it("activates when sections by resolved choice", () => {
const n = composed();
expect(blockActive(n, "ct.create", { target: "lxc" })).toBe(true);
expect(blockActive(n, "ct.host-1", { target: "lxc" })).toBe(true);
expect(blockActive(n, "ct.create", { target: "existing" })).toBe(false);
expect(blockActive(n, "install", { target: "existing" })).toBe(true);
expect(blockActive(n, "unknown", {})).toBe(false);
expect(scopeActive(n, "", {})).toBe(true);
expect(scopeActive(n, "ct", { target: "lxc" })).toBe(true);
expect(scopeActive(n, "ct", { target: "existing" })).toBe(false);
expect(scopeActive(n, "nope", { target: "lxc" })).toBe(false);
});
it("passes secrets only to their own scope under the local name", () => {
const n = composed();
expect(secretEnv(n, values, "ct")).toEqual({ ROOTPW: "pw-secret" });
expect(secretEnv(n, values)).toEqual({ TOKEN: "tok" });
});
it("resolves and validates host blocks", () => {
const n = composed();
const block = all(n.blocks).find(b => b.type === "host") as Extract<Block, { type: "host" }>;
const rv = resolveParams(n, values, hosts, runtime).values;
expect(renderHost(n, block, rv, runtime, hosts)).toMatchObject({ name: "web-ct", missing: ["ct.address"] });
expect(renderHost(n, block, rv, { "ct.address": "10.0.30.160" }, hosts)).toEqual({
id: "ct.host-1", name: "web-ct", address: "10.0.30.160", user: "root", port: 22, missing: [], invalid: {},
});
const bad: Notebook = parseNotebook('::host{name="a b" address="x y" user=r/oot port=0}\n');
expect(Object.keys(renderHost(bad, bad.blocks[0] as Extract<Block, { type: "host" }>, {}, {}, []).invalid).sort()).toEqual(["address", "name", "port", "user"]);
});
});
+26 -1
View File
@@ -111,4 +111,29 @@ add `failed` for failure. Refer to a real step ID. Each local run gets a fresh
uploads to transfer earlier results. Artifacts expire after 24 hours by default;
private keys are sensitive, downloadable once, then removed. Do not commit them.
See the three notebooks for complete SSH-key, read-only hardening and Debian package examples.
## Choices, chaining and new hosts
````markdown
:::when{target=lxc}
Shown, and runnable, only while the choice parameter `target` is `lxc` (or `a,b` for several).
::use{notebook="infra/lxc-container.md" as=ct with="hostname={{server_name}}"}
:::
```sh {run host="{{host}}" id=install}
apt-get install -y nginx
```
````
- `::use` includes another notebook (path relative to `notebooks/`). Its parameters
appear in their own form group as `alias.name`; refer to its captures as
`{{ct.address}}` and to its steps as `ct.<id>`. `with` sets defaults for its
parameters using this notebook's names. Never bind secrets.
- Defaults may reference captures: `host: { type: host, required: true, default: "{{ct.host}}" }`.
Only reference captures of *another* notebook from required parameters; within one
notebook make such parameters optional (e.g. `ctid: { type: name, default: "{{nextid}}" }`).
- `::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}`
offers to add a created machine to Hosts and stores its name in `{{host}}`.
- `{{shellbook.public_key}}` is ShellBook's SSH public key, e.g. for `pct create --ssh-public-keys`.
See the notebooks for complete SSH-key, read-only hardening, Debian package, LXC
container (`infra/lxc-container.md`) and chained service (`services/web-server.md`) examples.
@@ -0,0 +1,97 @@
---
title: Create an LXC container on Proxmox
params:
proxmox: { type: host, required: true, label: Proxmox host }
hostname: { type: name, required: true, label: Container hostname }
ctid: { type: name, default: "{{nextid}}", label: Container ID (empty = next free) }
os: { type: choice, options: [debian-12-standard, debian-13-standard, ubuntu-24.04-standard], default: debian-12-standard, label: Template }
cores: { type: name, default: "2", label: CPU cores }
memory: { type: name, default: "2048", label: Memory (MiB) }
swap: { type: name, default: "512", label: Swap (MiB) }
disk: { type: name, default: "8", label: Disk (GiB) }
storage: { type: name, default: local-lvm, label: Disk storage }
template_storage: { type: name, default: local, label: Template storage }
bridge: { type: name, default: vmbr0, label: Network bridge }
net: { type: string, default: "ip=dhcp", label: "IP config (ip=dhcp or ip=10.0.0.5/24,gw=10.0.0.1)" }
---
# Create LXC container {{hostname}}
Creates an unprivileged container on **{{proxmox}}** (connects as a user that may run
`pct`, usually root), starts it with ShellBook's SSH key for root, and adds it to
Hosts. Other notebooks can include this one with
`::use{notebook="infra/lxc-container.md" as=ct}` and target the new machine as
`{{ct.host}}`.
```sh {check host="{{proxmox}}" id=pve title="Proxmox tools are available"}
command -v pct
command -v pveam
command -v pvesh
```
```sh {check host="{{proxmox}}" id=next-id title="Next free container ID" capture=nextid}
pvesh get /cluster/nextid
```
```sh {check host="{{proxmox}}" id=id-free title="Container ID is free"}
if pct status {{ctid}} > /dev/null 2>&1; then
echo "Container {{ctid}} already exists" >&2
exit 1
fi
```
The template step refreshes the template index and downloads the newest
**{{os}}** template if it is not on **{{template_storage}}** yet.
```sh {run host="{{proxmox}}" id=template title="Download template" capture=template timeout=900}
pveam update > /dev/null
name=$(pveam available --section system | awk -v prefix={{os}} 'index($2, prefix) == 1 { print $2 }' | sort -V | tail -n 1)
if [ -z "$name" ]; then
echo "No template matching {{os}} is available" >&2
exit 1
fi
if ! pveam list {{template_storage}} | grep -qF "$name"; then
pveam download {{template_storage}} "$name" >&2
fi
printf '%s:vztmpl/%s\n' {{template_storage}} "$name"
```
```sh {run host="{{proxmox}}" id=create title="Create and start container" confirm timeout=600}
keys=$(mktemp)
trap 'rm -f "$keys"' EXIT
printf '%s\n' {{shellbook.public_key}} > "$keys"
pct create {{ctid}} {{template}} \
--hostname {{hostname}} \
--cores {{cores}} --memory {{memory}} --swap {{swap}} \
--rootfs {{storage}}:{{disk}} \
--net0 name=eth0,bridge={{bridge}},{{net}} \
--unprivileged 1 --features nesting=1 --onboot 1 \
--ssh-public-keys "$keys"
pct start {{ctid}}
```
The next check waits for the container's address and prints its SSH host key
fingerprints (stderr). Compare them with the fingerprint ShellBook shows on the first
connection.
```sh {check host="{{proxmox}}" id=address title="Wait for the container address" capture=address timeout=120}
ip=""
for _ in $(seq 1 45); do
ip=$(pct exec {{ctid}} -- hostname -I 2> /dev/null | awk '{ print $1 }' || true)
[ -n "$ip" ] && break
sleep 2
done
if [ -z "$ip" ]; then
echo "Container {{ctid}} has no IP address yet" >&2
exit 1
fi
pct exec {{ctid}} -- sh -c 'for key in /etc/ssh/ssh_host_*_key.pub; do ssh-keygen -lf "$key"; done' >&2 || true
printf '%s\n' "$ip"
```
::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}
```sh {check host="{{host}}" id=login title="ShellBook can log in"}
uname -a
head -n 2 /etc/os-release
```
@@ -0,0 +1,50 @@
---
title: Install a web server (nginx)
params:
target: { type: choice, options: [lxc, existing], default: lxc, label: Install on }
server_name: { type: name, required: true, default: web, label: Server name }
host: { type: host, required: true, default: "{{ct.host}}", label: Target server }
---
# Install nginx on {{host}}
Example of a chained notebook. Choose **Install on: lxc** to create a fresh Proxmox
container first (its form appears below), or **existing** to pick a server from
Hosts. The install steps then target **Target server**, which defaults to the new
container once it is in Hosts.
:::when{target=lxc}
## New container
::use{notebook="infra/lxc-container.md" as=ct with="hostname={{server_name}}"}
:::
## Install
Runs as root, or through passwordless `sudo -n` for other users.
```sh {check host="{{host}}" id=apt title="Debian/Ubuntu with apt and systemd"}
command -v apt-get
command -v systemctl
```
```sh {check host="{{host}}" id=installed title="nginx is installed"}
dpkg-query -W -f='${Status}\n' nginx | grep -qx 'install ok installed'
```
```sh {run host="{{host}}" id=install title="Install and start nginx" confirm timeout=600}
if [ "$(id -u)" -eq 0 ]; then as_root=""; else as_root="sudo -n"; fi
$as_root apt-get update
$as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y nginx
$as_root systemctl enable --now nginx
```
```sh {check host="{{host}}" id=active title="nginx is running and answers"}
systemctl is-active nginx
timeout 5 bash -c 'exec 3<>/dev/tcp/127.0.0.1/80'
```
:::after{step=install}
nginx is installed on **{{host}}**. Put your site into `/etc/nginx/sites-available/`
and review the firewall before exposing it.
:::