Skip to content
Myr

Merge build/104-vcs-policy-hooks: agent harnesses refuse hook bypasses, pushes, deletes, cf project commands and closed env reads

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 8165e49, a3e552a · Browse files · 9 files+2045 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+2045 added−0 removed

  • tests:+435 added−0 removed
  • other:+1610 added−0 removed

9 files+2045 added−0 removed

added:.claude/settings.json+15 added
added:.cursor/hooks.json+11 added
added:.pi/extensions/vcs-policy/index.ts+64 added
added:.pi/extensions/vcs-policy/README.md+2 added
added:packages/config/test/vcs-policy.test.ts+435 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Effect, Path, Schema, Stream } from "effect";4import { ChildProcess, ChildProcessSpawner } from "effect/process";56import {7 Decision,8 decide,9 reasons,10} from "../../../scripts/hooks/lib/policy.ts";11import type { Rule } from "../../../scripts/hooks/lib/policy.ts";1213/** What a row expects: the command runs, or the rule that refuses it. */14type Verdict = "Allow" | Rule;1516const verdictOf = (command: string): Verdict => {17 const decision = decide(command);1819 return Decision.$is("Deny")(decision) ? decision.rule : "Allow";20};2122/**23 * One refused command: `program` is argv[0], so each row is also tried through24 * a path and through `env`. `lead` is a `VAR=value` word that comes first.25 * Shell builtins (`source`, `.`) have no path and no `env` form.26 */27interface Refused {28 readonly program: string;29 readonly args: string;30 readonly rule: Rule;31 readonly lead?: string;32 readonly builtin?: true;33}3435const refused = (36 rule: Rule,37 program: string,38 args: string,39 lead?: string40): Refused =>41 lead === undefined ? { args, program, rule } : { args, lead, program, rule };4243/** Every variant the issue's Want names, each refused. */44const WANT: readonly Refused[] = [45 // Hook bypass: --no-verify and the unique prefixes git accepts for it.46 refused("hook-bypass", "git", "commit --no-verify -m x"),47 refused("hook-bypass", "git", "commit --no-verif -m x"),48 refused("hook-bypass", "git", "commit --no-veri -m x"),49 refused("hook-bypass", "git", "commit --no-ver -m x"),50 // `commit -n` and short-flag bundles that carry it.51 refused("hook-bypass", "git", "commit -n -m x"),52 refused("hook-bypass", "git", "commit -nm x"),53 refused("hook-bypass", "git", "commit -anm x"),54 refused("hook-bypass", "git", "-c core.hooksPath=/dev/null commit -m x"),55 refused("hook-bypass", "git", "commit -m x", "LEFTHOOK=0"),56 refused("hook-bypass", "lefthook", "uninstall"),57 // Pushes.58 refused("push", "git", "push"),59 refused("push", "git", "push origin main"),60 // Deletes: wrangler's always; cf's without --dry-run.61 refused("delete", "wrangler", "delete"),62 refused("delete", "wrangler", "delete my-worker"),63 refused(64 "delete",65 "cf",66 "artifacts namespaces repos delete x --namespace y --force"67 ),68 refused("delete", "cf", "accounts tokens revoke x"),69 refused(70 "delete",71 "bun",72 "run ops -- artifacts namespaces repos delete x --force"73 ),74 refused("delete", "bunx", "wrangler delete"),75 // cf's project commands, bare and through bunx, npx and `bun run ops --`.76 ...[77 "dev",78 "build",79 "deploy",80 "init",81 "migrate",82 "previews",83 "workers versions create",84 "workers triggers deploy",85 ].flatMap((command) => [86 refused("cf-project-command", "cf", command),87 refused("cf-project-command", "bunx", `cf ${command}`),88 refused("cf-project-command", "npx", `cf ${command}`),89 refused("cf-project-command", "bun", `run ops -- ${command}`),90 ]),91 // Reads of the closed env files.92 ...["cat", "head", "tail", "less", "more"].flatMap((program) => [93 refused("closed-env-read", program, ".env"),94 refused("closed-env-read", program, ".env.local"),95 refused("closed-env-read", program, "apps/platform/.env.development.local"),96 ]),97 refused("closed-env-read", "sed", "-n 1p .env"),98 refused("closed-env-read", "awk", "'{ print }' .env.local"),99 refused("closed-env-read", "grep", "TOKEN .env"),100 refused("closed-env-read", "rg", "TOKEN .env.production.local"),101 { args: ".env", builtin: true, program: "source", rule: "closed-env-read" },102 { args: ".env.local", builtin: true, program: ".", rule: "closed-env-read" },103];104105/** A refused row as written, inside compounds, through a path and through `env`. */106const forms = (row: Refused): readonly string[] => {107 const lead = row.lead === undefined ? "" : `${row.lead} `;108 const plain = `${lead}${row.program} ${row.args}`;109110 const compounds = [111 plain,112 `cd x && ${plain}`,113 `true; ${plain}`,114 `(${plain})`,115 `FOO=1 ${plain}`,116 ];117118 return row.builtin === true119 ? compounds120 : [121 ...compounds,122 `${lead}/usr/bin/${row.program} ${row.args}`,123 `env ${plain}`,124 ];125};126127describe(decide, () => {128 it.each(129 WANT.flatMap((row) => forms(row).map((command) => [command, row.rule]))130 )("refuses %s (%s)", (command, rule) => {131 expect(verdictOf(command)).toBe(rule);132 });133134 // Rows past the Want. Where the right answer was unclear, the row denies, and135 // the comment says why.136 it.each<readonly [string, Verdict]>([137 // The value of -m is a message even when it looks like a flag; git takes it138 // whole, so the commit still runs its hooks.139 ['git commit -m "no-verify docs"', "Allow"],140 ['git commit -m "skip --no-verify in docs"', "Allow"],141 ["git commit -m --no-verify", "Allow"],142 ["git commit -mn", "Allow"],143 ["git commit --amend --no-edit", "Allow"],144 ["git commit -am x # --no-verify", "Allow"],145 ["git log -n 5", "Allow"],146 ['git log --grep="--no-verify"', "Allow"],147 ["git --no-pager log -n 5", "Allow"],148 ["git merge -n main", "Allow"],149 ["git stash push -m x", "Allow"],150 ["git config --get core.hooksPath", "Allow"],151 // Quoting and escapes don't hide a flag from the shell, so not from us.152 ['git commit "--no-verify" -m x', "hook-bypass"],153 ['git commit --no-""verify -m x', "hook-bypass"],154 ["git commit --no-\\verify -m x", "hook-bypass"],155 ["git commit $'\\x2d\\x2dno-verify' -m x", "hook-bypass"],156 ["git --no-pager -C repo commit -n -m x", "hook-bypass"],157 ["git -c CORE.HOOKSPATH= commit -m x", "hook-bypass"],158 ["git --config-env=core.hooksPath=HOOKS commit -m x", "hook-bypass"],159 ["git config core.hooksPath /dev/null", "hook-bypass"],160 // An alias can wrap --no-verify or a push, and nothing here can see it.161 ["git -c alias.ci='commit --no-verify' ci -m x", "hook-bypass"],162 ['git config alias.ci "commit --no-verify"', "hook-bypass"],163 ["git merge --no-verify main", "hook-bypass"],164 ["git am -n patch.mbox", "hook-bypass"],165 ["export LEFTHOOK=0", "hook-bypass"],166 ["HUSKY=0 git commit -m x", "hook-bypass"],167 [168 "GIT_CONFIG_PARAMETERS=\"'core.hooksPath'='/dev/null'\" git commit -m x",169 "hook-bypass",170 ],171 ["bunx lefthook uninstall", "hook-bypass"],172 // Help never pushes: git turns `<cmd> --help` into `git help <cmd>`.173 ["git push --help", "Allow"],174 ["git help push", "Allow"],175 // A dry run still talks to a remote, and pushing is the user's step.176 ["git push --dry-run", "push"],177 ["git -C repo push", "push"],178 ["jj git push", "push"],179 // What a shell runs inside a substitution, `-c`, `eval` or a heredoc runs.180 ['echo "$(git push)"', "push"],181 ["echo `git push`", "push"],182 ['bash -c "git push"', "push"],183 ["sh -lc 'git commit -n -m x'", "hook-bypass"],184 ['eval "git push"', "push"],185 ["bash <<'EOF'\ngit push\nEOF", "push"],186 ["xargs git push < refs.txt", "push"],187 ["sudo -u root git push", "push"],188 ["timeout 5 git push", "push"],189 // Text that only mentions a command is not the command.190 ['echo "git push"', "Allow"],191 ["cat <<'EOF'\ngit push\nEOF", "Allow"],192 [193 "git commit -F - <<'EOF'\nSubject\n\n- Don't --no-verify, and don't git push\nEOF",194 "Allow",195 ],196 [197 "git commit -m \"$(cat <<'EOF'\nSubject\n\n- Don't git push\nEOF\n)\"",198 "Allow",199 ],200 // wrangler deploy stays allowed: infra/deploy.ts runs it, and the stage201 // rule lives there. wrangler delete is refused even as a dry run.202 ["wrangler deploy", "Allow"],203 ["wrangler deploy --dry-run", "Allow"],204 ["wrangler deploy --name remove-old", "Allow"],205 ["wrangler delete --dry-run", "delete"],206 ["wrangler queues purge jobs", "delete"],207 ["npx wrangler@4.147.0 delete x", "delete"],208 ["./node_modules/.bin/wrangler d1 delete db", "delete"],209 ["bun run ops -- artifacts namespaces repos delete x --dry-run", "Allow"],210 ["bun run ops -- workers list", "Allow"],211 ["bun run ops -- zones purge-cache x", "delete"],212 ["bun run ops -- workers delete x --dry-run=false", "delete"],213 // cf parses with yargs, which reads `false` after a boolean flag as its214 // value, and the last of `--dry-run` and `--no-dry-run` wins.215 ["bun run ops -- workers delete x --dry-run false", "delete"],216 ["bun run ops -- workers delete x --dry-run --no-dry-run", "delete"],217 ["bun run ops -- workers delete x --no-dry-run --dry-run", "Allow"],218 // AGENTS.md's discovery steps only read: `cli search`, `schema <command>`219 // and `<command> --help` (the help cf itself points to) delete nothing.220 ['bun run ops -- cli search "delete"', "Allow"],221 ["bun run ops -- schema artifacts namespaces repos delete", "Allow"],222 ["bun run ops -- artifacts namespaces repos delete --help", "Allow"],223 // cf's package installs its bin under a second name, `cloudflare`.224 ["./node_modules/.bin/cloudflare deploy", "cf-project-command"],225 ["bunx cloudflare workers delete x", "delete"],226 // cf's project commands are refused even as dry runs, and through varlock.227 ["cf deploy --dry-run", "cf-project-command"],228 ["cf --profile dev deploy", "cf-project-command"],229 // An option cf doesn't declare may take the next word as its value, so230 // any word it could have taken may be the command.231 ["cf --account-id x --env y deploy", "cf-project-command"],232 ["cf --account-id x workers list --name deploy", "Allow"],233 ["bunx varlock run --path infra/ -- cf deploy", "cf-project-command"],234 ["bun run verify", "Allow"],235 ["bun infra/deploy.ts --stage demo", "Allow"],236 // The closed env files, by any path, glob or redirect. Their schemas and237 // examples stay open, and so does searching other files for the name.238 ["cat .env.schema", "Allow"],239 ["cat apps/platform/.env.schema", "Allow"],240 ["cat .env.example", "Allow"],241 ["ls -la .env*", "Allow"],242 ["grep -n .env .gitignore", "Allow"],243 ["rg -n '\\.env' docs", "Allow"],244 ["cat < .env", "closed-env-read"],245 ["while read -r line; do echo $line; done < .env.local", "closed-env-read"],246 ["cat ./.env", "closed-env-read"],247 ['cat "$HOME/project/.env"', "closed-env-read"],248 ["cat .env*", "closed-env-read"],249 ["cat .env{,.local}", "closed-env-read"],250 ["grep -e TOKEN .env", "closed-env-read"],251 ["grep -A 2 TOKEN .env", "closed-env-read"],252 ["grep -f .env other.txt", "closed-env-read"],253 ["cp .env /tmp/x", "closed-env-read"],254 ["set -a; . ./.env; set +a", "closed-env-read"],255 // A recursive grep reads every file under its paths, the closed ones too,256 // unless --include or --exclude keeps them out. A pattern is not a file.257 ["grep -rn TOKEN .", "closed-env-read"],258 ["grep -R TOKEN apps/platform", "closed-env-read"],259 ["grep --recursive TOKEN", "closed-env-read"],260 ["grep -d recurse TOKEN .", "closed-env-read"],261 ["grep -rn TOKEN . --include='*'", "closed-env-read"],262 ["grep -rn TOKEN . --exclude='*.local'", "closed-env-read"],263 ["grep -rn TOKEN . --include='*.ts'", "Allow"],264 ["grep -rn TOKEN . --exclude='.env*'", "Allow"],265 ["grep -rn TOKEN . --exclude=.env --exclude='*.local'", "Allow"],266 ["grep -rn TOKEN . --exclude={.env,.env.local,.env.*.local}", "Allow"],267 ["grep -n -e .env .gitignore", "Allow"],268 // rg skips hidden and git-ignored files; the closed files are both, so it269 // reaches them only when told to search both.270 ["rg TOKEN", "Allow"],271 ["rg --hidden TOKEN", "Allow"],272 ["rg -uu TOKEN", "closed-env-read"],273 ["rg --hidden --no-ignore-vcs TOKEN", "closed-env-read"],274 ["rg -. -u TOKEN", "closed-env-read"],275 ["bun run env:check", "Allow"],276 ])("%s → %s", (command, verdict) => {277 expect(verdictOf(command)).toBe(verdict);278 });279280 it("gives each refusal one sentence from AGENTS.md, saying what to do instead", () => {281 expect(decide("git commit -n -m x")).toStrictEqual(282 Decision.Deny({283 reason:284 "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11).",285 rule: "hook-bypass",286 })287 );288 expect(reasons).toStrictEqual({289 "cf-project-command":290 "cf's project commands are not our deploy tool; use infra/deploy.ts.",291 "closed-env-read":292 "Never read .env, .env.local or .env.*.local, even in a recursive search (rg and git grep skip them); run bun run env:check.",293 delete: "Deleting Cloudflare resources needs the user's OK.",294 "hook-bypass":295 "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11).",296 push: "Pushing is the user's step; commit on the branch and stop.",297 });298 expect(decide("git status")).toStrictEqual(Decision.Allow());299 });300});301302// Vitest runs in the package's folder, two below the repo root.303const repoRoot = Effect.map(Path.Path, (path) => path.resolve("..", ".."));304305interface Ran {306 readonly exitCode: number;307 readonly stdout: string;308 readonly stderr: string;309}310311const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>312 bytes.pipe(Stream.decodeText(), Stream.mkString);313314/** Runs the hook as a harness does: `input` on stdin, then stdin closes. */315const hook = (input: string) =>316 Effect.scoped(317 Effect.gen(function* () {318 const path = yield* Path.Path;319 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;320 const root = yield* repoRoot;321322 const child = yield* spawner.spawn(323 ChildProcess.make(324 "bun",325 [path.join(root, "scripts/hooks/vcs-policy.ts")],326 {327 cwd: root,328 stdin: Stream.make(new TextEncoder().encode(input)),329 }330 )331 );332333 const [stdout, stderr, exitCode] = yield* Effect.all(334 [text(child.stdout), text(child.stderr), child.exitCode],335 { concurrency: "unbounded" }336 );337338 return { exitCode, stderr, stdout } satisfies Ran;339 })340 ).pipe(Effect.provide(NodeServices.layer));341342const CursorReply = Schema.fromJsonString(343 Schema.Struct({344 agent_message: Schema.optionalKey(Schema.String),345 permission: Schema.Literals(["allow", "deny"]),346 user_message: Schema.optionalKey(Schema.String),347 })348);349350const claude = (command: string) =>351 JSON.stringify({352 hook_event_name: "PreToolUse",353 session_id: "s",354 tool_input: { command, description: "d" },355 tool_name: "Bash",356 });357358const cursor = (command: string) =>359 JSON.stringify({360 command,361 conversation_id: "c",362 cwd: "/repo",363 hook_event_name: "beforeShellExecution",364 });365366const PUSH = "Pushing is the user's step; commit on the branch and stop.";367368describe("the hook adapter", () => {369 it.live("denies for Claude Code by exit 2, with the reason on stderr", () =>370 Effect.gen(function* () {371 const ran = yield* hook(claude("git commit -n -m x"));372373 expect(ran.exitCode).toBe(2);374 expect(ran.stdout).toBe("");375 expect(ran.stderr).toContain(376 "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11)."377 );378 })379 );380381 it.live("allows for Claude Code by exit 0, saying nothing", () =>382 Effect.gen(function* () {383 expect(yield* hook(claude("git status"))).toStrictEqual({384 exitCode: 0,385 stderr: "",386 stdout: "",387 });388 })389 );390391 it.live("denies for Cursor with its JSON reply, and exits 0", () =>392 Effect.gen(function* () {393 const ran = yield* hook(cursor("git push"));394 const reply = yield* Schema.decodeEffect(CursorReply)(ran.stdout);395396 expect(ran.exitCode).toBe(0);397 expect(reply.permission).toBe("deny");398 expect(reply.user_message).toContain(PUSH);399 expect(reply.agent_message).toContain(PUSH);400 })401 );402403 it.live("allows for Cursor with its JSON reply", () =>404 Effect.gen(function* () {405 const ran = yield* hook(cursor("git status"));406407 expect(ran.exitCode).toBe(0);408 expect(yield* Schema.decodeEffect(CursorReply)(ran.stdout)).toStrictEqual(409 { permission: "allow" }410 );411 })412 );413414 it.live("judges a bare {command}, denying by exit 2", () =>415 Effect.gen(function* () {416 const denied = yield* hook(JSON.stringify({ command: "git push" }));417 const allowed = yield* hook(JSON.stringify({ command: "git status" }));418419 expect(denied.exitCode).toBe(2);420 expect(denied.stderr).toContain(PUSH);421 expect(allowed.exitCode).toBe(0);422 })423 );424425 it.live("denies input it cannot read, failing closed", () =>426 Effect.gen(function* () {427 for (const input of ["not json", "{}", '{"command":7}', ""]) {428 const ran = yield* hook(input);429430 expect(ran.exitCode).toBe(2);431 expect(ran.stderr).toContain("could not read");432 }433 })434 );435});
added:scripts/hooks/lib/argv.ts+134 added
1/**2 * Reads one command's argv: which words are options, the values they take,3 * and which are operands. A program's `Grammar` names its options that take a4 * value; any option it doesn't name is taken to stand alone, which can only5 * turn a value into an option the policy judges, never hide one.6 */78/** A table of names, written as one space-separated line. */9export const names = (line: string): ReadonlySet<string> =>10 new Set(line.split(" ").filter((name) => name.length > 0));1112/** Which options take a value, for one program. */13export interface Grammar {14 /** Options whose value is the next word unless attached: `-m`, `--message`. */15 readonly values: ReadonlySet<string>;16 /** Short options whose value, if any, is attached: `-S[keyid]`. */17 readonly attached: ReadonlySet<string>;18}1920export interface Parsed {21 /** Each option by name: `-n`, `--no-verify`; a bundle `-anm` gives three. */22 readonly options: readonly string[];23 /** Each option that took a value, with that value. */24 readonly values: readonly (readonly [option: string, value: string])[];25 readonly operands: readonly string[];26}2728export const grammar = (values: string, attached = ""): Grammar => ({29 attached: names(attached),30 values: names(values),31});3233export const NO_OPTIONS = grammar("");3435/** What one word of bundled short options holds. */36interface Bundle {37 readonly options: readonly string[];38 /** The value the last option took, attached or from the next word. */39 readonly value?: string;40 /** Whether that value was the next word. */41 readonly takesNext: boolean;42}4344/** A bundle of short options, `-anm x`, `-mx`, `-Skey`: each letter, and a value if one takes it. */45const bundle = (46 arg: string,47 next: string | undefined,48 rules: Grammar49): Bundle => {50 const options: string[] = [];5152 for (let offset = 1; offset < arg.length; offset += 1) {53 const option = `-${arg[offset] ?? ""}`;54 const rest = arg.slice(offset + 1);5556 options.push(option);5758 if (rules.values.has(option) && rest.length === 0) {59 return next === undefined60 ? { options, takesNext: false }61 : { options, takesNext: true, value: next };62 }6364 if (rules.values.has(option) || rules.attached.has(option)) {65 return { options, takesNext: false, value: rest };66 }67 }6869 return { options, takesNext: false };70};7172/**73 * Splits `args` into options, the values they take, and operands. With74 * `permute`, options may follow operands, as git and GNU tools allow; without75 * it, the first operand and everything after it are operands, as a wrapper76 * hands them to the command it runs.77 */78export const parse = (79 args: readonly string[],80 rules: Grammar,81 permute: boolean82): Parsed => {83 const options: string[] = [];84 const values: (readonly [string, string])[] = [];85 const operands: string[] = [];86 let index = 0;8788 while (index < args.length) {89 const arg = args[index] ?? "";90 const next = args[index + 1];9192 index += 1;9394 if (arg === "--") {95 operands.push(...args.slice(index));96 break;97 }9899 if (!arg.startsWith("-") || arg === "-") {100 operands.push(...(permute ? [arg] : args.slice(index - 1)));101102 if (!permute) {103 break;104 }105 } else if (arg.startsWith("--")) {106 const equals = arg.indexOf("=");107 const name = equals === -1 ? arg : arg.slice(0, equals);108109 const takesNext =110 equals === -1 && rules.values.has(name) && next !== undefined;111112 options.push(name);113114 if (equals !== -1) {115 values.push([name, arg.slice(equals + 1)]);116 } else if (takesNext) {117 values.push([name, next]);118 index += 1;119 }120 } else {121 const short = bundle(arg, next, rules);122123 options.push(...short.options);124125 if (short.value !== undefined) {126 values.push([short.options.at(-1) ?? "", short.value]);127 }128129 index += short.takesNext ? 1 : 0;130 }131 }132133 return { operands, options, values };134};
added:scripts/hooks/lib/policy.ts+795 added
1// Ported from joelhooks/rat-stack@fba26d8 `scripts/vcs-command-policy.js`2// (MIT, LICENSES/rat-stack.MIT.txt). Changes are listed in PROVENANCE.md.3/**4 * The hook policy. Each agent harness asks it about a shell command before the5 * command runs (`scripts/hooks/vcs-policy.ts` for Claude Code and Cursor,6 * `.pi/extensions/vcs-policy` for pi). It allows or denies; it never rewrites.7 *8 * It reads the command as a shell would (`./shell.ts`): simple commands,9 * quotes and escapes, and what runs inside `$(…)`, backticks, `sh -c`, `eval`10 * and a heredoc fed to a shell. Each simple command then loses its leading11 * `VAR=value` words, wrappers (`env`, `command`, `exec`, `sudo`, …), package12 * runners (`bunx`, `npx`, `bun run ops --`, …) and any path on argv[0], and is13 * judged by its argv (`./argv.ts`), so flag text inside a quoted `-m` message14 * is a message. Where a command's meaning is unclear, the policy denies.15 *16 * Pure, with no Effect runtime: Bun, Node and pi's loader all import it.17 */18import { Data, Option } from "effect";1920import { grammar, names, NO_OPTIONS, parse } from "./argv.ts";21import type { Grammar, Parsed } from "./argv.ts";22import { simpleCommands, wordsOf } from "./shell.ts";2324/** The rules, each from AGENTS.md. */25export type Rule =26 | "hook-bypass"27 | "push"28 | "delete"29 | "cf-project-command"30 | "closed-env-read";3132export type Decision =33 | { readonly _tag: "Allow" }34 | { readonly _tag: "Deny"; readonly rule: Rule; readonly reason: string };3536export const Decision = Data.taggedEnum<Decision>();3738/** One sentence per rule: what AGENTS.md says, and what to do instead. */39export const reasons = {40 "cf-project-command":41 "cf's project commands are not our deploy tool; use infra/deploy.ts.",42 "closed-env-read":43 "Never read .env, .env.local or .env.*.local, even in a recursive search (rg and git grep skip them); run bun run env:check.",44 delete: "Deleting Cloudflare resources needs the user's OK.",45 "hook-bypass":46 "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11).",47 push: "Pushing is the user's step; commit on the branch and stop.",48} as const satisfies Readonly<Record<Rule, string>>;4950/** The rule a command breaks, or none. */51type Verdict = Option.Option<Rule>;5253const breaks = (rule: Rule, when: boolean): Verdict =>54 when ? Option.some(rule) : Option.none();5556const basename = (word: string) => word.slice(word.lastIndexOf("/") + 1);5758/** `wrangler@4.147.0` → `wrangler`; `@scope/pkg@1` → `@scope/pkg`. */59const withoutVersion = (name: string) => name.replace(/(?<=.)@[^/]*$/u, "");6061const contains = (62 words: readonly string[],63 sequence: readonly string[]64): boolean =>65 words.some((_, index) =>66 sequence.every((word, offset) => words[index + offset] === word)67 );6869// ---------------------------------------------------------------------------70// The rules.71// ---------------------------------------------------------------------------7273// hook-bypass -----------------------------------------------------------------7475/** Environment switches that turn a hook manager off. */76const HOOK_SWITCHES = names("HUSKY LEFTHOOK LEFTHOOK_EXCLUDE");7778const ASSIGNMENT = /^[A-Za-z_]\w*=/u;7980/** `LEFTHOOK=0`, `HUSKY=0`, or anything that sets `core.hooksPath`. */81const switchesOffHooks = (assignment: string) =>82 HOOK_SWITCHES.has(assignment.slice(0, assignment.indexOf("="))) ||83 /hookspath/iu.test(assignment);8485/**86 * A git config key that can skip hooks: `core.hooksPath`, or an alias, which87 * can wrap `--no-verify` or a push where nothing here can see it.88 */89const overridesHooks = (setting: string) => {90 const key = setting.split("=")[0]?.toLowerCase() ?? "";9192 return key === "core.hookspath" || key.startsWith("alias.");93};9495/** `--no-verify`, or a prefix git may accept for it (`--no-verif`, `--no-ver`). */96const isNoVerify = (option: string) =>97 option.length >= "--no-v".length && "--no-verify".startsWith(option);9899// Options before git's subcommand that take a value.100const GIT = grammar(101 "-C -c --attr-source --config-env --git-dir --list-cmds --namespace --super-prefix --work-tree"102);103104// Subcommands where `-n` means `--no-verify`, with the options that take a105// value, so `-m -n` is a message and `-nm x` is not.106const NO_VERIFY_SHORT: ReadonlyMap<string, Grammar> = new Map([107 [108 "am",109 grammar(110 "--directory --empty --exclude --include --patch-format --quoted-cr --resolvemsg --whitespace",111 "-C -S -p"112 ),113 ],114 [115 "commit",116 grammar(117 "-C -F -c -m -t --author --cleanup --date --file --fixup --message --pathspec-from-file --reedit-message --reuse-message --squash --template --trailer",118 "-S -u"119 ),120 ],121]);122123// `git config` forms that only read.124const CONFIG_READS = names(125 "--get --get-all --get-color --get-colorbool --get-regexp --get-urlmatch --list -l"126);127128const writesHookConfig = (parsed: Parsed) => {129 const reads =130 parsed.options.some((option) => CONFIG_READS.has(option)) ||131 ["get", "list"].includes(parsed.operands[0] ?? "");132133 return !reads && parsed.operands.some(overridesHooks);134};135136/** What git's subcommand, after the global options, breaks. */137const judgeGitSubcommand = (138 subcommand: string,139 rest: readonly string[]140): Verdict => {141 if (142 subcommand === "push" ||143 subcommand === "send-pack" ||144 (subcommand === "subtree" && rest.includes("push"))145 ) {146 return Option.some("push");147 }148149 const shortForm = NO_VERIFY_SHORT.get(subcommand);150 const parsed = parse(rest, shortForm ?? NO_OPTIONS, true);151152 return breaks(153 "hook-bypass",154 parsed.options.some(isNoVerify) ||155 (shortForm !== undefined && parsed.options.includes("-n")) ||156 (subcommand === "config" && writesHookConfig(parsed))157 );158};159160const judgeGit = (args: readonly string[]): Verdict => {161 const global = parse(args, GIT, false);162163 const settings = global.values.flatMap(([option, value]) =>164 option === "-c" || option === "--config-env" ? [value] : []165 );166167 const [subcommand, ...rest] = global.operands;168169 if (settings.some(overridesHooks)) {170 return Option.some("hook-bypass");171 }172173 // git runs `git <cmd> --help` as `git help <cmd>`.174 return subcommand === undefined || rest[0] === "--help"175 ? Option.none()176 : judgeGitSubcommand(subcommand, rest);177};178179const judgeLefthook = (args: readonly string[]): Verdict =>180 breaks(181 "hook-bypass",182 parse(args, NO_OPTIONS, true).operands.includes("uninstall")183 );184185// push ------------------------------------------------------------------------186187const judgeJj = (args: readonly string[]): Verdict =>188 breaks(189 "push",190 contains(parse(args, NO_OPTIONS, true).operands, ["git", "push"])191 );192193// delete ----------------------------------------------------------------------194195/**196 * wrangler's deleting subcommands are all `delete` or `purge`, and it deletes197 * without asking when it runs without a terminal. Only whole words count, so a198 * deploy whose name says `remove` still deploys.199 */200const WRANGLER_DELETES = names("delete purge");201202const judgeWrangler = (args: readonly string[]): Verdict =>203 breaks(204 "delete",205 parse(args, NO_OPTIONS, true).operands.some((word) =>206 WRANGLER_DELETES.has(word)207 )208 );209210/** A cf command word that deletes: `delete`, `bulk-delete`, `revoke`, `purge`… */211const DESTRUCTIVE = /(?:^|-)(?:delete|destroy|purge|remove|revoke)(?:-|$)/u;212213// cf-project-command ----------------------------------------------------------214215// cf's global options that take a value (`cf --help`, cf 1.0.0-beta.12).216const CF = grammar("-m -z --mode --persist-to --profile --zone");217218const CF_PROJECT = names("build deploy dev init migrate previews");219220const CF_PROJECT_SEQUENCES: readonly (readonly string[])[] = [221 ["workers", "triggers", "deploy"],222 ["workers", "versions", "create"],223];224225/** cf's commands that only read: AGENTS.md's `cli search` and `schema`. */226const CF_DISCOVERY = names("cli schema");227228/**229 * The words that may be cf's command. cf parses with yargs, which gives an230 * option it doesn't declare the next word as its value, so each such word may231 * be the command too: `cf --account-id x deploy`. The last word is the first232 * one no option can have taken.233 */234const cfCommandWords = (args: readonly string[]): readonly string[] => {235 const [word, next, ...rest] = args;236237 if (word === undefined) {238 return [];239 }240241 if (word === "--") {242 return next === undefined ? [] : [next];243 }244245 if (!word.startsWith("-") || word === "-") {246 return [word];247 }248249 if (word.includes("=") || next === undefined || next.startsWith("-")) {250 return cfCommandWords(args.slice(1));251 }252253 const after = cfCommandWords(rest);254255 return CF.values.has(word) ? after : [next, ...after];256};257258/** Values yargs reads as false for a boolean flag. */259const OFF = names("0 false");260261const DRY_RUN = "--dry-run";262263const setsDryRun = (word: string) =>264 word === DRY_RUN || word === "--no-dry-run" || word.startsWith(`${DRY_RUN}=`);265266/** Whether the last `--dry-run`, `--dry-run=…` or `--no-dry-run` turns it on. */267const dryRun = (args: readonly string[]): boolean => {268 const end = args.indexOf("--");269 const flags = end === -1 ? args : args.slice(0, end);270 const last = flags.findLastIndex(setsDryRun);271 const word = flags[last] ?? "--no-dry-run";272273 if (word === "--no-dry-run") {274 return false;275 }276277 return !OFF.has(278 word === DRY_RUN ? (flags[last + 1] ?? "") : word.slice(DRY_RUN.length + 1)279 );280};281282const judgeCf = (args: readonly string[]): Verdict => {283 const parsed = parse(args, CF, true);284 const commands = cfCommandWords(args);285 const [command = ""] = commands;286287 if (commands.length === 1 && CF_DISCOVERY.has(command)) {288 return Option.none();289 }290291 if (292 commands.some((word) => CF_PROJECT.has(word)) ||293 CF_PROJECT_SEQUENCES.some((sequence) => contains(parsed.operands, sequence))294 ) {295 return Option.some("cf-project-command");296 }297298 // `<command> --help` prints the command's help, as cf's own help suggests.299 const executes = !parsed.options.includes("--help") && !dryRun(args);300301 return breaks(302 "delete",303 executes && parsed.operands.some((word) => DESTRUCTIVE.test(word))304 );305};306307// closed-env-read -------------------------------------------------------------308309/**310 * Closed names to test globs against: one of each fixed name and a few of the311 * `.env.*.local` shape, so a glob covers the shape only if it matches them all.312 */313const CLOSED_SAMPLES = [314 ".env",315 ".env.local",316 ".env.development.local",317 ".env.production.local",318 ".env.test.local",319];320321const isClosedName = (name: string) =>322 name === ".env" || name === ".env.local" || /^\.env\..+\.local$/u.test(name);323324const GLOB = /[*?[]/u;325326const REGEXP_SPECIAL = /[$()*+.?[\\\]^{|}]/u;327328const globPart = (part: string) => {329 if (part === "*") {330 return ".*";331 }332333 if (part === "?" || part.startsWith("[")) {334 return ".";335 }336337 return REGEXP_SPECIAL.test(part) ? `\\${part}` : part;338};339340/**341 * Whether a glob could match `name`, as fnmatch does without `FNM_PERIOD`. A342 * bracket matches any one character, which only widens the match.343 */344const fnmatch = (pattern: string, name: string) =>345 new RegExp(346 `^${pattern.replaceAll(/\[[^\]]*\]|[\s\S]/gu, globPart)}$`,347 "u"348 ).test(name);349350/**351 * Whether a shell glob could match the dotfile `name`: a leading `*` never352 * matches one, as in a shell without `dotglob`.353 */354const globMatches = (pattern: string, name: string) =>355 pattern.startsWith(".") && fnmatch(pattern, name);356357/** `a{b,c}d` → `abd`, `acd`, as a shell expands braces. */358const braces = (word: string): readonly string[] => {359 const match = /\{(?<options>[^{}]*,[^{}]*)\}/u.exec(word);360361 if (match === null) {362 return [word];363 }364365 const before = word.slice(0, match.index);366 const after = word.slice(match.index + match[0].length);367368 return (match.groups?.options ?? "")369 .split(",")370 .flatMap((option) => braces(`${before}${option}${after}`));371};372373/** Whether `word`, or the part after its first `=`, names a closed env file. */374const namesClosedEnv = (word: string) =>375 [word, word.slice(word.indexOf("=") + 1)].some((value) =>376 braces(value).some((path) => {377 const name = basename(path.replace(/\/+$/u, ""));378379 return GLOB.test(name)380 ? CLOSED_SAMPLES.some((sample) => globMatches(name, sample))381 : isClosedName(name);382 })383 );384385/** The globs one option names, braces expanded: `--include={a,b}`. */386const globsOf = (parsed: Parsed, option: string) =>387 parsed.values.flatMap(([name, value]) =>388 name === option ? braces(value) : []389 );390391const GREP_RECURSIVE = names("-R -r --dereference-recursive --recursive");392393/**394 * `grep -r` reads every file under its paths, the closed ones too, unless395 * `--include` leaves them out or `--exclude` covers them (grep matches both396 * against the file's name with fnmatch, so `*` matches a leading dot).397 */398const grepReachesClosed = (parsed: Parsed) => {399 const recursive =400 parsed.options.some((option) => GREP_RECURSIVE.has(option)) ||401 parsed.values.some(402 ([option, value]) =>403 (option === "-d" || option === "--directories") && value === "recurse"404 );405406 const includes = globsOf(parsed, "--include");407 const excludes = globsOf(parsed, "--exclude");408409 return (410 recursive &&411 CLOSED_SAMPLES.some(412 (sample) =>413 (includes.length === 0 ||414 includes.some((glob) => fnmatch(glob, sample))) &&415 !excludes.some((glob) => fnmatch(glob, sample))416 )417 );418};419420const RG_HIDDEN = names("-. --hidden");421422const RG_IGNORED = names("--no-ignore --no-ignore-parent --no-ignore-vcs");423424/**425 * rg skips hidden files and the files .gitignore names, and the closed files426 * are both, so it reaches them only when told to search both: `-uu`, or427 * `--hidden` with `--no-ignore`.428 */429const rgReachesClosed = (parsed: Parsed) => {430 const unrestricted = parsed.options.filter(431 (option) => option === "-u" || option === "--unrestricted"432 ).length;433434 return (435 (unrestricted >= 2 ||436 parsed.options.some((option) => RG_HIDDEN.has(option))) &&437 (unrestricted >= 1 ||438 parsed.options.some((option) => RG_IGNORED.has(option)))439 );440};441442/**443 * A reader whose first operand is a pattern or a script, not a file, unless444 * one of `instead` supplies it.445 */446interface PatternFirst {447 readonly grammar: Grammar;448 readonly instead: ReadonlySet<string>;449 /** Options whose value is a pattern or a glob, never a file it reads. */450 readonly patterns: ReadonlySet<string>;451 /** Whether a search of whole directories can reach a closed file. */452 readonly reachesClosed: (parsed: Parsed) => boolean;453}454455const GREP: PatternFirst = {456 grammar: grammar(457 "-A -B -C -D -d -e -f -m --after-context --before-context --binary-files --context --devices --directories --exclude --exclude-dir --exclude-from --file --include --label --max-count --regexp"458 ),459 instead: names("-e -f --file --regexp"),460 patterns: names("-e --exclude --exclude-dir --include --regexp"),461 reachesClosed: grepReachesClosed,462};463464const AWK: PatternFirst = {465 grammar: grammar(466 "-E -F -W -f -i -l -v --assign --exec --field-separator --file --include --load"467 ),468 instead: names("-E -f --exec --file"),469 patterns: names(""),470 reachesClosed: () => false,471};472473const RG: PatternFirst = {474 grammar: grammar(475 "-A -B -C -E -M -T -d -e -f -g -j -m -r -t --after-context --before-context --color --colors --context --context-separator --encoding --engine --file --glob --iglob --ignore-file --max-columns --max-count --max-depth --max-filesize --path-separator --pre --pre-glob --regexp --replace --sort --sortr --threads --type --type-add --type-not"476 ),477 instead: names("-e -f --file --files --regexp --type-list"),478 patterns: names("-e --regexp"),479 reachesClosed: rgReachesClosed,480};481482const SED: PatternFirst = {483 grammar: grammar("-e -f -l --expression --file --line-length", "-i"),484 instead: names("-e -f --expression --file"),485 patterns: names(""),486 reachesClosed: () => false,487};488489const PATTERN_FIRST: ReadonlyMap<string, PatternFirst> = new Map([490 ["awk", AWK],491 ["egrep", GREP],492 ["fgrep", GREP],493 ["gawk", AWK],494 ["grep", GREP],495 ["mawk", AWK],496 ["nawk", AWK],497 ["rg", RG],498 ["sed", SED],499 ["zgrep", GREP],500]);501502/** Commands that read or copy the files they name. */503const READERS = new Set([504 ...names(505 ". ack ag base64 bat batcat cat cmp cp cut dd diff emacs head hexdump jq less more most nano nl nvim od paste rsync scp sort source strings tac tail uniq vi view vim wc xxd yq"506 ),507 ...PATTERN_FIRST.keys(),508]);509510const judgeRead = (program: string, args: readonly string[]): Verdict => {511 const patternFirst = PATTERN_FIRST.get(program);512 const parsed = parse(args, patternFirst?.grammar ?? NO_OPTIONS, true);513514 if (patternFirst === undefined) {515 return breaks(516 "closed-env-read",517 [...parsed.values.map(([, value]) => value), ...parsed.operands].some(518 namesClosedEnv519 )520 );521 }522523 const skipsFirst = !parsed.options.some((option) =>524 patternFirst.instead.has(option)525 );526527 const files = [528 ...parsed.values.flatMap(([option, value]) =>529 patternFirst.patterns.has(option) ? [] : [value]530 ),531 ...(skipsFirst ? parsed.operands.slice(1) : parsed.operands),532 ];533534 return breaks(535 "closed-env-read",536 files.some(namesClosedEnv) || patternFirst.reachesClosed(parsed)537 );538};539540// ---------------------------------------------------------------------------541// What actually runs: wrappers, shells and package runners.542// ---------------------------------------------------------------------------543544/** Reserved words that may open a simple command: `if git push; then`. */545const KEYWORDS = names("! do elif else if then until while { }");546547const DECLARATIONS = names("declare export local readonly typeset");548549const SHELLS = names("ash bash dash fish ksh sh zsh");550551const SHELL = grammar("-o --init-file --rcfile");552553/** Commands that run the command in their operands, with the options they take. */554const WRAPPERS: ReadonlyMap<string, Grammar> = new Map([555 ["builtin", NO_OPTIONS],556 ["command", NO_OPTIONS],557 ["doas", grammar("-C -a -u")],558 ["env", grammar("-C -P -S -u --chdir --split-string --unset")],559 ["exec", grammar("-a")],560 ["nice", grammar("-n --adjustment")],561 ["nohup", NO_OPTIONS],562 ["stdbuf", grammar("-e -i -o --error --input --output")],563 [564 "sudo",565 grammar(566 "-C -D -R -T -U -g -h -p -r -t -u --chdir --chroot --close-from --command-timeout --group --host --other-user --prompt --role --type --user"567 ),568 ],569 ["time", grammar("-f -o --format --output")],570 ["timeout", grammar("-k -s --kill-after --signal")],571 [572 "xargs",573 grammar(574 "-E -I -L -P -a -d -n -s --arg-file --delimiter --eof --max-args --max-chars --max-lines --max-procs --process-slot-var --replace",575 "-e -i -l"576 ),577 ],578]);579580/** The command a wrapper runs: `sudo -u root git push` → `git push`. */581const wrapped = (program: string, args: readonly string[]) => {582 const parsed = parse(args, WRAPPERS.get(program) ?? NO_OPTIONS, false);583584 // `env -S 'git push'` splits its string into words.585 const split = parsed.values.flatMap(([option, value]) =>586 option === "-S" || option === "--split-string" ? wordsOf(value) : []587 );588589 // `timeout 5 git push`: the duration comes first.590 const operands =591 program === "timeout" ? parsed.operands.slice(1) : parsed.operands;592593 return [...split, ...operands];594};595596const LAUNCHER = grammar("-p --package");597598const NPX = grammar("-c -p -w --call --package --workspace");599600const BUN = grammar(601 "-F -c -d -e -l -p -r --conditions --config --cwd --define --elide-lines --env-file --eval --filter --import --loader --preload --print --require --shell --tsconfig-override"602);603604// `bun -e` runs JavaScript, which is past what this policy can read.605const EVALUATES = names("-e -p --eval --print");606607const PACKAGE_MANAGER = grammar(608 "-C -F -w --cwd --dir --filter --prefix --workspace"609);610611const VARLOCK = grammar("-p --env --path");612613const SCRIPT_RUNS = names("run run-script");614615const PACKAGE_RUNS = names("dlx exec x");616617/** A launched package's command: `wrangler@4 delete` → `wrangler delete`. */618const launched = ([name = "", ...rest]: readonly string[]) => [619 withoutVersion(name),620 ...rest,621];622623/** What `npx` and its kin run: a package's bin, or `-c`'s script. */624const npx = (args: readonly string[]): readonly string[] => {625 const parsed = parse(args, NPX, false);626627 const call = parsed.values.find(628 ([option]) => option === "-c" || option === "--call"629 );630631 return call === undefined ? launched(parsed.operands) : ["sh", "-c", call[1]];632};633634/**635 * A package script, or a file or bin run by name. `ops` is the root script636 * `varlock run --path infra/ -- cf`, so `bun run ops -- x` runs `cf x`.637 */638const script = ([name = "", ...rest]: readonly string[]) => {639 const args = rest[0] === "--" ? rest.slice(1) : rest;640641 return name === "ops" ? ["cf", ...args] : [name, ...args];642};643644/** What bun, npm, pnpm or yarn runs, if anything. */645const packageManagerRuns = (646 program: string,647 args: readonly string[]648): Option.Option<readonly string[]> => {649 const parsed = parse(args, program === "bun" ? BUN : PACKAGE_MANAGER, false);650 const [subcommand = "", ...rest] = parsed.operands;651652 if (parsed.options.some((option) => EVALUATES.has(option))) {653 return Option.none();654 }655656 if (program === "bun" && subcommand === "exec") {657 return Option.some(["sh", "-c", rest.join(" ")]);658 }659660 if (SCRIPT_RUNS.has(subcommand)) {661 return Option.some(script(parse(rest, PACKAGE_MANAGER, false).operands));662 }663664 if (PACKAGE_RUNS.has(subcommand)) {665 return Option.some(npx(rest));666 }667668 // npm runs scripts only through `run`; bun, pnpm and yarn take a bare name.669 return program === "npm"670 ? Option.none()671 : Option.some(script(parsed.operands));672};673674/** The command a package runner runs, as words, if it runs one. */675const runs = (676 program: string,677 args: readonly string[]678): Option.Option<readonly string[]> => {679 if (program === "bunx" || program === "pnpx") {680 return Option.some(launched(parse(args, LAUNCHER, false).operands));681 }682683 if (program === "npx") {684 return Option.some(npx(args));685 }686687 if (program === "varlock") {688 const [subcommand, ...rest] = parse(args, VARLOCK, false).operands;689690 return subcommand === "run"691 ? Option.some(parse(rest, VARLOCK, false).operands)692 : Option.none();693 }694695 return packageManagerRuns(program, args);696};697698const PACKAGE_RUNNERS = names("bun bunx npm npx pnpm pnpx varlock yarn");699700const PROGRAMS: ReadonlyMap<string, (args: readonly string[]) => Verdict> =701 new Map([702 ["cf", judgeCf],703 // cf's package installs the same bin as `cloudflare`.704 ["cloudflare", judgeCf],705 ["git", judgeGit],706 ["jj", judgeJj],707 ["lefthook", judgeLefthook],708 ["wrangler", judgeWrangler],709 ]);710711type Judge = (command: string) => Verdict;712713/** A shell runs `-c`'s script, or with no script operand, the one on stdin. */714const judgeShell = (715 args: readonly string[],716 stdin: readonly string[],717 judge: Judge718): Verdict => {719 const parsed = parse(args, SHELL, false);720721 const scripts = parsed.options.includes("-c")722 ? parsed.operands.slice(0, 1)723 : stdin;724725 return Option.firstSomeOf(scripts.map(judge));726};727728/**729 * The rule one simple command breaks, if any. `judge` reads a nested script,730 * such as `sh -c`'s.731 */732const judgeWords = (733 words: readonly string[],734 stdin: readonly string[],735 judge: Judge736): Verdict => {737 const leading = words.findIndex((word) => !ASSIGNMENT.test(word));738 const assignments = leading === -1 ? words : words.slice(0, leading);739 const [head = "", ...args] = leading === -1 ? [] : words.slice(leading);740 const program = basename(head);741742 if (assignments.some(switchesOffHooks)) {743 return Option.some("hook-bypass");744 }745746 if (KEYWORDS.has(program)) {747 return judgeWords(args, stdin, judge);748 }749750 if (DECLARATIONS.has(program)) {751 return breaks("hook-bypass", args.some(switchesOffHooks));752 }753754 if (program === "eval") {755 return judge(args.join(" "));756 }757758 if (SHELLS.has(program)) {759 return judgeShell(args, stdin, judge);760 }761762 if (WRAPPERS.has(program)) {763 return judgeWords(wrapped(program, args), stdin, judge);764 }765766 if (PACKAGE_RUNNERS.has(program)) {767 return Option.flatMap(runs(program, args), (inner) =>768 judgeWords(inner, stdin, judge)769 );770 }771772 const judgeProgram = PROGRAMS.get(program);773774 if (judgeProgram !== undefined) {775 return judgeProgram(args);776 }777778 return READERS.has(program) ? judgeRead(program, args) : Option.none();779};780781const ruleOf: Judge = (command) =>782 Option.firstSomeOf(783 simpleCommands(command).map((simple) =>784 simple.reads.some(namesClosedEnv)785 ? Option.some<Rule>("closed-env-read")786 : judgeWords(simple.words, simple.stdin, ruleOf)787 )788 );789790/** Allow, or Deny with the rule the command breaks and what to do instead. */791export const decide = (command: string): Decision =>792 Option.match(ruleOf(command), {793 onNone: () => Decision.Allow(),794 onSome: (rule) => Decision.Deny({ reason: reasons[rule], rule }),795 });
added:scripts/hooks/lib/shell.ts+450 added
1/**2 * Reads a shell command line the way bash would, as far as the hook policy3 * needs: simple commands split on `; && || | ( )` and newlines, words after4 * quote removal (single, double, `$'…'` and backslash escapes), the files a5 * command reads with `<`, and heredoc and here-string text. What runs inside6 * `$(…)`, backticks and `<(…)` comes back as simple commands too; an unquoted7 * heredoc's substitutions run, a quoted one's don't.8 *9 * Variables and globs stay unexpanded, and a substitution's word holds its10 * source text. Unclosed quotes run to the end, so a command bash would refuse11 * to parse is still read for what it holds.12 */1314/**15 * One simple command: its words after quote removal, the files it reads with16 * `<`, and the heredoc or here-string text on its stdin.17 */18export interface Simple {19 readonly words: readonly string[];20 readonly reads: readonly string[];21 readonly stdin: readonly string[];22}2324/** A simple command while the scan is still reading it. */25interface Building {26 readonly words: string[];27 readonly reads: string[];28 readonly stdin: string[];29}3031interface Scanned {32 readonly commands: readonly Simple[];33 /** Just past the `)` that closed a nested scan, or the source's end. */34 readonly end: number;35}3637/** A heredoc whose body starts after the next newline. */38interface Heredoc {39 readonly delimiter: string;40 /** A quoted delimiter keeps `$(…)` in the body from running. */41 readonly quoted: boolean;42 /** `<<-` strips leading tabs from each line. */43 readonly tabs: boolean;44 readonly into: string[];45}4647/** What the word being read is for. */48type Slot =49 | "argument"50 | "read"51 | "write"52 | "here-string"53 | "heredoc"54 | "heredoc-tabs";5556/** Redirect operators, longest first, and what the word after each is. */57const REDIRECTS: readonly (readonly [string, Slot])[] = [58 ["<<<", "here-string"],59 ["<<-", "heredoc-tabs"],60 ["&>>", "write"],61 ["<<", "heredoc"],62 ["<>", "read"],63 ["<&", "write"],64 ["&>", "write"],65 [">>", "write"],66 [">|", "write"],67 [">&", "write"],68 ["<", "read"],69 [">", "write"],70];7172const BLANKS = new Set([" ", "\t"]);7374// Inside double quotes, `\` escapes only these.75const DOUBLE_QUOTE_ESCAPES = new Set(["$", "`", '"', "\\", "\n"]);7677// Inside backticks, `\` escapes only these.78const BACKTICK_ESCAPES = new Set(["`", "\\", "$"]);7980const ANSI_C: ReadonlyMap<string, string> = new Map([81 ["E", "\u001B"],82 ["a", "\u0007"],83 ["b", "\b"],84 ["e", "\u001B"],85 ["f", "\f"],86 ["n", "\n"],87 ["r", "\r"],88 ["t", "\t"],89 ["v", "\v"],90]);9192const ANSI_C_ESCAPE =93 /\\(?:x(?<hex>[\da-f]{1,2})|u(?<unicode>[\da-f]{1,4})|(?<octal>[0-7]{1,3})|(?<char>[\s\S]))/giu;9495const decodeEscape = (96 hex: string | undefined,97 unicode: string | undefined,98 octal: string | undefined,99 char: string | undefined100): string => {101 if (hex !== undefined) {102 return String.fromCodePoint(Number.parseInt(hex, 16));103 }104105 if (unicode !== undefined) {106 return String.fromCodePoint(Number.parseInt(unicode, 16));107 }108109 if (octal !== undefined) {110 return String.fromCodePoint(Number.parseInt(octal, 8));111 }112113 return ANSI_C.get(char ?? "") ?? char ?? "";114};115116/** The text of an ANSI-C quoted `$'…'` body, escapes decoded. */117const ansiC = (body: string): string => {118 let decoded = "";119 let from = 0;120121 for (const match of body.matchAll(ANSI_C_ESCAPE)) {122 const { char, hex, octal, unicode } = match.groups ?? {};123124 decoded += body.slice(from, match.index);125 decoded += decodeEscape(hex, unicode, octal, char);126 from = match.index + match[0].length;127 }128129 return decoded + body.slice(from);130};131132/**133 * Reads `src` from `start` into simple commands. A nested scan (inside `$(`)134 * stops at its unmatched `)`. Unclosed quotes run to the end, so a command a135 * shell would refuse to parse is still judged on what it holds.136 */137const scan = (src: string, start: number, nested: boolean): Scanned => {138 const commands: Simple[] = [];139 const heredocs: Heredoc[] = [];140 let simple: Building = { reads: [], stdin: [], words: [] };141 let word = "";142 let inWord = false;143 let quoted = false;144 let slot: Slot = "argument";145 let depth = 0;146 let at = start;147148 const append = (text: string, fromQuotes: boolean) => {149 word += text;150 inWord = true;151 quoted ||= fromQuotes;152 };153154 // `$(…)`: what it runs is judged; its source text stands in for its output.155 const substitution = (from: number) => {156 const inner = scan(src, from + 2, true);157158 commands.push(...inner.commands);159160 return { end: inner.end, text: src.slice(from, inner.end) };161 };162163 // `…`: up to the next unescaped backtick.164 const backtick = (from: number) => {165 let body = "";166 let end = from + 1;167168 while (end < src.length && src[end] !== "`") {169 const next = src[end + 1] ?? "";170 const escaped = src[end] === "\\" && BACKTICK_ESCAPES.has(next);171172 body += escaped ? next : (src[end] ?? "");173 end += escaped ? 2 : 1;174 }175176 commands.push(...scan(body, 0, false).commands);177178 return { end: end + 1, text: src.slice(from, end + 1) };179 };180181 // Double-quoted text, or an unquoted heredoc's body: `$(…)` and backticks182 // still run there. Stops before `limit`, or at `closing`.183 const expand = (from: number, limit: number, closing: string) => {184 let text = "";185 let end = from;186187 while (end < limit && src[end] !== closing) {188 const char = src[end] ?? "";189 const next = src[end + 1] ?? "";190191 if (char === "\\" && DOUBLE_QUOTE_ESCAPES.has(next)) {192 text += next === "\n" ? "" : next;193 end += 2;194 } else if ((char === "$" && next === "(") || char === "`") {195 const { end: after, text: source } =196 char === "`" ? backtick(end) : substitution(end);197198 text += source;199 end = after;200 } else {201 text += char;202 end += 1;203 }204 }205206 return { end: end + 1, text };207 };208209 // At a newline: each pending heredoc's body, line by line to its delimiter.210 const readHeredocs = (from: number): number => {211 let line = from;212213 for (const heredoc of heredocs) {214 const lines: string[] = [];215 const bodyStart = line;216 let bodyEnd = line;217218 while (line < src.length) {219 const newline = src.indexOf("\n", line);220 const eol = newline === -1 ? src.length : newline;221 const raw = src.slice(line, eol);222 const text = heredoc.tabs ? raw.replace(/^\t+/u, "") : raw;223224 line = eol + 1;225226 if (text === heredoc.delimiter) {227 break;228 }229230 lines.push(text);231 bodyEnd = eol;232 }233234 heredoc.into.push(lines.join("\n"));235236 if (!heredoc.quoted) {237 expand(bodyStart, bodyEnd, "");238 }239 }240241 heredocs.splice(0);242243 return line;244 };245246 const finishWord = () => {247 if (!inWord) {248 return;249 }250251 if (slot === "argument") {252 simple.words.push(word);253 } else if (slot === "read") {254 simple.reads.push(word);255 } else if (slot === "here-string") {256 simple.stdin.push(word);257 } else if (slot === "heredoc" || slot === "heredoc-tabs") {258 heredocs.push({259 delimiter: word,260 into: simple.stdin,261 quoted,262 tabs: slot === "heredoc-tabs",263 });264 }265266 word = "";267 inWord = false;268 quoted = false;269 slot = "argument";270 };271272 const finishCommand = () => {273 finishWord();274 slot = "argument";275276 const { reads, stdin, words } = simple;277278 if (words.length + reads.length + stdin.length > 0) {279 commands.push(simple);280 }281282 simple = { reads: [], stdin: [], words: [] };283 };284285 // `<`, `<<`, `>`, `>>`, `&>` and the rest. An unquoted all-digit word right286 // before one is its file descriptor, not an argument.287 const redirect = (): number => {288 if (inWord && !quoted && /^\d+$/u.test(word)) {289 word = "";290 inWord = false;291 } else {292 finishWord();293 }294295 const [operator, target] = REDIRECTS.find(([text]) =>296 src.startsWith(text, at)297 ) ?? [">", "write"];298299 slot = target;300301 return at + operator.length;302 };303304 // `$'…'`, `$(…)` and `${…}`; any other `$` is a literal.305 const dollar = (next: string): number | undefined => {306 if (next === "'") {307 let end = at + 2;308309 while (end < src.length && src[end] !== "'") {310 end += src[end] === "\\" ? 2 : 1;311 }312313 append(ansiC(src.slice(at + 2, Math.min(end, src.length))), true);314315 return end + 1;316 }317318 if (next === "(") {319 const inner = substitution(at);320321 append(inner.text, false);322323 return inner.end;324 }325326 if (next === "{") {327 const close = src.indexOf("}", at);328 const end = close === -1 ? src.length : close + 1;329330 append(src.slice(at, end), false);331332 return end;333 }334335 return undefined;336 };337338 // Quotes, escapes and expansions, each part of the current word. None when339 // `char` starts none of them.340 const wordPart = (char: string, next: string): number | undefined => {341 if (char === "\\") {342 if (next !== "\n") {343 append(next, true);344 }345346 return at + 2;347 }348349 if (char === "'") {350 const close = src.indexOf("'", at + 1);351 const end = close === -1 ? src.length : close;352353 append(src.slice(at + 1, end), true);354355 return end + 1;356 }357358 if (char === '"') {359 const inner = expand(at + 1, src.length, '"');360361 append(inner.text, true);362363 return inner.end;364 }365366 // Backticks, and the process substitutions `<(…)` and `>(…)`.367 if (char === "`" || ((char === "<" || char === ">") && next === "(")) {368 const inner = char === "`" ? backtick(at) : substitution(at);369370 append(inner.text, false);371372 return inner.end;373 }374375 return char === "$" ? dollar(next) : undefined;376 };377378 // Blanks, newlines, comments, redirects and the operators between simple379 // commands. None when `char` is none of them.380 const operator = (char: string, next: string): number | undefined => {381 if (BLANKS.has(char)) {382 finishWord();383384 return at + 1;385 }386387 if (char === "\n") {388 finishCommand();389390 return heredocs.length > 0 ? readHeredocs(at + 1) : at + 1;391 }392393 if (char === "#" && !inWord) {394 const newline = src.indexOf("\n", at);395396 return newline === -1 ? src.length : newline;397 }398399 if (char === "<" || char === ">" || (char === "&" && next === ">")) {400 return redirect();401 }402403 if (char === ";" || char === "&" || char === "|") {404 finishCommand();405406 return at + (next === char || (char === "|" && next === "&") ? 2 : 1);407 }408409 if (char === "(" || char === ")") {410 finishCommand();411 depth = char === "(" ? depth + 1 : Math.max(0, depth - 1);412413 return at + 1;414 }415416 return undefined;417 };418419 while (at < src.length) {420 const char = src[at] ?? "";421 const next = src[at + 1] ?? "";422423 if (char === ")" && nested && depth === 0) {424 finishCommand();425426 return { commands, end: at + 1 };427 }428429 const after = wordPart(char, next) ?? operator(char, next);430431 if (after === undefined) {432 append(char, false);433 at += 1;434 } else {435 at = after;436 }437 }438439 finishCommand();440441 return { commands, end: src.length };442};443444/** The simple commands in `command`, including those inside substitutions. */445export const simpleCommands = (command: string): readonly Simple[] =>446 scan(command, 0, false).commands;447448/** The words of the first simple command in `text`, as `env -S` splits it. */449export const wordsOf = (text: string): readonly string[] =>450 scan(text, 0, false).commands[0]?.words ?? [];
added:scripts/hooks/vcs-policy.ts+139 added
1// Ported from joelhooks/rat-stack@fba26d8 `scripts/hooks/block-git-no-verify.mjs`2// (MIT, LICENSES/rat-stack.MIT.txt). Changes are listed in PROVENANCE.md.3/**4 * vcs-policy: the hook Claude Code (PreToolUse on Bash, `.claude/settings.json`)5 * and Cursor (beforeShellExecution, `.cursor/hooks.json`) run before every shell6 * command. It reads the harness's JSON on stdin, asks `decide`, and answers in7 * that harness's shape:8 *9 * - Claude Code, or a bare `{"command": …}`: a refusal exits 2 with its reason10 * on stderr; an allowed command exits 0 and prints nothing.11 * - Cursor: prints `{"permission": "allow" | "deny", …}` and exits 0.12 *13 * Input it cannot read, or a failure while it judges, is a refusal: it fails14 * closed. A hook that cannot start at all (no `bun install` yet) exits 1,15 * which Cursor's `failClosed` blocks and Claude Code reports without blocking.16 */17import { BunRuntime, BunServices } from "@effect/platform-bun";18import {19 Data,20 Effect,21 Match,22 Option,23 Runtime,24 Schema,25 Stdio,26 Stream,27} from "effect";2829import { Decision, decide } from "./lib/policy.ts";3031/** Tags each payload with its harness, which its JSON doesn't carry. */32const harness = <const Name extends string>(name: Name) =>33 Schema.tag(name).pipe(Schema.withDecodingDefaultKey(Effect.succeed(name)));3435/** Claude Code's PreToolUse payload for the Bash tool. */36const ClaudePreToolUse = Schema.Struct({37 _tag: harness("Claude"),38 tool_input: Schema.Struct({ command: Schema.String }),39});4041/** Cursor's beforeShellExecution payload. */42const CursorShell = Schema.Struct({43 _tag: harness("Cursor"),44 command: Schema.String,45 hook_event_name: Schema.Literal("beforeShellExecution"),46});4748/** Any other caller: `{"command": "…"}`. */49const Bare = Schema.Struct({ _tag: harness("Bare"), command: Schema.String });5051const HookInput = Schema.fromJsonString(52 Schema.Union([ClaudePreToolUse, CursorShell, Bare])53);5455type HookInput = typeof HookInput.Type;5657const CANNOT_READ =58 'vcs-policy could not read a shell command from the hook\'s input, so it refuses it. It reads Claude Code\'s PreToolUse JSON, Cursor\'s beforeShellExecution JSON or {"command": "…"}.';5960/** A refusal this hook has already printed; it only sets the exit code. */61class Refused extends Data.TaggedError("Refused")<{62 readonly reason: string;63}> {64 override readonly [Runtime.errorExitCode] = 2;65 override readonly [Runtime.errorReported] = false;66}6768/** Who answers, and the refusal, if any, in words for the agent. */69interface Verdict {70 readonly harness: HookInput["_tag"];71 readonly refusal: Option.Option<string>;72}7374const commandOf = (input: HookInput) =>75 Match.valueTags(input, {76 Bare: ({ command }) => command,77 Claude: ({ tool_input }) => tool_input.command,78 Cursor: ({ command }) => command,79 });8081const explain = (decision: Decision): Option.Option<string> =>82 Decision.$match(decision, {83 Allow: () => Option.none(),84 Deny: ({ reason, rule }) =>85 Option.some(`vcs-policy refused this command (${rule}): ${reason}`),86 });8788const UNREADABLE: Verdict = {89 harness: "Bare",90 refusal: Option.some(CANNOT_READ),91};9293const judged: Effect.Effect<Verdict, never, Stdio.Stdio> = Effect.gen(94 function* () {95 const stdio = yield* Stdio.Stdio;96 const raw = yield* stdio.stdin.pipe(Stream.decodeText(), Stream.mkString);97 const input = yield* Schema.decodeEffect(HookInput)(raw);9899 return {100 harness: input._tag,101 refusal: explain(decide(commandOf(input))),102 };103 }104).pipe(105 // Unreadable stdin, a payload of no known shape, or a defect: refuse.106 Effect.catchCause(() => Effect.succeed(UNREADABLE))107);108109/** Cursor reads its answer, allow or deny, from stdout. */110const answerCursor = (refusal: Option.Option<string>) => {111 const reply = Option.match(refusal, {112 onNone: () => ({ permission: "allow" }),113 onSome: (message) => ({114 agent_message: message,115 permission: "deny",116 user_message: message,117 }),118 });119120 return Effect.flatMap(Stdio.Stdio, (stdio) =>121 Stream.run(Stream.make(`${JSON.stringify(reply)}\n`), stdio.stdout())122 );123};124125/** Claude Code and a bare caller read a refusal from exit 2 and stderr. */126const answerByExit = (refusal: Option.Option<string>) =>127 Option.match(refusal, {128 onNone: () => Effect.void,129 onSome: (message) =>130 Effect.flatMap(Stdio.Stdio, (stdio) =>131 Stream.run(Stream.make(`${message}\n`), stdio.stderr())132 ).pipe(Effect.andThen(Effect.fail(new Refused({ reason: message })))),133 });134135const main = Effect.flatMap(judged, ({ harness: answerer, refusal }) =>136 answerer === "Cursor" ? answerCursor(refusal) : answerByExit(refusal)137);138139BunRuntime.runMain(main.pipe(Effect.provide(BunServices.layer)));