Merge branch 't3/implement-core-notebook-parser'
This commit is contained in:
@@ -10,5 +10,8 @@
|
|||||||
"build": "tsc -p tsconfig.json --noEmit",
|
"build": "tsc -p tsconfig.json --noEmit",
|
||||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
"test": "vitest run --passWithNoTests"
|
"test": "vitest run --passWithNoTests"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"yaml": "^2.8.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+90
-26
@@ -1,19 +1,12 @@
|
|||||||
// Public API of @shellbook/core. Pure functions, no I/O.
|
// Public API of @shellbook/core. Pure functions, no I/O.
|
||||||
// Signatures are a CONTRACT used by server and web; implementations land in M0.
|
|
||||||
|
|
||||||
import type { Notebook, ParamValues, RenderedStep, Step } from "./types";
|
import type { Notebook, ParamValues, RenderedStep, Step } from "./types";
|
||||||
|
|
||||||
export type * from "./types";
|
export type * from "./types";
|
||||||
export type * from "./protocol";
|
export type * from "./protocol";
|
||||||
|
export { parseNotebook } from "./parser";
|
||||||
|
|
||||||
const notImplemented = (fn: string): never => {
|
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
|
||||||
throw new Error(`@shellbook/core: ${fn} is not implemented yet (M0)`);
|
const own = (object: object, key: string) => Object.hasOwn(object, key);
|
||||||
};
|
const dictionary = (): Record<string, string> => Object.create(null) as Record<string, string>;
|
||||||
|
|
||||||
/** Parse notebook Markdown (frontmatter, steps, :::after sections). Never throws; problems go to diagnostics. */
|
|
||||||
export function parseNotebook(source: string): Notebook {
|
|
||||||
return notImplemented(`parseNotebook(${source.length} chars)`);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Quote a value for POSIX sh. Returns the value unchanged when it only contains
|
* Quote a value for POSIX sh. Returns the value unchanged when it only contains
|
||||||
@@ -21,26 +14,58 @@ export function parseNotebook(source: string): Notebook {
|
|||||||
* The ONLY place in the codebase that quotes shell values.
|
* The ONLY place in the codebase that quotes shell values.
|
||||||
*/
|
*/
|
||||||
export function shellQuote(value: string): string {
|
export function shellQuote(value: string): string {
|
||||||
return notImplemented(`shellQuote(${value.length} chars)`);
|
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.
|
|
||||||
* Returns effective values and an error message per invalid/missing-required param.
|
|
||||||
* `hostNames` = names from hosts.yaml (for type "host").
|
|
||||||
*/
|
|
||||||
export function resolveParams(
|
export function resolveParams(
|
||||||
notebook: Notebook,
|
notebook: Notebook,
|
||||||
values: ParamValues,
|
values: ParamValues,
|
||||||
hostNames: readonly string[],
|
hostNames: readonly string[],
|
||||||
): { values: ParamValues; errors: Record<string, string> } {
|
): { values: ParamValues; errors: Record<string, string> } {
|
||||||
return notImplemented(`resolveParams(${notebook.params.length}, ${Object.keys(values).length}, ${hostNames.length})`);
|
const effective = dictionary();
|
||||||
|
const errors = dictionary();
|
||||||
|
const defs = new Map(notebook.params.map(def => [def.name, def]));
|
||||||
|
const active = new Set<string>();
|
||||||
|
const resolve = (name: string): string => {
|
||||||
|
if (own(effective, name)) return effective[name]!;
|
||||||
|
const def = defs.get(name);
|
||||||
|
if (!def) return "";
|
||||||
|
if (active.has(name)) { errors[name] = "Cyclic parameter default"; return ""; }
|
||||||
|
active.add(name);
|
||||||
|
let value = own(values, name) ? values[name] ?? "" : "";
|
||||||
|
if (!value && def.type !== "secret" && def.default !== undefined) {
|
||||||
|
value = def.default.replace(template, (match, ref: string) => {
|
||||||
|
const other = defs.get(ref);
|
||||||
|
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);
|
||||||
|
if (own(errors, ref)) errors[name] = `Invalid default dependency: ${ref}`;
|
||||||
|
if (!resolved) errors[name] = `Missing default dependency: ${ref}`;
|
||||||
|
return resolved || match;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
active.delete(name);
|
||||||
|
effective[name] = value;
|
||||||
|
if (!value) {
|
||||||
|
if (def.required) errors[name] ??= "Required parameter is missing";
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
// POSIX arguments and environment values cannot contain NUL, regardless of type.
|
||||||
|
if (value.includes("\0")) errors[name] = "Value cannot contain NUL";
|
||||||
|
else if (def.type === "host" && !hostNames.includes(value)) errors[name] = "Unknown host";
|
||||||
|
else if (def.type === "name" && !/^[A-Za-z0-9._-]+$/.test(value)) errors[name] = "Expected a name containing only letters, digits, ., _ or -";
|
||||||
|
else if (def.type === "path" && /[\r\n]/.test(value)) errors[name] = "Path cannot contain newlines";
|
||||||
|
else if (def.type === "choice" && !def.options?.includes(value)) errors[name] = "Value is not an available choice";
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
for (const def of notebook.params) resolve(def.name);
|
||||||
|
return { values: effective, errors };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Substitute {{name}} in a step: script values are shell-quoted via shellQuote,
|
* The single script substitution path: display and execution consume this result.
|
||||||
* attribute values (host, artifacts, uploads) are substituted raw but validated.
|
* Attributes use raw substitution and separate validation; secrets are env-only.
|
||||||
* Secret params must not be referenced with {{ }} (they are env vars) — reported in `invalid`.
|
|
||||||
*/
|
*/
|
||||||
export function renderStep(
|
export function renderStep(
|
||||||
notebook: Notebook,
|
notebook: Notebook,
|
||||||
@@ -49,15 +74,54 @@ export function renderStep(
|
|||||||
runtime: ParamValues,
|
runtime: ParamValues,
|
||||||
hostNames: readonly string[],
|
hostNames: readonly string[],
|
||||||
): RenderedStep {
|
): RenderedStep {
|
||||||
return notImplemented(`renderStep(${notebook.title}, ${step.attrs.id}, ${Object.keys(values).length}, ${Object.keys(runtime).length}, ${hostNames.length})`);
|
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 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";
|
||||||
|
const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes("..");
|
||||||
|
const artifacts = step.attrs.artifacts.map((raw, i) => {
|
||||||
|
const name = substitute(raw, false);
|
||||||
|
if (!plainFile(name)) invalid[`artifacts[${i}]`] = "Artifact must be a plain file name without ..";
|
||||||
|
return name;
|
||||||
|
});
|
||||||
|
const uploads = step.attrs.uploads.map((upload, i) => {
|
||||||
|
const src = substitute(upload.src, false), dst = substitute(upload.dst, false);
|
||||||
|
if (!plainFile(src)) invalid[`uploads[${i}].src`] = "Upload source must be a plain artifact file name without ..";
|
||||||
|
if (!dst || /[\0\r\n]/.test(dst)) invalid[`uploads[${i}].dst`] = "Upload destination must be a path without NUL or newlines";
|
||||||
|
return { src, dst };
|
||||||
|
});
|
||||||
|
return { stepId: step.attrs.id, kind: step.kind, host, local: step.attrs.local, script, artifacts, uploads, missing: [...missing], invalid };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Substitute {{name}} in prose/markdown for display (no quoting; secrets shown as ••••). */
|
/** 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 {
|
||||||
return notImplemented(`renderText(${text.length}, ${Object.keys(values).length}, ${notebook.title})`);
|
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 as NAME=value (exact param name). Server-side only. */
|
/** 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> {
|
export function secretEnv(notebook: Notebook, values: ParamValues): Record<string, string> {
|
||||||
return notImplemented(`secretEnv(${notebook.params.length}, ${Object.keys(values).length})`);
|
const env = dictionary();
|
||||||
|
for (const def of notebook.params) if (def.type === "secret" && own(values, def.name)) env[def.name] = values[def.name]!;
|
||||||
|
return env;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import { parseDocument } from "yaml";
|
||||||
|
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"]);
|
||||||
|
|
||||||
|
/** Small attribute scanner: quoted values may contain whitespace, braces and escaped quotes. */
|
||||||
|
function attributes(text: string, error: (message: string) => void): Map<string, (string | true)[]> {
|
||||||
|
const result = new Map<string, (string | true)[]>();
|
||||||
|
let rest = text.trim();
|
||||||
|
while (rest) {
|
||||||
|
const key = /^[A-Za-z_][\w-]*/.exec(rest)?.[0];
|
||||||
|
if (!key) { error(`Malformed attributes: ${rest}`); break; }
|
||||||
|
rest = rest.slice(key.length);
|
||||||
|
let value: string | true = true;
|
||||||
|
if (rest.startsWith("=")) {
|
||||||
|
rest = rest.slice(1);
|
||||||
|
const quote = rest[0];
|
||||||
|
if (quote === '"' || quote === "'") {
|
||||||
|
rest = rest.slice(1);
|
||||||
|
value = "";
|
||||||
|
let closed = false;
|
||||||
|
while (rest) {
|
||||||
|
const c = rest[0]!;
|
||||||
|
rest = rest.slice(1);
|
||||||
|
if (c === quote) { closed = true; break; }
|
||||||
|
if (c === "\\" && (rest[0] === quote || rest[0] === "\\")) {
|
||||||
|
value += rest[0]; rest = rest.slice(1);
|
||||||
|
} else value += c;
|
||||||
|
}
|
||||||
|
if (!closed) error(`Unclosed quote for ${key}`);
|
||||||
|
} else {
|
||||||
|
value = /^\S*/.exec(rest)![0];
|
||||||
|
rest = rest.slice(value.length);
|
||||||
|
if (!value) error(`Missing value for ${key}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rest && !/^\s/.test(rest)) { error(`Expected whitespace after ${key}`); break; }
|
||||||
|
result.set(key, [...(result.get(key) ?? []), value]);
|
||||||
|
rest = rest.trimStart();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseNotebook(source: string): Notebook {
|
||||||
|
const notebook: Notebook = { title: "Untitled", params: [], blocks: [], diagnostics: [] };
|
||||||
|
const rawLines = source.split("\n");
|
||||||
|
const lines = rawLines.map(line => line.replace(/\r$/, ""));
|
||||||
|
let hasTitle = false;
|
||||||
|
// A trailing newline terminates the preceding line; it does not create a source line.
|
||||||
|
if (lines.at(-1) === "") lines.pop();
|
||||||
|
const error = (message: string, line?: number) => notebook.diagnostics.push({ severity: "error", message, line });
|
||||||
|
let start = 0;
|
||||||
|
if (lines[0]?.replace(/^\uFEFF/, "") === "---") {
|
||||||
|
const end = lines.findIndex((line, i) => i > 0 && /^(---|\.\.\.)\s*$/.test(line));
|
||||||
|
if (end < 0) error("Unclosed frontmatter", 1);
|
||||||
|
else {
|
||||||
|
start = end + 1;
|
||||||
|
try {
|
||||||
|
const doc = parseDocument(lines.slice(1, end).join("\n"));
|
||||||
|
for (const e of doc.errors) error(`Invalid YAML: ${e.message}`, (e.linePos?.[0]?.line ?? 1) + 1);
|
||||||
|
const data: unknown = doc.toJS({ maxAliasCount: 100 });
|
||||||
|
if (!record(data)) error("Frontmatter must be a mapping", 1);
|
||||||
|
else {
|
||||||
|
if (typeof data.title === "string" && data.title.trim()) { notebook.title = data.title; hasTitle = true; }
|
||||||
|
else if (data.title !== undefined) error("title must be a non-empty string", 2);
|
||||||
|
if (data.params !== undefined && !record(data.params)) error("params must be a mapping", 2);
|
||||||
|
if (record(data.params)) for (const [name, raw] of Object.entries(data.params)) {
|
||||||
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) error(`Invalid parameter name: ${name}`, 2);
|
||||||
|
if (!record(raw)) { error(`Parameter ${name} must be a mapping`, 2); continue; }
|
||||||
|
if (!paramTypes.has(String(raw.type))) { error(`Unknown param type for ${name}`, 2); continue; }
|
||||||
|
const def: ParamDef = { name, type: raw.type as ParamDef["type"], required: raw.required === true };
|
||||||
|
for (const key of Object.keys(raw)) if (!["type", "required", "default", "label", "options"].includes(key)) error(`Unknown parameter field ${key} for ${name}`, 2);
|
||||||
|
if (raw.required !== undefined && typeof raw.required !== "boolean") error(`required must be boolean for ${name}`, 2);
|
||||||
|
if (raw.default !== undefined) {
|
||||||
|
if (def.type === "secret") error(`Secret ${name} cannot have a default`, 2);
|
||||||
|
else if (typeof raw.default === "string" || typeof raw.default === "number" || typeof raw.default === "boolean") def.default = String(raw.default);
|
||||||
|
else error(`Invalid default for ${name}`, 2);
|
||||||
|
}
|
||||||
|
if (typeof raw.label === "string") def.label = raw.label;
|
||||||
|
else if (raw.label !== undefined) error(`Invalid label for ${name}`, 2);
|
||||||
|
if (Array.isArray(raw.options) && raw.options.every(x => typeof x === "string")) def.options = raw.options;
|
||||||
|
else if (raw.options !== undefined) error(`Invalid options for ${name}`, 2);
|
||||||
|
if (def.type === "choice" && !def.options?.length) error(`Choice ${name} needs options`, 2);
|
||||||
|
notebook.params.push(def);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch { error("Invalid YAML frontmatter", 2); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const ids = new Set<string>();
|
||||||
|
const afterRefs: { id: string; line: number }[] = [];
|
||||||
|
let stepNumber = 0;
|
||||||
|
let heading: string | undefined;
|
||||||
|
let i = start;
|
||||||
|
const parseBlocks = (nested: boolean, depth = 0): Block[] => {
|
||||||
|
const blocks: Block[] = [];
|
||||||
|
let markdownStart = i;
|
||||||
|
const flush = () => {
|
||||||
|
if (i > markdownStart) blocks.push({ type: "markdown", text: rawLines.slice(markdownStart, i).join("\n") + (i < lines.length || /\n$/.test(source) ? "\n" : ""), range: { startLine: markdownStart + 1, endLine: i } });
|
||||||
|
};
|
||||||
|
while (i < lines.length) {
|
||||||
|
const line = lines[i]!;
|
||||||
|
if (/^\s{0,3}:::\s*$/.test(line) && nested) { flush(); return blocks; }
|
||||||
|
const after = /^\s{0,3}:::after\{(.*)\}\s*$/.exec(line);
|
||||||
|
if (after && depth < 100) {
|
||||||
|
flush(); const begin = i++;
|
||||||
|
const attrs = attributes(after[1]!, m => error(m, begin + 1));
|
||||||
|
const ref = attrs.get("step")?.[0];
|
||||||
|
const id = typeof ref === "string" ? ref : "";
|
||||||
|
if (!id) error("after requires step=id", begin + 1);
|
||||||
|
for (const key of attrs.keys()) if (!["step", "failed"].includes(key)) error(`Unknown after attribute: ${key}`, begin + 1);
|
||||||
|
if (attrs.has("failed") && attrs.get("failed")![0] !== true) error("failed must be a flag", begin + 1);
|
||||||
|
afterRefs.push({ id, line: begin + 1 });
|
||||||
|
const children = parseBlocks(true, depth + 1);
|
||||||
|
if (i === lines.length) error("Unclosed after container", begin + 1);
|
||||||
|
else i++;
|
||||||
|
blocks.push({ type: "after", stepId: id, onFailure: attrs.has("failed"), blocks: children, range: { startLine: begin + 1, endLine: i } });
|
||||||
|
markdownStart = i; continue;
|
||||||
|
}
|
||||||
|
const fence = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
|
||||||
|
if (fence) {
|
||||||
|
const begin = i;
|
||||||
|
const marker = fence[1]!;
|
||||||
|
const info = fence[2]!.trim();
|
||||||
|
const match = /^(sh|bash)\s+\{(run|check)(?:\s+([\s\S]*))?\}$/.exec(info);
|
||||||
|
let end = i + 1;
|
||||||
|
const closing = new RegExp(`^ {0,3}${marker[0]}{${marker.length},}\\s*$`);
|
||||||
|
while (end < lines.length && !closing.test(lines[end]!)) end++;
|
||||||
|
if (!match) { i = end < lines.length ? end + 1 : end; continue; }
|
||||||
|
flush();
|
||||||
|
stepNumber++;
|
||||||
|
if (end === lines.length) error("Unclosed step fence", begin + 1);
|
||||||
|
const attrs = attributes(match[3] ?? "", m => error(m, begin + 1));
|
||||||
|
const get = (key: string): string | undefined => {
|
||||||
|
const v = attrs.get(key)?.[0];
|
||||||
|
if (v === true) error(`${key} requires a value`, begin + 1);
|
||||||
|
return typeof v === "string" ? v : undefined;
|
||||||
|
};
|
||||||
|
for (const [key, vals] of attrs) {
|
||||||
|
if (!["host", "on", "id", "title", "sudo", "confirm", "capture", "artifacts", "upload", "timeout"].includes(key)) error(`Unknown attribute: ${key}`, begin + 1);
|
||||||
|
if (vals.length > 1 && key !== "upload") error(`Duplicate attribute: ${key}`, begin + 1);
|
||||||
|
if (["sudo", "confirm"].includes(key) && vals[0] !== true) error(`${key} must be a flag`, begin + 1);
|
||||||
|
}
|
||||||
|
const kind = match[2] as Step["kind"];
|
||||||
|
const title = get("title");
|
||||||
|
const id = get("id") || title?.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || `step-${stepNumber}`;
|
||||||
|
if (ids.has(id)) error(`Duplicate step id: ${id}`, begin + 1);
|
||||||
|
ids.add(id);
|
||||||
|
const on = get("on");
|
||||||
|
if (on !== undefined && on !== "local") error("on must be local", begin + 1);
|
||||||
|
const host = get("host");
|
||||||
|
if (on && host) error("host and on cannot be combined", begin + 1);
|
||||||
|
const timeout = get("timeout");
|
||||||
|
const timeoutSec = timeout === undefined ? (kind === "run" ? 300 : 30) : Number(timeout);
|
||||||
|
if (!Number.isFinite(timeoutSec) || timeoutSec <= 0) error("timeout must be positive seconds", begin + 1);
|
||||||
|
const artifacts = get("artifacts")?.split(",").map(x => x.trim()) ?? [];
|
||||||
|
const uploads: StepAttrs["uploads"] = [];
|
||||||
|
for (const value of attrs.get("upload") ?? []) {
|
||||||
|
if (value === true) { error("upload requires src:dst", begin + 1); continue; }
|
||||||
|
for (const pair of value.split(",")) {
|
||||||
|
const colon = pair.indexOf(":");
|
||||||
|
if (colon <= 0 || colon === pair.length - 1) error("upload requires src:dst", begin + 1);
|
||||||
|
else uploads.push({ src: pair.slice(0, colon).trim(), dst: pair.slice(colon + 1).trim() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
const step: Step = {
|
||||||
|
kind,
|
||||||
|
lang: match[1]!,
|
||||||
|
attrs: {
|
||||||
|
id, title, host: on === "local" ? undefined : host,
|
||||||
|
local: on === "local", sudo: attrs.has("sudo"),
|
||||||
|
confirm: kind === "run" && attrs.has("confirm"), capture,
|
||||||
|
artifacts: kind === "run" ? artifacts : [],
|
||||||
|
uploads: kind === "run" ? uploads : [], timeoutSec,
|
||||||
|
},
|
||||||
|
script: rawLines.slice(begin + 1, end).join("\n")
|
||||||
|
+ (end > begin + 1 && (end < lines.length || /\n$/.test(source)) ? "\n" : ""),
|
||||||
|
range: { startLine: begin + 1, endLine: end < lines.length ? end + 1 : end },
|
||||||
|
};
|
||||||
|
blocks.push({ type: "step", step });
|
||||||
|
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);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
flush(); return blocks;
|
||||||
|
};
|
||||||
|
notebook.blocks = parseBlocks(false);
|
||||||
|
if (!hasTitle && heading) notebook.title = heading;
|
||||||
|
for (const ref of afterRefs) if (!ids.has(ref.id)) error(`after references unknown step: ${ref.id}`, ref.line);
|
||||||
|
return notebook;
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { parseNotebook, renderStep, renderText, resolveParams, secretEnv, shellQuote } from "../src/index";
|
||||||
|
import type { Block, Notebook, Step } from "../src/index";
|
||||||
|
|
||||||
|
const steps = (blocks: Block[]): Step[] => blocks.flatMap(b => b.type === "step" ? [b.step] : b.type === "after" ? steps(b.blocks) : []);
|
||||||
|
const book = (params: string, script = "echo {{x}}", attrs = "on=local"): Notebook => parseNotebook(`---\nparams:\n${params}\n---\n\n\`\`\`sh {run ${attrs}}\n${script}\n\`\`\`\n`);
|
||||||
|
const render = (n: Notebook, values = {}, runtime = {}) => renderStep(n, steps(n.blocks)[0]!, values, runtime, ["server"]);
|
||||||
|
|
||||||
|
// Keep an exact copy of the spec's notebook example in a portable fixture.
|
||||||
|
const example = readFileSync(new URL("./fixtures/ssh-key.md", import.meta.url), "utf8");
|
||||||
|
describe("spec §3.1", () => {
|
||||||
|
it("parses params, steps, after sections and inclusive source ranges", () => {
|
||||||
|
const n = parseNotebook(example);
|
||||||
|
expect(n.diagnostics).toEqual([]);
|
||||||
|
expect(n.title).toBe("New server SSH key");
|
||||||
|
expect(n.params).toEqual([
|
||||||
|
{ name: "host", type: "host", required: true, label: "Target server" },
|
||||||
|
{ name: "user", type: "name", required: true, default: "admin", label: "Login user" },
|
||||||
|
{ name: "keyname", type: "name", required: false, default: "id_ed25519_{{host}}" },
|
||||||
|
]);
|
||||||
|
const ss = steps(n.blocks);
|
||||||
|
expect(ss.map(s => s.attrs.id)).toEqual(["user-exists", "password-login-disabled", "keygen", "authorize"]);
|
||||||
|
expect(ss.map(s => s.attrs.timeoutSec)).toEqual([30, 30, 300, 300]);
|
||||||
|
expect(ss[0]!.range).toEqual({ startLine: 13, endLine: 15 });
|
||||||
|
expect(ss[2]!.attrs).toMatchObject({ local: true, artifacts: ["{{keyname}}", "{{keyname}}.pub"] });
|
||||||
|
expect(n.blocks.find(b => b.type === "after")).toMatchObject({ stepId: "keygen", onFailure: false });
|
||||||
|
});
|
||||||
|
it("renders the exact scripts and resolved metadata", () => {
|
||||||
|
const n = parseNotebook(example);
|
||||||
|
const rendered = steps(n.blocks).map(s => renderStep(n, s, { host: "server" }, {}, ["server"]));
|
||||||
|
expect(rendered.map(s => s.script)).toEqual([
|
||||||
|
"id admin\n", "sshd -T | grep -qx 'passwordauthentication no'\n",
|
||||||
|
"ssh-keygen -q -t ed25519 -N '' -C admin@server -f id_ed25519_server\n",
|
||||||
|
"install -d -m 700 -o admin -g admin ~admin/.ssh\ncat /tmp/new_key.pub >> ~admin/.ssh/authorized_keys\nrm /tmp/new_key.pub\n",
|
||||||
|
]);
|
||||||
|
expect(rendered.every(s => !s.missing.length && !Object.keys(s.invalid).length)).toBe(true);
|
||||||
|
expect(rendered[2]!.artifacts).toEqual(["id_ed25519_server", "id_ed25519_server.pub"]);
|
||||||
|
expect(rendered[3]!.uploads).toEqual([{ src: "id_ed25519_server.pub", dst: "/tmp/new_key.pub" }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("parser", () => {
|
||||||
|
it("preserves ordinary fences and ignores headings/directives inside them", () => {
|
||||||
|
const text = "```markdown\n# fake\n:::after{step=no}\n```\n# Real\n```sh\necho hi\n```\n";
|
||||||
|
const n = parseNotebook(text);
|
||||||
|
expect(n.title).toBe("Real"); expect(n.diagnostics).toEqual([]);
|
||||||
|
expect(n.blocks).toEqual([{ type: "markdown", text, range: { startLine: 1, endLine: 8 } }]);
|
||||||
|
});
|
||||||
|
it("handles nested after sections and contained steps, including forward references", () => {
|
||||||
|
const n = parseNotebook(":::after{step=later failed}\ntext\n:::after{step=later}\n~~~bash {check id=later confirm sudo timeout=4}\nid\n~~~\n:::\n:::\n");
|
||||||
|
expect(n.diagnostics).toEqual([]); expect(n.blocks[0]).toMatchObject({ type: "after", onFailure: true, range: { startLine: 1, endLine: 8 } });
|
||||||
|
expect(steps(n.blocks)[0]!.attrs).toMatchObject({ confirm: false, sudo: true, timeoutSec: 4 });
|
||||||
|
});
|
||||||
|
it("supports repeatable and comma-separated uploads and quoted attributes", () => {
|
||||||
|
const n = book(" x: {type: string}", "hi", 'on=local title="Say \\"hi\\"" upload="a:/a,b:/b" upload=c:/c capture=result');
|
||||||
|
expect(n.diagnostics).toEqual([]);
|
||||||
|
expect(steps(n.blocks)[0]!.attrs).toMatchObject({ title: 'Say "hi"', uploads: [{ src: "a", dst: "/a" }, { src: "b", dst: "/b" }, { src: "c", dst: "/c" }], capture: "result" });
|
||||||
|
});
|
||||||
|
it.each([
|
||||||
|
["---\nparams: [\n---", "YAML"],
|
||||||
|
["---\nparams: []\n---", "mapping"],
|
||||||
|
["---\nparams:\n a: {type: bogus}\n---", "Unknown param type"],
|
||||||
|
["---\nparams:\n a: {type: secret, default: hidden}\n---", "cannot have a default"],
|
||||||
|
["---\nparams:\n a: {type: choice}\n---", "needs options"],
|
||||||
|
["---\ntitle: x", "Unclosed frontmatter"],
|
||||||
|
[":::after{step=no}\n:::", "unknown step"],
|
||||||
|
[":::after{step=no}", "Unclosed after"],
|
||||||
|
["```sh {run typo=x}\nx\n```", "Unknown attribute"],
|
||||||
|
["```sh {run timeout=0}\nx\n```", "timeout"],
|
||||||
|
["```sh {run on=remote}\nx\n```", "on must"],
|
||||||
|
["```sh {run host=a on=local}\nx\n```", "cannot be combined"],
|
||||||
|
["```sh {check upload=a:b artifacts=a}\nx\n```", "Checks cannot"],
|
||||||
|
["```sh {run upload=broken}\nx\n```", "src:dst"],
|
||||||
|
["```sh {run id=x id=y}\nx\n```", "Duplicate attribute"],
|
||||||
|
["```sh {run title=\"broken}\nx\n```", "Unclosed quote"],
|
||||||
|
["```sh {run}\nx", "Unclosed step"],
|
||||||
|
["```sh {run id=x}\nx\n```\n```sh {check id=x}\nx\n```", "Duplicate step id"],
|
||||||
|
])("reports malformed input without throwing: %s", (source, message) => {
|
||||||
|
expect(parseNotebook(source).diagnostics.some(d => d.message.includes(message))).toBe(true);
|
||||||
|
});
|
||||||
|
it("uses title fallback, numeric step ids, CRLF ranges and exact script whitespace", () => {
|
||||||
|
expect(parseNotebook("").title).toBe("Untitled");
|
||||||
|
const n = parseNotebook("---\r\ntitle: Front\r\n---\r\n# Heading\r\n```sh {run}\r\n echo x \r\n\r\n```\r\n");
|
||||||
|
expect(n.title).toBe("Front"); expect(steps(n.blocks)[0]).toMatchObject({ script: " echo x \r\n\r\n", attrs: { id: "step-1" }, range: { startLine: 5, endLine: 8 } });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("parameter resolution", () => {
|
||||||
|
it("resolves chains, explicit overrides and blank values via defaults", () => {
|
||||||
|
const n = book(" x: {type: name, default: '{{y}}.pub'}\n y: {type: name, default: '{{z}}'}\n z: {type: name, default: key}");
|
||||||
|
expect(resolveParams(n, { x: "", z: "custom" }, []).values).toEqual({ x: "custom.pub", y: "custom", z: "custom" });
|
||||||
|
expect(resolveParams(n, { x: "override" }, []).errors).toEqual({});
|
||||||
|
});
|
||||||
|
it.each([
|
||||||
|
["host", "other", "Unknown host"], ["name", "bad name", "Expected a name"], ["name", "", "missing"],
|
||||||
|
["path", "a\nb", "newlines"], ["path", "a\0b", "NUL"], ["choice, options: [a, b]", "c", "available choice"],
|
||||||
|
])("validates %s", (type, value, message) => {
|
||||||
|
const n = book(` x: {type: ${type}, required: true}`);
|
||||||
|
expect(resolveParams(n, { x: value }, ["server"]).errors.x).toContain(message);
|
||||||
|
});
|
||||||
|
it.each(["string", "path", "name", "host", "choice, options: [server]", "secret"])("accepts valid %s", type => {
|
||||||
|
expect(resolveParams(book(` x: {type: ${type}}`), { x: "server" }, ["server"]).errors).toEqual({});
|
||||||
|
});
|
||||||
|
it("rejects cyclic, unknown, missing and secret dependencies without leaking secrets", () => {
|
||||||
|
const n = book(" x: {type: string, default: '{{y}}'}\n y: {type: string, default: '{{x}}'}\n z: {type: string, default: '{{unknown}}'}\n a: {type: string, default: '{{TOKEN}}'}\n TOKEN: {type: secret}");
|
||||||
|
const r = resolveParams(n, { TOKEN: "hidden" }, []);
|
||||||
|
expect(Object.keys(r.errors).sort()).toEqual(["a", "x", "y", "z"]);
|
||||||
|
expect(r.values.a).not.toContain("hidden");
|
||||||
|
expect(resolveParams(book(" x: {type: string, default: '{{y}}'}\n y: {type: string}"), {}, []).errors.x).toContain("Missing default");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("rendering and secrets", () => {
|
||||||
|
it("uses shellQuote for scripts and raw substitution for metadata, without recursive substitution", () => {
|
||||||
|
const n = book(" x: {type: string}", "printf %s {{x}} {{captured}}", "host=\"{{target}}\" artifacts=\"{{file}}\" upload=\"{{file}}:{{dst}}\"");
|
||||||
|
const r = render(n, { x: "$(touch bad)'\n{{other}}" }, { captured: "a b", target: "server", file: "a key", dst: "/tmp/a b" });
|
||||||
|
expect(r.script).toBe(`printf %s ${shellQuote("$(touch bad)'\n{{other}}")} ${shellQuote("a b")}\n`);
|
||||||
|
expect(r.artifacts).toEqual(["a key"]); expect(r.uploads[0]!.dst).toBe("/tmp/a b");
|
||||||
|
expect(r.invalid).toEqual({});
|
||||||
|
});
|
||||||
|
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 r = render(n, { x: "bad value", unused: "bad value" }, { empty: "" });
|
||||||
|
expect(r.missing).toEqual(["required", "empty"]);
|
||||||
|
expect(Object.keys(r.invalid).sort()).toEqual(["host", "unknown", "x"]);
|
||||||
|
expect(r.script).toBe("{{x}} {{unknown}} {{empty}}\n");
|
||||||
|
});
|
||||||
|
it("never exposes secret values via templates, defaults, prose or runtime shadowing", () => {
|
||||||
|
const n = book(" x: {type: secret, required: true}", "echo {{x}} $x", "on=local artifacts={{x}} upload={{x}}:{{x}}");
|
||||||
|
const r = render(n, { x: "hidden" }, { x: "shadow" });
|
||||||
|
expect(JSON.stringify(r)).not.toContain("hidden"); expect(JSON.stringify(r)).not.toContain("shadow");
|
||||||
|
expect(r.invalid.x).toContain("environment");
|
||||||
|
expect(renderText("{{x}} {{unknown}}", { x: "hidden" }, n)).toBe("•••• {{unknown}}");
|
||||||
|
expect(secretEnv(n, { x: "hidden", other: "public" })).toEqual({ x: "hidden" });
|
||||||
|
expect(secretEnv(n, {})).toEqual({});
|
||||||
|
});
|
||||||
|
it.each(["../file", "a/b", "a\\b", "a..b", "a\nb", "a\0b"])("rejects unsafe artifact names: %s", value => {
|
||||||
|
const n = book(" x: {type: string}", "true", "on=local artifacts={{file}} upload={{file}}:/tmp/key");
|
||||||
|
const r = render(n, {}, { file: value });
|
||||||
|
expect(Object.keys(r.invalid).length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
it("validates filled secrets even when optional because they are passed as env vars", () => {
|
||||||
|
const n = book(" TOKEN: {type: secret}", "true");
|
||||||
|
expect(render(n, { TOKEN: "bad\0value" }).invalid.TOKEN).toContain("NUL");
|
||||||
|
expect(render(n).missing).toEqual([]);
|
||||||
|
});
|
||||||
|
it("preserves explicit Untitled frontmatter instead of replacing it with a heading", () => {
|
||||||
|
expect(parseNotebook("---\ntitle: Untitled\n---\n# Different").title).toBe("Untitled");
|
||||||
|
});
|
||||||
|
it("renders prose with raw values and handles inherited names safely", () => {
|
||||||
|
const n = book(" x: {type: string}");
|
||||||
|
expect(renderText("{{x}} {{toString}}", { x: "a & b" }, n)).toBe("a & b {{toString}}");
|
||||||
|
expect(render(n, {}, {}).invalid.x).toBeUndefined();
|
||||||
|
expect(render(n, {}, {}).missing).toContain("x");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("shellQuote", () => {
|
||||||
|
it.each(["abc", "A09._/@:=+-", "path/to/file"])("leaves safe values unchanged: %s", value => expect(shellQuote(value)).toBe(value));
|
||||||
|
it.each([["\r", "'\r'"], ["", "''"], ["a b", "'a b'"], ["'", "''\\'''"], ["$x`id`\n雪", "'$x`id`\n雪'"]])("quotes %s", (value, quoted) => expect(shellQuote(value)).toBe(quoted));
|
||||||
|
// Git for Windows strips CR and transforms backslashes in -c arguments.
|
||||||
|
// Feed generated scripts through stdin there; CR has separate pure coverage.
|
||||||
|
const candidates = process.platform === "win32" ? ["sh", "C:/Program Files/Git/bin/sh.exe"] : ["sh"];
|
||||||
|
const sh = candidates.find(path => { const r = spawnSync(path, ["-c", "printf shellbook"], { encoding: "utf8" }); return r.status === 0 && r.stdout === "shellbook"; });
|
||||||
|
it.skipIf(!sh)("round-trips 256 deterministic random strings through POSIX sh", () => {
|
||||||
|
const alphabet = Array.from("aZ09 '\"\n\t$`\\;|&(){}[]*?!雪😀é/@:=+-");
|
||||||
|
let seed = 123456789;
|
||||||
|
const random = () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed; };
|
||||||
|
for (let i = 0; i < 256; i++) {
|
||||||
|
let value = "";
|
||||||
|
const length = random() % 90;
|
||||||
|
for (let j = 0; j < length; j++) value += alphabet[random() % alphabet.length];
|
||||||
|
const script = `printf %s ${shellQuote(value)}`;
|
||||||
|
const result = process.platform === "win32"
|
||||||
|
? spawnSync(sh!, ["-c", 'eval "$(cat)"'], { input: script, encoding: "utf8" })
|
||||||
|
: spawnSync(sh!, ["-c", script], { encoding: "utf8" });
|
||||||
|
expect(result.status).toBe(0); expect(result.stdout).toBe(value);
|
||||||
|
}
|
||||||
|
}, 30000);
|
||||||
|
});
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
---
|
||||||
|
title: New server SSH key
|
||||||
|
params:
|
||||||
|
host: { type: host, required: true, label: Target server }
|
||||||
|
user: { type: name, required: true, default: admin, label: Login user }
|
||||||
|
keyname: { type: name, default: "id_ed25519_{{host}}" }
|
||||||
|
---
|
||||||
|
|
||||||
|
# New server SSH key
|
||||||
|
|
||||||
|
Creates a key pair for **{{user}}** on **{{host}}** and authorizes it.
|
||||||
|
|
||||||
|
```sh {check host="{{host}}" title="User exists"}
|
||||||
|
id {{user}}
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh {check host="{{host}}" title="Password login disabled"}
|
||||||
|
sshd -T | grep -qx 'passwordauthentication no'
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh {run on=local id=keygen title="Generate key pair" artifacts="{{keyname}},{{keyname}}.pub"}
|
||||||
|
ssh-keygen -q -t ed25519 -N '' -C {{user}}@{{host}} -f {{keyname}}
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh {run host="{{host}}" id=authorize title="Authorize key" confirm upload="{{keyname}}.pub:/tmp/new_key.pub"}
|
||||||
|
install -d -m 700 -o {{user}} -g {{user}} ~{{user}}/.ssh
|
||||||
|
cat /tmp/new_key.pub >> ~{{user}}/.ssh/authorized_keys
|
||||||
|
rm /tmp/new_key.pub
|
||||||
|
```
|
||||||
|
|
||||||
|
:::after{step=keygen}
|
||||||
|
Download the private key above, then save it:
|
||||||
|
|
||||||
|
- **Linux:** `~/.ssh/{{keyname}}`, then `chmod 600 ~/.ssh/{{keyname}}`
|
||||||
|
- **Windows:** `C:\Users\<you>\.ssh\{{keyname}}`
|
||||||
|
:::
|
||||||
Generated
+12
-1
@@ -34,7 +34,11 @@ importers:
|
|||||||
specifier: ^4.19.2
|
specifier: ^4.19.2
|
||||||
version: 4.23.15
|
version: 4.23.15
|
||||||
|
|
||||||
packages/core: {}
|
packages/core:
|
||||||
|
dependencies:
|
||||||
|
yaml:
|
||||||
|
specifier: ^2.8.1
|
||||||
|
version: 2.9.1
|
||||||
|
|
||||||
packages:
|
packages:
|
||||||
|
|
||||||
@@ -912,6 +916,11 @@ packages:
|
|||||||
utf-8-validate:
|
utf-8-validate:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
[email protected]:
|
||||||
|
resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==}
|
||||||
|
engines: {node: '>= 14.6'}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
snapshots:
|
snapshots:
|
||||||
|
|
||||||
'@esbuild/[email protected]':
|
'@esbuild/[email protected]':
|
||||||
@@ -1644,3 +1653,5 @@ snapshots:
|
|||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
|
[email protected]: {}
|
||||||
|
|||||||
Reference in New Issue
Block a user