// Public API of @shellbook/core. Pure functions, no I/O. 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, 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); const dictionary = (): Record => Object.create(null) as Record; /** * Quote a value for POSIX sh. Returns the value unchanged when it only contains * [A-Za-z0-9._/@:=+-] and is non-empty; otherwise single-quoted with ' escaped as '\''. * The ONLY place in the codebase that quotes shell values. */ 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. 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 } { 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(); 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] ?? "" : ""; 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); if (own(errors, ref)) errors[name] = `Invalid default dependency: ${ref}`; if (!resolved) errors[name] = `Missing default dependency: ${ref}`; return resolved || match; }); } 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"; 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 }; } /** * 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(); 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. */ export function renderStep( notebook: Notebook, step: Step, values: ParamValues, runtime: ParamValues, hostNames: readonly string[], ): RenderedStep { 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"; 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 }; } /** Resolve a `::host` block with the same rules as hosts.yaml entries. */ export function renderHost( notebook: Notebook, block: Extract, 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] ? values[name]! : match); } /** * 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 { const env = dictionary(); 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; }