Repository navigation
Expand file tree
/
Copy pathguard-pack.js
More file actions
166 lines (154 loc) · 7.24 KB
/
Copy pathguard-pack.js
File metadata and controls
166 lines (154 loc) · 7.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#!/usr/bin/env node
/**
* Guard Pack - PreToolUse Hook for Bash|Read|Edit|MultiEdit|Write|Agent|Task|Grep
* All seven guard hooks in ONE Node process. Installing the guards
* individually costs seven Node startups per matching tool call (about
* 35 ms each, see bench/RESULTS.md); this pack pays one.
*
* Evaluation order (cheap checks first, filesystem and subprocess work
* last): subagent-spawn-cap, config-guard, block-dangerous-commands,
* protect-secrets, protect-tests, git-safety, case-insensitive-guard. The
* first deny wins; an ask is held while the later guards run, because a
* later deny must outrank it (deny > ask, as when the standalone hooks run
* side by side). The verdict is emitted in that guard's own output
* format, suffixed "(via guard-pack)". A guard that throws is logged and
* the rest still run, so a real deny keeps its own reason; if none denies,
* the call is denied as a guard error (fail-closed, same as the standalone
* hooks; HOOK_FAIL_OPEN=true skips the broken guard instead).
*
* The seven guard scripts in lib/ are byte-identical copies of the individual
* plugin scripts; a repo test pins them, so they cannot drift. lib/host.js is
* the pack's own Codex adapter, not a copy. All the
* guards' env vars pass straight through, since the modules read them
* directly: HOOK_SAFETY_LEVEL (the six pattern guards uniformly),
* HOOK_ASK_CRITICAL / HOOK_ASK_HIGH / HOOK_ASK_STRICT, CONFIG_GUARD_ALLOW,
* and SPAWN_CAP_ASK / SPAWN_CAP_ASK_STEP / SPAWN_CAP_DENY / SPAWN_CAP_ALLOW.
* Want different safety levels per guard? Install the individual guard
* plugins instead of the pack.
*
* Do NOT install this pack alongside the individual guard plugins (or a
* manual registration of any of the seven): every duplicated guard runs
* twice on each matching tool call. Logs to: ~/.claude/hooks-logs/
*
* Codex CLI: .codex-plugin/plugin.json registers hooks/codex-hooks.json, which
* runs this script with --host codex on Bash and apply_patch; lib/host.js turns
* each patch into Claude-shaped Write/Edit/rm/mv calls for the same guards.
*
* Setup (plugin, recommended):
* /plugin marketplace add karanb192/claude-code-hooks
* /plugin install guard-pack@claude-code-hooks
* The plugin's hooks/hooks.json registers this script automatically.
*/
const fs = require('fs');
const path = require('path');
const LIB = path.join(__dirname, 'lib');
const host = require('./lib/host');
const LOG_DIR = path.join(process.env.HOME || process.env.USERPROFILE || require('os').homedir(), '.claude', 'hooks-logs');
const { GUARDS, failOpen, guardErrorReason } = require('./lib/dispatch');
const PACK_TOOLS = ['Bash', 'Read', 'Edit', 'MultiEdit', 'Write', 'Agent', 'Task', 'Grep'];
const ERROR_EMOJIS = { critical: '🚨' };
function log(data) {
try {
if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });
const file = path.join(LOG_DIR, `${new Date().toISOString().slice(0, 10)}.jsonl`);
fs.appendFileSync(file, JSON.stringify({ ts: new Date().toISOString(), hook: 'guard-pack', ...data }) + '\n');
} catch {}
}
// Evaluate all guards for one event; returns null or the winning verdict
// with its guard attached. Exported for tests.
function evaluate(toolName, toolInput, cwd, event) {
let ask = null;
let error = null;
for (const g of GUARDS) {
try {
if (g.skip && g.skip()) continue;
const mod = require(path.join(LIB, `${g.name}.js`));
const verdict = g.run(mod, toolName, toolInput, cwd, event);
if (!verdict) continue;
const hit = { guard: g.name, emojis: g.emojis, ...verdict };
if (!hit.ask) return hit;
ask = ask || hit;
} catch (e) {
log({ level: 'ERROR', guard: g.name, error: e.message });
if (!error && !failOpen()) error = { guard: g.name, emojis: ERROR_EMOJIS, id: 'guard-error', level: 'critical', ask: false, reason: guardErrorReason(g.name, e) };
}
}
return error || ask;
}
// Codex: check every Claude-shaped call a patch or command turns into, then
// answer with exit 2 and the reason on stderr. Codex cannot ask, so an ask
// verdict is sent as a block that says so.
function codexVerdict(data) {
let ask = null;
for (const call of host.codexCalls(data)) {
if (call.unreadable) return { reason: host.UNREADABLE_REASON, decision: 'deny', id: 'unreadable-patch', tool: data.tool_name };
if (!PACK_TOOLS.includes(call.tool)) continue;
const v = evaluate(call.tool, call.input, data.cwd, { ...data, hook_host: 'codex', tool_name: call.tool, tool_input: call.input });
if (!v) continue;
const hit = { ...v, tool: call.tool };
if (!v.ask) return { hit, decision: 'deny' };
ask = ask || hit;
}
return ask ? { hit: ask, decision: 'ask' } : null;
}
function runCodex(input) {
let answer = host.codexAnswer('');
let data;
try {
data = JSON.parse(input);
const r = codexVerdict(data);
if (r) {
const { session_id, cwd, permission_mode } = data;
if (r.hit) {
const v = r.hit;
log({ level: r.decision === 'ask' ? 'ASK' : 'BLOCKED', host: 'codex', guard: v.guard, id: v.id, priority: v.level, decision: 'deny', tool: data.tool_name, checked: v.tool, ...(v.log || {}), session_id, cwd, permission_mode });
answer = host.codexAnswer(`${v.emojis[v.level]} ${v.reason} (via guard-pack)${r.decision === 'ask' ? host.ASK_ON_CODEX : ''}`);
} else {
log({ level: 'BLOCKED', host: 'codex', id: r.id, decision: 'deny', tool: r.tool, session_id, cwd, permission_mode });
answer = host.codexAnswer(r.reason);
}
}
} catch (e) {
log({ level: 'ERROR', host: 'codex', error: e.message });
if (data !== null && typeof data === 'object' && !failOpen()) answer = host.codexAnswer(`${ERROR_EMOJIS.critical} ${guardErrorReason('guard-pack', e)}`);
}
if (answer.stderr) process.stderr.write(answer.stderr);
process.exitCode = answer.exitCode;
}
async function main() {
let input = '';
for await (const chunk of process.stdin) input += chunk;
if (host.hostFromArgv(process.argv) === 'codex') return runCodex(input);
let data;
try {
data = JSON.parse(input);
const { tool_name, tool_input, session_id, cwd, permission_mode } = data;
if (!PACK_TOOLS.includes(tool_name)) return console.log('{}');
const v = evaluate(tool_name, tool_input, cwd, data);
if (!v) return console.log('{}');
const decision = v.ask ? 'ask' : 'deny';
log({ level: v.ask ? 'ASK' : 'BLOCKED', guard: v.guard, id: v.id, priority: v.level, decision, tool: tool_name, ...(v.log || {}), session_id, cwd, permission_mode });
return console.log(JSON.stringify({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: decision,
permissionDecisionReason: `${v.emojis[v.level]} ${v.reason} (via guard-pack)`,
},
}));
} catch (e) {
log({ level: 'ERROR', error: e.message });
if (data === null || typeof data !== 'object' || failOpen()) return console.log('{}');
console.log(JSON.stringify({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: 'deny',
permissionDecisionReason: `${ERROR_EMOJIS.critical} ${guardErrorReason('guard-pack', e)}`,
},
}));
}
}
if (require.main === module) {
main();
} else {
module.exports = { GUARDS, PACK_TOOLS, evaluate, codexVerdict };
}