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.
This commit is contained in:
@@ -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<ServerConfig>;
|
||||
events?: EventsHub;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -15,6 +20,8 @@ export interface AppOptions {
|
||||
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
|
||||
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 }));
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import path from "node:path";
|
||||
|
||||
export interface ServerConfig {
|
||||
workspaceDir: string;
|
||||
dataDir: string;
|
||||
sshKeyPath: string;
|
||||
}
|
||||
|
||||
export function loadConfig(overrides: Partial<ServerConfig> = {}): 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"),
|
||||
};
|
||||
}
|
||||
@@ -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); };
|
||||
}
|
||||
}
|
||||
@@ -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<string, string>;
|
||||
}
|
||||
|
||||
export async function executeRun({ config, hub, runId, request, step, rendered, host, env }: ExecuteRun): Promise<void> {
|
||||
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<string>(session, done => session.realpath(remote, done));
|
||||
if (!real.startsWith(remoteDir! + "/")) throw new Error("Artifact escapes remote workdir");
|
||||
const info = await sftpRequest<import("ssh2").Stats>(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<string, string> {
|
||||
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<void>(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(); });
|
||||
}
|
||||
@@ -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<Client> {
|
||||
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<void>((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<number> {
|
||||
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, string>): 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<string, string>, sudo: boolean, timeoutMs: number, output: Output): Promise<number> {
|
||||
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<SFTPWrapper> {
|
||||
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<void> {
|
||||
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<T>(session: SFTPWrapper, request: (done: (error: Error | undefined, value: T) => void) => void): Promise<T> {
|
||||
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); });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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<string> {
|
||||
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<HostInfo[]> {
|
||||
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<string>();
|
||||
return entries.map((entry: Record<string, unknown>) => {
|
||||
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<string, Promise<unknown>>();
|
||||
async run<T>(key: string, task: () => Promise<T>): Promise<T> {
|
||||
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) };
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user