import { spawn, spawnSync } from "node:child_process"; import { existsSync, lstatSync, mkdtempSync, readdirSync, rmdirSync, rmSync, type Dirent } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { realPath } from "../hub/project.ts"; import { hubGitSync } from "../hub/git.ts"; import { denyRegexes, hubWriteRegexes, objectStoreRules, sbplString } from "./deny.ts"; import { stopOwnedProcess, trackGroup } from "../hub/child-process.ts"; import { sandboxCommandEnvironment } from "./shell-environment.ts"; const SANDBOX_EXEC = "/usr/bin/sandbox-exec"; export const OUTPUT_CAP = 20_000; export const sandboxAvailable = () => process.platform === "darwin" && existsSync(SANDBOX_EXEC); const q = sbplString; /** * Seatbelt profile for everything the local worker executes (bash, git). Path checks cannot scope a shell, * so the kernel does: writes only under cwd and temp, no reads of credential stores or denylisted files, * no network unless asked. In SBPL the last matching rule wins, so the denies come last. */ /** Toolchains and git identity: the only parts of the home directory a sandboxed command may read besides the project. */ const HOME_READABLE = [".bun", ".cargo", ".rustup", ".local", ".npm", ".cache", ".pyenv", ".nvm", ".deno", "go", ".gitconfig", ".config/git", "Library/Caches", ".volta", ".asdf", ".nodenv", ".rbenv", ".sdkman", "Library/Application Support/fnm", "Library/pnpm"]; /** * Public CA bundles: the name denies (`*.pem` for keys) also match these, and TLS needs them once network is on. * Allowed after the denies, by exact path. */ const CA_BUNDLES = ["/private/etc/ssl/cert.pem", "/opt/homebrew/etc/ca-certificates/cert.pem", "/opt/homebrew/etc/openssl@3/cert.pem", "/usr/local/etc/ca-certificates/cert.pem", "/usr/local/etc/openssl@3/cert.pem"]; /** * The selected Xcode or Command Line Tools dir: the `/usr/bin` shims (git, clang, make, python3) run what is in it. * Inside an app bundle that is the whole `Contents`: its tools load frameworks from `SharedFrameworks` next to it. */ function developerDir(): string | undefined { const out = spawnSync("xcode-select", ["-p"], { encoding: "utf8" }); let dir = out.status === 0 ? out.stdout.trim() : ""; // Seatbelt matches real paths: an Xcode selected through a symlink (`Xcode.app` -> `Xcode-26.0.app`) needs its target. try { dir = dir && realPath(dir); } catch { /* gone since it was selected: nothing the shims could run either */ } return dir ? dir.replace(/(\.app\/Contents)\/Developer\/?$/, "$1") : undefined; } /** A submodule or worktree keeps its git dir outside the project; git needs it, minus the parts that execute or reconfigure. */ function externalGitDirs(root: string): string[] { // Runs in the hub process, outside the sandbox: the hardened helper keeps the repo's config from naming a program (#281). const out = hubGitSync(["-C", root, "rev-parse", "--absolute-git-dir", "--git-common-dir"], { encoding: "utf8" }); if (out.status !== 0) return []; const dirs = out.stdout.trim().split("\n").map((d) => resolve(root, d)); return [...new Set(dirs)].filter((d) => !d.startsWith(`${root}/`)); } /** `/worktrees`: where every linked worktree keeps its git dir. The rules for it are patterns, so they need no worktree to exist (#518). */ function worktreesRoot(root: string): string | undefined { const out = hubGitSync(["-C", root, "rev-parse", "--git-common-dir"], { encoding: "utf8" }); return out.status === 0 && out.stdout.trim() ? join(resolve(root, out.stdout.trim()), "worktrees") : undefined; } /** * One modules tree: its root, the submodule git dirs found directly under it (`dirs`, each a directory holding HEAD and config, however it is named) and every directory entry * that must not be renamed, replaced, symlinked or recreated (the root, each git dir and every component between them, #281). Everything else under the root is refused to * write (#520): a git dir that is not discovered here is a plant, whatever its name. */ export interface ModuleGit { root: string; entries: string[]; dirs?: string[] } /** The deepest submodule nesting the profile follows: a git dir below it is not exempt, so a write there fails closed instead of going unprotected. */ const MODULE_DEPTH = 8; /** * The submodule git directories the project can reach, as modules trees. A plain checkout keeps them under the common dir's `modules/`; a LINKED worktree keeps its own under that * worktree's git dir, `/worktrees//modules/`, so the trees are the common dir's, this worktree's own git dir's (whether or not it exists yet, so it cannot be pre-created) * and every sibling worktree's that already has one: the common dir is writable from here (#518). Every discovered git dir also gets a tree of its own for its `modules/`, existing * or not, so a submodule of a submodule is covered the same way (#520). Discovered in the hub process, outside the sandbox. */ function moduleGitDirs(root: string): ModuleGit[] { const out = hubGitSync(["-C", root, "rev-parse", "--git-common-dir", "--absolute-git-dir"], { encoding: "utf8" }); if (out.status !== 0) return []; const [commonRaw, ownRaw] = out.stdout.trim().split("\n"); if (!commonRaw || !ownRaw) return []; const common = resolve(root, commonRaw), own = resolve(root, ownRaw); const roots = new Set([join(common, "modules"), join(own, "modules")]); try { for (const e of readdirSync(join(common, "worktrees"), { withFileTypes: true })) { if (!e.isDirectory()) continue; const modules = join(common, "worktrees", e.name, "modules"); if (existsSync(modules)) roots.add(modules); } } catch { /* no linked worktrees */ } const trees: ModuleGit[] = []; const tree = (modulesRoot: string, nesting: number): void => { const dirs: string[] = []; const walk = (dir: string, depth: number): void => { if (depth > 8) return; // a path this deep is not a submodule layout git makes let entries: Dirent[]; try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; // no modules tree (no submodules): nothing to discover } const names = new Set(entries.map((e) => e.name)); if (names.has("HEAD") && names.has("config")) { dirs.push(dir); return; } for (const e of entries) if (e.isDirectory()) walk(join(dir, e.name), depth + 1); }; walk(modulesRoot, 0); // Past the nesting limit nothing is exempt, so a write below it is refused rather than left unprotected. const found = nesting >= MODULE_DEPTH ? [] : dirs; const entries = new Set([modulesRoot]); for (const d of found) for (let p = d; p.length > modulesRoot.length; p = dirname(p)) entries.add(p); trees.push({ root: modulesRoot, entries: [...entries], dirs: found }); for (const d of found) { tree(join(d, "modules"), nesting + 1); // a submodule of a submodule, whether or not it exists yet // A submodule is a repository: its linked worktrees keep their own modules trees at `/worktrees//modules`. Existing ones are discovered here; ones that do not exist yet // are covered by pattern in hubWriteRegexes (#520 review). try { for (const e of readdirSync(join(d, "worktrees"), { withFileTypes: true })) { if (e.isDirectory() && existsSync(join(d, "worktrees", e.name, "modules"))) tree(join(d, "worktrees", e.name, "modules"), nesting + 1); } } catch { /* no linked worktrees */ } } }; for (const modulesRoot of roots) tree(modulesRoot, 0); return trees; } /** The system directories a deny-default profile lets commands read and run from: dyld, frameworks, toolchains. */ const SYSTEM_READABLE = ["/usr", "/bin", "/sbin", "/System", "/Library", "/opt", "/private/etc", "/private/var/db/timezone", "/private/var/db/dyld"]; /** * Directory lookups (users, groups), logging and notifications; plus name resolution and TLS trust when network is on. * No brokers that act outside the sandbox: LaunchServices would let `open` start a browser with network, and * SecurityServer would answer Keychain queries the credential-path denies are there to stop. */ const MACH_SERVICES = ["com.apple.system.opendirectoryd.libinfo", "com.apple.system.DirectoryService.libinfo_v1", "com.apple.system.logger", "com.apple.system.notification_center"]; const NETWORK_MACH_SERVICES = ["com.apple.dnssd.service", "com.apple.trustd", "com.apple.trustd.agent", "com.apple.networkd"]; /** Through the egress proxy (#65) the proxy resolves names: only TLS trust is looked up here, no DNS that could carry data. */ const PROXY_MACH_SERVICES = ["com.apple.trustd", "com.apple.trustd.agent"]; /** * Network for the commands: none, direct (`local.bash_network: "direct"`, everything, until 0.13.0), or only * the hub's egress proxy on a loopback port (#65), which opens allowlisted hosts. */ export type SandboxNetwork = boolean | { proxyPort: number }; /** * Starts from `(deny default)` (issue #39) and allows only what commands need: running and reading the system, * toolchain and project directories, writing the project and a temp dir of their own. The allow-default profile of * 0.9 and earlier was removed in 0.12.0 (issue #83). */ export function profile(cwd: string, network: SandboxNetwork, readAllow: string[] = [], deny: string[] = [], readOnly: string[] = []): string { const home = homedir(); const inHome = (p: string) => (p.startsWith("~/") ? join(home, p.slice(2)) : p); const root = realPath(cwd); const gitDirs = externalGitDirs(root); const moduleGit = moduleGitDirs(root); const worktrees = worktreesRoot(root); const creds = [".ssh", ".aws", ".gnupg", ".config/gh", ".config/gcloud", ".kube", ".docker", ".netrc", ".npmrc", ".omniroute", ".claude", ".codex", ".kimi-code", "Library/Keychains"]; const dev = developerDir(); const readable = [root, ...HOME_READABLE.map((p) => join(home, p)), ...readAllow.map(inHome), ...gitDirs, ...(dev ? [dev] : [])]; const subpaths = (paths: string[]) => paths.map((p) => `(subpath ${q(p)})`).join(" "); const globals = (names: string[]) => names.map((n) => `(global-name ${q(n)})`).join(" "); const proxy = typeof network === "object" ? `(allow network-outbound (remote ip ${q(`localhost:${network.proxyPort}`)}))` : undefined; const start = [ "(deny default)", "(allow process-fork)", // Runs from the system, toolchain and project directories only; a script runs through an allowed interpreter. // The user's temp dir and /private/tmp are shared with every other process: each command gets its own (#63). `(allow process-exec ${subpaths([...SYSTEM_READABLE, ...readable])})`, "(allow signal (target same-sandbox))", "(allow process-info* (target same-sandbox))", "(allow sysctl-read)", `(allow mach-lookup ${globals([...MACH_SERVICES, ...(proxy ? PROXY_MACH_SERVICES : network ? NETWORK_MACH_SERVICES : [])])})`, '(allow ipc-posix-shm-read-data ipc-posix-shm-read-metadata (ipc-posix-name "apple.shm.notification_center"))', "(allow file-read-metadata)", `(allow file-read* (literal "/") ${subpaths([...SYSTEM_READABLE, "/dev"])} ${subpaths(readable)})`, '(allow file-ioctl (regex #"^/dev/"))', ...(proxy ? [proxy] : network ? ["(allow network*)"] : []), ]; const places = `${creds.map((c) => `(subpath ${q(join(home, c))})`).join(" ")} ${denyRegexes(root, deny, false).join(" ")}`; return [ "(version 1)", ...start, "(deny file-write*)", ...(readOnly.length ? ["(allow file-write* (literal \"/dev/null\"))"] : [`(allow file-write* (subpath ${q(root)}) (regex #"^/dev/") ${gitDirs.map((d) => `(subpath ${q(d)})`).join(" ")})`]), // Inside cwd: nothing that runs later outside the sandbox, nothing that reconfigures the hub. The .git and // .agenthub patterns tolerate the code points HFS+ ignores in every segment, the .git name itself is refused // at any depth (creation, rename, symlink, gitfile), a submodule git dir's config and hooks under // .git/modules/ are refused at the depth submodules nest (#281), and the external git dirs get folded // hooks/config rules (#270). The cost: git init, clone and worktree add no longer run inside the sandbox. `(deny file-write* ${hubWriteRegexes(root, gitDirs, moduleGit, worktrees).join(" ")})`, // The shared object store: only new loose objects may be added (#864). ...(worktrees ? objectStoreRules(dirname(worktrees)) : []), `(deny file-read* file-write* ${creds.map((c) => `(subpath ${q(join(home, c))})`).join(" ")})`, `(deny file-read* file-write* ${denyRegexes(root, deny).join(" ")})`, // Python's own CA bundle (certifi, which pip vendors too): pip, requests and httpx read it instead of the system's (#64). // The last match wins: the denied places come again after it, so it overrides only the `.pem` name rule. ...(network ? [`(allow file-read* ${CA_BUNDLES.map((p) => `(literal ${q(p)})`).join(" ")} (regex ${q("/certifi/cacert\\.pem$")}))`, `(deny file-read* file-write* ${places})`] : []), ].join("\n"); } export interface ExecResult { code: number | null; output: string; /** Probe-only owned-process proof; ordinary command results retain their existing shape. */ quiescent?: boolean; stop?: () => Promise; } export interface ProbeCommandOptions { workspaceRoot: string; temporaryRoot: string; home: string; current(): void; physical(): void } /** Run argv under seatbelt with a scrubbed environment. Never runs unsandboxed: no sandbox, no exec. */ export function sandboxedExec(argv: string[], opts: { cwd: string; profile: string; timeoutMs?: number; env?: Record; signal?: AbortSignal; readOnlyData?: boolean; probe?: ProbeCommandOptions }): Promise { if (opts.probe) return probeCommand(argv, opts as Parameters[1]); if (opts.readOnlyData && /\(allow file-write\* \(subpath /.test(opts.profile)) return Promise.resolve({ code: null, output: "error: data.readonly command profile contains a broad write grant" }); if (!sandboxAvailable()) return Promise.resolve({ code: null, output: "error: command execution needs macOS sandbox-exec and is disabled on this host" }); if (opts.signal?.aborted) return Promise.resolve({ code: null, output: "error: command cancelled before execution" }); return new Promise((resolve) => { // A temp dir of its own (#63): the user's is shared with every other process, and what a command reads can reach // an answer shown to cloud peers. Allowed after the profile's denies, and gone when the command ends. const own = realPath(mkdtempSync(join(tmpdir(), "ahub-cmd-"))); const sandbox = `${opts.profile}\n(allow file-read* ${opts.readOnlyData ? "" : "file-write* "}process-exec (subpath ${q(own)}))`; // A path-only deny cannot contain hardlink aliases; data mode allows reads/stdout, never filesystem writes. const env = sandboxCommandEnvironment({ PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: homedir(), LANG: process.env.LANG ?? "en_US.UTF-8", TERM: "dumb", ...opts.env }, own); // Own process group: a timeout has to take the grandchildren too, or they keep the pipes open and the project writable. const child = spawn(SANDBOX_EXEC, ["-p", sandbox, ...argv], { cwd: opts.cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: true }); let output = ""; let killRequested = false; const take = (d: Buffer) => { if (output.length < OUTPUT_CAP) output += d.toString(); }; child.stdout.on("data", take); child.stderr.on("data", take); const killGroup = () => { try { process.kill(-child.pid!, "SIGKILL"); } catch { child.kill("SIGKILL"); } }; // A shell may report its killed child and exit 137 normally, without a native signal. const abort = () => { killRequested = true; killGroup(); }; opts.signal?.addEventListener("abort", abort, { once: true }); // Best effort, never in the way of the result: a command can mark its files immutable (`chflags uchg`), and then // the plain remove throws. What still fails is left to the OS temp cleanup. const dropOwn = () => { try { rmSync(own, { recursive: true, force: true }); } catch { try { spawnSync("chflags", ["-R", "nouchg", own]); rmSync(own, { recursive: true, force: true }); } catch { /* left behind */ } } }; const timer = setTimeout(abort, opts.timeoutMs ?? 120_000); let done = false; const finish = (code: number | null, signal: NodeJS.Signals | null) => { if (done) return; done = true; clearTimeout(timer); opts.signal?.removeEventListener("abort", abort); dropOwn(); const clipped = output.length >= OUTPUT_CAP ? `${output.slice(0, OUTPUT_CAP)}\n(output truncated)` : output; resolve({ code, output: signal || killRequested ? `${clipped}\n(killed: ${signal ?? "SIGKILL"}, timeout?)` : clipped }); }; child.on("error", (e) => (done || ((done = true), clearTimeout(timer), opts.signal?.removeEventListener("abort", abort), dropOwn(), resolve({ code: null, output: `error: ${e.message}` })))); child.on("close", finish); // `close` waits for every holder of the pipes; after `exit` give stragglers a moment, then stop waiting and reap them. child.on("exit", (code, signal) => setTimeout(() => (killGroup(), finish(code, signal)), 500).unref()); }); } /** Same sandbox entry point, with a readonly owned temp and verified cleanup for fixed host proof commands. */ async function probeCommand(argv: string[], opts: { cwd: string; profile: string; timeoutMs?: number; env?: Record; signal?: AbortSignal; probe: ProbeCommandOptions }): Promise { const proof = opts.probe; if (!sandboxAvailable()) return { code: null, output: "error: probe confinement needs macOS sandbox-exec", quiescent: true }; try { proof.physical(); proof.current(); const root = realPath(proof.workspaceRoot), temporary = realPath(proof.temporaryRoot), home = realPath(proof.home); if (realPath(opts.cwd) !== root || !temporary.startsWith(root + "/") || !opts.env || opts.env.HOME !== home || opts.env.PATH !== "/usr/bin:/bin:/usr/sbin:/sbin" || opts.env.LANG !== "C" || opts.env.TERM !== "dumb" || Object.keys(opts.env).some(key => !["PATH", "HOME", "LANG", "TERM"].includes(key))) throw new Error("probe command binding unavailable"); if (opts.signal?.aborted) throw new Error("probe command cancelled"); } catch { return { code: null, output: "error: probe command authority or environment unavailable", quiescent: true }; } const own = realPath(mkdtempSync(join(proof.temporaryRoot, "command-"))); const created = lstatSync(own); let removed = false; const dropOwn = () => { if (removed) return; proof.physical(); const current = lstatSync(own); if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== created.dev || current.ino !== created.ino || realPath(own) !== own) throw new Error("probe command temp ownership changed"); // The lane grants no temp writes. Unexpected contents are retained rather than recursively removed. rmdirSync(own); removed = true; }; // Never append the ordinary broad temp read/write/exec suffix: the verified profile already bounds this directory. const env = { ...opts.env, TMPDIR: `${own}/` }; return new Promise(resolve => { let child: ReturnType; try { proof.current(); child = spawn(SANDBOX_EXEC, ["-p", opts.profile, ...argv], { cwd: opts.cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: true }); } catch { try { dropOwn(); resolve({ code: null, output: "error: probe command did not launch", quiescent: true }); } catch { resolve({ code: null, output: "error: probe command setup cleanup is unconfirmed", quiescent: false, stop: async () => dropOwn() }); } return; } trackGroup(child); let output = "", settled = false, cancelled = false; let pipeTimer: ReturnType | undefined; const take = (data: Buffer) => { if (output.length < OUTPUT_CAP) output += data.toString(); }; child.stdout?.on("data", take); child.stderr?.on("data", take); const stop = async () => { await stopOwnedProcess(child, { group: true }); dropOwn(); }; const finish = async (code: number | null) => { if (settled) return; settled = true; clearTimeout(timer); if (pipeTimer) clearTimeout(pipeTimer); opts.signal?.removeEventListener("abort", abort); let quiescent = false; try { await stop(); quiescent = true; } catch { /* keep the child and directory in the returned owned stop handle */ } const clipped = output.length >= OUTPUT_CAP ? `${output.slice(0, OUTPUT_CAP)}\n(output truncated)` : output; const observed = child.signalCode ? `${clipped}\n(probe command signal: ${child.signalCode}; owned pid: ${child.pid})` : clipped; resolve({ code, output: cancelled ? `${observed}\n(probe command cancelled)` : observed, quiescent, ...(quiescent ? {} : { stop }) }); }; const abort = () => { cancelled = true; void finish(null); }; const timer = setTimeout(abort, opts.timeoutMs ?? 5000); opts.signal?.addEventListener("abort", abort, { once: true }); child.once("error", error => { output = `error: probe command spawn failed (${(error as NodeJS.ErrnoException).code ?? "unknown"})`; void finish(null); }); child.once("close", code => { void finish(code); }); // A leader exit is not proof that descendants released pipes. The owned stop proves or retains uncertainty. child.once("exit", code => { pipeTimer = setTimeout(() => { void finish(code); }, 500); }); if (child.exitCode !== null || child.signalCode !== null) pipeTimer = setTimeout(() => { void finish(child.exitCode); }, 500); if (opts.signal?.aborted) abort(); }); } /** The environment that sends a command's HTTPS through the egress proxy (#65); empty without one. */ export function proxyEnv(network: SandboxNetwork): Record { if (typeof network !== "object") return {}; const url = `http://127.0.0.1:${network.proxyPort}`; return { HTTPS_PROXY: url, https_proxy: url, HTTP_PROXY: url, http_proxy: url, ALL_PROXY: url, all_proxy: url, NO_PROXY: "", no_proxy: "" }; }