mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 06:21:59 +09:00
Merge PR #4826
This commit is contained in:
commit
f9063010a2
3 files changed
+98
-14
No files matched your search
@@ -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 <cmd>). 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);
|
||||
|
||||
@@ -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 <cmd>). 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);
|
||||
|
||||
@@ -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<number | null>((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]');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user