import { realpathSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; /** * `owned-root.sh`'s `refuse_wide_root`, for a TypeScript script. A folder a * script deletes FROM must never be `/`, the home folder or a folder the home * folder is inside: on 4 Oct 2026 a prune pointed directly under `$HOME` * deleted most of a home folder. Same judgement as the shell's, so the two * cannot drift apart in what they let through. */ export class WideRoot extends Error {} function realDir(path: string): string { try { return statSync(path).isDirectory() ? realpathSync(path) : ""; } catch { return ""; } } /** * Why `path` may not be a root a script deletes inside, or null when it may: * empty or `/`, relative, a `.` or `..` in it, or the home folder or a folder * the home folder is inside — as written or as it resolves through symlinks. */ export function wideRootWhy(path: string, home = homedir()): string | null { const bare = path.replace(/\/+$/, ""); if (!bare) return "it is empty or /"; if (!bare.startsWith("/")) return "it is not an absolute path"; if (bare.split("/").some((part) => part === "." || part === "..")) return "it has a . or .. in it"; const homeBare = home.replace(/\/+$/, ""); if (!homeBare) return null; const real = realDir(bare); if (real === "/") return "it is /"; for (const candidate of [bare, real]) { if (!candidate) continue; for (const inside of [homeBare, realDir(homeBare)]) { if (inside && `${inside}/`.startsWith(`${candidate.replace(/\/+$/, "")}/`)) return "it is the home folder or a folder the home folder is inside"; } } return null; } /** Throws `WideRoot` with a sentence when `path` is a root no script may delete inside. */ export function refuseWideRoot(what: string, path: string, home = homedir()): void { const why = wideRootWhy(path, home); if (why) throw new WideRoot(`REFUSED: ${what} is '${path}' — ${why}. This script deletes inside that folder, so it will not run there.`); } /** * `root/name` when `name` is one plain folder name, so a delete of it stays a * child of `root`; an id from elsewhere that is empty, `.`, `..` or holds a * slash would climb out of the root and is refused. */ export function ownedChild(root: string, name: string): string { if (!name || name === "." || name === ".." || /[/\\\0]/.test(name)) throw new WideRoot(`REFUSED: '${name}' is not one plain folder name, so a folder named by it would not stay inside ${root}.`); return join(root, name); }