import { randomUUID } from "node:crypto"; import { mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { checkToolAvailability, resolveCommand, SpawnTextResourceError, spawnToText, } from "../spawn"; const originalPath = process.env["PATH"]; const originalPathAlt = process.env["Path"]; afterEach(() => { if (originalPath === undefined) delete process.env["PATH"]; else process.env["PATH"] = originalPath; if (originalPathAlt === undefined) delete process.env["Path"]; else process.env["Path"] = originalPathAlt; }); async function makeFakeTool(dir: string, name: string) { if (process.platform === "win32") { const toolPath = path.join(dir, `${name}.cmd`); await writeFile(toolPath, "@echo off\r\nexit /b 0\r\n"); return toolPath; } const toolPath = path.join(dir, name); await writeFile(toolPath, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); return toolPath; } describe("spawnToText limits", () => { const node = process.execPath; it("does not spawn when signal is already aborted", async () => { const dir = await mkdtemp(path.join(tmpdir(), "pi-web-aborted-")); const marker = path.join(dir, "spawned"); const controller = new AbortController(); controller.abort(); try { await expect( spawnToText( node, [ "-e", `require("node:fs").writeFileSync(${JSON.stringify(marker)}, "spawned")`, ], undefined, { signal: controller.signal }, ), ).rejects.toBeInstanceOf(SpawnTextResourceError); await expect(readFile(marker, "utf8")).rejects.toMatchObject({ code: "ENOENT", }); } finally { await rm(dir, { recursive: true, force: true }); } }); it.skipIf(process.platform === "win32")( "aborts a SIGTERM-ignoring child and escalates to SIGKILL", async () => { const dir = await mkdtemp(path.join(tmpdir(), "pi-web-abort-")); const ready = path.join(dir, "ready"); const controller = new AbortController(); let pid = 0; try { const result = spawnToText( node, [ "-e", `process.on("SIGTERM", () => {}); require("node:fs").writeFileSync(${JSON.stringify(ready)}, String(process.pid)); process.stdin.pause(); setInterval(() => {}, 1000)`, ], "x".repeat(16 * 1024 * 1024), { signal: controller.signal }, ); const deadline = Date.now() + 2_000; while (Date.now() < deadline) { try { pid = Number(await readFile(ready, "utf8")); break; } catch { await new Promise((resolve) => setTimeout(resolve, 10)); } } expect(pid).toBeGreaterThan(0); controller.abort(); await expect(result).rejects.toBeInstanceOf(SpawnTextResourceError); const exitDeadline = Date.now() + 2_000; while (Date.now() < exitDeadline) { try { process.kill(pid, 0); await new Promise((resolve) => setTimeout(resolve, 20)); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ESRCH") return; throw error; } } throw new Error( `Owned child ${pid} remained alive after SIGKILL escalation`, ); } finally { controller.abort(); if (pid > 0) { try { process.kill(pid, "SIGKILL"); } catch { // The child may already have exited. } } await rm(dir, { recursive: true, force: true }); } }, ); it("enforces deadline without waiting for a hung process", async () => { const started = Date.now(); const run = () => spawnToText(node, ["-e", "setInterval(() => {}, 1_000)"], undefined, { timeoutMs: 50, }); await expect(run()).rejects.toBeInstanceOf(SpawnTextResourceError); await expect(run()).rejects.toThrow("timed out after 50ms"); expect(Date.now() - started).toBeLessThan(1_000); }); it("counts stdout bytes while decoding split UTF-8", async () => { await expect( spawnToText( node, [ "-e", "process.stdout.write(Buffer.from([0xe2, 0x82])); setTimeout(() => process.stdout.write(Buffer.from([0xac])), 10)", ], undefined, { maxStdoutBytes: 3 }, ), ).resolves.toBe("€"); await expect( spawnToText(node, ["-e", 'process.stdout.write("€€")'], undefined, { maxStdoutBytes: 5, }), ).rejects.toBeInstanceOf(SpawnTextResourceError); await expect( spawnToText(node, ["-e", 'process.stdout.write("€€")'], undefined, { maxStdoutBytes: 5, }), ).rejects.toThrow("stdout exceeded 5 byte limit"); }); it("bounds stderr before retaining diagnostics", async () => { await expect( spawnToText(node, ["-e", 'process.stderr.write("abcdef")'], undefined, { maxStderrBytes: 5, }), ).rejects.toBeInstanceOf(SpawnTextResourceError); await expect( spawnToText(node, ["-e", 'process.stderr.write("abcdef")'], undefined, { maxStderrBytes: 5, }), ).rejects.toThrow("stderr exceeded 5 byte limit"); }); it("enforces default stdout and stderr caps", async () => { await expect( spawnToText(node, [ "-e", 'process.stdout.write("x".repeat(8 * 1024 * 1024 + 1))', ]), ).rejects.toThrow("stdout exceeded 8388608 byte limit"); await expect( spawnToText(node, [ "-e", 'process.stderr.write("x".repeat(64 * 1024 + 1))', ]), ).rejects.toThrow("stderr exceeded 65536 byte limit"); }); it("keeps stdin error handling through teardown with pending input and output limits", async () => { await expect( spawnToText( node, [ "-e", 'process.stdin.pause(); process.stdout.write("overflow"); setInterval(() => {}, 1000)', ], "x".repeat(16 * 1024 * 1024), { maxStdoutBytes: 1 }, ), ).rejects.toBeInstanceOf(SpawnTextResourceError); }); it("returns normal native command output", async () => { await expect( spawnToText(node, ["-e", 'process.stdout.write("normal")']), ).resolves.toBe("normal"); }); }); describe("checkToolAvailability", () => { it("finds executables on PATH without requiring Unix which", async () => { const dir = await mkdtemp(path.join(tmpdir(), "pi-web-path-")); const name = `fake-tool-${randomUUID()}`; await makeFakeTool(dir, name); process.env["PATH"] = dir; await expect(checkToolAvailability(name, "missing")).resolves.toBeNull(); }); it("does not keep stale negative cache entries after PATH changes", async () => { const dir = await mkdtemp(path.join(tmpdir(), "pi-web-path-")); const emptyDir = await mkdtemp(path.join(tmpdir(), "pi-web-empty-path-")); const name = `fake-tool-${randomUUID()}`; process.env["PATH"] = emptyDir; await expect(checkToolAvailability(name, "missing")).resolves.toBe( "missing", ); await makeFakeTool(dir, name); process.env["PATH"] = dir; await expect(checkToolAvailability(name, "missing")).resolves.toBeNull(); }); it("resolves explicit command paths but rejects directories", async () => { const dir = await mkdtemp(path.join(tmpdir(), "pi-web-explicit-path-")); const name = `fake-tool-${randomUUID()}`; const executable = await makeFakeTool(dir, name); const resolved = await resolveCommand(path.join(dir, name)); if (!resolved) throw new Error("Explicit command fixture was not resolved"); // PATHEXT casing is not filesystem identity on Windows. expect(await realpath(resolved)).toBe(await realpath(executable)); expect(await resolveCommand(dir)).toBeNull(); }); it("runs PATH-resolved tools without a shell-specific lookup utility", async () => { const dir = await mkdtemp(path.join(tmpdir(), "pi web path ")); const name = `fake-tool-${randomUUID()}`; await makeFakeTool(dir, name); process.env["PATH"] = dir; await expect(spawnToText(name, ["arg with spaces"])).resolves.toBe(""); }); });