import { mkdir, open, readFile, writeFile, stat, readdir, rm } from "node:fs/promises"; import path from "node:path"; import { createHash } from "node:crypto"; import type { ServerConfig } from "../config"; import { httpError, safeFile, safeRelative } from "../workspace"; const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; export function runRoot(config: ServerConfig, id: string) { if (!RUN_ID.test(id)) throw httpError(400, "Invalid run ID"); return path.join(config.dataDir, "runs", id); } export interface Artifact { name: string; sensitive: boolean } /** Inspect only a bounded prefix, independent of the artifact size. */ export async function isSensitive(file: string): Promise { const handle = await open(file, "r"); try { const prefix = Buffer.alloc(512); const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0); return /^\s*-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/.test(prefix.toString("ascii", 0, bytesRead)); } finally { await handle.close(); } } /** Shared by collection and portable fixtures; metadata contains no file contents. */ export async function persistArtifacts(config: ServerConfig, id: string, names: string[]): Promise { const root = runRoot(config, id); const artifacts = await Promise.all(names.map(async name => ({ name, sensitive: await isSensitive(await safeFile(path.join(root, "artifacts"), name)) }))); await writeFile(path.join(root, "artifacts.json"), JSON.stringify(artifacts), { mode: 0o600 }); return artifacts; } export async function artifactFile(config: ServerConfig, id: string, name: string) { safeRelative(name); const root = runRoot(config, id); try { if (Date.now() - (await stat(root)).mtimeMs >= config.artifactTtlHours * 3600000) throw httpError(410, "Artifact expired"); const entries: (Artifact | string)[] = JSON.parse(await readFile(path.join(root, "artifacts.json"), "utf8")); const entry = entries.find(entry => (typeof entry === "string" ? entry : entry.name) === name); if (!entry) throw httpError(404, "Artifact not found"); const file = await safeFile(path.join(root, "artifacts"), name); if (!(await stat(file)).isFile()) throw httpError(410, "Artifact unavailable"); return { file, sensitive: typeof entry === "string" ? await isSensitive(file) : entry.sensitive }; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT" || (error as { statusCode?: number }).statusCode === 404 && (error as Error).message === "File not found") throw httpError(410, "Artifact not found or expired"); throw error; } } /** Exclusive on-disk claim prevents simultaneous sensitive downloads, including across app instances. */ export async function claimArtifact(file: string) { const locks = path.join(path.dirname(file), ".downloads"); await mkdir(locks, { recursive: true, mode: 0o700 }); const identity = process.platform === "win32" ? path.basename(file).toLowerCase() : path.basename(file); const lock = path.join(locks, createHash("sha256").update(identity).digest("hex")); try { const handle = await open(lock, "wx", 0o600); await handle.close(); } catch (error) { if ((error as NodeJS.ErrnoException).code === "EEXIST") throw httpError(410, "Sensitive artifact already claimed"); throw error; } // A preceding download may have deleted the file while this request awaited metadata. try { await stat(file); } catch (error) { await rm(lock, { force: true }); if ((error as NodeJS.ErrnoException).code === "ENOENT") throw httpError(410, "Artifact not found or expired"); throw error; } return async (success: boolean) => { // Keep the claim if deletion fails: fail closed rather than serve the key again. if (success) await rm(file, { force: true }); await rm(lock, { force: true }); }; } export async function sweepRuns(config: ServerConfig, active: ReadonlySet, now = Date.now()) { const base = path.join(config.dataDir, "runs"); await mkdir(base, { recursive: true, mode: 0o700 }); for (const entry of await readdir(base, { withFileTypes: true })) { if (!entry.isDirectory() || !RUN_ID.test(entry.name) || active.has(entry.name)) continue; const root = runRoot(config, entry.name); const info = await stat(root).catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return undefined; throw error; }); if (info && now - info.mtimeMs >= config.artifactTtlHours * 3600000 && !active.has(entry.name)) await rm(root, { recursive: true, force: true }); } }