From fd6c7c4864b30b5588597fa38b77a55bc9aa22ab Mon Sep 17 00:00:00 2001 From: Parman Mohammadalizadeh Date: Thu, 5 Nov 2026 16:36:13 +0100 Subject: [PATCH] fix(hooks): block pre-bash when the command cannot be validated pre-bash exited 0 on every failure path, so a command passed whenever the hook input arrived after the 500 ms stdin window, failed to parse, or raised an exception, and when the 5 s safety timer fired. pre-bash now exits 2 with a [BLOCKED] reason when no command string was obtained, when stdin is not valid JSON, in the handler and main catch paths, and from the safety timer. Every other hook keeps exiting 0. Fixes #4743 --- .claude/helpers/hook-handler.cjs | 25 +++++--- .../cli/.claude/helpers/hook-handler.cjs | 25 +++++--- .../issue-4743-pre-bash-fail-closed.test.ts | 62 +++++++++++++++++++ 3 files changed, 98 insertions(+), 14 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/issue-4743-pre-bash-fail-closed.test.ts diff --git a/.claude/helpers/hook-handler.cjs b/.claude/helpers/hook-handler.cjs index 89e6f95177..17e2930663 100755 --- a/.claude/helpers/hook-handler.cjs +++ b/.claude/helpers/hook-handler.cjs @@ -779,12 +779,19 @@ function claimSideEffectEvent(family, stdinData, event) { } } +// pre-bash is a gate (#4743): a path that cannot vouch for the command blocks it. +function blockPreBash(reason) { + console.error(`[BLOCKED] ${reason}`); + process.exit(2); +} + async function main() { if (ownedByMod(command)) return; // Global safety timeout: hooks must NEVER hang (#1530, #1531) const safetyTimer = setTimeout(() => { process.stderr.write("[WARN] Hook handler global timeout (5s), forcing exit\n"); + if (command === 'pre-bash') blockPreBash('pre-bash timed out before the command was validated'); process.exit(0); }, 5000); safetyTimer.unref(); // don't keep process alive just for this timer @@ -793,8 +800,9 @@ async function main() { try { stdinData = await readStdin(); } catch (e) { /* ignore stdin errors */ } let hookInput = {}; + let stdinUnparsable = false; if (stdinData.trim()) { - try { hookInput = JSON.parse(stdinData); } catch (e) { /* ignore parse errors */ } + try { hookInput = JSON.parse(stdinData); } catch (e) { stdinUnparsable = true; } } // ADR-512: record what finished and train from it, before the dedup below: it keys session-end @@ -954,11 +962,12 @@ const handlers = { 'pre-bash': () => { // Basic command safety check — prefer stdin command data from Claude Code. - // String() wrap is belt-and-suspenders for #2017: even if a future regression - // re-binds `prompt` or `hookInput.command` to a non-string, `.toLowerCase()` - // can no longer throw a TypeError that the global try/catch would swallow - // (silently exiting 0 and letting the dangerous command through). - const cmd = String(hookInput.command || toolInput.command || prompt || '').toLowerCase(); + // Only a non-empty string counts as the command (#2017, #4743): input that + // arrived late, did not parse, or carried no command blocks instead of passing. + if (stdinUnparsable) blockPreBash('pre-bash could not parse the hook input'); + const raw = [hookInput.command, toolInput.command, prompt].find((c) => typeof c === 'string' && c.trim()); + if (!raw) blockPreBash('pre-bash received no command to validate'); + const cmd = raw.toLowerCase(); const dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:']; // Join literal quote fragments and normalize root paths without shell evaluation. function hasRootDelete(command, depth = 0) { @@ -1308,6 +1317,7 @@ const handlers = { try { await Promise.resolve(handlers[command]()); } catch (e) { + if (command === 'pre-bash') blockPreBash(`pre-bash failed: ${e && e.message}`); // Hooks should never crash Claude Code - fail silently console.log(`[WARN] Hook ${command} encountered an error: ${e.message}`); } @@ -1319,7 +1329,7 @@ const handlers = { } } -// Non-blocking hooks exit 0; pre-bash denials exit 2 to block PreToolUse. +// Non-blocking hooks exit 0; pre-bash denials and failures exit 2 to block PreToolUse. // A denial exits immediately, before the normal completion path below. // // Only dispatch when run directly (node hook-handler.cjs ). When @@ -1331,6 +1341,7 @@ const handlers = { if (require.main === module) { process.exitCode = 0; main().catch((e) => { + if (command === 'pre-bash') blockPreBash(`pre-bash failed: ${e && e.message}`); try { console.log(`[WARN] Hook handler error: ${e.message}`); } catch (_) {} }).finally(() => { process.exit(0); diff --git a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs index 89e6f95177..17e2930663 100755 --- a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs +++ b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs @@ -779,12 +779,19 @@ function claimSideEffectEvent(family, stdinData, event) { } } +// pre-bash is a gate (#4743): a path that cannot vouch for the command blocks it. +function blockPreBash(reason) { + console.error(`[BLOCKED] ${reason}`); + process.exit(2); +} + async function main() { if (ownedByMod(command)) return; // Global safety timeout: hooks must NEVER hang (#1530, #1531) const safetyTimer = setTimeout(() => { process.stderr.write("[WARN] Hook handler global timeout (5s), forcing exit\n"); + if (command === 'pre-bash') blockPreBash('pre-bash timed out before the command was validated'); process.exit(0); }, 5000); safetyTimer.unref(); // don't keep process alive just for this timer @@ -793,8 +800,9 @@ async function main() { try { stdinData = await readStdin(); } catch (e) { /* ignore stdin errors */ } let hookInput = {}; + let stdinUnparsable = false; if (stdinData.trim()) { - try { hookInput = JSON.parse(stdinData); } catch (e) { /* ignore parse errors */ } + try { hookInput = JSON.parse(stdinData); } catch (e) { stdinUnparsable = true; } } // ADR-512: record what finished and train from it, before the dedup below: it keys session-end @@ -954,11 +962,12 @@ const handlers = { 'pre-bash': () => { // Basic command safety check — prefer stdin command data from Claude Code. - // String() wrap is belt-and-suspenders for #2017: even if a future regression - // re-binds `prompt` or `hookInput.command` to a non-string, `.toLowerCase()` - // can no longer throw a TypeError that the global try/catch would swallow - // (silently exiting 0 and letting the dangerous command through). - const cmd = String(hookInput.command || toolInput.command || prompt || '').toLowerCase(); + // Only a non-empty string counts as the command (#2017, #4743): input that + // arrived late, did not parse, or carried no command blocks instead of passing. + if (stdinUnparsable) blockPreBash('pre-bash could not parse the hook input'); + const raw = [hookInput.command, toolInput.command, prompt].find((c) => typeof c === 'string' && c.trim()); + if (!raw) blockPreBash('pre-bash received no command to validate'); + const cmd = raw.toLowerCase(); const dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:']; // Join literal quote fragments and normalize root paths without shell evaluation. function hasRootDelete(command, depth = 0) { @@ -1308,6 +1317,7 @@ const handlers = { try { await Promise.resolve(handlers[command]()); } catch (e) { + if (command === 'pre-bash') blockPreBash(`pre-bash failed: ${e && e.message}`); // Hooks should never crash Claude Code - fail silently console.log(`[WARN] Hook ${command} encountered an error: ${e.message}`); } @@ -1319,7 +1329,7 @@ const handlers = { } } -// Non-blocking hooks exit 0; pre-bash denials exit 2 to block PreToolUse. +// Non-blocking hooks exit 0; pre-bash denials and failures exit 2 to block PreToolUse. // A denial exits immediately, before the normal completion path below. // // Only dispatch when run directly (node hook-handler.cjs ). When @@ -1331,6 +1341,7 @@ const handlers = { if (require.main === module) { process.exitCode = 0; main().catch((e) => { + if (command === 'pre-bash') blockPreBash(`pre-bash failed: ${e && e.message}`); try { console.log(`[WARN] Hook handler error: ${e.message}`); } catch (_) {} }).finally(() => { process.exit(0); diff --git a/v3/@claude-flow/cli/__tests__/issue-4743-pre-bash-fail-closed.test.ts b/v3/@claude-flow/cli/__tests__/issue-4743-pre-bash-fail-closed.test.ts new file mode 100644 index 0000000000..71117e4e40 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/issue-4743-pre-bash-fail-closed.test.ts @@ -0,0 +1,62 @@ +/** Regression coverage for issue #4743: pre-bash blocks when it cannot read + * a command (late stdin, unparsable input, a thrown error), while the other + * hooks keep exiting 0 on the same input. */ +import { afterAll, describe, expect, it } from 'vitest'; +import { spawn, spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +const HELPER = path.resolve(__dirname, '../.claude/helpers/hook-handler.cjs'); +const project = mkdtempSync(path.join(tmpdir(), 'ruflo-4743-')); +const env = { ...process.env, CLAUDE_PROJECT_DIR: project, RUFLO_MODS_OWNS: '', PROMPT: '', TOOL_INPUT_command: '' }; + +afterAll(() => rmSync(project, { recursive: true, force: true })); + +function run(hook: string, input: string) { + return spawnSync(process.execPath, [HELPER, hook], { input, encoding: 'utf8', cwd: project, env, timeout: 10_000 }); +} + +describe('pre-bash fails closed — issue #4743', () => { + it.each([ + ['empty payload', '{}'], + ['null command', JSON.stringify({ tool_input: { command: null } })], + ['object command', JSON.stringify({ tool_input: { command: {} } })], + ['blank command', JSON.stringify({ tool_input: { command: ' ' } })], + ['unparsable input', '{"tool_input":{"command":"rm -rf /"'], + ['input that throws in main', 'null'], + ])('blocks on %s', (_name, input) => { + const r = run('pre-bash', input); + expect(r.status).toBe(2); + expect(r.stderr).toContain('[BLOCKED]'); + expect(r.stdout).not.toContain('[OK]'); + }); + + it('blocks when the input arrives after the stdin window', async () => { + const child = spawn(process.execPath, [HELPER, 'pre-bash'], { cwd: project, env }); + let stderr = ''; + child.stderr.on('data', (chunk) => { stderr += chunk; }); + const status = await new Promise((resolve) => { + child.on('close', resolve); + setTimeout(() => { + if (child.stdin.writable) child.stdin.end(JSON.stringify({ tool_input: { command: 'rm -rf /' } })); + }, 900); + }); + expect(status).toBe(2); + expect(stderr).toContain('[BLOCKED]'); + }); + + it('still validates a safe command and blocks a dangerous one', () => { + expect(run('pre-bash', JSON.stringify({ tool_input: { command: 'ls -la' } })).status).toBe(0); + expect(run('pre-bash', JSON.stringify({ tool_input: { command: 'rm -rf /' } })).status).toBe(2); + }); + + it.each([ + ['route', 'null'], + ['post-edit', '{"tool_input":'], + ])('%s stays non-blocking on bad input', (hook, input) => { + const r = run(hook, input); + expect(r.status).toBe(0); + expect(r.stderr).not.toContain('[BLOCKED]'); + }); +});