import { basename, dirname } from "node:path"; import { DENY_NAMES, DENY_SEGMENTS } from "@staix/agent-mem/platform"; // One core deny policy for path guards, sandbox rules, capture and memory extraction. export { DENY_NAMES, DENY_SEGMENTS, isDenied } from "@staix/agent-mem/platform"; /** Regex metacharacters only; `sbplString` quotes the finished regex. */ const sbplEscape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); /** * An SBPL string literal. Only the plain `"..."` form can hold a quote: in the raw `#"..."` form a backslash escapes * nothing, so a `"` in a path ended the literal and broke the whole profile (issue #23). */ export const sbplString = (s: string) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; /** * The 16 code points HFS+ ignores in file names: U+200C-200F, U+202A-202E, U+206A-206F, U+FEFF (a probe found * case-insensitive APFS ignores none). `mkdir .git` on HFS+ makes what everything afterwards opens as * `.git` (#270). One source for the seatbelt profile's folded patterns; the file tools' `foldSegment` removes * every default-ignorable, a superset of these. */ export const HFS_IGNORABLE_POINTS = ["\u200C", "\u200D", "\u200E", "\u200F", "\u202A", "\u202B", "\u202C", "\u202D", "\u202E", "\u206A", "\u206B", "\u206C", "\u206D", "\u206E", "\u206F", "\uFEFF"]; /** * One HFS+-ignorable code point as a seatbelt regex atom. A group alternation, not a character class: the * seatbelt regex engine is byte-oriented, so a quantifier after a multi-byte class member binds to its last * byte and a class never matches the plain name (verified with the real sandbox-exec, #270). */ const HFS_IGNORABLE = `(${HFS_IGNORABLE_POINTS.join("|")})`; /** A regex source matching `name` with any number of HFS+-ignorable code points interleaved, at the ends included. */ const hfsFoldedName = (name: string) => `${HFS_IGNORABLE}*${[...name].map((c) => sbplEscape(c)).join(`${HFS_IGNORABLE}*`)}${HFS_IGNORABLE}*`; /** * `config.worktree`, the per-worktree config git reads beside `config` (#518), folded in BOTH halves as two NAME-only regex sources that a rule must both match. One SBPL regex * literal dies at 1024 bytes in UTF-8 and every folded character costs about 65 bytes, so the whole name (1071) cannot be one literal, and a byte class cannot hold the * multi-byte code points (the engine is byte-oriented, verified), so the fold stays an alternation. The first source pins the front (a folded `config`, a dot, then the rest of * the name), the second the end (a folded `worktree`). Together they match every spelling of `config.worktree` with ignorable code points anywhere in it, and also * `config.worktree` in the same directory, which is over-refused on purpose and names no file git uses. * The root a rule is scoped to is NEVER part of these literals: it goes in its own `require-all` filter, so a long project or git path cannot push a folded name over the limit * (#518 review: a 450-byte path made a 1083-byte literal when the root and the name shared one). */ const CONFIG_WORKTREE_NAME: readonly [string, string] = [`^.*/${hfsFoldedName("config")}\\.[^/]*$`, `^.*/[^/]*${hfsFoldedName("worktree")}$`]; /** * Seatbelt rules for the hub's and git's own names (#270). `.agenthub` is refused anywhere under the project root. * `.git` is refused at any depth, the name itself included, so a planted repository cannot arrive by creation, * rename, symlink or gitfile, and `config` and `hooks` directly under it are folded too; the cost is that * `git init`, `git clone` and `git worktree add` no longer run inside the sandbox. `commondir` is refused at any * depth below a `.git` and below each external git dir: that is where git keeps it for linked worktrees and * submodules. A submodule's git dir under `.git/modules/` gets the same `config`/`hooks` refusal at whatever depth * submodules nest (a nested one lives under `.git/modules//modules/`, #281), anchored at the discovered * modules root so a directory named `refs`, `config` or `hooks` ABOVE the project neither disables the rule nor * trips it; a `/refs/` or `/logs/` segment below the root keeps a branch or tag named `config` or `hooks` writable * (the round-3 regression of #277), at the price of leaving a submodule whose own path holds a `refs` or `logs` * segment unprotected. The basenames are folded; a folded INTERMEDIATE component on HFS+ (a spelling of `modules`) * is a known residual, the same one the external git dir rules carry. The directory entries above those files are * protected as the `.git` name is: the discovered git dirs, the modules root and every component in between are * refused as targets (rename, replace, symlink, recreate). An external git dir's `config`/`hooks` rules cover only * its own children (plus the hooks directory's contents): at any depth they would deny refs named `config` or * `hooks` in a worktree or submodule project (`git branch fix/config` fails on `.git/logs/refs/heads/fix/config`). * Every pattern keeps its `^` anchor (an unanchored starred alternation does not match in this engine) and no * folded literal contains the root: an SBPL string literal dies at 1024 bytes ("Error reading string"), which a * long project path would trip. ponytail: the modules rules do contain the (plain) modules root; a project path * over roughly 600 bytes with submodules would exceed the limit — fold the root's segments if one ever shows up. */ /** * `hooks` as the entry directly under `parent`, and everything below it, anchored by DEPTH instead of by the unanchored any-prefix name: that one also matches an ancestor of the * project that happens to be named `hooks`, and paired with a plain root prefix it refused every write below the root (#520). Seatbelt ignores a `{n}` repeat, so the depth is * written out as that many `/[^/]+` terms (verified with the real sandbox-exec), which keeps the literal independent of the path's characters and costs 6 bytes a component. * A path with more than MAX_ANCHOR_DEPTH components would push the folded name past the 1024-byte limit, which stops every sandboxed command, so it falls back to the * unanchored name: that over-refuses only when an ancestor is named `hooks`, never under-protects. Pair it with a plain `^/` filter. */ const MAX_ANCHOR_DEPTH = 80; const hooksUnder = (parent: string): string => { const depth = parent.split("/").filter(Boolean).length; return depth > MAX_ANCHOR_DEPTH ? `^.*/${hfsFoldedName("hooks")}(/|$)` : `^${"/[^/]+".repeat(depth)}/${hfsFoldedName("hooks")}(/|$)`; }; /** * #1123: a sandboxed command may not move what a branch, HEAD or a linked worktree points at. `refs/**` (branches, tags, `refs/stash`), `packed-refs*`, `HEAD*` (its lock too) and * `worktrees/**` (a linked worktree's admin dir: its HEAD, index, logs) are refused directly under every plain `.git` and under each external git dir (the common dir and a linked * worktree's own, whatever they are named). The hub's own git runs outside the sandbox and is unaffected, so #1115's hub commit still lands. * * Every name must sit DIRECTLY under its git dir. An unanchored `refs` or `worktrees` filter would also match an ANCESTOR of the project with that name, and a project under * `~/worktrees/` would lose every `.git` write (the #520 `hooks` lesson). So each rule is adjacent by construction: one literal for `.git` + a short name, or, for the long names * (`worktrees`, `packed-refs`, where `.git` + name would pass the 1024-byte literal limit), a front half and a back half that must both match, or a depth anchor for an external dir. * A submodule's git dir (`.git/modules/`, nested ones, and `.git/worktrees//modules/` for a linked worktree) is covered the same way (`subDirs`, the discovered * ones: a git dir that is not discovered is refused whole by the #518/#520 rules), per the person's "deny .git writes" decision: nothing is listed as a residual. */ const refDepth = (d: string): number => d.split("/").filter(Boolean).length; /** * `^(/[^/]+){depth}/(/|$)`: `name` as the entry directly under `d`, the depth written out because seatbelt ignores `{n}`. The folded names cost (measured, bytes of regex): `refs` 334, * `worktrees` 669, so past the depth where the path plus the name would near 1024 it falls back to the unanchored name, which over-refuses only under an ancestor with that name and * never under-protects. */ const refUnder = (d: string, name: string): string => { const depth = refDepth(d), cost = Buffer.byteLength(hfsFoldedName(name)) + depth * 6 + 8; return cost > 1000 ? `^.*/${hfsFoldedName(name)}(/|$)` : `^${"/[^/]+".repeat(depth)}/${hfsFoldedName(name)}(/|$)`; }; function gitRefRules(gitDirs: string[], subDirs: string[] = []): string[] { const git = hfsFoldedName(".git"); const re = (s: string) => `(regex ${sbplString(s)})`; const name = (n: string) => hfsFoldedName(n); // A linked worktree's own submodule git dirs (`worktrees//modules/**`) are governed by the #518/#520 rules, not these. const plainSub = `(require-not ${re(`^.*/${git}/worktrees/[^/]+/modules(/|$)`)})`; const plain = [ // `.git` (335 bytes) + `HEAD` or `refs` (334) fit one literal: adjacent by construction. `HEAD.lock` goes with `HEAD`. re(`^.*/${git}/${name("HEAD")}(\\.lock)?$`), re(`^.*/${git}/${name("refs")}(/|$)`), // `.git` + `packed-refs` (803) and `.git` + `worktrees` (669) do not fit one literal. The front literal pins the start of the name right under a `.git`, and for `worktrees` the // back literal pins its end; `packed` alone covers `packed-refs` and its lock/new files, which is the intent. re(`^.*/${git}/${name("packed")}`), `(require-all ${re(`^.*/${git}/${name("work")}`)} ${re(`^.*${name("trees")}(/|$)`)} ${plainSub})`, ]; const external = [...gitDirs, ...subDirs].flatMap((d) => { const own = sbplString(d), direct = re(`^${sbplEscape(d)}/[^/]+$`); return [ `(require-all ${direct} ${re(`^.*/${name("HEAD")}(\\.lock)?$`)})`, `(require-all ${direct} ${re(`^.*/${name("packed")}`)})`, `(require-all (subpath ${own}) ${re(refUnder(d, "refs"))})`, `(require-all (subpath ${own}) ${re(refUnder(d, "worktrees"))} (require-not ${re(`^${sbplEscape(d)}/worktrees/[^/]+/modules(/|$)`)}))`, ]; }); return [...plain, ...external]; } export function hubWriteRegexes(root: string, gitDirs: string[] = [], moduleGit: readonly { root: string; entries: string[]; dirs?: string[] }[] = [], worktreesRoot?: string): string[] { const git = hfsFoldedName(".git"); const re = (s: string) => `(regex ${sbplString(s)})`; const external = gitDirs.flatMap((d) => [ `(require-all ${re(`^${sbplEscape(d)}/[^/]+$`)} ${re(`^.*/(${hfsFoldedName("config")}|${hfsFoldedName("hooks")})$`)})`, `(require-all ${re(`^${sbplEscape(d)}/[^/]+$`)} ${CONFIG_WORKTREE_NAME.map(re).join(" ")})`, `(subpath ${sbplString(`${d}/hooks`)})`, `(require-all (subpath ${sbplString(d)}) ${re(`^.*/${hfsFoldedName("commondir")}$`)})`, ]); // Every modules tree (#518, #520): the common dir's, a linked worktree's own, each sibling's, and the `modules/` of every discovered submodule git dir. Nothing is exempt by name: // a `refs` or `logs` component does not make a path safe, because a later unsandboxed `git submodule update --init` reuses any git dir found at `/` and runs its // config and hooks. So under a modules root, everything that is not inside a DISCOVERED git dir is refused (that is a plant, a new or a renamed git dir), and inside each discovered // git dir `D` the protected files are anchored to `D` itself: `D/config`, `D/config.worktree`, `D/hooks` and what is below it, and `D/worktrees/*/config.worktree`. // Ordinary git work writes `D/refs`, `D/logs`, `D/objects`, `D/index`, `D/HEAD`, ... and none of those is refused, so no refs/logs exception is needed. // Each literal holds either a path or a folded name, never both (the 1024-byte limit, #518 review); the folded names sit in `^.*/$` filters beside a plain anchor. const allDirs = moduleGit.flatMap((tree) => tree.dirs ?? []); const modules = moduleGit.flatMap((tree) => { const root = sbplEscape(tree.root); const found = tree.dirs ?? []; // absent means nothing is exempt: everything under the root is refused, which fails closed const inside = found.map((d) => `(require-not ${re(`^${sbplEscape(d)}(/|$)`)})`).join(" "); const anchored = found.flatMap((d) => { const dir = sbplEscape(d); return [ `(require-all ${re(`^${dir}/[^/]+$`)} ${re(`^.*/${hfsFoldedName("config")}$`)})`, `(require-all ${re(`^${dir}/[^/]+$`)} ${CONFIG_WORKTREE_NAME.map(re).join(" ")})`, `(require-all ${re(`^${dir}/`)} ${re(hooksUnder(d))})`, // A linked worktree of a submodule keeps its own config.worktree one level down. `(require-all ${re(`^${dir}/worktrees/[^/]+/[^/]+$`)} ${CONFIG_WORKTREE_NAME.map(re).join(" ")})`, // The directories on the way to those files are directory-entry targets, so none can be moved out of the protected path, edited and put back (#520 review): `worktrees` // and each `worktrees/` (no rename, replace, symlink or removal), and the `hooks` directory itself. The root and the folded name are separate filters. `(require-all ${re(`^${dir}/[^/]+$`)} ${re(`^.*/${hfsFoldedName("worktrees")}$`)})`, re(`^${dir}/worktrees/[^/]+$`), `(require-all ${re(`^${dir}/[^/]+$`)} ${re(`^.*/${hfsFoldedName("hooks")}$`)})`, // A submodule's own linked worktrees keep their `modules/` at `D/worktrees//modules` (#520 review), inside the exemption above. Everything under one that is not inside a // DISCOVERED git dir is refused, whether the worktree exists yet or not (the pattern needs no discovery), and the `modules` entry itself cannot be renamed or replaced. `(require-all ${re(`^${dir}/worktrees/[^/]+/modules/.`)} ${allDirs.filter((f) => f.startsWith(`${d}/worktrees/`)).map((f) => `(require-not ${re(`^${sbplEscape(f)}(/|$)`)})`).join(" ")})`, `(require-all ${re(`^${dir}/worktrees/[^/]+/[^/]+$`)} ${re(`^.*/${hfsFoldedName("modules")}$`)})`, ]; }); return [ // Everything under the root that is not inside a discovered git dir. The root's own entry is a directory entry rule below, so this is the contents. `(require-all ${re(`^${root}/.`)} ${inside})`, ...anchored, // A submodule git dir as a directory entry: no rename, replace, symlink or recreate. The basename is folded (HFS+ opens the folded spelling as the real entry); // the directory and the folded name are separate filters (a ~520-byte git path went over the limit when they shared one, #518 review). ...tree.entries.map((d) => `(require-all ${re(`^${sbplEscape(dirname(d))}/[^/]+$`)} ${re(`^.*/${hfsFoldedName(basename(d))}$`)})`), ]; }); // Every linked worktree's git dir under `/worktrees/` by pattern, not by discovery (#518): a sibling's `modules/` tree that does not exist yet, or a sibling created // after this profile was built, is as protected as one that does. The sandbox can write the common dir, so it could otherwise pre-create them. The worktree name is one // plain component (a folded spelling of `worktrees` or of a sibling's name on HFS+ is the same residual as the folded `modules` component above). const siblings = worktreesRoot ? (() => { const w = sbplEscape(worktreesRoot); return [ // The ancestors of every protected git dir, as directory entries: no rename, replace, symlink or recreate. Without them the container or a worktree git dir could be moved // out of the protected path, its submodule config or hooks edited, and moved back (#518 review). Git itself never renames or removes these during ordinary work. // The container's folded name and the directory it sits in are separate filters (one literal holding both grows with the path); a worktree git dir has any name. `(require-all ${re(`^${sbplEscape(dirname(worktreesRoot))}/[^/]+$`)} ${re(`^.*/${hfsFoldedName(basename(worktreesRoot))}$`)})`, re(`^${w}/[^/]+$`), // A worktree git dir's own `config` and `config.worktree`: direct children only. `(require-all ${re(`^${w}/[^/]+/[^/]+$`)} ${re(`^.*/${hfsFoldedName("config")}$`)})`, `(require-all ${re(`^${w}/[^/]+/[^/]+$`)} ${CONFIG_WORKTREE_NAME.map(re).join(" ")})`, // A worktree git dir's own `hooks` directory and everything in it, which git runs for that worktree, anchored by depth so an ancestor named `hooks` is not matched (#520). // Its `modules/` is a different component, so this never reaches a submodule's own tree. `(require-all ${re(`^${w}/[^/]+/`)} ${re(hooksUnder(`${worktreesRoot}/x`))})`, // Every write under any worktree's `modules/` that is not inside a DISCOVERED submodule git dir (#520): a plant, or a tree that does not exist yet. The discovered git dirs // (the sandboxed worktree's own, and any sibling's that exists) are exempt here and get their anchored rules from their own tree above. No name is exempt. `(require-all ${re(`^${w}/[^/]+/modules/.`)} ${moduleGit.flatMap((tree) => tree.dirs ?? []).filter((d) => d.startsWith(`${worktreesRoot}/`)).map((d) => `(require-not ${re(`^${sbplEscape(d)}(/|$)`)})`).join(" ")})`, `(require-all ${re(`^${w}/[^/]+/[^/]+$`)} ${re(`^.*/${hfsFoldedName("modules")}$`)})`, ]; })() : []; return [ `(require-all (subpath ${sbplString(root)}) ${re(`^.*/${hfsFoldedName(".agenthub")}(/|$)`)})`, re(`^.*/${git}$`), re(`^.*/${git}/${hfsFoldedName("config")}$`), `(require-all ${re(`^.*/${git}/[^/]+$`)} ${CONFIG_WORKTREE_NAME.map(re).join(" ")})`, re(`^.*/${git}/${hfsFoldedName("hooks")}(/|$)`), `(require-all ${re(`^.*/${git}/.*$`)} ${re(`^.*/${hfsFoldedName("commondir")}$`)})`, ...gitRefRules(gitDirs, allDirs), ...modules, ...siblings, ...external, ]; } /** * Full SBPL rule lines for the shared object store `/objects` (#864). Every checkout of the repository, and the hub's own host add/commit/push (#845), trusts what is * there without rehashing it, so a sandboxed command may only ADD loose objects: `git add` and `git commit` keep working, and git skips writing an object that exists. Refused: * every write under `objects/info` (alternates, http-alternates, commit-graph) and `objects/pack` (a new pack wins over a loose copy of the same id, since git reads packs * first); the `objects`, `objects/info` and `objects/pack` entries themselves (no rename, replace or removal); removing or renaming a fan-out directory; and changing, * removing, chmod-ing or renaming over an existing loose object. The cost: `git gc`, `git repack`, `git fetch`, `git maintenance` and `git commit-graph write` do not run in * the sandbox. A hardlink to an existing loose object is refused under these rules (verified, into the project and into the command's own temp dir). Residual: an object id * that does not exist yet can be planted before git writes it (the attacker must predict its exact content); a local checkout shows it, a push of it is rejected by the * receiving side's rehash. Seatbelt ignores `{n}` * repeats, so the two fan-out hex digits are written out (verified with the real sandbox-exec). */ export function objectStoreRules(common: string): string[] { const objects = `${common}/objects`, o = sbplEscape(objects); const re = (s: string) => `(regex ${sbplString(s)})`; return [ `(deny file-write* (subpath ${sbplString(`${objects}/info`)}) (subpath ${sbplString(`${objects}/pack`)}) ${[objects, `${objects}/info`, `${objects}/pack`].map((p) => `(literal ${sbplString(p)})`).join(" ")})`, `(deny file-write-unlink ${re(`^${o}/[0-9a-f][0-9a-f]$`)})`, `(deny file-write-data file-write-unlink file-write-mode file-write-flags ${re(`^${o}/[0-9a-f][0-9a-f]/[0-9a-f]+$`)})`, ]; } /** * Seatbelt regex filters equivalent to isDenied. Seatbelt sees absolute paths, so the `local.deny` substrings are * anchored under the project root: a bare "private/" would otherwise match /private/var/... and deny the whole temp tree. */ export function denyRegexes(root: string, extra: string[] = [], withNames = true): string[] { const names = DENY_NAMES.map((re) => { const body = re.startsWith("^") ? re.slice(1) : `[^/]*${re}`; return `/${body}${body.endsWith("$") ? "" : "[^/]*$"}`; }); return [ ...DENY_SEGMENTS.map((s) => `/${sbplEscape(s)}(/|$)`), ...(withNames ? names : []), ...extra.filter(Boolean).map((e) => `^${sbplEscape(root)}/.*${sbplEscape(e)}`), ].map((re) => `(regex ${sbplString(re)})`); }