feat(core): implement notebook parsing and safe parameter rendering (#1)

Parse YAML frontmatter, shell steps and conditional sections with source ranges and diagnostics. Resolve typed defaults and runtime values through one script substitution path, keeping secrets env-only and validating artifact metadata.

Add yaml for standards-compliant frontmatter parsing and bounded alias handling rather than implementing YAML locally. Cover the spec example and edge cases with 59 core tests, including 256 POSIX shell quoting round trips.
This commit is contained in:
Florian Schmidt
2026-11-16 00:05:27 +01:00
parent d06f4336ae
commit f0d5de691a
6 changed files with 520 additions and 27 deletions
+90 -26
View File
@@ -1,19 +1,12 @@
// 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";
export type * from "./types";
export type * from "./protocol";
export { parseNotebook } from "./parser";
const notImplemented = (fn: string): never => {
throw new Error(`@shellbook/core: ${fn} is not implemented yet (M0)`);
};
/** 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)`);
}
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
const own = (object: object, key: string) => Object.hasOwn(object, key);
const dictionary = (): Record<string, string> => Object.create(null) as Record<string, string>;
/**
* 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.
*/
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.
* Returns effective values and an error message per invalid/missing-required param.
* `hostNames` = names from hosts.yaml (for type "host").
*/
/** Resolve defaults ({{other}} references) and validate all params by type. */
export function resolveParams(
notebook: Notebook,
values: ParamValues,
hostNames: readonly 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,
* attribute values (host, artifacts, uploads) are substituted raw but validated.
* Secret params must not be referenced with {{ }} (they are env vars) — reported in `invalid`.
* The single script substitution path: display and execution consume this result.
* Attributes use raw substitution and separate validation; secrets are env-only.
*/
export function renderStep(
notebook: Notebook,
@@ -49,15 +74,54 @@ export function renderStep(
runtime: ParamValues,
hostNames: readonly string[],
): 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 {
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> {
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;
}