import { spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, realpathSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { ownedChild, refuseWideRoot, WideRoot, wideRootWhy } from "../lib/owned-root"; /** * `scripts/lib/owned-root.ts` — `refuse_wide_root` for a TypeScript script. * Every case runs against a FAKE home, and each verdict is checked against the * shell's own so the two judge alike. */ const LIB = join(__dirname, "..", "lib", "owned-root.sh"); function fakeHome(): string { const home = mkdtempSync(join(tmpdir(), "owned-root-ts-home-")); mkdirSync(join(home, "Code"), { recursive: true }); return home; } const shellRefuses = (home: string, path: string) => spawnSync("bash", ["-euo", "pipefail", "-c", `. "${LIB}"; refuse_wide_root "the root" "${path}"`], { env: { PATH: process.env.PATH ?? "", HOME: home }, encoding: "utf8" }).status === 2; describe("refuseWideRoot", () => { // RULE: A TypeScript script's deletable root is refused exactly where refuse_wide_root refuses it: empty, relative, /, a . or .., the home folder, a folder the home is inside, or a symlink to one. it("refuses the home folder and everything above it, as the shell does", () => { const home = fakeHome(); symlinkSync(home, join(home, "Code", "link-to-home")); const wide = ["", "/", home, `${home}/`, `${home}/..`, `${home}/Code/../..`, "relative/dir", tmpdir(), realpathSync(tmpdir()), join(home, "Code", "link-to-home")]; for (const path of wide) { expect(wideRootWhy(path, home), path).not.toBeNull(); expect(shellRefuses(home, path), path).toBe(true); expect(() => refuseWideRoot("the root", path, home)).toThrow(WideRoot); } for (const path of [join(home, ".cache", "cottondb", "fetch"), join(home, "Code"), join(home, "CottonDevHousehold")]) { expect(wideRootWhy(path, home), path).toBeNull(); expect(shellRefuses(home, path), path).toBe(false); expect(() => refuseWideRoot("the root", path, home)).not.toThrow(); } }); it("says what was refused and why in one sentence", () => { expect(() => refuseWideRoot("the fetch work folder", "/", "/Users/someone")).toThrow( "REFUSED: the fetch work folder is '/' — it is empty or /. This script deletes inside that folder, so it will not run there.", ); }); // RULE: A folder named by an id from elsewhere stays a child of its root: an id that is empty, . or .., or holds a slash is refused. it("keeps a child named by an id inside its root", () => { expect(ownedChild("/w", "fet_01J")).toBe("/w/fet_01J"); for (const id of ["", ".", "..", "a/b", "../x", "/abs", "a\\b"]) expect(() => ownedChild("/w", id), id).toThrow(WideRoot); }); });