@codewizard-dt/bootstrap 2.14.0 → 2.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/hooks/README.md +592 -12
- package/lib/hooks/absolute-path-guard.js +142 -0
- package/lib/hooks/claude-settings-guard.js +235 -0
- package/lib/hooks/env-content-read-guard.js +367 -0
- package/lib/hooks/git-protected-ops-block.js +12 -7
- package/lib/hooks/interpreter-indirection-guard.js +576 -0
- package/lib/hooks/lib/command-parse.js +63 -0
- package/lib/hooks/package-install-consent.js +151 -0
- package/lib/hooks/protected-write-guard.js +237 -0
- package/lib/scripts/README.md +62 -5
- package/lib/scripts/build-mcp-guide.sh +9 -1
- package/lib/scripts/install-global.sh +25 -2
- package/lib/scripts/install-mcps.sh +140 -36
- package/lib/scripts/lib.sh +10 -6
- package/lib/scripts/merge-gitignore.sh +163 -27
- package/lib/scripts/merge-settings-deny.js +112 -39
- package/lib/scripts/templates/file-suggestion.sh +142 -0
- package/lib/scripts/templates/gitignore +8 -0
- package/lib/scripts/templates/guides/stubs/playwright.md +2 -0
- package/lib/scripts/templates/settings-deny.json +81 -1
- package/lib/skills/debug-logs/SKILL.md +1 -1
- package/lib/skills/git-commit/SKILL.md +8 -0
- package/package.json +5 -2
- package/raw/research/brave-mcp-single-docker-container/index.md +0 -94
- package/raw/research/brave-mcp-single-docker-container/sources.md +0 -70
- package/raw/research/dark-mode-theme/index.md +0 -85
- package/raw/research/dark-mode-theme/sources.md +0 -49
- package/raw/research/mcp-add-scope-writes/index.md +0 -46
- package/raw/research/mcp-add-scope-writes/sources.md +0 -38
- package/raw/research/mcp-one-process-per-user/index.md +0 -75
- package/raw/research/mcp-one-process-per-user/sources.md +0 -66
- package/raw/research/mcp-scope-conflict-handling/index.md +0 -61
- package/raw/research/mcp-scope-conflict-handling/sources.md +0 -32
- package/raw/research/serena-mcp-disconnect/index.md +0 -81
- package/raw/research/serena-mcp-disconnect/sources.md +0 -87
- package/raw/research/wiki-tooling-improvements/index.md +0 -126
- package/raw/research/wiki-tooling-improvements/sources.md +0 -73
- package/raw/software-factory-case-study.pdf +0 -0
|
@@ -0,0 +1,576 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
// interpreter-indirection-guard.js — PreToolUse hook (matcher: Bash)
|
|
5
|
+
//
|
|
6
|
+
// Blocks two forms of interpreter indirection in ANY segment of a Bash command:
|
|
7
|
+
// 1. an interpreter given its program as an inline argument — `bash -c '…'`,
|
|
8
|
+
// `sh -c`, `zsh -c`, `python -c`, `python3 -c`, `node -e`, `node --eval`,
|
|
9
|
+
// `ruby -e`, `perl -e`
|
|
10
|
+
// 2. an interpreter whose program is a command substitution — `sh -c "$(curl …)"`,
|
|
11
|
+
// `` bash `curl …` ``
|
|
12
|
+
//
|
|
13
|
+
// Why a hook and not a deny rule: a deny rule matches the literal spelling of a
|
|
14
|
+
// command. The entire point of `-c` is that the real command lives inside a
|
|
15
|
+
// quoted string, where no permission pattern can reach it — one approved
|
|
16
|
+
// `bash -c` can carry a fetcher, a redirect into ~/.zshrc, or an absolute-path
|
|
17
|
+
// `rm`. A hook receives the raw, undecomposed string and can parse the
|
|
18
|
+
// invocation form itself, and can return a reason explaining the alternative.
|
|
19
|
+
//
|
|
20
|
+
// The interpreter token is matched on its BASENAME with leading backslashes
|
|
21
|
+
// stripped, so `/bin/bash -c`, `env bash -c`, and `\bash -c` are all caught
|
|
22
|
+
// where a literal `bash -c` deny pattern is not.
|
|
23
|
+
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
// RECURSIVE RE-EVALUATION, not blanket deny (TASK-028). The rule this hook now
|
|
26
|
+
// enforces is: *you may not use `bash -c` to do something you could not do
|
|
27
|
+
// without it.*
|
|
28
|
+
//
|
|
29
|
+
// The blanket deny this replaces was justified on the grounds that inspecting
|
|
30
|
+
// the payload is defeated by one line of obfuscation
|
|
31
|
+
// (`bash -c 'c=cur;l=l;$c$l http://x'`). True — but that argument only bites
|
|
32
|
+
// against an adversary, and against an adversary this hook already fails via
|
|
33
|
+
// its own documented escape hatch: `printf '…' > /tmp/x.sh && bash /tmp/x.sh`
|
|
34
|
+
// runs the identical program and never touches this guard. So blanket deny
|
|
35
|
+
// bought nothing extra against the threat it cannot stop, while charging real
|
|
36
|
+
// friction against the mistake it actually catches — routine `node -e` and
|
|
37
|
+
// `python3 -c` one-liners were simply unavailable.
|
|
38
|
+
//
|
|
39
|
+
// Why re-evaluation rather than a substring blocklist of dangerous payloads: a
|
|
40
|
+
// fixed danger list is a SECOND matching vocabulary that drifts out of sync
|
|
41
|
+
// with the guards it duplicates. Re-running the payload through the existing
|
|
42
|
+
// guards is exactly as strong as the direct-command path by construction,
|
|
43
|
+
// needs no new vocabulary, and has near-zero false positives — anything
|
|
44
|
+
// permitted when typed directly is permitted inside `-c`.
|
|
45
|
+
//
|
|
46
|
+
// Mechanism: the sibling guards are SPAWNED as subprocesses against a
|
|
47
|
+
// synthesized PreToolUse payload. They are shipped, globally-installed
|
|
48
|
+
// controls; re-evaluation deliberately requires zero changes to them, uses
|
|
49
|
+
// them exactly as Claude Code does, and stays in sync automatically. Extracting
|
|
50
|
+
// their decision logic into shared pure functions would remove the spawns and
|
|
51
|
+
// is the better eventual refactor — it is not done here because it means
|
|
52
|
+
// editing five live controls to save a few processes.
|
|
53
|
+
//
|
|
54
|
+
// The payload is ALSO matched against `permissions.deny`, because the sibling
|
|
55
|
+
// guards do not span it: nothing in lib/hooks/ blocks a bare `rm -rf ~` or
|
|
56
|
+
// `sudo …`, and re-evaluating through the hooks alone would have opened a hole
|
|
57
|
+
// that blanket deny had closed. That check is the one place a second matching
|
|
58
|
+
// vocabulary was unavoidable; see DENY_SOURCES / patternToRegExp below.
|
|
59
|
+
//
|
|
60
|
+
// Known gaps, deliberate: other POSIX shells (`dash`, `ksh`) are not in the
|
|
61
|
+
// list, and bundled short flags (`sh -ec '…'`) are not decomposed.
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
const fs = require('fs');
|
|
65
|
+
const path = require('path');
|
|
66
|
+
const { spawnSync } = require('child_process');
|
|
67
|
+
const { readHookInput, deny, splitSegments } = require('./lib/command-parse');
|
|
68
|
+
|
|
69
|
+
// The other command-class guards, re-run against the extracted payload.
|
|
70
|
+
//
|
|
71
|
+
// interpreter-indirection-guard.js is DELIBERATELY ABSENT: spawning this hook
|
|
72
|
+
// against its own extracted payload would recurse without bound. Nesting is
|
|
73
|
+
// handled in-process by MAX_INLINE_DEPTH below, which is why it can be.
|
|
74
|
+
const SIBLING_GUARDS = [
|
|
75
|
+
'absolute-path-guard.js',
|
|
76
|
+
'protected-write-guard.js',
|
|
77
|
+
'env-content-read-guard.js',
|
|
78
|
+
'package-install-consent.js',
|
|
79
|
+
'git-protected-ops-block.js',
|
|
80
|
+
];
|
|
81
|
+
|
|
82
|
+
// A wedged sibling must not hang the tool call it was asked about. Exceeding
|
|
83
|
+
// this budget is treated as trouble, and trouble denies (see askSibling).
|
|
84
|
+
const SIBLING_TIMEOUT_MS = 2000;
|
|
85
|
+
|
|
86
|
+
// How many interpreter-indirection layers may be unwrapped before the shape
|
|
87
|
+
// itself is the objection. `bash -c "bash -c '…'"` is allowed (one nesting);
|
|
88
|
+
// a third layer is denied. Nesting is legitimate almost never and is a
|
|
89
|
+
// plausible evasion shape, but refusing to nest AT ALL would break the
|
|
90
|
+
// occasional real `ssh host bash -c` idiom, so this is a cap, not a ban.
|
|
91
|
+
const MAX_INLINE_DEPTH = 2;
|
|
92
|
+
|
|
93
|
+
// Interpreter basename → flags that make the NEXT argument an inline program.
|
|
94
|
+
const EVAL_FLAGS = new Map([
|
|
95
|
+
['bash', ['-c']],
|
|
96
|
+
['sh', ['-c']],
|
|
97
|
+
['zsh', ['-c']],
|
|
98
|
+
['python', ['-c']],
|
|
99
|
+
['python3', ['-c']],
|
|
100
|
+
['node', ['-e', '--eval']],
|
|
101
|
+
['ruby', ['-e']],
|
|
102
|
+
['perl', ['-e']],
|
|
103
|
+
]);
|
|
104
|
+
|
|
105
|
+
// Offset-preserving counterparts of splitSegments/tokenize from
|
|
106
|
+
// ./lib/command-parse. The shared helpers discard positions, and the payload
|
|
107
|
+
// after an eval flag can only be isolated from the raw string (see
|
|
108
|
+
// extractPayload), so every match has to carry its index in the command.
|
|
109
|
+
function segmentsWithOffsets(cmd) {
|
|
110
|
+
// Capturing split: even indices are segments, odd indices are the separators.
|
|
111
|
+
const parts = String(cmd ?? '').split(/(;|&&|\|\||\|)/);
|
|
112
|
+
const segments = [];
|
|
113
|
+
let offset = 0;
|
|
114
|
+
for (let i = 0; i < parts.length; i++) {
|
|
115
|
+
if (i % 2 === 0) segments.push({ text: parts[i], start: offset });
|
|
116
|
+
offset += parts[i].length;
|
|
117
|
+
}
|
|
118
|
+
return segments;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function tokensWithOffsets(segment, base) {
|
|
122
|
+
return [...String(segment ?? '').matchAll(/\S+/g)].map(m => ({ text: m[0], start: base + m.index }));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Returns the interpreter basename for a token, or null. Leading backslashes
|
|
126
|
+
// are stripped because `\bash` bypasses alias and shell-function lookup, and is
|
|
127
|
+
// a spelling a literal deny pattern misses.
|
|
128
|
+
function interpreterName(token) {
|
|
129
|
+
const cleaned = token.replace(/^\\+/, '');
|
|
130
|
+
const base = cleaned.slice(cleaned.lastIndexOf('/') + 1);
|
|
131
|
+
return EVAL_FLAGS.has(base) ? base : null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// `startsWith` rather than equality so the unspaced and assigned forms
|
|
135
|
+
// (`-c'echo hi'`, `--eval=code`) are caught alongside the spaced form. The
|
|
136
|
+
// LONGEST match wins: `--eval=1` also starts with `-e`, and taking that would
|
|
137
|
+
// put the payload boundary in the middle of the flag (`val=1`).
|
|
138
|
+
function matchedEvalFlag(name, token) {
|
|
139
|
+
return EVAL_FLAGS.get(name)
|
|
140
|
+
.filter(flag => token.startsWith(flag))
|
|
141
|
+
.sort((a, b) => b.length - a.length)[0] ?? null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Undo the one level of backslash-escaping a double-quoted shell string carries.
|
|
145
|
+
// Inside double quotes POSIX treats `\` as literal EXCEPT before `$`, `` ` ``,
|
|
146
|
+
// `"`, `\`, and newline — so only those five are unescaped.
|
|
147
|
+
//
|
|
148
|
+
// This is not cosmetic. Without it the nested form `bash -c "bash -c \"…\""`
|
|
149
|
+
// yields a payload still containing `\"`, which re-parses as an UNQUOTED
|
|
150
|
+
// argument and silently truncates to `\"bash` — the depth cap below would then
|
|
151
|
+
// never see the third layer it exists to stop.
|
|
152
|
+
function unescapeDoubleQuoted(body) {
|
|
153
|
+
return body.replace(/\\([$`"\\\n])/g, '$1');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Index of the quote closing the one at `open`, or -1 if it never closes.
|
|
157
|
+
// Single quotes take no escapes in POSIX shells; inside double quotes a
|
|
158
|
+
// backslash-escaped quote does not close the string.
|
|
159
|
+
function findClosingQuote(raw, open) {
|
|
160
|
+
const quote = raw[open];
|
|
161
|
+
for (let i = open + 1; i < raw.length; i++) {
|
|
162
|
+
if (quote === '"' && raw[i] === '\\') { i += 1; continue; }
|
|
163
|
+
if (raw[i] === quote) return i;
|
|
164
|
+
}
|
|
165
|
+
return -1;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Isolate the inline program that follows a matched eval flag, stripping the
|
|
169
|
+
// one layer of quoting the shell already consumed (tool_input.command carries
|
|
170
|
+
// the quotes literally).
|
|
171
|
+
//
|
|
172
|
+
// Reads the RAW command string, never the token array, because tokens lose the
|
|
173
|
+
// payload twice over: whitespace splitting shears `bash -c 'echo a b'` down to
|
|
174
|
+
// `'echo`, and segment splitting cuts on `;`/`|` with no regard for quoting, so
|
|
175
|
+
// `bash -c 'echo a; echo b'` is already truncated before tokenizing. Both are
|
|
176
|
+
// silent truncations — the extracted payload would look well-formed and be a
|
|
177
|
+
// fragment of the real one.
|
|
178
|
+
//
|
|
179
|
+
// Returns { interpreter, flag, payload, quote } for the caller to act on, or
|
|
180
|
+
// null when no payload can be isolated (flag last, unbalanced quoting, glued
|
|
181
|
+
// concatenation). null means DENY: an unparseable payload is not an allowed one.
|
|
182
|
+
function extractPayload(raw, interpreter, flag, flagStart) {
|
|
183
|
+
let i = flagStart + flag.length;
|
|
184
|
+
|
|
185
|
+
if (raw[i] === '=') i += 1; // --eval=code
|
|
186
|
+
else while (i < raw.length && /\s/.test(raw[i])) i += 1; // -c 'code' (fused -c'code' needs neither)
|
|
187
|
+
|
|
188
|
+
if (i >= raw.length) return null;
|
|
189
|
+
|
|
190
|
+
const quote = raw[i];
|
|
191
|
+
if (quote === "'" || quote === '"') {
|
|
192
|
+
const close = findClosingQuote(raw, i);
|
|
193
|
+
if (close === -1) return null;
|
|
194
|
+
// Anything glued to the closing quote is shell concatenation
|
|
195
|
+
// (`bash -c 'echo '"$X"`): the program is not the quoted span alone, and
|
|
196
|
+
// reassembling it would require expanding the parts we cannot see.
|
|
197
|
+
const after = raw[close + 1];
|
|
198
|
+
if (after !== undefined && !/\s/.test(after)) return null;
|
|
199
|
+
const body = raw.slice(i + 1, close);
|
|
200
|
+
return {
|
|
201
|
+
interpreter,
|
|
202
|
+
flag,
|
|
203
|
+
payload: quote === '"' ? unescapeDoubleQuoted(body) : body,
|
|
204
|
+
quote,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const end = raw.slice(i).search(/\s/);
|
|
209
|
+
const payload = end === -1 ? raw.slice(i) : raw.slice(i, i + end);
|
|
210
|
+
return payload ? { interpreter, flag, payload, quote: null } : null;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Ask one sibling guard about a synthesized payload.
|
|
214
|
+
//
|
|
215
|
+
// Returns null when the guard allowed, or { kind, reason } where kind is
|
|
216
|
+
// 'deny' (the guard decided against it) or 'trouble' (the guard's verdict is
|
|
217
|
+
// unknown). BOTH block. A guard whose verdict cannot be obtained has not
|
|
218
|
+
// approved anything, and a control that degrades to permissive under load or
|
|
219
|
+
// after a botched install is worse than one that occasionally over-blocks.
|
|
220
|
+
function askSibling(guard, hookPayload) {
|
|
221
|
+
const script = path.join(__dirname, guard);
|
|
222
|
+
|
|
223
|
+
try {
|
|
224
|
+
// These hooks are installed by rsync into ~/.claude/hooks/, file by file.
|
|
225
|
+
// An absent sibling is a control that silently stopped applying — the one
|
|
226
|
+
// case where "skip that check" is exactly the wrong response.
|
|
227
|
+
if (!fs.existsSync(script)) {
|
|
228
|
+
return { kind: 'trouble', reason: `\`${guard}\` is not installed alongside this hook (looked in ${__dirname}), so its check could not be run` };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const r = spawnSync(process.execPath, [script], {
|
|
232
|
+
input: hookPayload,
|
|
233
|
+
encoding: 'utf8',
|
|
234
|
+
timeout: SIBLING_TIMEOUT_MS,
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
// spawnSync reports a timeout as an error, a signal, or both, depending on
|
|
238
|
+
// platform and on where the child was when the timer fired.
|
|
239
|
+
if (r.error) {
|
|
240
|
+
return { kind: 'trouble', reason: `\`${guard}\` could not be run (${r.error.code || r.error.message})` };
|
|
241
|
+
}
|
|
242
|
+
if (r.signal) {
|
|
243
|
+
return { kind: 'trouble', reason: `\`${guard}\` was killed by ${r.signal} — it did not answer within ${SIBLING_TIMEOUT_MS}ms` };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// stdout is read BEFORE the exit code, because that is the ordering Claude
|
|
247
|
+
// Code itself uses: the decision is the envelope, not the status.
|
|
248
|
+
const stdout = String(r.stdout ?? '').trim();
|
|
249
|
+
if (stdout) {
|
|
250
|
+
let envelope;
|
|
251
|
+
try {
|
|
252
|
+
envelope = JSON.parse(stdout);
|
|
253
|
+
} catch {
|
|
254
|
+
return { kind: 'trouble', reason: `\`${guard}\` wrote something that is not a decision envelope` };
|
|
255
|
+
}
|
|
256
|
+
const decision = envelope?.hookSpecificOutput?.permissionDecision;
|
|
257
|
+
if (decision === 'deny') {
|
|
258
|
+
return {
|
|
259
|
+
kind: 'deny',
|
|
260
|
+
reason: String(envelope.hookSpecificOutput.permissionDecisionReason ?? `\`${guard}\` denied it`),
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Every sibling exits 0 on every path by design, including its denials, so
|
|
266
|
+
// a non-zero status means it crashed rather than decided. Its verdict is
|
|
267
|
+
// unknown, which blocks for the same reason a timeout does.
|
|
268
|
+
if (r.status !== 0) {
|
|
269
|
+
return { kind: 'trouble', reason: `\`${guard}\` exited ${r.status} without reaching a decision` };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return null;
|
|
273
|
+
} catch (err) {
|
|
274
|
+
// readHookInput's own catch exits 0 (allow). Anything thrown in here must
|
|
275
|
+
// therefore be converted to a decision HERE, or fail-closed becomes
|
|
276
|
+
// fail-open at the outermost layer.
|
|
277
|
+
return { kind: 'trouble', reason: `\`${guard}\` could not be consulted (${err && err.message})` };
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// ---------------------------------------------------------------------------
|
|
282
|
+
// The deny list, re-checked
|
|
283
|
+
//
|
|
284
|
+
// The sibling guards do NOT cover everything `permissions.deny` covers. No hook
|
|
285
|
+
// in this directory objects to a bare `rm -rf ~`, `sudo …`, `crontab -r` or
|
|
286
|
+
// `git push --force` — the deny list does, and Claude Code applies it to the
|
|
287
|
+
// literal command string, which means it never sees inside `bash -c '…'`.
|
|
288
|
+
// Re-evaluating the payload through the hooks ALONE would therefore open a hole
|
|
289
|
+
// that the blanket deny this hook replaced had closed. So the extracted payload
|
|
290
|
+
// is matched against the deny list as well.
|
|
291
|
+
//
|
|
292
|
+
// This is the one place where a second matching vocabulary is unavoidable:
|
|
293
|
+
// Claude Code does not expose its permission matcher, so the semantics have to
|
|
294
|
+
// be reproduced here. It is kept to the four the shipped list actually depends
|
|
295
|
+
// on, and no further — see patternToRegExp for what is deliberately NOT
|
|
296
|
+
// reproduced.
|
|
297
|
+
// ---------------------------------------------------------------------------
|
|
298
|
+
|
|
299
|
+
// Where the rules come from, in preference order. Both are resolved from
|
|
300
|
+
// __dirname so one code path serves both locations this file lives in:
|
|
301
|
+
// ~/.claude/hooks/ → ../settings.json — the LIVE list Claude Code enforces,
|
|
302
|
+
// including the user's own additions
|
|
303
|
+
// <repo>/lib/hooks/ → ../scripts/templates/settings-deny.json — the template
|
|
304
|
+
// Only one of the two exists on any given machine, so the ordering is a
|
|
305
|
+
// fallback rather than a precedence question.
|
|
306
|
+
const DENY_SOURCES = [
|
|
307
|
+
{ file: path.join(__dirname, '..', 'settings.json'), pick: j => j && j.permissions && j.permissions.deny },
|
|
308
|
+
{ file: path.join(__dirname, '..', 'scripts', 'templates', 'settings-deny.json'), pick: j => j },
|
|
309
|
+
];
|
|
310
|
+
|
|
311
|
+
// Translate one `Bash(...)` deny pattern into a matcher.
|
|
312
|
+
//
|
|
313
|
+
// Reproduced, because the shipped list depends on all four:
|
|
314
|
+
// `dd *` a trailing space-star is a WORD BOUNDARY, not a plain
|
|
315
|
+
// wildcard: it matches `dd` and `dd if=…`, but not `ddrescue`
|
|
316
|
+
// `git stash:*` `:*` is recognized only as a suffix, where it means
|
|
317
|
+
// exactly the same thing as a trailing ` *`
|
|
318
|
+
// `sh` no wildcard at all is an EXACT match — it must not catch
|
|
319
|
+
// `sh -c` or `shellcheck`
|
|
320
|
+
// `git * --force*` `*` is an ordinary wildcard at ANY position, not just at
|
|
321
|
+
// the end; this is the entry that catches
|
|
322
|
+
// `git -C /elsewhere push --force`, so first-token matching
|
|
323
|
+
// would not have been enough
|
|
324
|
+
//
|
|
325
|
+
// NOT reproduced, deliberately:
|
|
326
|
+
// - `Edit(…)` / `Read(…)` entries. They are file-tool rules and cannot match a
|
|
327
|
+
// command string at all, so they are skipped rather than mis-applied.
|
|
328
|
+
// - `permissions.allow` / `ask` and their precedence. This is a deny-only
|
|
329
|
+
// check, which matches Claude Code in the direction that matters: deny wins.
|
|
330
|
+
// - Project-scoped `.claude/settings.json` and `.claude/settings.local.json`.
|
|
331
|
+
// Only the user-scope list is consulted.
|
|
332
|
+
// - Claude Code's own command decomposition. Segments come from the shared
|
|
333
|
+
// `splitSegments`, which splits on `;`/`&&`/`||`/`|` without regard for
|
|
334
|
+
// quoting, so `bash -c "git commit -m 'a; sudo b'"` over-blocks. That errs
|
|
335
|
+
// toward blocking, never toward allowing.
|
|
336
|
+
function patternToRegExp(pattern) {
|
|
337
|
+
// `:*` carries meaning only as a suffix, where it is exactly a trailing ` *`.
|
|
338
|
+
let p = pattern.endsWith(':*') ? pattern.slice(0, -2) + ' *' : pattern;
|
|
339
|
+
|
|
340
|
+
const boundary = p.endsWith(' *');
|
|
341
|
+
if (boundary) p = p.slice(0, -2);
|
|
342
|
+
|
|
343
|
+
// Split on `*` first so it is the only character that survives escaping.
|
|
344
|
+
const body = p.split('*').map(part => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*');
|
|
345
|
+
|
|
346
|
+
// The boundary form matches the bare command too: `dd *` blocks `dd`.
|
|
347
|
+
return new RegExp('^' + body + (boundary ? '( .*)?' : '') + '$');
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Read and compiled AT MOST ONCE per process, on first use.
|
|
351
|
+
//
|
|
352
|
+
// Not at module load, because this hook runs on every Bash call and the vast
|
|
353
|
+
// majority carry no interpreter at all: those must not pay for an fs read and
|
|
354
|
+
// 93 regex compiles they will never consult. Not per call either — `scan`
|
|
355
|
+
// recurses and asks again at each nesting level. So: lazy, then cached, with
|
|
356
|
+
// `loaded` distinguishing "not tried yet" from "tried and found nothing".
|
|
357
|
+
//
|
|
358
|
+
// A load failure is RECORDED, not thrown. The decision belongs at decision time
|
|
359
|
+
// (denyListVerdict, which denies), because a throw here would exit non-zero and
|
|
360
|
+
// Claude Code reads that as a broken hook rather than as a block.
|
|
361
|
+
let denyRules = null;
|
|
362
|
+
let denyRulesLoaded = false;
|
|
363
|
+
|
|
364
|
+
function loadDenyRules() {
|
|
365
|
+
if (denyRulesLoaded) return denyRules;
|
|
366
|
+
denyRulesLoaded = true;
|
|
367
|
+
|
|
368
|
+
for (const source of DENY_SOURCES) {
|
|
369
|
+
try {
|
|
370
|
+
if (!fs.existsSync(source.file)) continue;
|
|
371
|
+
const list = source.pick(JSON.parse(fs.readFileSync(source.file, 'utf8')));
|
|
372
|
+
if (!Array.isArray(list)) continue;
|
|
373
|
+
|
|
374
|
+
const rules = [];
|
|
375
|
+
for (const entry of list) {
|
|
376
|
+
if (typeof entry !== 'string') continue;
|
|
377
|
+
const m = /^Bash\((.*)\)$/.exec(entry);
|
|
378
|
+
if (m) rules.push({ pattern: m[1], re: patternToRegExp(m[1]) });
|
|
379
|
+
}
|
|
380
|
+
if (rules.length) {
|
|
381
|
+
denyRules = { rules, file: source.file };
|
|
382
|
+
return denyRules;
|
|
383
|
+
}
|
|
384
|
+
} catch {
|
|
385
|
+
// Unreadable or malformed — try the next source, and if there is none,
|
|
386
|
+
// denyRules stays null, which denies.
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return denyRules;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Match the extracted payload against the deny list, segment by segment, so a
|
|
393
|
+
// denied command cannot hide behind `cd /tmp && rm -rf ~`.
|
|
394
|
+
//
|
|
395
|
+
// Same contract as askSibling: null means nothing objected; 'deny' means a rule
|
|
396
|
+
// matched; 'trouble' means the rules could not be consulted, which blocks. A
|
|
397
|
+
// guard that silently stops checking because it could not find its rule file is
|
|
398
|
+
// indistinguishable, from the outside, from a guard that approved the command.
|
|
399
|
+
function denyListVerdict(payload) {
|
|
400
|
+
const loaded = loadDenyRules();
|
|
401
|
+
if (!loaded) {
|
|
402
|
+
return {
|
|
403
|
+
kind: 'trouble',
|
|
404
|
+
reason:
|
|
405
|
+
'the permission deny list could not be read from ' +
|
|
406
|
+
DENY_SOURCES.map(s => `\`${s.file}\``).join(' or ') +
|
|
407
|
+
', so the rules that block what no hook covers (`rm -rf ~`, `sudo …`, ' +
|
|
408
|
+
'`git push --force`) could not be applied to it',
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
for (const segment of splitSegments(payload)) {
|
|
413
|
+
for (const rule of loaded.rules) {
|
|
414
|
+
if (rule.re.test(segment)) {
|
|
415
|
+
return {
|
|
416
|
+
kind: 'deny',
|
|
417
|
+
reason: `\`${segment}\` matches the permission deny rule \`Bash(${rule.pattern})\``,
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
return null;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// Re-run the deny list and every sibling guard against `payload` as if it had
|
|
427
|
+
// been typed directly. Denies — and never returns — the moment one objects.
|
|
428
|
+
function reEvaluate(payload, cwd, context) {
|
|
429
|
+
// `cwd` is carried through from the original call, not defaulted here:
|
|
430
|
+
// protected-write-guard.js resolves relative redirect targets against it, so
|
|
431
|
+
// dropping it would silently weaken that check for `bash -c 'echo x > .zshrc'`.
|
|
432
|
+
const hookPayload = JSON.stringify({
|
|
433
|
+
tool_name: 'Bash',
|
|
434
|
+
tool_input: { command: payload },
|
|
435
|
+
...(cwd ? { cwd } : {}),
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
// Every source of a verdict funnels through here so the two kinds are phrased
|
|
439
|
+
// once. `deny` exits the process, so this never returns on an objection.
|
|
440
|
+
const judge = verdict => {
|
|
441
|
+
if (!verdict) return;
|
|
442
|
+
|
|
443
|
+
if (verdict.kind === 'deny') {
|
|
444
|
+
// The objecting check's OWN reason is surfaced, merely prefixed. A generic
|
|
445
|
+
// "blocked inside bash -c" would tell the caller that something was
|
|
446
|
+
// wrong without telling them what, which is how a block gets worked
|
|
447
|
+
// around instead of fixed.
|
|
448
|
+
deny(
|
|
449
|
+
`Blocked inside \`${context}\` — ${verdict.reason}\n\n` +
|
|
450
|
+
`(The inline program was extracted and re-evaluated as if you had typed it directly. ` +
|
|
451
|
+
`\`${context}\` grants no permission that the same command typed plainly would not: ` +
|
|
452
|
+
`fix the command itself rather than re-wrapping it.)`
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
deny(
|
|
457
|
+
`Blocked inside \`${context}\` — the inline program could not be fully checked: ` +
|
|
458
|
+
`${verdict.reason}. ` +
|
|
459
|
+
`The payload is re-evaluated through the other command-class guards and the permission ` +
|
|
460
|
+
`deny list before it is allowed to run, and a check that cannot be completed is treated ` +
|
|
461
|
+
`as a block, not as a pass. Run the command outside \`${context}\` so the ordinary rules ` +
|
|
462
|
+
`apply to it, or repair the installation (\`./lib/scripts/install-global.sh\`).`
|
|
463
|
+
);
|
|
464
|
+
};
|
|
465
|
+
|
|
466
|
+
// The deny list first: it is a pure in-process match against an already-parsed
|
|
467
|
+
// list, so it costs nothing, and it covers precisely the commands the siblings
|
|
468
|
+
// do not.
|
|
469
|
+
judge(denyListVerdict(payload));
|
|
470
|
+
|
|
471
|
+
for (const guard of SIBLING_GUARDS) judge(askSibling(guard, hookPayload));
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// Walk one command level: find each interpreter+eval-flag invocation, isolate
|
|
475
|
+
// its program, and judge it. Recurses into the extracted program so a nested
|
|
476
|
+
// `bash -c` is judged too.
|
|
477
|
+
//
|
|
478
|
+
// `depth` is an ordinary in-process argument rather than an environment
|
|
479
|
+
// variable threaded through subprocesses, because nesting is resolved entirely
|
|
480
|
+
// in-process — extractPayload already hands back the inner program, so there is
|
|
481
|
+
// nothing to spawn and therefore no process boundary for a counter to cross.
|
|
482
|
+
// The siblings that DO run as subprocesses never re-enter this hook (it is
|
|
483
|
+
// deliberately absent from SIBLING_GUARDS), so no depth needs to reach them.
|
|
484
|
+
function scan(raw, depth, cwd) {
|
|
485
|
+
for (const segment of segmentsWithOffsets(raw)) {
|
|
486
|
+
const tokens = tokensWithOffsets(segment.text, segment.start);
|
|
487
|
+
|
|
488
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
489
|
+
const name = interpreterName(tokens[i].text);
|
|
490
|
+
if (!name) continue;
|
|
491
|
+
|
|
492
|
+
const next = tokens[i + 1];
|
|
493
|
+
const flag = next ? matchedEvalFlag(name, next.text) : null;
|
|
494
|
+
if (flag) {
|
|
495
|
+
const context = `${name} ${flag}`;
|
|
496
|
+
const inline = extractPayload(raw, name, flag, next.start);
|
|
497
|
+
|
|
498
|
+
// Unconditional, and deliberately never re-evaluated: with `$(…)` or
|
|
499
|
+
// backticks the program does not exist until execution time, so there
|
|
500
|
+
// is genuinely nothing in this command to inspect — no payload to
|
|
501
|
+
// re-run the other guards against, and no later check can recover one.
|
|
502
|
+
if (inline && /\$\(|`/.test(inline.payload)) {
|
|
503
|
+
deny(
|
|
504
|
+
`Blocked: \`${context}\` — the inline program is a command substitution ` +
|
|
505
|
+
`(\`$(…)\` or backticks). The code that would run is fetched or generated at ` +
|
|
506
|
+
`execution time, so it does not exist in the command being approved: it cannot be ` +
|
|
507
|
+
`inspected, and this block is not subject to any further check. ` +
|
|
508
|
+
`Safe alternative: fetch or generate the script into a file, read it, then run the ` +
|
|
509
|
+
`file, so its contents are reviewable before it runs.`
|
|
510
|
+
);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// Extraction failed — flag last, unbalanced quoting, or shell
|
|
514
|
+
// concatenation. An unparseable payload is not an allowed payload: the
|
|
515
|
+
// whole basis for permitting `-c` is that its program can be read.
|
|
516
|
+
if (!inline) {
|
|
517
|
+
deny(
|
|
518
|
+
`Blocked: \`${context}\` — the inline script could not be isolated from the ` +
|
|
519
|
+
`command, so it could not be checked. The program a \`-c\`/\`-e\` flag introduces ` +
|
|
520
|
+
`is only permitted because it can be extracted and re-evaluated against the same ` +
|
|
521
|
+
`rules as a plainly-typed command; when extraction fails there is nothing to ` +
|
|
522
|
+
`evaluate, and an unreadable program is not an approved one. ` +
|
|
523
|
+
`This usually means the quoting is unbalanced or the script is assembled by ` +
|
|
524
|
+
`concatenation (\`bash -c 'echo '"$X"\`). ` +
|
|
525
|
+
`Safe alternative: write the script to a file and run the file ` +
|
|
526
|
+
`(\`bash script.sh\`, \`node script.js\`, \`python3 script.py\`), so its contents ` +
|
|
527
|
+
`are reviewable before it runs.`
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
if (depth >= MAX_INLINE_DEPTH) {
|
|
532
|
+
deny(
|
|
533
|
+
`Blocked: \`${context}\` nested ${depth + 1} levels deep. One interpreter carrying ` +
|
|
534
|
+
`an inline program is ordinary; an inline program that is ITSELF an interpreter ` +
|
|
535
|
+
`carrying an inline program is allowed once, and beyond that the shape is the ` +
|
|
536
|
+
`objection rather than the contents — each layer of quoting is another chance for ` +
|
|
537
|
+
`what actually executes to differ from what was read. ` +
|
|
538
|
+
`Safe alternative: write the innermost script to a file and run the file.`
|
|
539
|
+
);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// Only reached once a segment genuinely contains an interpreter plus an
|
|
543
|
+
// eval flag, which is what keeps the five spawns off the common path.
|
|
544
|
+
reEvaluate(inline.payload, cwd, context);
|
|
545
|
+
scan(inline.payload, depth + 1, cwd);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// The interpreter's first non-flag argument is where the program name (or,
|
|
549
|
+
// with an eval flag, the program itself) goes. A command substitution
|
|
550
|
+
// there means the code is produced at execution time and never appears in
|
|
551
|
+
// the command being approved.
|
|
552
|
+
const firstArg = tokens.slice(i + 1).map(t => t.text).find(t => !t.startsWith('-'));
|
|
553
|
+
if (firstArg && /\$\(|`/.test(firstArg)) {
|
|
554
|
+
deny(
|
|
555
|
+
`Blocked: \`${name}\` is being handed a command substitution ` +
|
|
556
|
+
`(\`$(…)\` or backticks) as its program. The code that would run is fetched or ` +
|
|
557
|
+
`generated at execution time, so it never appears in the command being approved ` +
|
|
558
|
+
`and no permission rule can inspect it. ` +
|
|
559
|
+
`Safe alternative: fetch or generate the script into a file, read it, then run the ` +
|
|
560
|
+
`file, so its contents are reviewable before it runs.`
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
readHookInput(data => {
|
|
568
|
+
if (data.tool_name !== 'Bash') return;
|
|
569
|
+
|
|
570
|
+
const fullCmd = String(data.tool_input?.command ?? '').trim();
|
|
571
|
+
if (!fullCmd) return;
|
|
572
|
+
|
|
573
|
+
const cwd = typeof data.cwd === 'string' && data.cwd ? data.cwd : '';
|
|
574
|
+
|
|
575
|
+
scan(fullCmd, 0, cwd);
|
|
576
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* command-parse.js — shared parsing helpers for PreToolUse hooks
|
|
5
|
+
*
|
|
6
|
+
* Every helper here is fail-open: malformed input exits 0 silently rather than
|
|
7
|
+
* throwing, because a hook that exits non-zero breaks the tool call it was
|
|
8
|
+
* never meant to gate.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Accumulate the hook payload from stdin, parse it, and hand it to `handler`.
|
|
13
|
+
* Unparseable input exits 0 without output. `handler` is expected to end the
|
|
14
|
+
* process itself when it decides to deny; the trailing exit covers the
|
|
15
|
+
* allow path.
|
|
16
|
+
*/
|
|
17
|
+
function readHookInput(handler) {
|
|
18
|
+
let raw = '';
|
|
19
|
+
process.stdin.setEncoding('utf8');
|
|
20
|
+
process.stdin.on('data', d => { raw += d; });
|
|
21
|
+
process.stdin.on('end', () => {
|
|
22
|
+
let data;
|
|
23
|
+
try { data = JSON.parse(raw); } catch { process.exit(0); }
|
|
24
|
+
// The handler is guarded too, not just the parse: `null`, a number, or a
|
|
25
|
+
// string are all valid JSON that no hook's `data.tool_name` survives. A
|
|
26
|
+
// throw here would exit non-zero, which Claude Code reads as a hook failure
|
|
27
|
+
// and which breaks the very tool call the hook exists to let through.
|
|
28
|
+
// `deny()` exits before returning, so a real denial never reaches the catch.
|
|
29
|
+
try { handler(data); } catch { process.exit(0); }
|
|
30
|
+
process.exit(0);
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Split a command into independently-inspectable segments. Pipes are included
|
|
36
|
+
* alongside the separators so a blocked command cannot hide behind
|
|
37
|
+
* `&&`, `;`, `||`, or `| tail -20`.
|
|
38
|
+
*/
|
|
39
|
+
function splitSegments(cmd) {
|
|
40
|
+
return String(cmd ?? '').split(/;|&&|\|\||\|/).map(s => s.trim()).filter(Boolean);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function tokenize(segment) {
|
|
44
|
+
return String(segment ?? '').trim().split(/\s+/).filter(Boolean);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function deny(reason) {
|
|
48
|
+
console.log(JSON.stringify({
|
|
49
|
+
hookSpecificOutput: {
|
|
50
|
+
hookEventName: 'PreToolUse',
|
|
51
|
+
permissionDecision: 'deny',
|
|
52
|
+
permissionDecisionReason: String(reason),
|
|
53
|
+
},
|
|
54
|
+
}));
|
|
55
|
+
process.exit(0);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
module.exports = {
|
|
59
|
+
readHookInput,
|
|
60
|
+
splitSegments,
|
|
61
|
+
tokenize,
|
|
62
|
+
deny,
|
|
63
|
+
};
|