feat(core): parameter fields in text, groups and gating by used values (#16)

- `::param{name=x}` places a parameter's input inside the text.
- `:::group{title="…" collapsed}` is a collapsible container for anything;
  groups are presentational and never gate steps. Included notebooks
  namespace field names and group titles.
- `groupInputs` reports a container's input status (missing, filled,
  optional, none) from its fields, the parameters its steps use and, for
  `::use`, the included notebook's parameters.
- A step is gated only by the values it uses: referenced parameters, the
  required secrets its script reads and valid set secrets of its scope.
  Unused required parameters no longer block early steps of a guided
  runbook.
- Spec §3.2/§3.6/§3.7, workspace format guide and a guided admin-user
  example notebook.
This commit is contained in:
Florian Schmidt
2026-11-16 16:49:47 +01:00
parent cae72c7f28
commit bdbcd2dcd5
10 changed files with 475 additions and 31 deletions
+38 -6
View File
@@ -93,7 +93,11 @@ Download the private key above, then save it:
- **Substitution in scripts is shell-safe**: the value is inserted shell-quoted when it - **Substitution in scripts is shell-safe**: the value is inserted shell-quoted when it
contains anything outside `[A-Za-z0-9._/@:=+-]`. The displayed script and the executed contains anything outside `[A-Za-z0-9._/@:=+-]`. The displayed script and the executed
script are the same string. One function does this (`core/shellQuote`), nowhere else. script are the same string. One function does this (`core/shellQuote`), nowhere else.
- A step with a missing required param shows the script with `{{name}}` highlighted and a disabled Run button. - A step needs exactly the values it uses: every param and runtime value it references, and
the required secrets its script reads as `$NAME`/`${NAME}`. While one is missing the script
shows `{{name}}` highlighted and Run is disabled. Required params the step does not use never
block it, so a guided notebook (§3.7) runs its first steps before later values are entered.
Set secrets of the step's notebook are always validated, because all are passed as env vars.
### 3.3 Step attributes ### 3.3 Step attributes
@@ -149,12 +153,11 @@ notebook that first creates an LXC container:
- `with` sets defaults of the included params, written in the including notebook's - `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 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`). 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 - Steps are gated only by the values they use (§3.2); an included notebook's empty form
value it references. never blocks the parent's steps unless they reference its values.
- Non-secret defaults may reference captures and builtins (`default: "{{ct.host}}"`). Until - 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 the value exists the field shows "Available after the step that sets ct.host". Only
required param that waits for a capture of its own notebook would block the step steps that reference such a param wait for it.
producing it; make such params optional.
- `::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}` adds - `::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 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 host with that name). `capture` stores the host name as a runtime value so later
@@ -163,6 +166,35 @@ notebook that first creates an LXC container:
`{{shellbook.public_key}}` is ShellBook's SSH public key. The server sets them on every `{{shellbook.public_key}}` is ShellBook's SSH public key. The server sets them on every
run; client-sent values are ignored. run; client-sent values are ignored.
### 3.7 Guided text: parameter fields and groups
Authors can ask for each value where the text explains it:
```markdown
:::group{title="1. Network" collapsed}
Pick the bridge the container joins:
::param{name=bridge}
:::
```
- `::param{name=x}` on its own line shows the input of the declared parameter `x` at that
point. It is bound to the same value as the parameter panel, which still lists every
parameter. Inside an included notebook the name is namespaced like everything else.
- `:::group{title="…" collapsed}` … `:::` is a titled, collapsible container for any
blocks, including nested groups. `collapsed` starts it closed; the user's choice is
remembered per notebook. The title may use `{{name}}` like prose. Groups are purely
presentational: unlike `:::when` they never hide or block steps.
- A group's **inputs** are its `::param` fields, the parameters its steps and `::host`
blocks reference (those are needed: the step cannot run without them) and, for a
`::use` section, the included notebook's parameters. Inactive `:::when` sections and
runtime values are ignored. Core `groupInputs` computes the status, shown as the outline
color and in words: orange (missing) while a required or needed input is empty or a
value is invalid, green (filled) when every input has a value, grey (optional) when
only optional inputs are empty or there are none.
- Included notebooks (`::use`) are shown as groups with the same status, so a reusable
group is a notebook included where it is needed.
## 4. Execution ## 4. Execution
- Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY. - Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY.
+10 -8
View File
@@ -15,7 +15,7 @@ export function notebookIncludes(notebook: Notebook): string[] {
const walk = (blocks: Block[]) => { const walk = (blocks: Block[]) => {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "use" && !block.blocks.length) { if (includePath(block.path)) paths.push(block.path); } 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); else if (block.type === "after" || block.type === "when" || block.type === "use" || block.type === "group") walk(block.blocks);
} }
}; };
walk(notebook.blocks); walk(notebook.blocks);
@@ -53,6 +53,8 @@ function prefixBlocks(blocks: Block[], alias: string): Block[] {
case "after": return { ...block, stepId: qualify(alias, block.stepId), blocks: prefixBlocks(block.blocks, 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 "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 "use": return { ...block, scope: qualify(alias, block.scope), bindings: {}, blocks: prefixBlocks(block.blocks, alias) };
case "group": return { ...block, title: rewrite(block.title, alias), blocks: prefixBlocks(block.blocks, alias) };
case "param": return { ...block, name: qualify(alias, block.name) };
case "host": return { case "host": return {
...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope), ...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope),
name: rewrite(block.name, alias), address: rewrite(block.address, alias), name: rewrite(block.name, alias), address: rewrite(block.address, alias),
@@ -77,7 +79,7 @@ function blockIds(blocks: Block[], into: string[] = []): string[] {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "step") into.push(block.step.attrs.id); if (block.type === "step") into.push(block.step.attrs.id);
else if (block.type === "host") into.push(block.id); else if (block.type === "host") into.push(block.id);
else if (block.type !== "markdown") blockIds(block.blocks, into); else if ("blocks" in block) blockIds(block.blocks, into);
} }
return into; return into;
} }
@@ -98,7 +100,7 @@ function compose(path: string, notebook: Notebook, load: (path: string) => Noteb
const params: ParamDef[] = [...notebook.params]; const params: ParamDef[] = [...notebook.params];
const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line }); const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line });
const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => { 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 === "after" || block.type === "when" || block.type === "group") return { ...block, blocks: resolve(block.blocks) };
if (block.type !== "use") return block; if (block.type !== "use") return block;
const line = block.range.startLine; const line = block.range.startLine;
// The parser already reported an invalid path; never hand it to the loader. // The parser already reported an invalid path; never hand it to the loader.
@@ -132,11 +134,11 @@ function compose(path: string, notebook: Notebook, load: (path: string) => Noteb
return { ...notebook, params, blocks, diagnostics }; return { ...notebook, params, blocks, diagnostics };
} }
/** Find a step anywhere in the block tree (after, when and use containers). */ /** Find a step anywhere in the block tree (after, when, use and group containers). */
export function findStep(blocks: Block[], id: string): Step | undefined { export function findStep(blocks: Block[], id: string): Step | undefined {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "step" && block.step.attrs.id === id) return block.step; if (block.type === "step" && block.step.attrs.id === id) return block.step;
if (block.type === "after" || block.type === "when" || block.type === "use") { if ("blocks" in block) {
const found = findStep(block.blocks, id); const found = findStep(block.blocks, id);
if (found) return found; if (found) return found;
} }
@@ -155,7 +157,7 @@ export function blockActive(notebook: Notebook, id: string, values: ParamValues)
if (block.type === "when") { if (block.type === "when") {
const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? "")); const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? ""));
if (found !== undefined) return found; if (found !== undefined) return found;
} else if (block.type === "after" || block.type === "use") { } else if (block.type === "after" || block.type === "use" || block.type === "group") {
const found = walk(block.blocks, active); const found = walk(block.blocks, active);
if (found !== undefined) return found; if (found !== undefined) return found;
} }
@@ -171,7 +173,7 @@ export function scopeActive(notebook: Notebook, scope: string, values: ParamValu
const walk = (blocks: Block[], active: boolean): boolean | undefined => { const walk = (blocks: Block[], active: boolean): boolean | undefined => {
for (const block of blocks) { for (const block of blocks) {
if (block.type === "use" && block.scope === scope) return active; if (block.type === "use" && block.scope === scope) return active;
if (block.type === "markdown" || block.type === "step" || block.type === "host") continue; if (!("blocks" in block)) continue;
const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? ""))); const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? "")));
if (found !== undefined) return found; if (found !== undefined) return found;
} }
@@ -185,7 +187,7 @@ export function captureNames(blocks: Block[], into = new Set<string>()): Set<str
for (const block of blocks) { for (const block of blocks) {
if (block.type === "step" && block.step.attrs.capture) into.add(block.step.attrs.capture); 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 === "host" && block.capture) into.add(block.capture);
else if (block.type !== "markdown" && block.type !== "step" && block.type !== "host") captureNames(block.blocks, into); else if ("blocks" in block) captureNames(block.blocks, into);
} }
return into; return into;
} }
+76 -10
View File
@@ -1,5 +1,5 @@
// Public API of @shellbook/core. Pure functions, no I/O. // Public API of @shellbook/core. Pure functions, no I/O.
import type { Block, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types"; import type { Block, GroupInputs, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types";
import { captureNames, isBuiltin } from "./compose"; import { captureNames, isBuiltin } from "./compose";
export type * from "./types"; export type * from "./types";
export type * from "./protocol"; export type * from "./protocol";
@@ -78,8 +78,10 @@ export function resolveParams(
} }
/** /**
* Shared template substitution for steps and host blocks. Required params gate only * Shared template substitution for steps and host blocks. A block needs exactly the values
* blocks of their own scope: an included notebook's form does not block the parent. * it uses (spec §3.6): referenced parameters and runtime values, and for scripts the
* required secrets of its scope that the script reads. Required parameters it does not
* use never block it, so guided notebooks can run early steps before later values exist.
*/ */
function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) { function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) {
const resolved = resolveParams(notebook, values, hostNames, runtime); const resolved = resolveParams(notebook, values, hostNames, runtime);
@@ -87,12 +89,18 @@ function substitution(notebook: Notebook, scope: string | undefined, values: Par
const defs = new Map(notebook.params.map(def => [def.name, def])); const defs = new Map(notebook.params.map(def => [def.name, def]));
const invalid = dictionary(); const invalid = dictionary();
const missing = new Set<string>(); const missing = new Set<string>();
for (const def of notebook.params) { const ownSecrets = notebook.params.filter(def => def.type === "secret" && (def.scope ?? "") === (scope ?? ""));
if ((def.scope ?? "") !== (scope ?? "")) continue; // Every set secret of the scope is passed as an env var (secretEnv), so it must be valid.
if (def.required && !resolved.values[def.name]) missing.add(def.name); for (const def of ownSecrets)
if ((def.required || def.type === "secret") && resolved.values[def.name] if (resolved.values[def.name] && own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!; /** A required secret the script reads as $NAME or ${NAME} (its local name) must be set. */
const readsSecrets = (script: string) => {
for (const def of ownSecrets) {
const local = def.scope ? def.name.slice(def.scope.length + 1) : def.name;
if (def.required && !resolved.values[def.name] && new RegExp("\\$\\{?" + local + "(?![A-Za-z0-9_])").test(script))
missing.add(def.name);
} }
};
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => { const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
const def = defs.get(name); const def = defs.get(name);
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; } if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
@@ -110,7 +118,7 @@ function substitution(notebook: Notebook, scope: string | undefined, values: Par
if (own(invalid, name)) return match; if (own(invalid, name)) return match;
return script ? shellQuote(value) : value; return script ? shellQuote(value) : value;
}); });
return { substitute, invalid, missing }; return { substitute, readsSecrets, invalid, missing };
} }
/** /**
@@ -124,8 +132,9 @@ export function renderStep(
runtime: ParamValues, runtime: ParamValues,
hostNames: readonly string[], hostNames: readonly string[],
): RenderedStep { ): RenderedStep {
const { substitute, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames); const { substitute, readsSecrets, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames);
const script = substitute(step.script, true); const script = substitute(step.script, true);
readsSecrets(step.script);
const host = step.attrs.local || step.attrs.host === undefined ? undefined : substitute(step.attrs.host, false); 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"; if (!step.attrs.local && (!host || !hostNames.includes(host))) invalid.host ??= "Unknown or missing target host";
const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes(".."); const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes("..");
@@ -162,6 +171,63 @@ export function renderHost(
return { id: block.id, name, address, user, port, missing: [...missing], invalid }; return { id: block.id, name, address, user, port, missing: [...missing], invalid };
} }
/**
* Input status of a container block (`:::group`, `::use`; spec §3.7). Its inputs are its
* `::param` fields, the parameters its steps and host blocks reference (those are needed:
* the step cannot run without them) and, for `::use`, the included notebook's parameters.
* Sections of inactive `:::when` blocks are ignored; runtime values are not inputs.
*/
export function groupInputs(
notebook: Notebook,
block: Block,
values: ParamValues,
hostNames: readonly string[],
runtime: ParamValues = {},
): GroupInputs {
const resolved = resolveParams(notebook, values, hostNames, runtime);
const defs = new Map(notebook.params.map(def => [def.name, def]));
const params: string[] = [];
const needed = new Set<string>();
const add = (name: string, need: boolean) => {
const def = defs.get(name);
if (!def) return;
if (!params.includes(name)) params.push(name);
if (need || def.required) needed.add(name);
};
const references = (text: string) => { for (const match of text.matchAll(template)) add(match[1]!, true); };
const walk = (items: Block[]) => {
for (const item of items) {
switch (item.type) {
case "param": add(item.name, false); break;
case "step": {
const attrs = item.step.attrs;
// In display order: the target first, then the script.
if (attrs.host !== undefined) references(attrs.host);
references(item.step.script);
attrs.artifacts.forEach(references);
for (const upload of attrs.uploads) { references(upload.src); references(upload.dst); }
break;
}
case "host": [item.name, item.address, item.user, item.port].forEach(references); break;
case "when": if (item.values.includes(resolved.values[item.param] ?? "")) walk(item.blocks); break;
case "use":
for (const def of notebook.params) if (def.scope === item.scope) add(def.name, false);
walk(item.blocks); break;
case "after": case "group": walk(item.blocks); break;
case "markdown": break;
}
}
};
walk([block]);
const filled = (name: string) => !!resolved.values[name];
const missing = params.filter(name => needed.has(name) && !filled(name));
const invalid = params.filter(name => filled(name) && own(resolved.errors, name));
const status = missing.length || invalid.length ? "missing"
: !params.length ? "none"
: params.every(filled) ? "filled" : "optional";
return { status, params, missing, invalid };
}
/** Substitute prose without quoting; secrets always appear masked. */ /** Substitute prose without quoting; secrets always appear masked. */
export function renderText(text: string, values: ParamValues, notebook: Notebook): string { 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)); const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name));
+26 -3
View File
@@ -156,7 +156,24 @@ export function parseNotebook(source: string): Notebook {
blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } }); blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue; markdownStart = i; continue;
} }
const leaf = /^\s{0,3}::(use|host)\{(.*)\}\s*$/.exec(line); const group = /^\s{0,3}:::group\{(.*)\}\s*$/.exec(line);
if (group && depth < 100) {
flush(); const begin = i++;
const attrs = attributes(group[1]!, m => error(m, begin + 1));
for (const key of attrs.keys()) if (!["title", "collapsed"].includes(key)) error(`Unknown group attribute: ${key}`, begin + 1);
const title = attrs.get("title");
if (title?.length !== 1 || typeof title[0] !== "string" || !title[0].trim()) error('group requires title="…"', begin + 1);
if (attrs.has("collapsed") && attrs.get("collapsed")![0] !== true) error("collapsed must be a flag", begin + 1);
const children = parseBlocks(true, depth + 1);
if (i === lines.length) error("Unclosed group container", begin + 1);
else i++;
blocks.push({
type: "group", title: typeof title?.[0] === "string" ? title[0] : "", collapsed: attrs.has("collapsed"),
blocks: children, range: { startLine: begin + 1, endLine: i },
});
markdownStart = i; continue;
}
const leaf = /^\s{0,3}::(use|host|param)\{(.*)\}\s*$/.exec(line);
if (leaf) { if (leaf) {
flush(); flush();
const lineNo = i + 1; const lineNo = i + 1;
@@ -167,7 +184,13 @@ export function parseNotebook(source: string): Notebook {
return typeof v?.[0] === "string" ? v[0] : undefined; return typeof v?.[0] === "string" ? v[0] : undefined;
}; };
const range = { startLine: lineNo, endLine: lineNo }; const range = { startLine: lineNo, endLine: lineNo };
if (leaf[1] === "use") { if (leaf[1] === "param") {
for (const key of attrs.keys()) if (key !== "name") error(`Unknown param attribute: ${key}`, lineNo);
const name = get("name") ?? "";
if (!name) error("param requires name=parameter", lineNo);
else if (!notebook.params.some(def => def.name === name)) error(`param references unknown parameter: ${name}`, lineNo);
blocks.push({ type: "param", name, range });
} else if (leaf[1] === "use") {
for (const key of attrs.keys()) if (!["notebook", "as", "with"].includes(key)) error(`Unknown use attribute: ${key}`, lineNo); for (const key of attrs.keys()) if (!["notebook", "as", "with"].includes(key)) error(`Unknown use attribute: ${key}`, lineNo);
const path = get("notebook") ?? ""; const path = get("notebook") ?? "";
const alias = get("as") ?? ""; const alias = get("as") ?? "";
@@ -270,7 +293,7 @@ export function parseNotebook(source: string): Notebook {
i = end < lines.length ? end + 1 : end; markdownStart = i; continue; i = end < lines.length ? end + 1 : end; markdownStart = i; continue;
} }
heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1]; heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1];
if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host)\b/.test(line)) error("Malformed or unexpected directive", i + 1); if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host|param)\b/.test(line)) error("Malformed or unexpected directive", i + 1);
i++; i++;
} }
flush(); return blocks; flush(); return blocks;
+37
View File
@@ -105,6 +105,26 @@ export type Block =
blocks: Block[]; blocks: Block[];
range: SourceRange; range: SourceRange;
} }
| {
/** `::param{name=x}` — the parameter's input field at this point of the text. */
type: "param";
/** Parameter name (namespaced like `ct.hostname` inside an included notebook). */
name: string;
range: SourceRange;
}
| {
/**
* `:::group{title="…" collapsed}` — a titled, collapsible container for any blocks.
* Purely presentational: it never gates display or execution.
*/
type: "group";
/** Template; `{{name}}` is substituted like prose. */
title: string;
/** `collapsed` flag: starts closed until the user opens it. */
collapsed: boolean;
blocks: Block[];
range: SourceRange;
}
| { | {
/** `::host{name= address= user= port= capture=}` — add a machine to Hosts from the notebook. */ /** `::host{name= address= user= port= capture=}` — add a machine to Hosts from the notebook. */
type: "host"; type: "host";
@@ -120,6 +140,23 @@ export type Block =
range: SourceRange; range: SourceRange;
}; };
/**
* How far the inputs of a group (or included notebook) are filled in:
* "missing" — a needed value is empty or a value is invalid; "filled" — every input has a
* value; "optional" — only optional inputs are empty; "none" — the group has no inputs.
*/
export type InputStatus = "none" | "optional" | "filled" | "missing";
export interface GroupInputs {
status: InputStatus;
/** Parameters the group asks for or uses, in document order. */
params: string[];
/** Needed (required, or referenced by a step or host block) but empty. */
missing: string[];
/** Filled but invalid. */
invalid: string[];
}
/** A `::host` block with all templates resolved. */ /** A `::host` block with all templates resolved. */
export interface RenderedHost { export interface RenderedHost {
id: string; id: string;
+1 -1
View File
@@ -46,7 +46,7 @@ const files: Record<string, string> = { "infra/lxc.md": lxc, "services/web.md":
const load = (path: string) => files[path] === undefined ? undefined : parseNotebook(files[path]!); const load = (path: string) => files[path] === undefined ? undefined : parseNotebook(files[path]!);
const composed = () => composeNotebook("services/web.md", parseNotebook(service), load); const composed = () => composeNotebook("services/web.md", parseNotebook(service), load);
function all(blocks: Block[]): Block[] { function all(blocks: Block[]): Block[] {
return blocks.flatMap(b => b.type === "markdown" || b.type === "step" || b.type === "host" ? [b] : [b, ...all(b.blocks)]); return blocks.flatMap(b => "blocks" in b ? [b, ...all(b.blocks)] : [b]);
} }
const hosts = ["pve", "web-ct", "existing"]; const hosts = ["pve", "web-ct", "existing"];
+2 -1
View File
@@ -132,7 +132,8 @@ describe("rendering and secrets", () => {
it("blocks missing and invalid used params, unknown variables and invalid hosts", () => { it("blocks missing and invalid used params, unknown variables and invalid hosts", () => {
const n = book(" x: {type: name}\n required: {type: string, required: true}\n unused: {type: name}", "{{x}} {{unknown}} {{empty}}", "host=missing"); const n = book(" x: {type: name}\n required: {type: string, required: true}\n unused: {type: name}", "{{x}} {{unknown}} {{empty}}", "host=missing");
const r = render(n, { x: "bad value", unused: "bad value" }, { empty: "" }); const r = render(n, { x: "bad value", unused: "bad value" }, { empty: "" });
expect(r.missing).toEqual(["required", "empty"]); // An unused required param does not block the step (guided notebooks, spec §3.6).
expect(r.missing).toEqual(["empty"]);
expect(Object.keys(r.invalid).sort()).toEqual(["host", "unknown", "x"]); expect(Object.keys(r.invalid).sort()).toEqual(["host", "unknown", "x"]);
expect(r.script).toBe("{{x}} {{unknown}} {{empty}}\n"); expect(r.script).toBe("{{x}} {{unknown}} {{empty}}\n");
}); });
+202
View File
@@ -0,0 +1,202 @@
import { describe, expect, it } from "vitest";
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { blockActive, composeNotebook, findStep, groupInputs, parseNotebook, renderStep } from "../src/index";
import type { Block, Notebook } from "../src/index";
const fence = "```";
const source = `---
title: Groups
params:
host: { type: host, required: true }
user: { type: name, default: admin }
port: { type: string }
note: { type: string }
mode: { type: choice, options: [a, b] }
---
# Groups
:::group{title="Connect to {{host}}"}
First pick the server:
::param{name=host}
${fence}sh {check host="{{host}}" id=ping}
id {{user}}
${fence}
:::group{title="Optional details" collapsed}
::param{name=note}
:::
:::
:::group{title="Prose only"}
Nothing to fill in here.
:::
`;
const groups = (blocks: Block[]): Extract<Block, { type: "group" }>[] =>
blocks.flatMap(b => (b.type === "group" ? [b, ...groups(b.blocks)] : "blocks" in b ? groups(b.blocks) : []));
const hosts = ["web"];
describe("group and param directives", () => {
it("parses nested groups, the collapsed flag and parameter fields", () => {
const n = parseNotebook(source);
expect(n.diagnostics).toEqual([]);
const [connect, details, prose] = groups(n.blocks);
expect(connect).toMatchObject({ title: "Connect to {{host}}", collapsed: false, range: { startLine: 13 } });
expect(connect!.blocks.map(b => b.type)).toEqual(["markdown", "param", "markdown", "step", "markdown", "group"]);
expect(connect!.blocks[1]).toMatchObject({ type: "param", name: "host", range: { startLine: 16, endLine: 16 } });
expect(details).toMatchObject({ title: "Optional details", collapsed: true });
expect(details!.blocks).toEqual([expect.objectContaining({ type: "param", name: "note" })]);
expect(prose!.blocks).toEqual([expect.objectContaining({ type: "markdown" })]);
});
it("does not gate steps inside groups", () => {
const n = parseNotebook(source);
expect(findStep(n.blocks, "ping")?.attrs.host).toBe("{{host}}");
expect(blockActive(n, "ping", {})).toBe(true);
expect(renderStep(n, findStep(n.blocks, "ping")!, { host: "web" }, {}, hosts).script).toBe("id admin\n");
});
it.each([
[":::group{}\n:::", 'group requires title="…"'],
[':::group{title="x" open}\n:::', "Unknown group attribute: open"],
[':::group{title="x" collapsed=yes}\n:::', "collapsed must be a flag"],
[':::group{title="x"}\ntext', "Unclosed group container"],
["::param{name=nope}", "param references unknown parameter: nope"],
["::param{}", "param requires name=parameter"],
["::param{name=user label=x}", "Unknown param attribute: label"],
["::param name=user", "Malformed or unexpected directive"],
])("reports %j", (body, message) => {
const n = parseNotebook(`---\nparams:\n user: { type: name }\n---\n${body}\n`);
expect(n.diagnostics).toContainEqual(expect.objectContaining({ severity: "error", message, line: 5 }));
});
it("namespaces fields and group titles of included notebooks", () => {
const child = `---\ntitle: Child\nparams:\n name: { type: name, required: true }\n---\n:::group{title="Name {{name}}"}\n::param{name=name}\n:::\n`;
const root = `::use{notebook="lib/child.md" as=c}\n`;
const composed = composeNotebook("root.md", parseNotebook(root), path => (path === "lib/child.md" ? parseNotebook(child) : undefined));
expect(composed.diagnostics).toEqual([]);
const [group] = groups(composed.blocks);
expect(group).toMatchObject({ title: "Name {{c.name}}", blocks: [{ type: "param", name: "c.name" }] });
});
});
describe("groupInputs", () => {
const notebook = parseNotebook(source);
const [connect, details, prose] = groups(notebook.blocks);
const status = (block: Block, values: Record<string, string>, n: Notebook = notebook) =>
groupInputs(n, block, values, hosts);
it("is missing while a required field is empty, filled when every input has a value", () => {
expect(status(connect!, {})).toEqual({ status: "missing", params: ["host", "user", "note"], missing: ["host"], invalid: [] });
// user has a default; the optional note in the nested group still counts for the outer one.
expect(status(connect!, { host: "web" }).status).toBe("optional");
expect(status(connect!, { host: "web", note: "x" })).toMatchObject({ status: "filled", missing: [] });
});
it("treats a parameter a step references as needed and reports invalid values", () => {
expect(status(connect!, { host: "web", user: "" }).status).toBe("optional"); // default fills it
const n = parseNotebook(source.replace("user: { type: name, default: admin }", "user: { type: name }"));
const [group] = groups(n.blocks);
expect(status(group!, { host: "web" }, n)).toMatchObject({ status: "missing", missing: ["user"] });
expect(status(group!, { host: "nope", user: "root" }, n)).toMatchObject({ status: "missing", missing: [], invalid: ["host"] });
});
it("is optional with only optional fields and none without inputs", () => {
expect(status(details!, {})).toEqual({ status: "optional", params: ["note"], missing: [], invalid: [] });
expect(status(details!, { note: "x" }).status).toBe("filled");
expect(status(prose!, {})).toEqual({ status: "none", params: [], missing: [], invalid: [] });
});
it("ignores inactive when sections and runtime values", () => {
const n = parseNotebook(`---
params:
mode: { type: choice, options: [a, b], default: a }
x: { type: string, required: true }
---
:::group{title="G"}
:::when{mode=b}
::param{name=x}
:::
${fence}sh {run on=local id=r capture=out}
echo {{mode}}
${fence}
${fence}sh {run on=local id=s}
echo {{out}}
${fence}
:::
`);
expect(n.diagnostics).toEqual([]);
const [group] = groups(n.blocks);
expect(status(group!, {}, n)).toEqual({ status: "filled", params: ["mode"], missing: [], invalid: [] });
expect(status(group!, { mode: "b" }, n)).toMatchObject({ status: "missing", missing: ["x"] });
});
it("counts an included notebook's own parameters for its ::use section", () => {
const child = `---\ntitle: Child\nparams:\n name: { type: name, required: true }\n size: { type: string }\n---\ntext\n`;
const composed = composeNotebook("root.md", parseNotebook(`::use{notebook="lib/child.md" as=c}\n`), () => parseNotebook(child));
const use = composed.blocks.find(b => b.type === "use")!;
expect(status(use, {}, composed)).toEqual({ status: "missing", params: ["c.name", "c.size"], missing: ["c.name"], invalid: [] });
expect(status(use, { "c.name": "x" }, composed).status).toBe("optional");
});
});
describe("shipped templates", () => {
const root = fileURLToPath(new URL("../../../templates/workspace/notebooks/", import.meta.url));
const files = readdirSync(root, { recursive: true, encoding: "utf8" }).filter(f => f.endsWith(".md"));
it.each(files)("%s parses without errors", file => {
const n = parseNotebook(readFileSync(join(root, file), "utf8"));
// Included notebooks are resolved by the server; parsing alone must be clean.
expect(n.diagnostics).toEqual([]);
});
it("guides the admin-user example with fields in each group", () => {
const n = parseNotebook(readFileSync(join(root, "admin-user.md"), "utf8"));
const all = groups(n.blocks);
expect(all.map(g => g.title)).toEqual(["1. Pick the server", "2. Describe the user", "3. Create the user", "4. Verify"]);
expect(groupInputs(n, all[2]!, {}, hosts)).toMatchObject({ status: "missing", missing: ["host", "user", "pubkey"] });
const values = { host: "web", user: "ops", pubkey: "ssh-ed25519 AAAA ops" };
expect(all.map(g => groupInputs(n, g, values, hosts).status)).toEqual(["filled", "filled", "filled", "filled"]);
expect(renderStep(n, findStep(n.blocks, "create")!, values, {}, hosts).script)
.toContain(String.raw`printf '%s\n' 'ssh-ed25519 AAAA ops' > /home/ops/.ssh/authorized_keys`);
});
});
describe("step gating for guided notebooks", () => {
const n = parseNotebook(`---
params:
host: { type: host, required: true }
user: { type: name, required: true }
TOKEN: { type: secret, required: true }
OTHER: { type: secret, required: true }
---
${fence}sh {check host="{{host}}" id=first}
true
${fence}
${fence}sh {run host="{{host}}" id=later}
useradd {{user}}
${fence}
${fence}sh {run host="{{host}}" id=token}
curl -H "Authorization: Bearer \${TOKEN}" https://example.invalid
${fence}
`);
const step = (id: string) => findStep(n.blocks, id)!;
const render = (id: string, values: Record<string, string>) => renderStep(n, step(id), values, {}, hosts);
it("blocks a step only on the values it uses", () => {
// Required, but unused by this step: an earlier step runs before later values are known.
expect(render("first", { host: "web" })).toMatchObject({ missing: [], invalid: {} });
expect(render("later", { host: "web" }).missing).toEqual(["user"]);
});
it("treats a required secret the script reads as $NAME or \${NAME} as used", () => {
expect(render("token", { host: "web" }).missing).toEqual(["TOKEN"]);
expect(render("token", { host: "web", TOKEN: "t" })).toMatchObject({ missing: [], invalid: {} });
// A $TOKENX or OTHER mention is not TOKEN.
expect(render("first", { host: "web" }).missing).not.toContain("OTHER");
});
});
+24 -1
View File
@@ -48,7 +48,9 @@ Non-secret defaults may reference other parameters.
Use `{{name}}` in prose, attributes and scripts. Script substitution is already Use `{{name}}` in prose, attributes and scripts. Script substitution is already
shell-quoted by ShellBook's core: write `id {{user}}`, not `id '{{user}}'`. shell-quoted by ShellBook's core: write `id {{user}}`, not `id '{{user}}'`.
Do not invent escaping rules or assume templates expand like shell variables. Do not invent escaping rules or assume templates expand like shell variables.
Missing required parameters disable execution. In shell strings use ordinary A step runs once every value it uses is set: its `{{…}}` references and the required
secrets its script reads as `$NAME`. Unused required parameters do not block it, so
early steps can run before later values are known. In shell strings use ordinary
shell variables where needed, e.g. `destination={{destination}}` then `"$destination"`. shell variables where needed, e.g. `destination={{destination}}` then `"$destination"`.
## Step syntax and every attribute ## Step syntax and every attribute
@@ -135,5 +137,26 @@ apt-get install -y nginx
offers to add a created machine to Hosts and stores its name in `{{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`. - `{{shellbook.public_key}}` is ShellBook's SSH public key, e.g. for `pct create --ssh-public-keys`.
## Guided text: fields and groups
````markdown
:::group{title="1. Network" collapsed}
Pick the bridge the container joins:
::param{name=bridge}
```sh {check host="{{host}}" id=bridge-exists}
ip link show {{bridge}}
```
:::
````
- `::param{name=x}` on its own line shows parameter `x`'s input at that point (same
value as the parameter panel). Use it to ask for each value where it is explained.
- `:::group{title="…"}` … `:::` is a collapsible section for anything (text, fields,
steps, nested groups); `collapsed` starts it closed. Its outline is orange while a
required field or a parameter its steps use is empty, green when all its inputs are
filled, grey otherwise. Groups never hide or block steps; use `:::when` for that.
See the notebooks for complete SSH-key, read-only hardening, Debian package, LXC 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. container (`infra/lxc-container.md`) and chained service (`services/web-server.md`) examples.
@@ -0,0 +1,58 @@
---
title: Create an admin user
params:
host: { type: host, required: true, label: Target server }
user: { type: name, required: true, label: User name }
pubkey: { type: string, required: true, label: Public SSH key }
shell: { type: path, default: /bin/bash, label: Login shell }
---
# Create an admin user
A guided runbook: each section asks for what it needs where it is explained. A
section's outline turns green once its values are filled in. For Debian hosts;
runs need passwordless sudo and ask for confirmation.
:::group{title="1. Pick the server"}
Choose the machine from Hosts. This check only reads state.
::param{name=host}
```sh {check host="{{host}}" id=can-sudo title="Passwordless sudo works" sudo}
true
```
:::
:::group{title="2. Describe the user"}
Pick a login name (letters, digits, `.`, `_`, `-`) and paste the public key the
user logs in with, e.g. the content of their `~/.ssh/id_ed25519.pub`.
::param{name=user}
::param{name=pubkey}
::param{name=shell}
```sh {check host="{{host}}" id=user-free title="User does not exist yet"}
! id {{user}}
```
:::
:::group{title="3. Create the user"}
Creates **{{user}}** in the `sudo` group and authorizes the key.
```sh {run host="{{host}}" id=create title="Create user and authorize key" sudo confirm}
useradd --create-home --shell {{shell}} --groups sudo {{user}}
install -d -m 700 -o {{user}} -g {{user}} /home/{{user}}/.ssh
printf '%s\n' {{pubkey}} > /home/{{user}}/.ssh/authorized_keys
chown {{user}}:{{user}} /home/{{user}}/.ssh/authorized_keys
chmod 600 /home/{{user}}/.ssh/authorized_keys
```
:::
:::group{title="4. Verify" collapsed}
```sh {check host="{{host}}" id=verify title="User is in sudo and has the key" sudo}
id -nG {{user}} | grep -qw sudo
test -s /home/{{user}}/.ssh/authorized_keys
```
:::