import { createHash } from "node:crypto"; import { closeSync, constants, fstatSync, mkdirSync, mkdtempSync, openSync, readSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; import { dirname, extname, isAbsolute, join, resolve } from "node:path"; import { homedir, tmpdir } from "node:os"; import { sbplString } from "../local/deny.ts"; import { spawnSync } from "node:child_process"; import { realPath } from "./project.ts"; import { profile, sandboxAvailable } from "../local/sandbox.ts"; export type ProjectionConfig = Record; const EMPTY_ROOT = "/var/empty"; export const MAX_PROJECTION_INPUT = 16 * 1024 * 1024; export const MAX_PROJECTION_TEXT = 256 * 1024; const MAX_INPUT = MAX_PROJECTION_INPUT, MAX_TEXT = MAX_PROJECTION_TEXT; /** Only machine-local config chooses programs; no implicit shell or command-string parsing. */ export function projectionConfig(raw: unknown): ProjectionConfig { if (raw === undefined) return {}; if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).length > 16) throw new Error("text_projection must be a bounded extension-to-argv map"); const out: ProjectionConfig = Object.create(null); for (const [ext, argv] of Object.entries(raw)) { if (!/^\.[a-z0-9]{1,16}$/.test(ext) || !Array.isArray(argv) || !argv.length || argv.length > 16 || argv.some(arg => typeof arg !== "string" || !arg || arg.length > 2000 || /[\x00-\x1f\x7f]/.test(arg)) || argv.filter(arg => arg === "{input}").length !== 1 || argv[0] === "{input}") throw new Error("text_projection entries require a bounded argv with one separate {input} argument"); out[ext] = [...argv]; } return out; } export interface ProjectedText { inputHash: string; rawHash: string; rawBlob: string; configHash: string; text: string } const hash = (data: string | Buffer) => createHash("sha256").update(data).digest("hex"); /** The program and script files an argv runs, resolved as the converter will see them. */ function programFiles(cwd: string, argv: string[]): { index: number; file: string; size: number; mtimeMs: number; ctimeMs: number }[] { const out: { index: number; file: string; size: number; mtimeMs: number; ctimeMs: number }[] = []; for (const [index, arg] of argv.entries()) { if (index !== 0 && !/\.(?:sh|py|js|mjs|cjs|ts|rb|pl)$/.test(arg)) continue; const choices = isAbsolute(arg) ? [arg] : index === 0 && !arg.includes("/") ? (process.env.PATH ?? "/usr/bin:/bin").split(":").slice(0, 32).map(dir => join(dir, arg)) : [resolve(cwd, arg)]; for (const file of choices) try { const st = statSync(file); if (!st.isFile()) continue; out.push({ index, file, size: st.size, mtimeMs: st.mtimeMs, ctimeMs: st.ctimeMs }); break; } catch { /* another PATH entry */ } } return out; } function commandFingerprint(cwd: string, argv: string[]): string { return hash([JSON.stringify(argv), ...programFiles(cwd, argv).flatMap(p => [p.file, String(p.size), String(p.mtimeMs), String(p.ctimeMs)])].join("\\n")); } function boundedCache(file: string): string { const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); try { const st = fstatSync(fd); if (!st.isFile() || st.nlink !== 1 || st.size > MAX_TEXT * 2) throw new Error("invalid cache file"); const bytes = Buffer.alloc(st.size); let got = 0; while (got < bytes.length) { const n = readSync(fd, bytes, got, bytes.length - got, got); if (!n) break; got += n; } if (got !== st.size) throw new Error("cache changed"); return bytes.toString("utf8"); } finally { closeSync(fd); } } /** Projections are presentation evidence, never proof of who wrote the original bytes. */ export class TextProjections { private readonly sandbox: string; private readonly warned = new Set(); /** Inputs whose full-budget conversion failed: the same bytes under the same command are not converted again. */ private readonly failed = new Set(); constructor(private readonly options: { cwd: string; projectRoot?: string; stateDir: string; config: ProjectionConfig; deny?: string[]; readAllow?: string[]; log?: (line: string) => void }) { // Rooted at an empty system directory, not the project. The project guarantee: project file data is denied, then the // snapshot, the argv-named program/script files and the directory listings above an in-project script are granted, so // no other project file is readable (system, toolchain, home and local.read_allow paths outside the project remain granted). // Only where conversion can run: /var/empty is a macOS directory, and a host without the sandbox never converts. this.sandbox = Object.keys(options.config).length && sandboxAvailable() ? profile(EMPTY_ROOT, false, options.readAllow, options.deny, ["."]) : ""; } private warn(ext: string): void { if (this.warned.has(ext)) return; this.warned.add(ext); this.options.log?.("text projection " + ext + " unavailable; retained original facts behavior"); } get enabled(): boolean { return Object.keys(this.options.config).length > 0; } handles(file: string): boolean { return !!this.options.config[extname(file).toLowerCase()]; } /** Current configured converter identity, without reading a source or running conversion. */ fingerprint(file: string): string | undefined { const argv = this.options.config[extname(file).toLowerCase()]; if (!argv) return undefined; try { const commandHash = commandFingerprint(this.options.cwd, argv); return this.options.projectRoot === undefined ? commandHash : hash(commandHash + "\nproject-root:" + realPath(this.options.projectRoot)); } catch { return undefined; } } project(file: string): ProjectedText | undefined { const ext = extname(file).toLowerCase(), argv = this.options.config[ext]; if (!argv) return undefined; let fd: number | undefined; try { const root = realPath(this.options.cwd), input = realPath(file); if (!input.startsWith(root + "/")) throw new Error("input outside project"); fd = openSync(input, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); const before = fstatSync(fd); if (!before.isFile() || before.size > MAX_INPUT) throw new Error("input cap"); const bytes = Buffer.alloc(before.size); let got = 0; while (got < bytes.length) { const n = readSync(fd, bytes, got, bytes.length - got, got); if (!n) break; got += n; } const after = fstatSync(fd); if (got !== before.size || before.size !== after.size || before.mtimeMs !== after.mtimeMs) throw new Error("input changed"); return this.convert(ext, bytes, () => { const final = fstatSync(fd!); if (final.size !== before.size || final.mtimeMs !== before.mtimeMs) throw new Error("input changed during conversion"); }); } catch { this.warn(ext); return undefined; } finally { if (fd !== undefined) closeSync(fd); } } /** Historic raw bytes; optional deadline uses performance.now(), shared across the preview. No current file read. */ projectBytes(file: string, bytes: Buffer, deadline?: number): ProjectedText | undefined { const ext = extname(file).toLowerCase(); if (!this.options.config[ext]) return undefined; try { const root = realPath(this.options.cwd), input = resolve(root, file); if (!input.startsWith(root + "/") || !Buffer.isBuffer(bytes) || bytes.length > MAX_INPUT) throw new Error("snapshot input cap or path"); return this.convert(ext, Buffer.from(bytes), undefined, deadline); } catch { this.warn(ext); return undefined; } } private convert(ext: string, bytes: Buffer, verify?: () => void, deadline?: number): ProjectedText | undefined { const argv = this.options.config[ext]; if (!argv) return undefined; let scratch: string | undefined; try { if (deadline !== undefined && (!Number.isFinite(deadline) || deadline <= performance.now())) throw new Error("projection deadline"); const rawHash = createHash("sha1").update(bytes).digest("hex"), rawBlob = createHash("sha1").update("blob " + bytes.length + "\0").update(bytes).digest("hex"); const inputHash = hash(bytes), commandHash = commandFingerprint(this.options.cwd, argv); const configHash = this.options.projectRoot === undefined ? commandHash : hash(commandHash + "\nproject-root:" + realPath(this.options.projectRoot)); const key = hash(inputHash + "\n" + configHash + "\n" + ext); const cacheDir = join(this.options.stateDir, "text-projections"), cache = join(cacheDir, key + ".json"); try { const cached = boundedCache(cache); if (Buffer.byteLength(cached) <= MAX_TEXT * 2) { const value = JSON.parse(cached) as ProjectedText; if (value.inputHash === inputHash && value.rawHash === rawHash && value.rawBlob === rawBlob && value.configHash === configHash && typeof value.text === "string" && Buffer.byteLength(value.text) <= MAX_TEXT) return value; } } catch { /* missing/invalid cache is not evidence */ } if (this.failed.has(key)) throw new Error("conversion failed before"); if (!sandboxAvailable()) throw new Error("sandbox unavailable"); scratch = realPath(mkdtempSync(join(tmpdir(), "ahub-projection-input-"))); const snapshot = join(scratch, "input" + ext); writeFileSync(snapshot, bytes, { mode: 0o400 }); // A read_allow entry may enclose the project. Seatbelt lets a later rule win only for the operation it names, so the // deny and the literal grants after it both name file-read-data. The converter runs in its scratch directory (getcwd // needs that directory's data), with its program and script arguments resolved to absolute paths. const root = realPath(this.options.cwd), protectedRoot = realPath(this.options.projectRoot ?? this.options.cwd); if (root !== protectedRoot && !root.startsWith(protectedRoot + "/")) throw new Error("execution root outside protected project"); const projectDeny = "\n(deny file-read-data (subpath " + sbplString(protectedRoot) + "))"; const resolved = programFiles(this.options.cwd, argv); // A module loader lists the directories above its script: grant those listings (not their files) up to the root. const listings = new Set(); for (const program of resolved) for (let dir = dirname(realPath(program.file)); dir.startsWith(root + "/") || dir === root; dir = dirname(dir)) { listings.add(dir); if (dir === root) break; } const programs = resolved.map(p => "\n(allow file-read* file-read-data process-exec (literal " + sbplString(realPath(p.file)) + "))").join("") + [...listings].map(dir => "\n(allow file-read-data (literal " + sbplString(dir) + "))").join("") + "\n(allow file-read* file-read-data (literal " + sbplString(scratch) + "))"; const absolute = new Map(resolved.map(p => [p.index, p.file])); const result = spawnSync(process.execPath, [join(import.meta.dir, "projection-exec.ts")], { cwd: scratch, timeout: deadline === undefined ? 8000 : Math.ceil(Math.max(1, Math.min(8000, deadline - performance.now()))), maxBuffer: MAX_TEXT * 2, encoding: "utf8", input: JSON.stringify({ cwd: scratch, sandbox: this.sandbox + projectDeny + "\n(allow file-read* file-read-data (literal " + sbplString(snapshot) + "))" + programs, argv: argv.map((arg, index) => arg === "{input}" ? snapshot : absolute.get(index) ?? arg), ...(deadline === undefined ? {} : { timeoutMs: Math.max(1, Math.min(5000, deadline - performance.now() - 100)) }) }), env: { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: homedir(), LANG: "en_US.UTF-8", TERM: "dumb" }, }); // ponytail: in-memory for this process, cleared at 1024 keys; persist it if restarts make retries costly. const failure = () => { if (deadline === undefined) { if (this.failed.size >= 1024) this.failed.clear(); this.failed.add(key); } return new Error("conversion failed"); }; if (result.error) throw new Error("conversion helper failed"); // a spawn or helper failure may be transient: not remembered if (result.status !== 0) throw failure(); const converted = JSON.parse(result.stdout) as { ok?: boolean; text?: string }; if (converted.ok !== true || typeof converted.text !== "string" || Buffer.byteLength(converted.text) > MAX_TEXT || converted.text.includes("\0")) throw failure(); verify?.(); const value = { inputHash, rawHash, rawBlob, configHash, text: converted.text }; mkdirSync(cacheDir, { recursive: true }); const temporary = cache + "." + crypto.randomUUID() + ".tmp"; writeFileSync(temporary, JSON.stringify(value), { mode: 0o600 }); renameSync(temporary, cache); return value; } catch { this.warn(ext); return undefined; } finally { if (scratch) rmSync(scratch, { recursive: true, force: true }); } } }