From 6926526a56fd0ab15f94415c1f686a33a7c28c82 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Mon, 16 Nov 2026 00:07:42 +0100 Subject: [PATCH] feat(server): implement workspace and SSH run pipeline (#3) Add strict host-key confirmation, FIFO execution, streamed events, audit records, captures and SFTP artifacts/uploads. Use ssh2 for SSH/SFTP, yaml for inventory parsing, and compile-time ssh2/ws declarations. --- apps/server/README.md | 60 +++++++ apps/server/package.json | 6 +- apps/server/src/app.ts | 7 + apps/server/src/config.ts | 15 ++ apps/server/src/runs/events.ts | 10 ++ apps/server/src/runs/index.ts | 206 ++++++++++++++++++++++ apps/server/src/ssh/index.ts | 138 +++++++++++++++ apps/server/src/workspace/index.ts | 103 +++++++++++ apps/server/test/m2.test.ts | 274 +++++++++++++++++++++++++++++ pnpm-lock.yaml | 104 +++++++++++ 10 files changed, 922 insertions(+), 1 deletion(-) create mode 100644 apps/server/README.md create mode 100644 apps/server/src/config.ts create mode 100644 apps/server/src/runs/events.ts create mode 100644 apps/server/src/runs/index.ts create mode 100644 apps/server/src/ssh/index.ts create mode 100644 apps/server/src/workspace/index.ts create mode 100644 apps/server/test/m2.test.ts diff --git a/apps/server/README.md b/apps/server/README.md new file mode 100644 index 0000000..74fa99f --- /dev/null +++ b/apps/server/README.md @@ -0,0 +1,60 @@ +# Server execution (M2, issue #3) + +`buildApp({ config: { workspaceDir, dataDir, sshKeyPath }, events })` accepts +overrides for tests and embedding. Defaults come from `SHELLBOOK_WORKSPACE` +(`workspace`), `SHELLBOOK_DATA` (`data`), and `SHELLBOOK_SSH_KEY` +(`data/id_ed25519`). Paths resolve against the service working directory. + +The workspace contains `notebooks/**/*.md`, `hosts.yaml`, and `known_hosts`. +Inventory accepts either a YAML list or `{ hosts: [...] }`; every entry requires +`name`, `address`, and `user`. Port defaults to 22, tags to an empty list. +Nested notebook and artifact route parameters must be URL-encoded as a single +parameter. Saves require an existing notebook and its SHA256 content version; +concurrent saves in this process are serialized and stale versions return 409. +Filesystem symlinks, traversal, Windows drive paths and non-Markdown notebooks +are rejected. The workspace is trusted local storage; external editors must not +replace directories with symlinks concurrently with requests. + +Pass a shared `EventsHub` from `src/runs/events.ts` as `events` to publish watcher +events using `hub.publish(event)`. Each connected `/api/events` WebSocket receives +the shared events. There is no replay buffer. Subscribe before POSTing a run. +Run execution is FIFO per SSH address/port (including different inventory aliases), +with a separate local queue. Different endpoints can execute concurrently. + +SSH uses the configured private key without a PTY. Host keys are pinned in +OpenSSH's plain `host key-type base64-key` format (bracketed host/port for non-22 +ports). Hashed hostnames, wildcard entries, certificates and marker directives +are not supported. Existing plain keys are checked strictly. Unknown or changed +keys abort before exec; `acceptHostKey` must equal the observed SHA256 fingerprint +before a pin is written or replaced. Failed authentication never writes a pin. + +The script passed to bash is the core-rendered script. Execution setup selects a +fresh workdir, and prepends `export NAME=` lines on stdin +for secrets. This avoids sshd `AcceptEnv` and sudo environment filtering and also +works with Windows WSL bash. Secret values are never placed in exec argv. Neither +the transport prelude nor raw SSH errors are logged. Local runs use the same +stdin transport. Streamed output and captures redact exact secret values across +chunk boundaries; encoded or transformed secret output cannot be detected. +Audit records store only the rendered script, with defensive secret redaction. + +Local working files are in `data/runs//work/`. Declared successful artifacts +are copied to a separate `artifacts/` tree and listed in `artifacts.json`; only +listed files can be downloaded or used as upload sources, including after a +restart. Local upload destinations must be relative to the fresh workdir. Remote +uploads may use absolute destinations (the notebook format intentionally permits +`/tmp/new_key.pub`). Remote artifact realpaths must remain inside the fresh +`mktemp -d` directory. Cleanup is attempted before closing SSH; connection loss +or forced timeout can leave remote temporary files behind. + +Execution timeouts close the channel and connection; Unix local runs kill the +process group. Windows process-tree termination depends on the installed bash +implementation. SFTP establishment and transfers have a 30-second limit. Capture +is limited to 1 MiB. Authentication, retention/24-hour artifact expiration and +sensitive one-download artifacts are separate integration work; this module +does not add those policies. The service has root-equivalent access and must be +deployed with the authentication plugin and trusted workspace permissions. + +Dependencies: `ssh2` supplies SSH/SFTP and strict host verification, `yaml` parses +the inventory. `@types/ssh2` and `@types/ws` are compile-time declarations only. +Tests use an in-process SSH/SFTP server that never invokes a real shell. Local +bash tests skip only when bash cannot successfully execute a probe. diff --git a/apps/server/package.json b/apps/server/package.json index 445bd6e..667c673 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -12,9 +12,13 @@ "dependencies": { "@fastify/websocket": "^11.0.1", "@shellbook/core": "workspace:*", - "fastify": "^5.1.0" + "fastify": "^5.1.0", + "ssh2": "^1.17.0", + "yaml": "^2.9.1" }, "devDependencies": { + "@types/ssh2": "^1.15.6", + "@types/ws": "^8.18.2", "tsx": "^4.19.2" } } diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 183e24a..cb75769 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -1,8 +1,13 @@ import Fastify, { type FastifyInstance } from "fastify"; import websocket from "@fastify/websocket"; +import { loadConfig, type ServerConfig } from "./config"; +import { workspacePlugin } from "./workspace"; +import { runsPlugin, EventsHub } from "./runs"; export interface AppOptions { logger?: boolean; + config?: Partial; + events?: EventsHub; } /** @@ -15,6 +20,8 @@ export interface AppOptions { export async function buildApp(options: AppOptions = {}): Promise { const app = Fastify({ logger: options.logger ?? false }); await app.register(websocket); + await app.register(workspacePlugin, { config: loadConfig(options.config) }); + await app.register(runsPlugin, { config: loadConfig(options.config), hub: options.events ?? new EventsHub() }); app.get("/api/health", async () => ({ ok: true })); diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts new file mode 100644 index 0000000..270370c --- /dev/null +++ b/apps/server/src/config.ts @@ -0,0 +1,15 @@ +import path from "node:path"; + +export interface ServerConfig { + workspaceDir: string; + dataDir: string; + sshKeyPath: string; +} + +export function loadConfig(overrides: Partial = {}): ServerConfig { + return { + workspaceDir: path.resolve(overrides.workspaceDir ?? process.env.SHELLBOOK_WORKSPACE ?? "workspace"), + dataDir: path.resolve(overrides.dataDir ?? process.env.SHELLBOOK_DATA ?? "data"), + sshKeyPath: path.resolve(overrides.sshKeyPath ?? process.env.SHELLBOOK_SSH_KEY ?? "data/id_ed25519"), + }; +} diff --git a/apps/server/src/runs/events.ts b/apps/server/src/runs/events.ts new file mode 100644 index 0000000..86975b4 --- /dev/null +++ b/apps/server/src/runs/events.ts @@ -0,0 +1,10 @@ +import type { ServerEvent } from "@shellbook/core"; + +export class EventsHub { + private listeners = new Set<(event: ServerEvent) => void>(); + publish(event: ServerEvent) { for (const listener of this.listeners) listener(event); } + subscribe(listener: (event: ServerEvent) => void) { + this.listeners.add(listener); + return () => { this.listeners.delete(listener); }; + } +} diff --git a/apps/server/src/runs/index.ts b/apps/server/src/runs/index.ts new file mode 100644 index 0000000..1032594 --- /dev/null +++ b/apps/server/src/runs/index.ts @@ -0,0 +1,206 @@ +import { randomUUID } from "node:crypto"; +import { appendFile, mkdir, readFile, writeFile, copyFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { createReadStream } from "node:fs"; +import { parseNotebook, resolveParams, renderStep, secretEnv, shellQuote, type Block, type Step, type Notebook, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core"; +import type { FastifyInstance } from "fastify"; +import type { Client } from "ssh2"; +import type { ServerConfig } from "../config"; +import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace"; +import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, type Output } from "../ssh"; +import { EventsHub } from "./events"; +export { EventsHub } from "./events"; + +export function findStep(blocks: Block[], id: string): Step | undefined { + for (const block of blocks) { + if (block.type === "step" && block.step.attrs.id === id) return block.step; + if (block.type === "after") { const found = findStep(block.blocks, id); if (found) return found; } + } +} + +export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: HostInfo[]) { + if (notebook.diagnostics.some(d => d.severity === "error")) throw httpError(400, "Notebook has errors"); + const step = findStep(notebook.blocks, req.stepId); + if (!step) throw httpError(404, "Step not found"); + const names = hosts.map(h => h.name); + const resolved = resolveParams(notebook, req.params, names); + if (Object.keys(resolved.errors).length) throw httpError(400, "Parameters are missing or invalid"); + const rendered = renderStep(notebook, step, resolved.values, req.runtime, names); + if (rendered.missing.length || Object.keys(rendered.invalid).length) throw httpError(400, "Step parameters are missing or invalid"); + const host = hosts.find(h => h.name === rendered.host); + if (!rendered.local && !host) throw httpError(400, "Unknown target host"); + for (const name of rendered.artifacts) safeRelative(name); + if (rendered.kind === "check" && (rendered.uploads.length || rendered.artifacts.length)) throw httpError(400, "Checks cannot upload or collect artifacts"); + if (!Number.isFinite(step.attrs.timeoutSec) || step.attrs.timeoutSec <= 0) throw httpError(400, "Invalid timeout"); + return { step, rendered, host, env: secretEnv(notebook, resolved.values) }; +} + +/** Streaming redaction retains possible secret prefixes across chunks. */ +export function redactor(secrets: string[], output: (data: string) => void) { + const values = secrets.filter(Boolean).sort((a, b) => b.length - a.length); + let pending = ""; + function flush(final: boolean) { + let result = ""; + while (pending) { + if (!final && values.some(value => value.startsWith(pending))) break; + const match = values.find(value => pending.startsWith(value)); + if (match) { result += "[REDACTED]"; pending = pending.slice(match.length); } + else { result += pending[0]; pending = pending.slice(1); } + } + if (result) output(result); + } + return { write(data: string) { pending += data; flush(false); }, end() { flush(true); } }; +} + +function runRoot(config: ServerConfig, id: string) { + if (!/^[0-9a-f-]{36}$/.test(id)) throw httpError(400, "Invalid run ID"); + return path.join(config.dataDir, "runs", id); +} +async function artifactFile(config: ServerConfig, id: string, name: string) { + safeRelative(name); + const root = runRoot(config, id); + const names: string[] = JSON.parse(await readFile(path.join(root, "artifacts.json"), "utf8")); + if (!names.includes(name)) throw httpError(404, "Artifact not found"); + const file = await safeFile(path.join(root, "artifacts"), name); + if (!(await stat(file)).isFile()) throw httpError(404, "Artifact not a file"); + return file; +} + +export interface ExecuteRun { + config: ServerConfig; hub: EventsHub; runId: string; request: StartRunRequest; + step: Step; rendered: RenderedStep; host?: HostInfo; env: Record; +} + +export async function executeRun({ config, hub, runId, request, step, rendered, host, env }: ExecuteRun): Promise { + const start = Date.now(); + const root = runRoot(config, runId); + const workdir = path.join(root, "work"); + const artifactDir = path.join(root, "artifacts"); + const secrets = Object.values(env).filter(Boolean); + const clean = (value: string) => { for (const secret of [...secrets].sort((a,b) => b.length-a.length)) value = value.split(secret).join("[REDACTED]"); return value; }; + let stdout = ""; + let captureTooLarge = false; + let exitCode = -1; + let client: Client | undefined; + let remoteDir: string | undefined; + const artifacts: string[] = []; + const streams = { + stdout: redactor(secrets, data => { + if (step.attrs.capture) { + if (stdout.length + data.length > 1024 * 1024) captureTooLarge = true; + else stdout += data; + } + hub.publish({ type: "run.output", runId, stream: "stdout", data }); + }), + stderr: redactor(secrets, data => hub.publish({ type: "run.output", runId, stream: "stderr", data })), + }; + const output: Output = (stream, data) => streams[stream].write(data); + try { + await mkdir(workdir, { recursive: true, mode: 0o700 }); + await mkdir(artifactDir, { mode: 0o700 }); + hub.publish({ type: "run.started", runId, notebookPath: request.notebookPath, stepId: rendered.stepId, host: rendered.host, script: clean(rendered.script) }); + const timeout = step.attrs.timeoutSec * 1000; + if (!rendered.local) { + client = await connect(config, host!, request.acceptHostKey); + let directory = ""; + const code = await exec(client, "mktemp -d", "", timeout, (stream, data) => { if (stream === "stdout") directory += data; }); + remoteDir = directory.trim(); + if (code !== 0 || !/^\/[A-Za-z0-9_./-]+$/.test(remoteDir) || remoteDir === "/" || remoteDir.includes("..")) throw new Error("Cannot create remote workdir"); + } + for (const upload of rendered.uploads) { + const sourceId = request.artifactSources[upload.src]; + if (!sourceId) throw new Error("Missing upload source"); + const source = await artifactFile(config, sourceId, upload.src); + if (rendered.local) { + // Local upload destinations must remain inside this run's workdir. + safeRelative(upload.dst); + const target = path.join(workdir, upload.dst); + await mkdir(path.dirname(target), { recursive: true }); + await copyFile(source, target); + } else { + if (!upload.dst || /[\x00\r\n]/.test(upload.dst)) throw new Error("Invalid upload destination"); + const session = await sftp(client!); + try { await transfer(session, "fastPut", source, path.posix.resolve(remoteDir!, upload.dst)); } + finally { session.end(); } + } + } + if (rendered.local) exitCode = await localExec(workdir, rendered.script, env, step.attrs.sudo, timeout, output); + else exitCode = await exec(client!, `cd ${shellQuote(remoteDir!)} && ${step.attrs.sudo ? "sudo -n " : ""}bash -euo pipefail -s`, scriptInput(rendered.script, env), timeout, output); + streams.stdout.end(); streams.stderr.end(); + if (captureTooLarge) throw new Error("Captured output exceeds 1 MiB"); + if (exitCode === 0) { + for (const name of rendered.artifacts) { + safeRelative(name); + if (secrets.some(secret => name.includes(secret))) throw new Error("Secret in artifact name"); + const target = path.join(artifactDir, name); + await mkdir(path.dirname(target), { recursive: true }); + if (rendered.local) { + const source = await safeFile(workdir, name); + if (!(await stat(source)).isFile()) throw new Error("Artifact is not a regular file"); + await copyFile(source, target); + } else { + const session = await sftp(client!); + try { + const remote = path.posix.join(remoteDir!, name); + const real = await sftpRequest(session, done => session.realpath(remote, done)); + if (!real.startsWith(remoteDir! + "/")) throw new Error("Artifact escapes remote workdir"); + const info = await sftpRequest(session, done => session.stat(real, done)); + if (!info.isFile()) throw new Error("Artifact is not a regular file"); + await transfer(session, "fastGet", real, target); + } finally { session.end(); } + } + artifacts.push(name); + } + } + await writeFile(path.join(root, "artifacts.json"), JSON.stringify(artifacts), { mode: 0o600 }); + } catch (error) { + exitCode = -1; + if (error instanceof HostKeyError) hub.publish({ type: "run.hostKeyUnknown", runId, host: rendered.host!, fingerprint: error.fingerprint, changed: error.changed }); + else hub.publish({ type: "run.error", runId, message: "Run failed (connection, execution, or file transfer error)" }); + } finally { + streams.stdout.end(); streams.stderr.end(); + if (client && remoteDir) { + try { await exec(client, `rm -rf -- ${shellQuote(remoteDir)}`, "", 5000, () => {}); } catch { /* Connection may already be closed after timeout. */ } + } + client?.end(); + const durationMs = Date.now() - start; + await mkdir(config.dataDir, { recursive: true, mode: 0o700 }); + try { + await appendFile(path.join(config.dataDir, "audit.jsonl"), JSON.stringify({ time: new Date(start).toISOString(), notebookPath: request.notebookPath, stepId: rendered.stepId, host: rendered.host ?? "local", script: clean(rendered.script), exitCode, durationMs }) + "\n", { mode: 0o600 }); + } catch { + exitCode = -1; + hub.publish({ type: "run.error", runId, message: "Run audit could not be persisted" }); + } + hub.publish({ type: "run.finished", runId, exitCode, durationMs, artifacts: exitCode === 0 ? artifacts : [], ...(exitCode === 0 && step.attrs.capture ? { captured: { name: step.attrs.capture, value: stdout.trim() } } : {}) }); + } +} + +function stringMap(value: unknown): value is Record { + return !!value && typeof value === "object" && !Array.isArray(value) && Object.values(value).every(v => typeof v === "string"); +} +export async function runsPlugin(app: FastifyInstance, { config, hub }: { config: ServerConfig; hub: EventsHub }) { + const queue = new SerialQueue(); + app.get("/api/events", { websocket: true }, socket => { + const unsubscribe = hub.subscribe(event => { if (socket.readyState === 1) socket.send(JSON.stringify(event)); }); + socket.on("close", unsubscribe); + socket.on("error", unsubscribe); + }); + app.post<{ Body: StartRunRequest }>("/api/runs", async (req, reply) => { + const body = req.body; + if (!body || typeof body.notebookPath !== "string" || typeof body.stepId !== "string" || !stringMap(body.params) || !stringMap(body.runtime) || !stringMap(body.artifactSources) || (body.acceptHostKey !== undefined && typeof body.acceptHostKey !== "string")) throw httpError(400, "Invalid run request"); + const { source } = await readNotebook(config, body.notebookPath); + const prepared = prepareRun(parseNotebook(source), body, await readHosts(config)); + const runId = randomUUID(); + // Queue immediately; defer the work to allow the HTTP response to reach the subscriber. + void queue.run(prepared.host ? `${prepared.host.address}:${prepared.host.port}` : "local", async () => { + await new Promise(resolve => setImmediate(resolve)); + await executeRun({ config, hub, runId, request: body, ...prepared }); + }).catch(() => hub.publish({ type: "run.error", runId, message: "Run persistence failed" })); + return reply.code(202).send({ runId }); + }); + app.get<{ Params: { runId: string; name: string } }>("/api/runs/:runId/artifacts/:name", async (req, reply) => { + const file = await artifactFile(config, req.params.runId, req.params.name); + return reply.type("application/octet-stream").header("Content-Disposition", "attachment").send(createReadStream(file)); + }); + app.addHook("onClose", async () => { await queue.idle(); }); +} diff --git a/apps/server/src/ssh/index.ts b/apps/server/src/ssh/index.ts new file mode 100644 index 0000000..10b07a4 --- /dev/null +++ b/apps/server/src/ssh/index.ts @@ -0,0 +1,138 @@ +import { Client, type ClientChannel, type SFTPWrapper } from "ssh2"; +import { createHash } from "node:crypto"; +import { readFile, writeFile, mkdir } from "node:fs/promises"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { StringDecoder } from "node:string_decoder"; +import { shellQuote, type HostInfo } from "@shellbook/core"; +import type { ServerConfig } from "../config"; +import { SerialQueue } from "../workspace"; + +export type Output = (stream: "stdout" | "stderr", data: string) => void; +export class HostKeyError extends Error { + constructor(public fingerprint: string, public changed: boolean) { super("Host key requires confirmation"); } +} +const keyWrites = new SerialQueue(); +export function fingerprint(key: Buffer) { return "SHA256:" + createHash("sha256").update(key).digest("base64").replace(/=+$/, ""); } + +export async function connect(config: ServerConfig, host: HostInfo, accepted?: string): Promise { + const file = path.join(config.workspaceDir, "known_hosts"); + const privateKey = await readFile(config.sshKeyPath); + // Serialize read/verify/write, so simultaneous first connections cannot overwrite pins. + return keyWrites.run(file, async () => { + const contents = await readFile(file, "utf8").catch((e: NodeJS.ErrnoException) => { if (e.code === "ENOENT") return ""; throw e; }); + const identity = host.port === 22 ? host.address : `[${host.address}]:${host.port}`; + const lines = contents.split(/\r?\n/); + const matches = lines.filter(line => line.split(/\s+/)[0]?.split(",").includes(identity)); + let failure: HostKeyError | undefined; + let newKey: Buffer | undefined; + const client = new Client(); + await new Promise((resolve, reject) => { + client.once("ready", resolve); + client.on("error", err => reject(failure ?? err)); + client.once("close", () => reject(failure ?? new Error("SSH connection closed"))); + client.connect({ host: host.address, port: host.port, username: host.user, privateKey, readyTimeout: 10000, + hostVerifier(key: Buffer) { + const encoded = key.toString("base64"); + if (matches.some(line => line.split(/\s+/)[2] === encoded)) return true; + const fp = fingerprint(key); + if (accepted === fp) { newKey = key; return true; } + failure = new HostKeyError(fp, matches.length > 0); + return false; + }, + }); + }).catch(err => { client.destroy(); throw err; }); + if (newKey) { + const typeLength = newKey.readUInt32BE(0); + const type = newKey.subarray(4, 4 + typeLength).toString(); + // Preserve other aliases on a replaced known_hosts line. + const retained = lines.map(line => { + if (!matches.includes(line)) return line; + const fields = line.split(/\s+/); + const aliases = fields[0]!.split(",").filter(alias => alias !== identity); + return aliases.length ? [aliases.join(","), ...fields.slice(1)].join(" ") : ""; + }).filter(Boolean); + retained.push(`${identity} ${type} ${newKey.toString("base64")}`); + try { await writeFile(file, retained.join("\n") + "\n", { mode: 0o600 }); } + catch (err) { client.end(); throw err; } + } + return client; + }); +} + +export function exec(client: Client, command: string, input: string, timeoutMs: number, output: Output): Promise { + return new Promise((resolve, reject) => { + let channel: ClientChannel | undefined; + const timer = setTimeout(() => { + channel?.signal("KILL"); + channel?.close(); + client.destroy(); + reject(new Error("Execution timed out")); + }, timeoutMs); + const done = (error?: Error, code = -1) => { clearTimeout(timer); error ? reject(error) : resolve(code); }; + client.exec(command, (error, stream) => { + if (error) return done(error); + channel = stream; + const stdout = new StringDecoder("utf8"); + const stderr = new StringDecoder("utf8"); + stream.on("data", (data: Buffer) => output("stdout", stdout.write(data))); + stream.stderr.on("data", (data: Buffer) => output("stderr", stderr.write(data))); + stream.once("error", done); + stream.once("close", (code: number | undefined) => { output("stdout", stdout.end()); output("stderr", stderr.end()); done(undefined, code ?? -1); }); + stream.end(input); + }); + }); +} + +/** Secrets travel only on stdin, before the literal rendered script, never in exec argv. */ +export function scriptInput(script: string, env: Record): string { + const exports = Object.entries(env).map(([name, value]) => { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || value.includes("\0")) throw new Error("Invalid secret environment variable"); + return `export ${name}=${shellQuote(value)}\n`; + }).join(""); + return exports + script; +} + +export async function localExec(cwd: string, script: string, env: Record, sudo: boolean, timeoutMs: number, output: Output): Promise { + const input = scriptInput(script, env); + await mkdir(cwd, { recursive: true, mode: 0o700 }); + return new Promise((resolve, reject) => { + const args = ["-euo", "pipefail", "-s"]; + const child = spawn(sudo ? "sudo" : "bash", sudo ? ["-n", "bash", ...args] : args, { + cwd, detached: process.platform !== "win32", stdio: ["pipe", "pipe", "pipe"], + }); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + if (process.platform !== "win32" && child.pid) { try { process.kill(-child.pid, "SIGKILL"); } catch { child.kill("SIGKILL"); } } + else child.kill("SIGKILL"); + }, timeoutMs); + child.stdout.setEncoding("utf8").on("data", data => output("stdout", data)); + child.stderr.setEncoding("utf8").on("data", data => output("stderr", data)); + child.stdin.on("error", () => {}); // Early shell exit may close stdin. + child.once("error", error => { clearTimeout(timer); reject(error); }); + child.once("close", code => { clearTimeout(timer); timedOut ? reject(new Error("Execution timed out")) : resolve(code ?? -1); }); + child.stdin.end(input); + }); +} + +export function sftp(client: Client): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { client.destroy(); reject(new Error("SFTP session timed out")); }, 30000); + client.sftp((err, session) => { clearTimeout(timer); err ? reject(err) : resolve(session); }); + }); +} +export function transfer(session: SFTPWrapper, method: "fastGet" | "fastPut", from: string, to: string): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { session.destroy(); reject(new Error("SFTP transfer timed out")); }, 30000); + session[method](from, to, err => { clearTimeout(timer); err ? reject(err) : resolve(); }); + }); +} + +export function sftpRequest(session: SFTPWrapper, request: (done: (error: Error | undefined, value: T) => void) => void): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { session.destroy(); reject(new Error("SFTP metadata request timed out")); }, 30000); + request((error, value) => { clearTimeout(timer); error ? reject(error) : resolve(value); }); + }); +} + diff --git a/apps/server/src/workspace/index.ts b/apps/server/src/workspace/index.ts new file mode 100644 index 0000000..4e5d922 --- /dev/null +++ b/apps/server/src/workspace/index.ts @@ -0,0 +1,103 @@ +import { createHash } from "node:crypto"; +import { readFile, writeFile, readdir, realpath, lstat } from "node:fs/promises"; +import path from "node:path"; +import { parse } from "yaml"; +import { parseNotebook, type HostInfo } from "@shellbook/core"; +import type { FastifyInstance } from "fastify"; +import type { ServerConfig } from "../config"; + +export const version = (source: string) => createHash("sha256").update(source).digest("hex"); +export const httpError = (statusCode: number, message: string) => Object.assign(new Error(message), { statusCode }); + +/** Reject Windows paths too, even when the service runs on Linux. No symlinks. */ +export function safeRelative(name: string): string { + if (typeof name !== "string" || !name || /[\\:\x00-\x1f]/.test(name) || name.split("/").some(p => !p || p === "." || p === "..")) { + throw httpError(400, "Invalid relative path"); + } + return name; +} + +export async function safeFile(root: string, name: string): Promise { + safeRelative(name); + try { + const base = await realpath(root); + let current = base; + for (const part of name.split("/")) { + current = path.join(current, part); + if ((await lstat(current)).isSymbolicLink()) throw httpError(400, "Symlinks are not allowed"); + } + return current; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") throw httpError(404, "File not found"); + throw error; + } +} + +export async function readNotebook(config: ServerConfig, name: string) { + if (!name.endsWith(".md")) throw httpError(400, "Only Markdown notebooks are allowed"); + const file = await safeFile(path.join(config.workspaceDir, "notebooks"), name); + return { file, source: await readFile(file, "utf8") }; +} + +export async function readHosts(config: ServerConfig): Promise { + const document: unknown = parse(await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8")); + const entries = Array.isArray(document) ? document : (document as { hosts?: unknown } | null)?.hosts; + if (!Array.isArray(entries)) throw httpError(400, "hosts.yaml must contain a host list"); + const names = new Set(); + return entries.map((entry: Record) => { + if (!entry || typeof entry !== "object") throw httpError(400, "Invalid host"); + const { name, address, user, port = 22, tags = [] } = entry; + if (typeof name !== "string" || !/^[A-Za-z0-9._-]+$/.test(name) || names.has(name) || + typeof address !== "string" || !address || /[\s\x00]/.test(address) || + typeof user !== "string" || !/^[A-Za-z0-9._-]+$/.test(user) || + !Number.isInteger(port) || Number(port) < 1 || Number(port) > 65535 || + !Array.isArray(tags) || tags.some(t => typeof t !== "string")) throw httpError(400, "Invalid or duplicate host entry"); + names.add(name); + return { name, address, user, port: Number(port), tags: tags as string[] }; + }); +} + +export class SerialQueue { + private tails = new Map>(); + async run(key: string, task: () => Promise): Promise { + const prior = this.tails.get(key) ?? Promise.resolve(); + const next = prior.catch(() => {}).then(task); + this.tails.set(key, next); + try { return await next; } + finally { if (this.tails.get(key) === next) this.tails.delete(key); } + } + async idle() { await Promise.allSettled(this.tails.values()); } +} + +export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) { + const saves = new SerialQueue(); + app.get("/api/hosts", async () => ({ hosts: await readHosts(config) })); + app.get("/api/notebooks", async () => { + const notebooks: { path: string; title: string }[] = []; + async function walk(dir: string, prefix = "") { + for (const entry of await readdir(dir, { withFileTypes: true })) { + const name = prefix + entry.name; + if (entry.isDirectory()) await walk(path.join(dir, entry.name), name + "/"); + else if (entry.isFile() && name.endsWith(".md")) { + const { source } = await readNotebook(config, name); + notebooks.push({ path: name, title: parseNotebook(source).title }); + } + } + } + await walk(path.join(config.workspaceDir, "notebooks")); + return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) }; + }); + app.get<{ Params: { path: string } }>("/api/notebooks/:path", async req => { + const { source } = await readNotebook(config, req.params.path); + return { path: req.params.path, source, notebook: parseNotebook(source), version: version(source) }; + }); + app.put<{ Params: { path: string }; Body: { source: string; baseVersion: string } }>("/api/notebooks/:path", async req => { + if (!req.body || typeof req.body.source !== "string" || typeof req.body.baseVersion !== "string") throw httpError(400, "Invalid save request"); + return saves.run(req.params.path, async () => { + const { file, source } = await readNotebook(config, req.params.path); + if (version(source) !== req.body.baseVersion) throw httpError(409, "Notebook changed"); + await writeFile(file, req.body.source, "utf8"); + return { version: version(req.body.source) }; + }); + }); +} diff --git a/apps/server/test/m2.test.ts b/apps/server/test/m2.test.ts new file mode 100644 index 0000000..0cf6f59 --- /dev/null +++ b/apps/server/test/m2.test.ts @@ -0,0 +1,274 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { mkdtemp, mkdir, writeFile, readFile, symlink, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { generateKeyPairSync, randomUUID } from "node:crypto"; +import { spawnSync } from "node:child_process"; +import { Server, utils, type Connection } from "ssh2"; +import type { HostInfo, Notebook, Step, RenderedStep, StartRunRequest, ServerEvent } from "@shellbook/core"; +import { parseNotebook, resolveParams, renderStep } from "@shellbook/core"; +import { buildApp } from "../src/app"; +import { loadConfig, type ServerConfig } from "../src/config"; +import { SerialQueue, safeRelative } from "../src/workspace"; +import { connect, exec, fingerprint, HostKeyError, localExec, scriptInput } from "../src/ssh"; +import { executeRun, EventsHub, prepareRun, redactor } from "../src/runs"; + +vi.mock("@shellbook/core", () => ({ + parseNotebook: vi.fn((source: string) => ({ title: source.split("\n")[0], params: [], blocks: [], diagnostics: [] })), + shellQuote: (value: string) => /^[A-Za-z0-9._/@:=+-]+$/.test(value) ? value : "'" + value.replaceAll("'", "'\\''") + "'", + resolveParams: vi.fn((_notebook: Notebook, values: Record) => ({ values, errors: {} })), + renderStep: vi.fn(() => rendered()), + secretEnv: vi.fn(() => ({})), +})); + +const cleanup: (() => Promise)[] = []; +afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); vi.clearAllMocks(); }); +async function fixture() { + const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-")); + cleanup.push(() => rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })); + const config = loadConfig({ workspaceDir: path.join(dir, "workspace"), dataDir: path.join(dir, "data"), sshKeyPath: path.join(dir, "key") }); + await mkdir(path.join(config.workspaceDir, "notebooks", "nested"), { recursive: true }); + await writeFile(path.join(config.workspaceDir, "notebooks", "nested", "test.md"), "# Test\necho ok"); + await writeFile(path.join(config.workspaceDir, "hosts.yaml"), "- name: test\n address: localhost\n user: admin\n"); + const privateKey = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString(); + await writeFile(config.sshKeyPath, privateKey); + return config; +} +function step(): Step { + return { kind: "run", lang: "sh", script: "echo ok\n", range: { startLine: 1, endLine: 3 }, attrs: { id: "test", local: false, sudo: false, confirm: false, artifacts: [], uploads: [], timeoutSec: 1 } }; +} +function rendered(): RenderedStep { return { stepId: "test", kind: "run", host: "test", local: false, script: "echo ok\n", artifacts: [], uploads: [], missing: [], invalid: {} }; } +function request(): StartRunRequest { return { notebookPath: "nested/test.md", stepId: "test", params: {}, runtime: {}, artifactSources: {} }; } +async function sshFixture() { + const config = await fixture(); + const key = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString(); + const parsed = utils.parseKey(key); + if (parsed instanceof Error) throw parsed; + const fp = fingerprint(parsed.getPublicSSH()); + const clients = new Set(); + const received: { command: string; input: string }[] = []; + const files = new Map([["/tmp/shellbook-test/out.txt", Buffer.from("artifact bytes")]]); + const server = new Server({ hostKeys: [key] }, client => { + clients.add(client); + client.on("error", () => {}); + client.on("close", () => clients.delete(client)); + client.on("authentication", ctx => ctx.accept()); + client.on("ready", () => client.on("session", accept => { + const session = accept(); + session.on("exec", (acceptExec, _reject, info) => { + const stream = acceptExec(); + const record = { command: info.command, input: "" }; + received.push(record); + stream.on("data", (data: Buffer) => { record.input += data.toString(); }); + stream.on("end", () => { + if (record.input.includes("HANG")) return; + if (info.command === "mktemp -d") stream.write("/tmp/shellbook-test\n"); + else if (info.command.startsWith("rm -rf")) { /* deterministic cleanup */ } + else { stream.write("hello "); stream.stderr.write("warning\n"); stream.write("world\n"); } + stream.exit(record.input.includes("FAIL") ? 7 : 0); + stream.end(); + }); + }); + session.on("sftp", acceptSftp => { + const session = acceptSftp(); + const { OK, EOF, NO_SUCH_FILE } = utils.sftp.STATUS_CODE; + const attrs = (name: string) => ({ mode: 0o100600, uid: 0, gid: 0, size: files.get(name)?.length ?? 0, atime: 0, mtime: 0 }); + session.on("REALPATH", (id, name) => session.name(id, [{ filename: name, longname: name, attrs: attrs(name) }])); + session.on("STAT", (id, name) => files.has(name) ? session.attrs(id, attrs(name)) : session.status(id, NO_SUCH_FILE)); + session.on("OPEN", (id, name, flags) => { + if (flags & 8) files.set(name, Buffer.alloc(0)); + if (!files.has(name)) return session.status(id, NO_SUCH_FILE); + session.handle(id, Buffer.from(name)); + }); + session.on("FSTAT", (id, handle) => session.attrs(id, attrs(handle.toString()))); + session.on("READ", (id, handle, offset, length) => { + const data = files.get(handle.toString())!; + if (offset >= data.length) session.status(id, EOF); + else session.data(id, data.subarray(offset, offset + length)); + }); + session.on("WRITE", (id, handle, offset, data) => { + const name = handle.toString(); const old = files.get(name)!; + const next = Buffer.alloc(Math.max(old.length, offset + data.length)); old.copy(next); data.copy(next, offset); files.set(name, next); + session.status(id, OK); + }); + session.on("CLOSE", id => session.status(id, OK)); + }); + })); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + cleanup.push(async () => { for (const client of clients) client.end(); await new Promise(resolve => server.close(() => resolve())); }); + const address = server.address(); + if (typeof address === "string" || !address) throw new Error("Missing test address"); + const host: HostInfo = { name: "test", address: "127.0.0.1", port: address.port, user: "admin", tags: [] }; + return { config, host, fp, received, files }; +} + +describe("workspace", () => { + it("reads nested notebooks, lists them, hashes versions, rejects stale concurrent saves", async () => { + const app = await buildApp({ config: await fixture() }); cleanup.push(() => app.close()); + const url = "/api/notebooks/nested%2Ftest.md"; + const res = await app.inject(url); + expect(res.statusCode).toBe(200); + expect(res.json().notebook.title).toBe("# Test"); + expect((await app.inject("/api/notebooks")).json().notebooks).toEqual([{ path: "nested/test.md", title: "# Test" }]); + const payload = { source: "# Updated", baseVersion: res.json().version }; + const saves = await Promise.all([app.inject({ method: "PUT", url, payload }), app.inject({ method: "PUT", url, payload })]); + expect(saves.map(r => r.statusCode).sort()).toEqual([200, 409]); + expect((await app.inject(url)).json().version).not.toBe(payload.baseVersion); + }); + it("validates inventory and applies defaults", async () => { + const config = await fixture(); const app = await buildApp({ config }); cleanup.push(() => app.close()); + expect((await app.inject("/api/hosts")).json().hosts[0]).toEqual({ name: "test", address: "localhost", user: "admin", port: 22, tags: [] }); + await writeFile(path.join(config.workspaceDir, "hosts.yaml"), "- name: bad\n address: localhost\n"); + expect((await app.inject("/api/hosts")).statusCode).toBe(400); + }); + it.each(["../secret.md", "/absolute.md", "C:/secret.md", "a\\b.md", "a/../b.md", "a//b.md", "a\0.md"])("rejects unsafe path %s", name => { + expect(() => safeRelative(name)).toThrow(); + }); + it("rejects symlink notebooks and non-md paths", async () => { + const config = await fixture(); + await symlink(path.join(config.workspaceDir, "notebooks", "nested"), path.join(config.workspaceDir, "notebooks", "link"), "junction"); + const app = await buildApp({ config }); cleanup.push(() => app.close()); + expect((await app.inject("/api/notebooks/link%2Ftest.md")).statusCode).toBe(400); + expect((await app.inject("/api/notebooks/hosts.yaml")).statusCode).toBe(400); + }); +}); + +describe("SSH with a deterministic in-process server", () => { + it("aborts unknown keys, rejects incorrect acceptance, pins accepted key and reconnects", async () => { + const { config, host, fp, received } = await sshFixture(); + await expect(connect(config, host)).rejects.toMatchObject({ fingerprint: fp, changed: false }); + await expect(connect(config, host, "SHA256:wrong")).rejects.toBeInstanceOf(HostKeyError); + expect(received).toEqual([]); + const client = await connect(config, host, fp); client.end(); + expect(await readFile(path.join(config.workspaceDir, "known_hosts"), "utf8")).toContain(`[127.0.0.1]:${host.port} ssh-rsa `); + const second = await connect(config, host); second.end(); + }); + it("flags changed keys and only replaces after matching acceptance", async () => { + const { config, host, fp } = await sshFixture(); + await writeFile(path.join(config.workspaceDir, "known_hosts"), `[127.0.0.1]:${host.port} ssh-rsa wrong\n`); + await expect(connect(config, host)).rejects.toMatchObject({ changed: true, fingerprint: fp }); + const client = await connect(config, host, fp); client.end(); + const second = await connect(config, host); second.end(); + }); + it("streams both channels and preserves exit codes without running a shell", async () => { + const { config, host, fp, received } = await sshFixture(); + const client = await connect(config, host, fp); + const output: [string, string][] = []; + expect(await exec(client, "bash -euo pipefail -s", "FAIL\n", 2000, (stream, data) => output.push([stream, data]))).toBe(7); + client.end(); + expect(output.filter(([s]) => s === "stdout").map(([,d]) => d).join("")).toBe("hello world\n"); + expect(output.filter(([s]) => s === "stderr").map(([,d]) => d).join("")).toBe("warning\n"); + expect(received[0]).toEqual({ command: "bash -euo pipefail -s", input: "FAIL\n" }); + }); + it("kills a channel that exceeds its timeout", async () => { + const { config, host, fp } = await sshFixture(); + const client = await connect(config, host, fp); + await expect(exec(client, "bash -euo pipefail -s", "HANG", 50, () => {})).rejects.toThrow("timed out"); + }); + it("executes the run pipeline, captures stdout, audits and cleans remote directory", async () => { + const { config, host, fp, received } = await sshFixture(); + const hub = new EventsHub(); const events: ServerEvent[] = []; hub.subscribe(e => events.push(e)); + const s = step(); s.attrs.capture = "result"; s.attrs.sudo = true; + const req = request(); req.acceptHostKey = fp; + const r = rendered(); + await executeRun({ config, hub, runId: randomUUID(), request: req, host, rendered: r, step: s, env: { TOKEN: "secret'word" } }); + expect(received[1]?.command).toBe("cd /tmp/shellbook-test && sudo -n bash -euo pipefail -s"); + expect(received[1]?.input).toBe(scriptInput(r.script, { TOKEN: "secret'word" })); + expect(received[2]?.command).toBe("rm -rf -- /tmp/shellbook-test"); + expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: 0, captured: { name: "result", value: "hello world" } }); + const audit = await readFile(path.join(config.dataDir, "audit.jsonl"), "utf8"); + expect(JSON.parse(audit).script).toBe(r.script); + expect(audit + JSON.stringify(events)).not.toContain("secret'word"); + }); + it("emits TOFU events and a failed audited result", async () => { + const { config, host, fp } = await sshFixture(); const hub = new EventsHub(); const events: ServerEvent[] = []; hub.subscribe(e => events.push(e)); + await executeRun({ config, hub, runId: randomUUID(), request: request(), step: step(), rendered: rendered(), host, env: {} }); + expect(events).toContainEqual(expect.objectContaining({ type: "run.hostKeyUnknown", fingerprint: fp, changed: false })); + expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: -1 }); + }); + it("collects remote artifacts, serves downloads, and uploads a prior artifact via SFTP", async () => { + const { config, host, fp, files } = await sshFixture(); + const hub = new EventsHub(); const events: ServerEvent[] = []; hub.subscribe(e => events.push(e)); + const first = randomUUID(); const r = rendered(); r.artifacts = ["out.txt"]; + const req = request(); req.acceptHostKey = fp; + await executeRun({ config, hub, runId: first, request: req, step: step(), rendered: r, host, env: {} }); + expect(events.at(-1)).toMatchObject({ exitCode: 0, artifacts: ["out.txt"] }); + const app = await buildApp({ config }); cleanup.push(() => app.close()); + const download = await app.inject(`/api/runs/${first}/artifacts/out.txt`); + expect(download.statusCode).toBe(200); expect(download.body).toBe("artifact bytes"); + expect((await app.inject(`/api/runs/${first}/artifacts/undeclared.txt`)).statusCode).toBe(404); + const next = rendered(); next.uploads = [{ src: "out.txt", dst: "/tmp/uploaded.txt" }]; + await executeRun({ config, hub, runId: randomUUID(), request: { ...request(), artifactSources: { "out.txt": first } }, step: step(), rendered: next, host, env: {} }); + expect(events.at(-1)).toMatchObject({ exitCode: 0 }); + expect(files.get("/tmp/uploaded.txt")?.toString()).toBe("artifact bytes"); + }); +}); + +describe("pipeline helpers", () => { + it("accepts HTTP runs and broadcasts protocol events over WebSocket", async () => { + const { config, host } = await sshFixture(); + await writeFile(path.join(config.workspaceDir, "hosts.yaml"), JSON.stringify([host])); + vi.mocked(parseNotebook).mockReturnValueOnce({ title: "Test", params: [], blocks: [{ type: "step", step: step() }], diagnostics: [] }); + const hub = new EventsHub(); + const app = await buildApp({ config, events: hub }); cleanup.push(() => app.close()); + await app.ready(); + const socket = await app.injectWS("/api/events"); cleanup.push(async () => socket.close()); + const events: ServerEvent[] = []; + const finished = new Promise(resolve => socket.on("message", data => { + const event = JSON.parse(data.toString()) as ServerEvent; events.push(event); + if (event.type === "run.finished") resolve(); + })); + hub.publish({ type: "file.changed", path: "nested/test.md" }); + const res = await app.inject({ method: "POST", url: "/api/runs", payload: request() }); + expect(res.statusCode).toBe(202); + await finished; + expect(events).toContainEqual({ type: "file.changed", path: "nested/test.md" }); + expect(events).toContainEqual(expect.objectContaining({ type: "run.hostKeyUnknown", runId: res.json().runId })); + expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: -1 }); + }); + it("refuses missing or invalid parameters before execution", () => { + const notebook: Notebook = { title: "Test", params: [], blocks: [{ type: "step", step: step() }], diagnostics: [] }; + vi.mocked(resolveParams).mockReturnValueOnce({ values: {}, errors: { required: "missing" } }); + expect(() => prepareRun(notebook, request(), [])).toThrow("Parameters are missing or invalid"); + vi.mocked(renderStep).mockReturnValueOnce({ ...rendered(), missing: ["required"] }); + expect(() => prepareRun(notebook, request(), [])).toThrow("Step parameters are missing or invalid"); + }); + it("serializes a host FIFO, allows another host, and recovers after errors", async () => { + const queue = new SerialQueue(); const order: string[] = []; + let release!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const a = queue.run("a", async () => { order.push("a1"); await gate; throw new Error("failed"); }); + const failed = expect(a).rejects.toThrow("failed"); + const a2 = queue.run("a", async () => { order.push("a2"); }); + await queue.run("b", async () => { order.push("b"); }); + expect(order).toEqual(["a1", "b"]); release(); await failed; await a2; + expect(order).toEqual(["a1", "b", "a2"]); + }); + it("redacts secrets split across chunks", () => { + let text = ""; const redact = redactor(["secret", "secret-long"], data => { text += data; }); + redact.write("before sec"); redact.write("ret-long after sec"); redact.write("ret!"); redact.end(); + expect(text).toBe("before [REDACTED] after [REDACTED]!"); + }); + it("rejects invalid secret env names", () => { expect(() => scriptInput("echo hi", { "bad;name": "x" })).toThrow(); }); + it("refuses broken notebooks and unknown steps before running", () => { + const notebook: Notebook = { title: "Test", params: [], blocks: [{ type: "step", step: step() }], diagnostics: [{ severity: "error", message: "bad" }] }; + expect(() => prepareRun(notebook, request(), [])).toThrow("Notebook has errors"); + notebook.diagnostics = []; expect(() => prepareRun(notebook, { ...request(), stepId: "absent" }, [])).toThrow("Step not found"); + expect(() => prepareRun(notebook, request(), [])).toThrow("Unknown target host"); + }); + const bashAvailable = spawnSync("bash", ["-c", "exit 0"], { timeout: 5000 }).status === 0; + it.skipIf(!bashAvailable)("runs local bash with env and correct exit code", async () => { + const config = await fixture(); let text = ""; + const code = await localExec(path.join(config.dataDir, "local"), "printf '%s' \"$TOKEN\"; exit 4", { TOKEN: "abc" }, false, 2000, (_, data) => { text += data; }); + expect(code).toBe(4); expect(text).toBe("abc"); + }); + it.skipIf(!bashAvailable)("collects only declared local files after success", async () => { + const config = await fixture(); const hub = new EventsHub(); const events: ServerEvent[] = []; hub.subscribe(e => events.push(e)); + const r = rendered(); r.local = true; r.script = "printf artifact > result.txt"; r.artifacts = ["result.txt"]; + const id = randomUUID(); + await executeRun({ config, hub, runId: id, request: request(), step: step(), rendered: r, env: {} }); + expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: 0, artifacts: ["result.txt"] }); + expect(await readFile(path.join(config.dataDir, "runs", id, "artifacts", "result.txt"), "utf8")).toBe("artifact"); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7f4132b..6b1af71 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -29,7 +29,19 @@ importers: fastify: specifier: ^5.1.0 version: 5.12.8 + ssh2: + specifier: ^1.17.0 + version: 1.17.0 + yaml: + specifier: ^2.9.1 + version: 2.9.1 devDependencies: + '@types/ssh2': + specifier: ^1.15.6 + version: 1.15.6 + '@types/ws': + specifier: ^8.18.2 + version: 8.18.2 tsx: specifier: ^4.19.2 version: 4.23.15 @@ -495,9 +507,18 @@ packages: '@types/estree@1.0.10': resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} + '@types/node@18.19.130': + resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==} + '@types/node@22.20.5': resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==} + '@types/ssh2@1.15.6': + resolution: {integrity: sha512-oGdxhBqcRTwSTKFm+9EiKzkNVYRLEFkcW44lhguvBalGJbWfGnDt/ezwSUZc+SF9m9bMc3VyklNAtp7zICjS5w==} + + '@types/ws@8.18.2': + resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==} + '@vitest/expect@2.1.9': resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==} @@ -541,6 +562,9 @@ packages: ajv@8.20.0: resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + asn1@0.2.6: + resolution: {integrity: sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==} + assertion-error@2.0.1: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} @@ -552,6 +576,13 @@ packages: avvio@9.3.1: resolution: {integrity: sha512-QyTKW61/qlba+cUQBm/sT9X8lri4UdomqSDwCnrnj1IvLVDRRiXRkz4CgBRWB+/cmfC7SK5WQc8T1vSdGvaUcQ==} + bcrypt-pbkdf@1.0.2: + resolution: {integrity: sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==} + + buildcheck@0.0.7: + resolution: {integrity: sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==} + engines: {node: '>=10.0.0'} + cac@6.7.14: resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} engines: {node: '>=8'} @@ -568,6 +599,10 @@ packages: resolution: {integrity: sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==} engines: {node: '>=22'} + cpu-features@0.0.10: + resolution: {integrity: sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==} + engines: {node: '>=10.0.0'} + debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} @@ -672,6 +707,9 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + nan@2.30.0: + resolution: {integrity: sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==} + nanoid@3.3.20: resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -752,6 +790,9 @@ packages: resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} engines: {node: '>=10'} + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + secure-json-parse@4.1.1: resolution: {integrity: sha512-lnd81MQEZKjhW/Gd2TQqdd4XP6QYNdDW/EP+I7nTrFHP9y2LmaGPIHk9xsnzcOiEr1c39c/e84xFgGviQKBTRw==} @@ -777,6 +818,10 @@ packages: resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} engines: {node: '>= 10.x'} + ssh2@1.17.0: + resolution: {integrity: sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==} + engines: {node: '>=10.16.0'} + stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} @@ -820,11 +865,17 @@ packages: engines: {node: '>=18.0.0'} hasBin: true + tweetnacl@0.14.5: + resolution: {integrity: sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==} + typescript@5.9.3: resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} engines: {node: '>=14.17'} hasBin: true + undici-types@5.26.5: + resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==} + undici-types@6.21.0: resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} @@ -912,6 +963,11 @@ packages: utf-8-validate: optional: true + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} + engines: {node: '>= 14.6'} + hasBin: true + snapshots: '@esbuild/aix-ppc64@0.21.5': @@ -1179,10 +1235,22 @@ snapshots: '@types/estree@1.0.10': {} + '@types/node@18.19.130': + dependencies: + undici-types: 5.26.5 + '@types/node@22.20.5': dependencies: undici-types: 6.21.0 + '@types/ssh2@1.15.6': + dependencies: + '@types/node': 18.19.130 + + '@types/ws@8.18.2': + dependencies: + '@types/node': 22.20.5 + '@vitest/expect@2.1.9': dependencies: '@vitest/spy': 2.1.9 @@ -1236,6 +1304,10 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 + asn1@0.2.6: + dependencies: + safer-buffer: 2.1.2 + assertion-error@2.0.1: {} atomic-sleep@1.0.0: {} @@ -1245,6 +1317,13 @@ snapshots: '@fastify/error': 4.2.1 fastq: 1.20.3 + bcrypt-pbkdf@1.0.2: + dependencies: + tweetnacl: 0.14.5 + + buildcheck@0.0.7: + optional: true + cac@6.7.14: {} chai@5.3.3: @@ -1259,6 +1338,12 @@ snapshots: cookie@2.0.2: {} + cpu-features@0.0.10: + dependencies: + buildcheck: 0.0.7 + nan: 2.30.0 + optional: true + debug@4.4.3: dependencies: ms: 2.1.3 @@ -1420,6 +1505,9 @@ snapshots: ms@2.1.3: {} + nan@2.30.0: + optional: true + nanoid@3.3.20: {} on-exit-leak-free@2.1.2: {} @@ -1520,6 +1608,8 @@ snapshots: safe-stable-stringify@2.5.0: {} + safer-buffer@2.1.2: {} + secure-json-parse@4.1.1: {} semver@7.8.6: {} @@ -1536,6 +1626,14 @@ snapshots: split2@4.2.0: {} + ssh2@1.17.0: + dependencies: + asn1: 0.2.6 + bcrypt-pbkdf: 1.0.2 + optionalDependencies: + cpu-features: 0.0.10 + nan: 2.30.0 + stackback@0.0.2: {} std-env@3.10.0: {} @@ -1568,8 +1666,12 @@ snapshots: optionalDependencies: fsevents: 2.3.3 + tweetnacl@0.14.5: {} + typescript@5.9.3: {} + undici-types@5.26.5: {} + undici-types@6.21.0: {} util-deprecate@1.0.2: {} @@ -1644,3 +1746,5 @@ snapshots: wrappy@1.0.2: {} ws@8.23.0: {} + + yaml@2.9.1: {}