From 4d7fd2fd703093765b5bb226d184b7f7ccf0b992 Mon Sep 17 00:00:00 2001 From: carlos-alm Date: Fri, 7 Aug 2026 11:22:20 -0600 Subject: [PATCH 1/3] fix(hooks): guard-git.sh clean guard blocks dry-run and matches raw substrings (#2099) git's clean subcommand was blocked unconditionally, including -n/--dry-run - a pure listing operation that never deletes, and exactly the discovery mechanism /housekeep's Phase 2 recommends for finding gitignored dirt files. Now only blocks when -f/--force is present and -n/--dry-run is absent (git itself always treats --dry-run as overriding -f, so it never deletes either way). Separately, every dangerous-verb check in this hook scanned the raw command text with no awareness of shell quoting, so a substring inside an unrelated command's quoted argument (or heredoc-authored commit message body) matched the same pattern as a real invocation. Adds mask-quoted-text.mjs, which masks quoted-string contents and heredoc bodies before the verb-detection checks run, fixing this false-positive class for every check in the file at its root. Extraction logic (detect_work_dir, MSG_FILE, the AI-attribution scan) keeps reading the raw, unmasked command since those need real values. docs check acknowledged --- .claude/hooks/guard-git.sh | 33 ++++- .claude/hooks/mask-quoted-text.mjs | 89 +++++++++++++ tests/unit/hook-guard-git-clean.test.ts | 158 ++++++++++++++++++++++++ 3 files changed, 277 insertions(+), 3 deletions(-) create mode 100644 .claude/hooks/mask-quoted-text.mjs create mode 100644 tests/unit/hook-guard-git-clean.test.ts diff --git a/.claude/hooks/guard-git.sh b/.claude/hooks/guard-git.sh index 13faa4ce6..05f672dc8 100644 --- a/.claude/hooks/guard-git.sh +++ b/.claude/hooks/guard-git.sh @@ -26,6 +26,21 @@ if ! echo "$COMMAND" | grep -qE '(^|[[:space:]]|&&[[:space:]]*)(git|gh)[[:space: exit 0 fi +# Mask the *contents* of quoted strings (single or double) before any of the +# "does this command invoke a dangerous verb" checks below run (#2099). Every +# such check is a plain substring/regex scan over the command text, with no +# awareness of shell quoting — so text that merely APPEARS inside a quoted +# argument (e.g. `gh issue create --body "...git clean -fd..."`) matched the +# same pattern as a real invocation and got blocked. See mask-quoted-text.mjs +# for the masking rules. Extraction logic below (detect_work_dir, MSG_FILE, +# the AI-attribution scan) deliberately keeps reading the raw, unmasked +# $COMMAND — masking only feeds the verb-detection checks that use $NCOMMAND. +HOOK_DIR="$(cd "$(dirname "$0")" && pwd)" +MASKED_COMMAND=$(echo "$COMMAND" | node "$HOOK_DIR/mask-quoted-text.mjs" 2>/dev/null) || true +if [ -z "$MASKED_COMMAND" ]; then + MASKED_COMMAND="$COMMAND" +fi + # Normalize: strip `git -C ""` / `git -C ` so downstream subcommand # patterns (git[[:space:]]+push, git[[:space:]]+commit, …) match regardless of whether `-C` is # present. detect_work_dir still inspects the raw $COMMAND to find the target. @@ -33,7 +48,7 @@ fi # the opening `"` of a quoted path (which would leave a trailing `path"` in # NCOMMAND). The pattern re-anchors on `git`, so multi-`-C` chains (e.g. # `git -C /a -C /b push`) need a second pass to collapse the residual `-C`. -NCOMMAND=$(echo "$COMMAND" | sed -E 's/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+"[^"]+"/\1git/g; s/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+[^"[:space:]][^[:space:]]*/\1git/g') +NCOMMAND=$(echo "$MASKED_COMMAND" | sed -E 's/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+"[^"]+"/\1git/g; s/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+[^"[:space:]][^[:space:]]*/\1git/g') NCOMMAND=$(echo "$NCOMMAND" | sed -E 's/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+"[^"]+"/\1git/g; s/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+[^"[:space:]][^[:space:]]*/\1git/g') deny() { @@ -74,9 +89,21 @@ if echo "$NCOMMAND" | grep -qE '(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+res fi fi -# git clean (delete untracked files) +# git clean (delete untracked files) — #2099: `-n`/`--dry-run` is a pure +# listing operation (git itself treats --dry-run as always overriding -f, so +# it never deletes regardless of what else is on the line) and is exactly the +# discovery mechanism /housekeep's Phase 2 recommends; only block an +# invocation that would actually delete (carries -f/--force, and no +# -n/--dry-run). A bare `git clean` with neither flag already refuses to run +# without config changes this hook has no visibility into, so it's left +# unblocked rather than flagging something git itself won't execute. if echo "$NCOMMAND" | grep -qE '(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+clean'; then - deny "BLOCKED: 'git clean' deletes untracked files that may belong to other sessions." + CLEAN_SEGMENT=$(echo "$NCOMMAND" | awk 'BEGIN{RS="&&"}{ if ($0 ~ /(^|[[:space:]])git[[:space:]]+clean/) { print; exit } }') + if ! echo "$CLEAN_SEGMENT" | grep -qE '(^|[[:space:]])(-n|--dry-run)([[:space:]]|$)'; then + if echo "$CLEAN_SEGMENT" | grep -qE '(^|[[:space:]])(-[a-zA-Z]*f[a-zA-Z]*|--force)([[:space:]]|$)'; then + deny "BLOCKED: 'git clean -f'/'--force' deletes untracked files that may belong to other sessions. Preview first with 'git clean -n'/'--dry-run'." + fi + fi fi # git stash (hides all changes) diff --git a/.claude/hooks/mask-quoted-text.mjs b/.claude/hooks/mask-quoted-text.mjs new file mode 100644 index 000000000..49d6e56c9 --- /dev/null +++ b/.claude/hooks/mask-quoted-text.mjs @@ -0,0 +1,89 @@ +#!/usr/bin/env node +// mask-quoted-text.mjs — reads a shell command line from stdin and writes it +// back with the *contents* of every quoted string (single or double) and +// every heredoc body replaced by `#`/masked placeholders, preserving quote +// delimiters and overall length/line structure. +// +// Used by guard-git.sh (#2099) so its "does this command invoke a dangerous +// verb" checks scan text that can never accidentally match inside data that +// isn't a real command invocation — e.g. +// `gh issue create --body "...git clean -fd..."` previously tripped the +// same regex as a real `git clean` invocation, since those checks are plain +// substring/regex scans with no awareness of shell quoting. Heredoc bodies +// (`git commit -m "$(cat <<'EOF' ... EOF)"`, the form this repo's own +// CLAUDE.md mandates for commit messages) are the same class of problem: +// the message text is data, not commands, but sits outside any single-line +// quote pair. +// +// This is a heuristic, not a full shell-grammar parser: `\"` inside a +// double-quoted string is treated as an escaped quote (consumed as two +// masked characters, not a string terminator); single-quoted strings in real +// shells never support backslash escapes at all, so none are attempted here. +// Heredoc detection looks for `<<[-~]?['"]?WORD['"]?` anywhere on a line and +// masks every line up to (not including) a line whose trimmed content is +// exactly WORD — real shells only allow the plain form (no `<<`, redirects, +// or trailing text) on a terminator line, which this mirrors. Proportionate +// to a PreToolUse guard, matching the tolerance for edge cases already +// accepted by guard-git.sh's other regex-based checks. + +const HEREDOC_START = /<<-?~?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/; + +function maskHeredocBodies(text) { + const lines = text.split('\n'); + const out = []; + let delimiter = null; + for (const line of lines) { + if (delimiter !== null) { + if (line.trim() === delimiter) { + delimiter = null; + out.push(line); + } else { + out.push('#'.repeat(line.length)); + } + continue; + } + out.push(line); + const match = line.match(HEREDOC_START); + if (match) { + delimiter = match[2]; + } + } + return out.join('\n'); +} + +function maskQuotedStrings(input) { + let out = ''; + let quote = null; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (quote) { + if (ch === '\\' && quote === '"' && i + 1 < input.length) { + out += '##'; + i++; + continue; + } + if (ch === quote) { + out += ch; + quote = null; + continue; + } + out += ch === '\n' ? '\n' : '#'; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + out += ch; + continue; + } + out += ch; + } + return out; +} + +let input = ''; +process.stdin.on('data', (chunk) => { + input += chunk; +}); +process.stdin.on('end', () => { + process.stdout.write(maskQuotedStrings(maskHeredocBodies(input))); +}); diff --git a/tests/unit/hook-guard-git-clean.test.ts b/tests/unit/hook-guard-git-clean.test.ts new file mode 100644 index 000000000..bda4673c2 --- /dev/null +++ b/tests/unit/hook-guard-git-clean.test.ts @@ -0,0 +1,158 @@ +/** + * Regression guard for issue #2099: `.claude/hooks/guard-git.sh`'s `git + * clean` check had two bugs. + * + * 1. It blocked every invocation unconditionally, including `-n`/`--dry-run` + * — a pure listing operation that never deletes anything, and exactly the + * discovery mechanism `/housekeep`'s Phase 2 recommends for finding + * gitignored dirt files. + * 2. Every "does this command invoke a dangerous verb" check in the file + * (not just `git clean`) scanned the raw command TEXT with no awareness + * of shell quoting, so a command like + * `gh issue create --body "...git clean -fd..."` matched the same regex + * as a real invocation, even though the match was inside a quoted + * argument to an unrelated command. + * + * The fix: mask quoted-string contents before the verb-detection checks run + * (`mask-quoted-text.mjs`), and only block `git clean` when it carries + * `-f`/`--force` and lacks `-n`/`--dry-run` (which git itself treats as + * always overriding `-f`). + */ +import { execFileSync } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const REPO_ROOT = path.resolve(__dirname, '..', '..'); +const HOOK_PATH = path.join(REPO_ROOT, '.claude', 'hooks', 'guard-git.sh'); + +interface HookDecision { + hookSpecificOutput?: { + permissionDecision?: string; + permissionDecisionReason?: string; + }; +} + +function runHook(command: string): HookDecision { + const toolInput = JSON.stringify({ tool_input: { command } }); + const stdout = execFileSync('bash', [HOOK_PATH], { input: toolInput, encoding: 'utf8' }); + return stdout.trim() ? JSON.parse(stdout) : {}; +} + +function isDenied(command: string): boolean { + return runHook(command).hookSpecificOutput?.permissionDecision === 'deny'; +} + +describe('guard-git.sh git clean dry-run/force distinction (#2099)', () => { + it('blocks a force-deleting invocation', () => { + expect(isDenied('git clean -fd')).toBe(true); + expect(isDenied('git clean --force')).toBe(true); + }); + + it('allows -n/--dry-run through (pure listing, never deletes)', () => { + expect(isDenied('git clean -n')).toBe(false); + expect(isDenied('git clean --dry-run')).toBe(false); + }); + + it('allows -f combined with --dry-run (git always treats dry-run as overriding force)', () => { + expect(isDenied('git clean -fdX --dry-run')).toBe(false); + }); + + it('allows a bare git clean with neither flag (git itself refuses to run it)', () => { + expect(isDenied('git clean')).toBe(false); + }); + + it('still blocks a force-clean chained after another command', () => { + expect(isDenied('git push -f && git clean -fd')).toBe(true); + }); +}); + +describe('guard-git.sh does not false-positive on quoted text (#2099)', () => { + it('does not block a gh command whose quoted body merely mentions git clean', () => { + expect(isDenied('gh issue create --body "please dont run git clean -fd"')).toBe(false); + }); + + it('does not block when the quoted text contains escaped double quotes', () => { + expect(isDenied('gh issue create --body "he said \\"git clean -fd\\" was risky"')).toBe(false); + }); + + it('still blocks a real git add -A after a cd into a path that merely contains "git clean" text', () => { + expect(isDenied('cd "/tmp/git clean demo" && git add -A')).toBe(true); + }); + + it('still blocks real, unquoted dangerous invocations for every existing check', () => { + expect(isDenied('git add -A')).toBe(true); + expect(isDenied('git add .')).toBe(true); + expect(isDenied('git reset --hard')).toBe(true); + expect(isDenied('git checkout -- .')).toBe(true); + expect(isDenied('git restore .')).toBe(true); + expect(isDenied('git stash')).toBe(true); + }); + + it('still allows the safe forms of those same commands', () => { + expect(isDenied('git add foo.txt')).toBe(false); + expect(isDenied('git restore --staged foo.txt')).toBe(false); + }); + + it('does not block a commit whose heredoc-authored message body mentions git clean', () => { + // CLAUDE.md mandates exactly this heredoc form for commit messages — + // a real commit whose message discusses (or fixes) git clean, like this + // very commit, must not be self-blocked. + const command = [ + `git commit -m "$(cat <<'EOF'`, + `fix(hooks): example commit message`, + ``, + `git clean was blocked unconditionally, including -n/--dry-run.`, + `EOF`, + `)" some-file.txt`, + ].join('\n'); + expect(isDenied(command)).toBe(false); + }); +}); + +describe('guard-git.sh mask-quoted-text.mjs', () => { + const MASK_SCRIPT = path.join(REPO_ROOT, '.claude', 'hooks', 'mask-quoted-text.mjs'); + + function mask(input: string): string { + return execFileSync('node', [MASK_SCRIPT], { input, encoding: 'utf8' }); + } + + it('masks quoted content while preserving unquoted text verbatim', () => { + expect(mask('gh issue create --body "git clean -fd"')).toBe( + `gh issue create --body "${'#'.repeat('git clean -fd'.length)}"`, + ); + }); + + it('leaves an unquoted real invocation completely untouched', () => { + const cmd = 'git clean -fd'; + expect(mask(cmd)).toBe(cmd); + }); + + it('treats an escaped double quote inside a double-quoted string as non-terminating', () => { + const input = 'gh issue create --body "he said \\"git clean\\" was risky"'; + const output = mask(input); + expect(output).not.toContain('git clean'); + expect(output.startsWith('gh issue create --body "')).toBe(true); + expect(output.endsWith('"')).toBe(true); + }); + + it('masks single-quoted content the same way as double-quoted', () => { + expect(mask("echo 'git clean -fd'")).toBe(`echo '${'#'.repeat('git clean -fd'.length)}'`); + }); + + it('masks a heredoc body between its < { + const input = ["cat <<'EOF'", 'git clean -fd', 'EOF'].join('\n'); + const output = mask(input); + const lines = output.split('\n'); + expect(lines[0]).toBe(`cat <<'${'#'.repeat(3)}'`); + expect(lines[1]).toBe('#'.repeat('git clean -fd'.length)); + expect(lines[2]).toBe('EOF'); + }); + + it('does not treat text past the terminator line as still inside the heredoc', () => { + const input = ["cat <<'EOF'", 'masked body', 'EOF', 'git clean -fd'].join('\n'); + const output = mask(input); + expect(output.split('\n').at(-1)).toBe('git clean -fd'); + }); +}); From 1378355dcb3c0f41ff29f3b30e78c7fb1bac40da Mon Sep 17 00:00:00 2001 From: carlos-alm Date: Fri, 7 Aug 2026 12:02:05 -0600 Subject: [PATCH 2/3] fix(hooks): address review feedback on the clean-guard and quote-masking fix (#2099) Three issues surfaced during review of the initial #2099 fix: 1. Segment splitting for the dry-run/force distinction only recognized && as a command boundary, so a flag on a ;/|/newline-separated command could suppress the block for an unrelated, actually-destructive invocation. Replaced the inline awk/grep pair with check-git-clean-force.mjs, which splits on every real separator and matches whole tokens (also fixing bundled short flags like -ndf/-fnd, which the previous standalone -n/-f regex missed). 2. Masking every quoted string unconditionally hid genuinely executable nested-shell payloads, e.g. bash -c "git clean -fd" or eval "git reset --hard" - the quoted text there is code, not inert data. Quotes and heredocs immediately preceded by -c/--command/-e/--eval/eval are now left completely unmasked instead. 3. The initial fast-path gate (does this command mention git/gh at all) required whitespace immediately before git/gh, so a quote-prefixed invocation like "git clean -fd" (inside bash -c "...") never reached any of the checks below in the first place - independent of masking. Loosened to also accept a quote character as a valid prefix boundary. Also strips residual quote characters from NCOMMAND after masking, since an exec-triggered (intentionally unmasked) quote's own delimiters would otherwise sit directly adjacent to the verb and defeat the whitespace-anchored checks. docs check acknowledged --- .claude/hooks/check-git-clean-force.mjs | 39 +++++++++++++++++++++++ .claude/hooks/guard-git.sh | 32 ++++++++++++++----- .claude/hooks/mask-quoted-text.mjs | 42 +++++++++++++++++++++++-- tests/unit/hook-guard-git-clean.test.ts | 34 ++++++++++++++++++++ 4 files changed, 137 insertions(+), 10 deletions(-) create mode 100644 .claude/hooks/check-git-clean-force.mjs diff --git a/.claude/hooks/check-git-clean-force.mjs b/.claude/hooks/check-git-clean-force.mjs new file mode 100644 index 000000000..7fe30136e --- /dev/null +++ b/.claude/hooks/check-git-clean-force.mjs @@ -0,0 +1,39 @@ +#!/usr/bin/env node +// check-git-clean-force.mjs — reads the (masked, -C-normalized) NCOMMAND +// from stdin and prints `BLOCK` if it contains a `git clean` invocation that +// would actually delete (carries -f/--force and lacks -n/--dry-run), +// otherwise prints nothing. Used by guard-git.sh (#2099). +// +// Splits into logical command segments on every real shell command +// separator (&&, ||, ;, |, newline) — not just `&&` — so a flag on one +// command can never be misread as belonging to an unrelated `git clean` on +// a different segment (Greptile review: `git clean -fd; ls -n` must still +// block, since the `-n` belongs to `ls`, not the clean invocation). +// +// Within a segment, flags are matched against whole whitespace-separated +// tokens (not a substring/boundary regex against the raw segment text), so +// bundled short options are recognized correctly: `-ndf` and `-fnd` both +// carry both `-n` and `-f`, matching git's own bundled short-flag parsing. + +const SEGMENT_SEPARATOR = /&&|\|\||[;|\n]/; +const CLEAN_INVOCATION = /(^|\s)git\s+clean(\s|$)/; +const FORCE_TOKEN = /^(--force|-[a-zA-Z]*f[a-zA-Z]*)$/; +const DRY_RUN_TOKEN = /^(--dry-run|-[a-zA-Z]*n[a-zA-Z]*)$/; + +let input = ''; +process.stdin.on('data', (chunk) => { + input += chunk; +}); +process.stdin.on('end', () => { + const segments = input.split(SEGMENT_SEPARATOR); + for (const segment of segments) { + if (!CLEAN_INVOCATION.test(segment)) continue; + const tokens = segment.trim().split(/\s+/); + const hasForce = tokens.some((t) => FORCE_TOKEN.test(t)); + const hasDryRun = tokens.some((t) => DRY_RUN_TOKEN.test(t)); + if (hasForce && !hasDryRun) { + process.stdout.write('BLOCK'); + return; + } + } +}); diff --git a/.claude/hooks/guard-git.sh b/.claude/hooks/guard-git.sh index 05f672dc8..3bfe537d5 100644 --- a/.claude/hooks/guard-git.sh +++ b/.claude/hooks/guard-git.sh @@ -21,8 +21,14 @@ if [ -z "$COMMAND" ]; then exit 0 fi -# Act on git and gh commands (may appear after cd "..." &&) -if ! echo "$COMMAND" | grep -qE '(^|[[:space:]]|&&[[:space:]]*)(git|gh)[[:space:]]+'; then +# Act on git and gh commands (may appear after cd "..." && or inside a quoted +# nested-shell invocation, e.g. `bash -c "git clean -fd"` — #2099 Greptile +# review). This is only a cheap fast-path skip, so it's deliberately +# permissive (["'] as an extra allowed prefix boundary alongside +# start/whitespace/&&) rather than exact: a false "yes" here just means the +# rest of the script runs its checks anyway, while a false "no" would exit +# before ever reaching them. +if ! echo "$COMMAND" | grep -qE '(^|[[:space:]]|&&[[:space:]]*|["'"'"'])(git|gh)[[:space:]]+'; then exit 0 fi @@ -51,6 +57,16 @@ fi NCOMMAND=$(echo "$MASKED_COMMAND" | sed -E 's/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+"[^"]+"/\1git/g; s/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+[^"[:space:]][^[:space:]]*/\1git/g') NCOMMAND=$(echo "$NCOMMAND" | sed -E 's/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+"[^"]+"/\1git/g; s/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+[^"[:space:]][^[:space:]]*/\1git/g') +# Strip any remaining literal quote characters from NCOMMAND (#2099 Greptile +# review): an exec-triggered quote (`bash -c "git clean -fd"`) is left +# unmasked by mask-quoted-text.mjs, but its quote DELIMITERS survive — e.g. +# `"git` — which sit directly adjacent to the verb, defeating every +# `(^|[[:space:]])`-anchored check below. NCOMMAND is used exclusively for +# verb detection (never for value extraction — detect_work_dir/MSG_FILE read +# the raw $COMMAND instead), so quote characters carry no meaning here once +# masking has already run. +NCOMMAND=$(echo "$NCOMMAND" | sed -E "s/[\"']/ /g") + deny() { local reason="$1" node -e " @@ -97,12 +113,14 @@ fi # -n/--dry-run). A bare `git clean` with neither flag already refuses to run # without config changes this hook has no visibility into, so it's left # unblocked rather than flagging something git itself won't execute. +# Delegates to check-git-clean-force.mjs (not an inline awk/grep pair) so the +# per-segment split and bundled-short-flag matching (`-ndf`, `-fnd`, …) are +# correct — an earlier version here split only on `&&`, so a flag on an +# unrelated `;`/`|`/newline-separated command could suppress the block, and +# missed bundled `-n` (Greptile review on #2099's own PR). if echo "$NCOMMAND" | grep -qE '(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+clean'; then - CLEAN_SEGMENT=$(echo "$NCOMMAND" | awk 'BEGIN{RS="&&"}{ if ($0 ~ /(^|[[:space:]])git[[:space:]]+clean/) { print; exit } }') - if ! echo "$CLEAN_SEGMENT" | grep -qE '(^|[[:space:]])(-n|--dry-run)([[:space:]]|$)'; then - if echo "$CLEAN_SEGMENT" | grep -qE '(^|[[:space:]])(-[a-zA-Z]*f[a-zA-Z]*|--force)([[:space:]]|$)'; then - deny "BLOCKED: 'git clean -f'/'--force' deletes untracked files that may belong to other sessions. Preview first with 'git clean -n'/'--dry-run'." - fi + if [ "$(echo "$NCOMMAND" | node "$HOOK_DIR/check-git-clean-force.mjs" 2>/dev/null)" = "BLOCK" ]; then + deny "BLOCKED: 'git clean -f'/'--force' deletes untracked files that may belong to other sessions. Preview first with 'git clean -n'/'--dry-run'." fi fi diff --git a/.claude/hooks/mask-quoted-text.mjs b/.claude/hooks/mask-quoted-text.mjs index 49d6e56c9..9c58072a2 100644 --- a/.claude/hooks/mask-quoted-text.mjs +++ b/.claude/hooks/mask-quoted-text.mjs @@ -15,6 +15,17 @@ // the message text is data, not commands, but sits outside any single-line // quote pair. // +// EXEC_TRIGGER_TOKENS (Greptile review on #2099's own PR): a quote or +// heredoc immediately following `-c`/`--command`/`-e`/`--eval`/`eval` is not +// inert data — shells and interpreters (`bash -c "..."`, `sh -c '...'`, +// `node -e "..."`, `eval "..."`) execute that string as real code. Masking +// it would hide a genuine `git clean -fd` payload from every verb-detection +// check below. Such quotes/heredocs are left completely unmasked instead. +// This is a token-adjacency heuristic, not full shell-grammar parsing — it +// does not resolve indirection (e.g. a variable holding `-c`), matching the +// tolerance for edge cases already accepted by guard-git.sh's other +// regex-based checks. +// // This is a heuristic, not a full shell-grammar parser: `\"` inside a // double-quoted string is treated as an escaped quote (consumed as two // masked characters, not a string terminator); single-quoted strings in real @@ -22,21 +33,32 @@ // Heredoc detection looks for `<<[-~]?['"]?WORD['"]?` anywhere on a line and // masks every line up to (not including) a line whose trimmed content is // exactly WORD — real shells only allow the plain form (no `<<`, redirects, -// or trailing text) on a terminator line, which this mirrors. Proportionate -// to a PreToolUse guard, matching the tolerance for edge cases already -// accepted by guard-git.sh's other regex-based checks. +// or trailing text) on a terminator line, which this mirrors. const HEREDOC_START = /<<-?~?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/; +const EXEC_TRIGGER_TOKENS = new Set(['-c', '--command', '-e', '--eval', 'eval']); + +/** The whitespace-delimited token immediately before `pos` in `str`, or ''. */ +function precedingToken(str, pos) { + let end = pos; + while (end > 0 && /\s/.test(str[end - 1])) end--; + let start = end; + while (start > 0 && !/\s/.test(str[start - 1])) start--; + return str.slice(start, end); +} function maskHeredocBodies(text) { const lines = text.split('\n'); const out = []; let delimiter = null; + let execTriggered = false; for (const line of lines) { if (delimiter !== null) { if (line.trim() === delimiter) { delimiter = null; out.push(line); + } else if (execTriggered) { + out.push(line); } else { out.push('#'.repeat(line.length)); } @@ -46,6 +68,13 @@ function maskHeredocBodies(text) { const match = line.match(HEREDOC_START); if (match) { delimiter = match[2]; + // Coarse, line-level check: does this heredoc's own start line carry + // an exec-trigger token anywhere on it (e.g. `bash -c "$(cat <<'EOF'`)? + // A false "yes" here only means a heredoc that didn't need the + // exemption stays unmasked — a missed mask, not a hidden invocation — + // which is the safe direction to err in. + const tokens = line.trim().split(/\s+/); + execTriggered = tokens.some((t) => EXEC_TRIGGER_TOKENS.has(t)); } } return out.join('\n'); @@ -54,9 +83,15 @@ function maskHeredocBodies(text) { function maskQuotedStrings(input) { let out = ''; let quote = null; + let quoteExecTriggered = false; for (let i = 0; i < input.length; i++) { const ch = input[i]; if (quote) { + if (quoteExecTriggered) { + out += ch; + if (ch === quote) quote = null; + continue; + } if (ch === '\\' && quote === '"' && i + 1 < input.length) { out += '##'; i++; @@ -72,6 +107,7 @@ function maskQuotedStrings(input) { } if (ch === '"' || ch === "'") { quote = ch; + quoteExecTriggered = EXEC_TRIGGER_TOKENS.has(precedingToken(input, i)); out += ch; continue; } diff --git a/tests/unit/hook-guard-git-clean.test.ts b/tests/unit/hook-guard-git-clean.test.ts index bda4673c2..1d1eb1f41 100644 --- a/tests/unit/hook-guard-git-clean.test.ts +++ b/tests/unit/hook-guard-git-clean.test.ts @@ -66,6 +66,28 @@ describe('guard-git.sh git clean dry-run/force distinction (#2099)', () => { it('still blocks a force-clean chained after another command', () => { expect(isDenied('git push -f && git clean -fd')).toBe(true); }); + + it('recognizes a dry-run flag bundled with other short options', () => { + // Greptile review on this PR: -ndf/-fnd bundle -n (dry-run) with -d/-f — + // git's own arg parser treats every letter in a bundled short-opt group + // independently, so this must NOT block despite -f being present. + expect(isDenied('git clean -ndf')).toBe(false); + expect(isDenied('git clean -fnd')).toBe(false); + }); + + it('recognizes a force flag bundled with other short options (no dry-run present)', () => { + expect(isDenied('git clean -fd')).toBe(true); + expect(isDenied('git clean -df')).toBe(true); + }); + + it('does not let a flag on a different, non-&&-separated command suppress the block', () => { + // Greptile review: an earlier version split segments only on `&&`, so a + // `;`/`|`/newline-separated command's own -n could be misread as + // belonging to the git clean invocation. + expect(isDenied('git clean -fd; ls -n')).toBe(true); + expect(isDenied('git clean -fd | cat -n')).toBe(true); + expect(isDenied('git clean -fd\nls -n')).toBe(true); + }); }); describe('guard-git.sh does not false-positive on quoted text (#2099)', () => { @@ -95,6 +117,18 @@ describe('guard-git.sh does not false-positive on quoted text (#2099)', () => { expect(isDenied('git restore --staged foo.txt')).toBe(false); }); + it('still blocks a real invocation nested inside bash -c / sh -c / eval (Greptile review)', () => { + // A quote immediately after -c/-e/eval is executable code, not inert + // data — masking it would hide a real destructive invocation. + expect(isDenied('bash -c "git clean -fd"')).toBe(true); + expect(isDenied("sh -c 'git add -A'")).toBe(true); + expect(isDenied('eval "git reset --hard"')).toBe(true); + }); + + it('still allows inert quoted text passed to -c-like flags when it names no dangerous verb', () => { + expect(isDenied('bash -c "echo hello"')).toBe(false); + }); + it('does not block a commit whose heredoc-authored message body mentions git clean', () => { // CLAUDE.md mandates exactly this heredoc form for commit messages — // a real commit whose message discusses (or fixes) git clean, like this From 83bf4d41e1550977587b2c3b231ef9f14de08201 Mon Sep 17 00:00:00 2001 From: carlos-alm Date: Fri, 7 Aug 2026 12:33:19 -0600 Subject: [PATCH 3/3] fix(hooks): address round-2 review feedback - background op, pathspecs, command substitution (#2099) Three more bypasses surfaced on re-review: 1. The segment splitter only recognized && as a separator, not a standalone & (background execution) - a flag on a &-separated command could still suppress the block for an unrelated, actually-destructive clean. 2. Tokens after a bare -- were still matched as options - git itself treats everything after -- as a literal pathspec, so "-f -- -n" was read as force-with-dry-run instead of force-with-a-path-named-"-n". 3. $(...) and backtick command substitution execute even inside an ordinary double-quoted argument (single quotes are the only thing that suppresses this) and inside a heredoc body whose delimiter is unquoted - masking those spans hid a genuinely executed nested command. Such spans are now always left unmasked (with balanced paren/backtick matching), and NCOMMAND normalization now also treats the resulting bare (/)/backtick delimiters as boundaries, since they'd otherwise sit directly adjacent to the verb and defeat the whitespace-anchored checks. docs check acknowledged --- .claude/hooks/check-git-clean-force.mjs | 20 +++-- .claude/hooks/guard-git.sh | 37 ++++---- .claude/hooks/mask-quoted-text.mjs | 111 ++++++++++++++++++++---- tests/unit/hook-guard-git-clean.test.ts | 42 +++++++++ 4 files changed, 169 insertions(+), 41 deletions(-) diff --git a/.claude/hooks/check-git-clean-force.mjs b/.claude/hooks/check-git-clean-force.mjs index 7fe30136e..ceb993a85 100644 --- a/.claude/hooks/check-git-clean-force.mjs +++ b/.claude/hooks/check-git-clean-force.mjs @@ -5,17 +5,21 @@ // otherwise prints nothing. Used by guard-git.sh (#2099). // // Splits into logical command segments on every real shell command -// separator (&&, ||, ;, |, newline) — not just `&&` — so a flag on one +// separator (&&, &, ||, ;, |, newline) — not just `&&` — so a flag on one // command can never be misread as belonging to an unrelated `git clean` on -// a different segment (Greptile review: `git clean -fd; ls -n` must still -// block, since the `-n` belongs to `ls`, not the clean invocation). +// a different segment (Greptile review: `git clean -fd; ls -n` and +// `git clean -fd & ls -n` must still block, since the `-n` belongs to the +// other command, not the clean invocation). // // Within a segment, flags are matched against whole whitespace-separated // tokens (not a substring/boundary regex against the raw segment text), so // bundled short options are recognized correctly: `-ndf` and `-fnd` both // carry both `-n` and `-f`, matching git's own bundled short-flag parsing. +// Tokens at or after a bare `--` are pathspecs, not options (git's own +// convention) — `git clean -f -- -n` must still block, since the trailing +// `-n` names a literal path, not a dry-run flag (Greptile review). -const SEGMENT_SEPARATOR = /&&|\|\||[;|\n]/; +const SEGMENT_SEPARATOR = /&&|&|\|\||[;|\n]/; const CLEAN_INVOCATION = /(^|\s)git\s+clean(\s|$)/; const FORCE_TOKEN = /^(--force|-[a-zA-Z]*f[a-zA-Z]*)$/; const DRY_RUN_TOKEN = /^(--dry-run|-[a-zA-Z]*n[a-zA-Z]*)$/; @@ -28,9 +32,11 @@ process.stdin.on('end', () => { const segments = input.split(SEGMENT_SEPARATOR); for (const segment of segments) { if (!CLEAN_INVOCATION.test(segment)) continue; - const tokens = segment.trim().split(/\s+/); - const hasForce = tokens.some((t) => FORCE_TOKEN.test(t)); - const hasDryRun = tokens.some((t) => DRY_RUN_TOKEN.test(t)); + const allTokens = segment.trim().split(/\s+/); + const pathspecBoundary = allTokens.indexOf('--'); + const optionTokens = pathspecBoundary === -1 ? allTokens : allTokens.slice(0, pathspecBoundary); + const hasForce = optionTokens.some((t) => FORCE_TOKEN.test(t)); + const hasDryRun = optionTokens.some((t) => DRY_RUN_TOKEN.test(t)); if (hasForce && !hasDryRun) { process.stdout.write('BLOCK'); return; diff --git a/.claude/hooks/guard-git.sh b/.claude/hooks/guard-git.sh index 3bfe537d5..c22273800 100644 --- a/.claude/hooks/guard-git.sh +++ b/.claude/hooks/guard-git.sh @@ -21,14 +21,15 @@ if [ -z "$COMMAND" ]; then exit 0 fi -# Act on git and gh commands (may appear after cd "..." && or inside a quoted -# nested-shell invocation, e.g. `bash -c "git clean -fd"` — #2099 Greptile -# review). This is only a cheap fast-path skip, so it's deliberately -# permissive (["'] as an extra allowed prefix boundary alongside -# start/whitespace/&&) rather than exact: a false "yes" here just means the -# rest of the script runs its checks anyway, while a false "no" would exit -# before ever reaching them. -if ! echo "$COMMAND" | grep -qE '(^|[[:space:]]|&&[[:space:]]*|["'"'"'])(git|gh)[[:space:]]+'; then +# Act on git and gh commands (may appear after cd "..." &&, inside a quoted +# nested-shell invocation like `bash -c "git clean -fd"`, or inside a command +# substitution like `"message $(git clean -fd)"` — #2099 Greptile review). +# This is only a cheap fast-path skip, so it's deliberately permissive +# (["'`(] as extra allowed prefix boundaries alongside start/whitespace/&&) +# rather than exact: a false "yes" here just means the rest of the script +# runs its checks anyway, while a false "no" would exit before ever reaching +# them. +if ! echo "$COMMAND" | grep -qE '(^|[[:space:]]|&&[[:space:]]*|["'"'"'`(])(git|gh)[[:space:]]+'; then exit 0 fi @@ -57,15 +58,17 @@ fi NCOMMAND=$(echo "$MASKED_COMMAND" | sed -E 's/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+"[^"]+"/\1git/g; s/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+[^"[:space:]][^[:space:]]*/\1git/g') NCOMMAND=$(echo "$NCOMMAND" | sed -E 's/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+"[^"]+"/\1git/g; s/(^|[[:space:]]|&&[[:space:]]*)git[[:space:]]+-C[[:space:]]+[^"[:space:]][^[:space:]]*/\1git/g') -# Strip any remaining literal quote characters from NCOMMAND (#2099 Greptile -# review): an exec-triggered quote (`bash -c "git clean -fd"`) is left -# unmasked by mask-quoted-text.mjs, but its quote DELIMITERS survive — e.g. -# `"git` — which sit directly adjacent to the verb, defeating every -# `(^|[[:space:]])`-anchored check below. NCOMMAND is used exclusively for -# verb detection (never for value extraction — detect_work_dir/MSG_FILE read -# the raw $COMMAND instead), so quote characters carry no meaning here once -# masking has already run. -NCOMMAND=$(echo "$NCOMMAND" | sed -E "s/[\"']/ /g") +# Strip any remaining literal quote/substitution-delimiter characters from +# NCOMMAND (#2099 Greptile review): an exec-triggered quote +# (`bash -c "git clean -fd"`) or a command substitution +# (`"message $(git clean -fd)"`, which executes even inside an otherwise +# masked double-quoted string) is left unmasked by mask-quoted-text.mjs, but +# its delimiters survive — e.g. `"git` or `$(git` — sitting directly adjacent +# to the verb, defeating every `(^|[[:space:]])`-anchored check below. +# NCOMMAND is used exclusively for verb detection (never for value +# extraction — detect_work_dir/MSG_FILE read the raw $COMMAND instead), so +# these characters carry no meaning here once masking has already run. +NCOMMAND=$(echo "$NCOMMAND" | sed -E "s/[\"'\`()]/ /g") deny() { local reason="$1" diff --git a/.claude/hooks/mask-quoted-text.mjs b/.claude/hooks/mask-quoted-text.mjs index 9c58072a2..5c13945cc 100644 --- a/.claude/hooks/mask-quoted-text.mjs +++ b/.claude/hooks/mask-quoted-text.mjs @@ -15,27 +15,34 @@ // the message text is data, not commands, but sits outside any single-line // quote pair. // -// EXEC_TRIGGER_TOKENS (Greptile review on #2099's own PR): a quote or -// heredoc immediately following `-c`/`--command`/`-e`/`--eval`/`eval` is not -// inert data — shells and interpreters (`bash -c "..."`, `sh -c '...'`, -// `node -e "..."`, `eval "..."`) execute that string as real code. Masking -// it would hide a genuine `git clean -fd` payload from every verb-detection -// check below. Such quotes/heredocs are left completely unmasked instead. -// This is a token-adjacency heuristic, not full shell-grammar parsing — it -// does not resolve indirection (e.g. a variable holding `-c`), matching the -// tolerance for edge cases already accepted by guard-git.sh's other -// regex-based checks. +// EXEC_TRIGGER_TOKENS (Greptile review): a quote or heredoc immediately +// following `-c`/`--command`/`-e`/`--eval`/`eval` is not inert data — shells +// and interpreters (`bash -c "..."`, `sh -c '...'`, `node -e "..."`, +// `eval "..."`) execute that string as real code. Masking it would hide a +// genuine `git clean -fd` payload from every verb-detection check below. +// Such quotes/heredocs are left completely unmasked instead. +// +// COMMAND SUBSTITUTION (Greptile review): `$(...)` and `` `...` `` execute +// their contents even inside an ORDINARY double-quoted string that is +// otherwise inert data (`git commit -m "message $(git clean -fd)"` really +// does run `git clean -fd` when bash expands it) — single quotes are the +// only quoting that suppresses this. The same applies inside a heredoc body +// whose delimiter is UNQUOTED (`< 0; j++) { + span += text[j]; + if (text[j] === '(') depth++; + else if (text[j] === ')') depth--; + } + return { span, nextIndex: j }; + } + if (text[i] === '`') { + let j = i + 1; + let span = '`'; + for (; j < text.length; j++) { + span += text[j]; + if (text[j] === '`') { + j++; + break; + } + } + return { span, nextIndex: j }; + } + return null; +} + +/** + * Mask every character in `text` to `#` (preserving newlines), except for + * `$(...)`/`` `...` `` spans (see `scanCommandSubstitution`), which are + * copied verbatim — those execute unconditionally in real bash wherever + * expansion is active at all, regardless of surrounding masking context. + */ +function maskExceptCommandSubstitution(text) { + let out = ''; + for (let i = 0; i < text.length; i++) { + const sub = scanCommandSubstitution(text, i); + if (sub) { + out += sub.span; + i = sub.nextIndex - 1; + continue; + } + out += text[i] === '\n' ? '\n' : '#'; + } + return out; +} + function maskHeredocBodies(text) { const lines = text.split('\n'); const out = []; let delimiter = null; let execTriggered = false; + let delimiterQuoted = false; for (const line of lines) { if (delimiter !== null) { if (line.trim() === delimiter) { @@ -59,8 +120,12 @@ function maskHeredocBodies(text) { out.push(line); } else if (execTriggered) { out.push(line); - } else { + } else if (delimiterQuoted) { out.push('#'.repeat(line.length)); + } else { + // Unquoted heredoc delimiter (`< { expect(isDenied('git clean -fd | cat -n')).toBe(true); expect(isDenied('git clean -fd\nls -n')).toBe(true); }); + + it('does not let a standalone & (background) separator leak a flag across commands', () => { + // Greptile review (round 2): the segment splitter initially only + // recognized && as a separator, not a lone &. + expect(isDenied('git clean -fd & ls -n')).toBe(true); + }); + + it('does not treat a pathspec after -- as a dry-run flag', () => { + // Greptile review (round 2): `-n` after `--` names a literal path, not + // an option — git's own convention for disambiguating dash-prefixed + // pathspecs from flags. + expect(isDenied('git clean -f -- -n')).toBe(true); + }); + + it('still recognizes a real -n option before the -- pathspec boundary', () => { + expect(isDenied('git clean -fn -- -weird-file')).toBe(false); + }); }); describe('guard-git.sh does not false-positive on quoted text (#2099)', () => { @@ -129,6 +146,31 @@ describe('guard-git.sh does not false-positive on quoted text (#2099)', () => { expect(isDenied('bash -c "echo hello"')).toBe(false); }); + it('still blocks a command substitution inside an ordinary double-quoted argument (Greptile review)', () => { + // $(...) and `...` execute even inside an otherwise-inert double-quoted + // string — real bash actually runs `git clean -fd` here when expanding + // the -m argument, regardless of it being "just a commit message". + expect(isDenied('git commit -m "message $(git clean -fd)"')).toBe(true); + expect(isDenied('git commit -m "message `git add -A`"')).toBe(true); + }); + + it('does not treat command substitution inside a SINGLE-quoted argument as executable', () => { + // Single quotes suppress all expansion in real bash — $(...) there is + // genuinely inert literal text. + expect(isDenied("git commit -m 'message $(git clean -fd)'")).toBe(false); + }); + + it('still blocks command substitution inside an unquoted-delimiter heredoc body', () => { + // < { + const command = [`cat <<'EOF'`, `text $(git clean -fd) more text`, `EOF`].join('\n'); + expect(isDenied(command)).toBe(false); + }); + it('does not block a commit whose heredoc-authored message body mentions git clean', () => { // CLAUDE.md mandates exactly this heredoc form for commit messages — // a real commit whose message discusses (or fixes) git clean, like this