hookset 0.0.1 → 1.0.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/LICENSE +21 -0
- package/README.md +204 -0
- package/claude/guard-bash.mjs +559 -0
- package/claude/stop-after-3.mjs +158 -0
- package/dist/bin.js +4 -0
- package/dist/cli.js +54 -0
- package/dist/core.d.ts +86 -0
- package/dist/core.js +299 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/runtime.js +1 -0
- package/package.json +75 -1
- package/presets/lefthook/commit-msg.yml +11 -0
- package/presets/lefthook/pre-commit.yml +7 -0
- package/presets/lefthook/pre-push.yml +22 -0
- package/stations.json +28 -0
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// guard-bash — Claude Code PreToolUse hook for Bash, Edit and Write. Canonical copy:
|
|
3
|
+
// burgee packages/hookset/claude/. `hookset init --claude` vendors it into a repo's
|
|
4
|
+
// .claude/hooks/, byte-identical, and `hookset check` fails when the copy drifts.
|
|
5
|
+
//
|
|
6
|
+
// It replaces prose that every CLAUDE.md used to repeat. A rule an agent can break
|
|
7
|
+
// with one command is a check, not a sentence: the denial below is the documentation.
|
|
8
|
+
//
|
|
9
|
+
// 1. Skipping git hooks (--no-verify and its abbreviations, `git commit -n`, LEFTHOOK=0/HUSKY=0,
|
|
10
|
+
// also exported earlier in the same command) — the hooks are the gate.
|
|
11
|
+
// 2. Pointing git at other hooks (`git config core.hooksPath`, `git -c core.hooksPath=`,
|
|
12
|
+
// GIT_CONFIG_KEY_n=core.hooksPath) or removing them (`lefthook uninstall`, rm/mv/chmod .git/hooks).
|
|
13
|
+
// 3. Hand-rolled CI polling (`until/while/for … gh … sleep`, `watch … gh`) — the harness kills
|
|
14
|
+
// those loops and the turn ends knowing nothing. `gh pr checks <PR> --watch` blocks correctly.
|
|
15
|
+
// 4. Asks (never denies) before a publish: npm/pnpm/yarn/bun `publish`, `unpublish`, `deprecate`,
|
|
16
|
+
// `dist-tag add|rm`, `changeset publish`, `lerna publish`, and the commands the repo lists
|
|
17
|
+
// under `ask` in .claude/hookset.json (deploys, releases).
|
|
18
|
+
// 5. Denies Edit/Write on a path matching a glob the repo lists under `frozen` there, and on
|
|
19
|
+
// a generated file (`generated`: glob -> the command that writes it), naming that command.
|
|
20
|
+
// 6. Denies `git commit` / `git push` run in the foreground under the default 2-minute
|
|
21
|
+
// timeout: their hooks are the repo's gate and take minutes. The denial names the fix
|
|
22
|
+
// (timeout 600000 or run_in_background), so no CLAUDE.md has to say "not a hang".
|
|
23
|
+
// 7. Asks before a push that rewrites or deletes remote history: --force, --force-with-lease,
|
|
24
|
+
// -f, +refspec, --delete, :refspec, --mirror, --prune.
|
|
25
|
+
//
|
|
26
|
+
// Matching is done on tokens, not regexes over the raw command: quoted strings and
|
|
27
|
+
// heredoc bodies are data (commit messages, PR bodies), and no pattern here can backtrack.
|
|
28
|
+
// Reads the PreToolUse payload on stdin. Prints a deny or ask decision, or nothing (no opinion).
|
|
29
|
+
// `node guard-bash.mjs --self-test` runs the cases at the bottom.
|
|
30
|
+
|
|
31
|
+
import { posix } from "node:path";
|
|
32
|
+
|
|
33
|
+
const SEPARATORS = new Set([";", "&", "|", "\n", "(", ")"]);
|
|
34
|
+
|
|
35
|
+
/** Drop heredoc bodies: everything after a `<<WORD` line until the line that is WORD. */
|
|
36
|
+
function dropHeredocs(cmd) {
|
|
37
|
+
const out = [];
|
|
38
|
+
let end = null;
|
|
39
|
+
for (const line of cmd.split("\n")) {
|
|
40
|
+
if (end !== null) {
|
|
41
|
+
if (line.trim() === end) end = null;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
out.push(line);
|
|
45
|
+
const at = line.indexOf("<<");
|
|
46
|
+
// `<<<` is a herestring, not a heredoc: it has no body to skip.
|
|
47
|
+
if (at !== -1 && line[at + 2] !== "<") {
|
|
48
|
+
const word = line
|
|
49
|
+
.slice(at + 2)
|
|
50
|
+
.replace(/^-/, "")
|
|
51
|
+
.trim()
|
|
52
|
+
.split(" ")[0]
|
|
53
|
+
.replaceAll("'", "")
|
|
54
|
+
.replaceAll('"', "");
|
|
55
|
+
if (word) end = word;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return out.join("\n");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Index just past the quote that closes the one at `start`. */
|
|
62
|
+
function skipQuoted(src, start) {
|
|
63
|
+
const quote = src[start];
|
|
64
|
+
let i = start + 1;
|
|
65
|
+
while (i < src.length && src[i] !== quote)
|
|
66
|
+
i += src[i] === "\\" && quote === '"' ? 2 : 1;
|
|
67
|
+
return i + 1;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const VALUE_FLAG = /^(-[a-zA-Z]*[mF]|--message|--file|--trailer)$/;
|
|
71
|
+
|
|
72
|
+
/** True when words[k] is a flag that takes the next word as its value, and was not itself one. */
|
|
73
|
+
function takesValue(words, k) {
|
|
74
|
+
return k >= 0 && VALUE_FLAG.test(words[k]) && !takesValue(words, k - 1);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Split into commands of whitespace-separated words. Quoted text becomes an empty word, except a
|
|
79
|
+
* quoted single word ("--no-verify", "core.hooksPath=x"), which the shell passes on as that word.
|
|
80
|
+
*/
|
|
81
|
+
export function commands(cmd) {
|
|
82
|
+
const src = dropHeredocs(cmd ?? "").replace(/\\\n/g, " ");
|
|
83
|
+
const result = [];
|
|
84
|
+
let words = [];
|
|
85
|
+
let word = "";
|
|
86
|
+
const flushWord = () => {
|
|
87
|
+
if (word !== "") words.push(word);
|
|
88
|
+
word = "";
|
|
89
|
+
};
|
|
90
|
+
const flushCommand = () => {
|
|
91
|
+
flushWord();
|
|
92
|
+
if (words.length) result.push(words);
|
|
93
|
+
words = [];
|
|
94
|
+
};
|
|
95
|
+
let i = 0;
|
|
96
|
+
while (i < src.length) {
|
|
97
|
+
const ch = src[i];
|
|
98
|
+
if (ch === "'" || ch === '"') {
|
|
99
|
+
const end = skipQuoted(src, i);
|
|
100
|
+
const inner = src.slice(i + 1, end - 1);
|
|
101
|
+
// A quoted single word reaches the program as that word, unless it is a message or file value.
|
|
102
|
+
const isValue = word === "" && takesValue(words, words.length - 1);
|
|
103
|
+
word += !isValue && /^\S+$/.test(inner) ? inner : '""';
|
|
104
|
+
i = end;
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (SEPARATORS.has(ch)) flushCommand();
|
|
108
|
+
else if (ch === " " || ch === "\t") flushWord();
|
|
109
|
+
else word += ch;
|
|
110
|
+
i++;
|
|
111
|
+
}
|
|
112
|
+
flushCommand();
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const GIT_OPTS_WITH_VALUE = new Set([
|
|
117
|
+
"-C",
|
|
118
|
+
"-c",
|
|
119
|
+
"--git-dir",
|
|
120
|
+
"--work-tree",
|
|
121
|
+
"--namespace",
|
|
122
|
+
]);
|
|
123
|
+
|
|
124
|
+
/** Index of git's subcommand in `words` (past `git -C dir`, `git -c k=v`), or -1. */
|
|
125
|
+
function gitSub(words) {
|
|
126
|
+
const g = words.indexOf("git");
|
|
127
|
+
if (g === -1) return -1;
|
|
128
|
+
let s = g + 1;
|
|
129
|
+
while (words[s]?.startsWith("-"))
|
|
130
|
+
s += GIT_OPTS_WITH_VALUE.has(words[s]) ? 2 : 1;
|
|
131
|
+
return s;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function skipsHooks(words) {
|
|
135
|
+
const s = gitSub(words);
|
|
136
|
+
if (s === -1) return false;
|
|
137
|
+
const env = words.slice(0, words.indexOf("git"));
|
|
138
|
+
const sub = words[s];
|
|
139
|
+
const args = words.slice(s + 1);
|
|
140
|
+
// git takes any unambiguous prefix of a long option: `--no-veri` skips hooks like `--no-verify`.
|
|
141
|
+
if (args.some((a) => /^--no-veri(f|fy)?$/.test(a))) return true;
|
|
142
|
+
if (
|
|
143
|
+
sub === "commit" &&
|
|
144
|
+
args.some((a) => /^-[a-zA-Z]+$/.test(a) && a.includes("n"))
|
|
145
|
+
)
|
|
146
|
+
return true;
|
|
147
|
+
const offEnv = env.some((w) => /^(LEFTHOOK|HUSKY)=(0|false)$/.test(w));
|
|
148
|
+
return offEnv && (sub === "commit" || sub === "push");
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const HOOKS_OFF = /^(LEFTHOOK|HUSKY)=(0|false)$/;
|
|
152
|
+
|
|
153
|
+
/** `export LEFTHOOK=0; git push`: the variable outlives its own command, so any commit or push after it is unhooked. */
|
|
154
|
+
function hooksOffInShell(cmds) {
|
|
155
|
+
if (!cmds.some((w) => w.some((x) => HOOKS_OFF.test(x)))) return false;
|
|
156
|
+
return cmds.some((w) => {
|
|
157
|
+
const s = gitSub(w);
|
|
158
|
+
return s !== -1 && (w[s] === "commit" || w[s] === "push");
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const HOOK_FILE_TOOLS = new Set(["rm", "mv", "chmod", "unlink", "truncate", "ln"]);
|
|
163
|
+
|
|
164
|
+
/** `lefthook uninstall`, `rm .git/hooks/pre-push`, `> .git/hooks/pre-commit`: the hooks are gone. */
|
|
165
|
+
function removesHooks(words) {
|
|
166
|
+
if (hasPhrase(words, "lefthook uninstall")) return true;
|
|
167
|
+
const inHooks = (w) => /(^|\/)\.git\/hooks(\/|$)/.test(w.replace(/^>+/, ""));
|
|
168
|
+
if (words.some((w, i) => inHooks(w) && (/^>/.test(w) || /^>+$/.test(words[i - 1] ?? "")))) return true;
|
|
169
|
+
const tool = words.findIndex((w) => HOOK_FILE_TOOLS.has(w.split("/").pop()));
|
|
170
|
+
return tool !== -1 && words.slice(tool + 1).some(inHooks);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** `git config [--global|--local] core.hooksPath x`, `git -c core.hooksPath=x …`, `GIT_CONFIG_KEY_0=core.hooksPath`. */
|
|
174
|
+
function movesHooks(words) {
|
|
175
|
+
if (words.some((w) => /^GIT_CONFIG_KEY_\d+=core\.hookspath$/i.test(w))) return true;
|
|
176
|
+
if (removesHooks(words)) return true;
|
|
177
|
+
const g = words.indexOf("git");
|
|
178
|
+
if (g === -1) return false;
|
|
179
|
+
const rest = words.slice(g + 1);
|
|
180
|
+
for (let i = 0; i < rest.length; i++)
|
|
181
|
+
if (rest[i] === "-c" && /^core\.hookspath=/i.test(rest[i + 1] ?? "")) return true;
|
|
182
|
+
const c = rest.indexOf("config");
|
|
183
|
+
return c !== -1 && rest.slice(c + 1).some((w) => /^core\.hookspath$/i.test(w)) && !rest.includes("--get") && !rest.includes("--unset");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** True when `words` holds `phrase` (a space-separated word list) as a contiguous run. */
|
|
187
|
+
function hasPhrase(words, phrase) {
|
|
188
|
+
const want = phrase.split(" ").filter(Boolean);
|
|
189
|
+
if (!want.length) return false;
|
|
190
|
+
for (let i = 0; i + want.length <= words.length; i++)
|
|
191
|
+
if (want.every((w, j) => words[i + j] === w)) return true;
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export const PUBLISH = ["npm publish", "pnpm publish", "yarn npm publish", "changeset publish", "lerna publish"];
|
|
196
|
+
|
|
197
|
+
const PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]);
|
|
198
|
+
/** Subcommands that change the registry for everyone: no later command takes them back. */
|
|
199
|
+
const REGISTRY_WRITES = new Set(["publish", "unpublish", "deprecate"]);
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The registry write `words` runs, or null: npm, pnpm, yarn or bun (by any path, `/usr/bin/npm`)
|
|
203
|
+
* with `publish`, `unpublish`, `deprecate` or `dist-tag add|rm` as its subcommand, after global
|
|
204
|
+
* options: `npm --access=public publish`, `npm --registry https://r publish`. An option without `=`
|
|
205
|
+
* may take the next word as its value, so that word is skipped unless it is the subcommand itself.
|
|
206
|
+
*/
|
|
207
|
+
function publishesAfterOptions(words) {
|
|
208
|
+
const isWrite = (k) => REGISTRY_WRITES.has(words[k]) || (words[k] === "dist-tag" && /^(add|rm)$/.test(words[k + 1] ?? ""));
|
|
209
|
+
for (let i = 0; i < words.length; i++) {
|
|
210
|
+
const tool = words[i].split("/").pop();
|
|
211
|
+
if (!PACKAGE_MANAGERS.has(tool)) continue;
|
|
212
|
+
let j = i + 1;
|
|
213
|
+
while (j < words.length && words[j].startsWith("-")) {
|
|
214
|
+
// Any option without `=` may take the next word as its value (`--registry url`, `-F pkg`).
|
|
215
|
+
const valued = !words[j].includes("=");
|
|
216
|
+
j++;
|
|
217
|
+
if (valued && j < words.length && !words[j].startsWith("-") && !isWrite(j)) j++;
|
|
218
|
+
}
|
|
219
|
+
if (isWrite(j)) return `${tool} ${words[j]}${words[j] === "dist-tag" ? ` ${words[j + 1]}` : ""}`;
|
|
220
|
+
}
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** True when `words` is a `git push` that rewrites or deletes history on the remote. */
|
|
225
|
+
function forcePushes(words) {
|
|
226
|
+
const s = gitSub(words);
|
|
227
|
+
if (s === -1 || words[s] !== "push") return false;
|
|
228
|
+
return words.slice(s + 1).some(
|
|
229
|
+
(a) =>
|
|
230
|
+
/^--(force|force-with-lease|mirror|delete|prune)(=.*)?$/.test(a) ||
|
|
231
|
+
(/^-[a-zA-Z]+$/.test(a) && /[fd]/.test(a)) ||
|
|
232
|
+
/^[+:]./.test(a),
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const RULES = [
|
|
237
|
+
{
|
|
238
|
+
id: "no-verify",
|
|
239
|
+
test: (cmds) => cmds.some(skipsHooks) || hooksOffInShell(cmds),
|
|
240
|
+
reason:
|
|
241
|
+
"Git hooks are this repo's gate: never skip them (--no-verify, commit -n, LEFTHOOK=0). " +
|
|
242
|
+
"If a hook fails, fix what it reports. If it is slow, wait: commit/push hooks can take 3–4 minutes, " +
|
|
243
|
+
"and a killed push may still have landed (check `git log origin/<branch> -1` before retrying).",
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
id: "hooks-path",
|
|
247
|
+
test: (cmds) => cmds.some(movesHooks),
|
|
248
|
+
reason:
|
|
249
|
+
"Do not point git at other hooks (core.hooksPath) or remove them (lefthook uninstall, .git/hooks): lefthook installed this repo's hooks and they are the gate. " +
|
|
250
|
+
"If a hook is wrong, fix lefthook.yml or the hookset preset in a PR.",
|
|
251
|
+
},
|
|
252
|
+
{
|
|
253
|
+
id: "ci-poll-loop",
|
|
254
|
+
test: (cmds) => {
|
|
255
|
+
const all = cmds.flat();
|
|
256
|
+
if (cmds.some((w) => w[0] === "watch" && w.includes("gh"))) return true;
|
|
257
|
+
return (
|
|
258
|
+
(all.includes("until") || all.includes("while") || all.includes("for")) &&
|
|
259
|
+
all.includes("gh") &&
|
|
260
|
+
all.includes("sleep")
|
|
261
|
+
);
|
|
262
|
+
},
|
|
263
|
+
reason:
|
|
264
|
+
"Do not hand-roll CI polling loops: the harness timeout kills them and the turn ends knowing nothing. " +
|
|
265
|
+
"Use `gh pr checks <PR> --watch` (or `gh run watch <run-id>`; in interlace, `pr-blockers watch`). " +
|
|
266
|
+
"`--watch` returning means nothing is pending, not that everything passed: check the results after.",
|
|
267
|
+
},
|
|
268
|
+
];
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* The verdict for one Bash command: `{ decision: "deny" | "ask", id, reason }`, or null.
|
|
272
|
+
* `ask` holds extra phrases the repo wants a person to approve (from .claude/hookset.json).
|
|
273
|
+
*/
|
|
274
|
+
export function decide(command, ask = []) {
|
|
275
|
+
const cmds = commands(command);
|
|
276
|
+
for (const r of RULES)
|
|
277
|
+
if (r.test(cmds)) return { decision: "deny", id: r.id, reason: r.reason };
|
|
278
|
+
const phrase =
|
|
279
|
+
PUBLISH.find((p) => cmds.some((w) => hasPhrase(w, p))) ??
|
|
280
|
+
cmds.map(publishesAfterOptions).find(Boolean);
|
|
281
|
+
if (phrase)
|
|
282
|
+
return {
|
|
283
|
+
decision: "ask",
|
|
284
|
+
id: "publish",
|
|
285
|
+
reason: `\`${phrase}\` changes the package registry outside this repo, and that cannot be undone. A person approves it; CI release workflows are the usual route.`,
|
|
286
|
+
};
|
|
287
|
+
if (cmds.some(forcePushes))
|
|
288
|
+
return {
|
|
289
|
+
decision: "ask",
|
|
290
|
+
id: "force-push",
|
|
291
|
+
reason:
|
|
292
|
+
"This push rewrites or deletes history on the remote, which other sessions and reviewers may have built on. A person approves it. " +
|
|
293
|
+
"If a push was rejected because the remote has commits you lack, merge them instead: `git fetch origin <branch> && git merge --no-edit FETCH_HEAD`.",
|
|
294
|
+
};
|
|
295
|
+
const listed = ask.find((p) => cmds.some((w) => hasPhrase(w, p)));
|
|
296
|
+
if (listed)
|
|
297
|
+
return {
|
|
298
|
+
decision: "ask",
|
|
299
|
+
id: "repo-ask",
|
|
300
|
+
reason: `This repo lists \`${listed}\` in .claude/hookset.json as a step a person approves: it overwrites or ships something that is hard to take back.`,
|
|
301
|
+
};
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Below this a foreground Bash call is killed while a commit or push hook is still running. */
|
|
306
|
+
export const HOOKED_MIN_TIMEOUT_MS = 300_000;
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* The verdict for a `git commit` or `git push` given the Bash call's `timeout` and
|
|
310
|
+
* `run_in_background`, or null. Their hooks run the repo's gate for minutes; the default
|
|
311
|
+
* 2-minute timeout kills them mid-gate and the agent retries a push that may have landed.
|
|
312
|
+
*/
|
|
313
|
+
export function decideHooked(command, { timeout, run_in_background } = {}) {
|
|
314
|
+
if (run_in_background === true || (Number(timeout) || 0) >= HOOKED_MIN_TIMEOUT_MS) return null;
|
|
315
|
+
const hooked = commands(command).find((w) => {
|
|
316
|
+
const s = gitSub(w);
|
|
317
|
+
// `git commit --dry-run` runs no hooks; `git push --dry-run` still runs pre-push.
|
|
318
|
+
return s !== -1 && (w[s] === "commit" ? !w.includes("--dry-run") : w[s] === "push") && !w.includes("--help");
|
|
319
|
+
});
|
|
320
|
+
if (!hooked) return null;
|
|
321
|
+
const sub = hooked[gitSub(hooked)];
|
|
322
|
+
return {
|
|
323
|
+
decision: "deny",
|
|
324
|
+
id: "hooked-timeout",
|
|
325
|
+
reason:
|
|
326
|
+
`\`git ${sub}\` runs this repo's ${sub === "push" ? "pre-push" : "commit"} hooks, which take minutes: not a hang. ` +
|
|
327
|
+
"Run it again with `timeout: 600000` (or `run_in_background: true`) and wait for it. " +
|
|
328
|
+
"If an earlier push was killed, check `git log origin/<branch> -1` first: it may have landed.",
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** `*` within a segment, `**` across segments, `?` one character. Paths use forward slashes. */
|
|
333
|
+
export function globToRegExp(glob) {
|
|
334
|
+
let re = "";
|
|
335
|
+
for (let i = 0; i < glob.length; i++) {
|
|
336
|
+
const ch = glob[i];
|
|
337
|
+
if (ch === "*" && glob[i + 1] === "*") {
|
|
338
|
+
re += glob[i + 2] === "/" ? "(?:.*/)?" : ".*";
|
|
339
|
+
i += glob[i + 2] === "/" ? 2 : 1;
|
|
340
|
+
} else if (ch === "*") re += "[^/]*";
|
|
341
|
+
else if (ch === "?") re += "[^/]";
|
|
342
|
+
else re += /[.+^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
|
|
343
|
+
}
|
|
344
|
+
return new RegExp(`^${re}$`);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** The verdict for an Edit/Write on `file` (relative to the repo), or null. */
|
|
348
|
+
export function decideEdit(file, frozen = [], generated = {}) {
|
|
349
|
+
// posix.normalize folds `a/../b` and `./a`, so a dotted path cannot step around a frozen glob.
|
|
350
|
+
const rel = posix.normalize(String(file ?? "").replaceAll("\\", "/")).replace(/^\.\//, "");
|
|
351
|
+
const made = Object.entries(generated).find(([g]) => globToRegExp(g).test(rel));
|
|
352
|
+
if (made)
|
|
353
|
+
return {
|
|
354
|
+
decision: "deny",
|
|
355
|
+
id: "generated",
|
|
356
|
+
reason: `${rel} is generated (\`${made[0]}\` in .claude/hookset.json). Edit its source, then run \`${made[1]}\`.`,
|
|
357
|
+
};
|
|
358
|
+
const hit = frozen.find((g) => globToRegExp(g).test(rel));
|
|
359
|
+
return hit
|
|
360
|
+
? {
|
|
361
|
+
decision: "deny",
|
|
362
|
+
id: "frozen",
|
|
363
|
+
reason: `${rel} matches the frozen glob \`${hit}\` in .claude/hookset.json. It changes only by a decision: record one, then edit the list in its own PR.`,
|
|
364
|
+
}
|
|
365
|
+
: null;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export const CASES = {
|
|
369
|
+
deny: [
|
|
370
|
+
"git commit --no-verify -m x",
|
|
371
|
+
"git push --no-verify origin x",
|
|
372
|
+
'git commit -nm "x"',
|
|
373
|
+
"git commit -n -m x",
|
|
374
|
+
"LEFTHOOK=0 git push",
|
|
375
|
+
"cd repo && git commit --no-verify",
|
|
376
|
+
'git commit "--no-verify" -m x',
|
|
377
|
+
"git -C . commit -n -m x",
|
|
378
|
+
"LEFTHOOK=0 git -c core.x=1 push",
|
|
379
|
+
"git config core.hooksPath /dev/null",
|
|
380
|
+
"git -c core.hooksPath=/tmp/none push",
|
|
381
|
+
'git -c "core.hooksPath=/dev/null" push',
|
|
382
|
+
'git commit -m -F "--no-verify"',
|
|
383
|
+
"HUSKY=false git commit -m x",
|
|
384
|
+
"read -r b <<< 'x'\ngit commit --no-verify -m y",
|
|
385
|
+
"git commit \\\n --no-verify -m x",
|
|
386
|
+
"until gh pr view 5 --json state | grep MERGED; do sleep 30; done",
|
|
387
|
+
"while true; do gh run list; sleep 10; done",
|
|
388
|
+
"until gh workflow view ci; do sleep 5; done",
|
|
389
|
+
"git push --no-veri origin x",
|
|
390
|
+
"git commit --no-verif -m x",
|
|
391
|
+
"export LEFTHOOK=0; git push",
|
|
392
|
+
"LEFTHOOK=0\ngit commit -m x",
|
|
393
|
+
"export HUSKY=false && git -C . commit -m x",
|
|
394
|
+
"lefthook uninstall",
|
|
395
|
+
"npx lefthook uninstall",
|
|
396
|
+
"rm .git/hooks/pre-push",
|
|
397
|
+
"rm -f /repo/.git/hooks/pre-commit",
|
|
398
|
+
"chmod -x .git/hooks/pre-commit",
|
|
399
|
+
"mv .git/hooks .git/hooks.off",
|
|
400
|
+
"echo > .git/hooks/pre-push",
|
|
401
|
+
"GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=core.hooksPath GIT_CONFIG_VALUE_0=/dev/null git push",
|
|
402
|
+
"for i in 1 2 3; do gh pr checks 5; sleep 30; done",
|
|
403
|
+
"watch -n 30 gh pr checks 5",
|
|
404
|
+
],
|
|
405
|
+
allow: [
|
|
406
|
+
'git commit -m "docs: explain why --no-verify is banned"',
|
|
407
|
+
'git commit -m "--no-verify"',
|
|
408
|
+
'git commit -am "--no-verify"',
|
|
409
|
+
"git commit -F - <<'EOF'\nnever use --no-verify\nEOF",
|
|
410
|
+
"git commit -F - <<'EOF'\nuntil gh pr checks; do sleep 1; done\nEOF\ngit push",
|
|
411
|
+
"gh pr checks 12 --watch",
|
|
412
|
+
"git -C . log -n 3",
|
|
413
|
+
'git commit -am "x"',
|
|
414
|
+
"sleep 5",
|
|
415
|
+
"LEFTHOOK=0 npm ci",
|
|
416
|
+
"git log -n 3",
|
|
417
|
+
"git config --get core.hooksPath",
|
|
418
|
+
'echo "npm publish" > notes.txt',
|
|
419
|
+
'git commit -m "never use --no-veri"',
|
|
420
|
+
"cat .git/hooks/pre-push",
|
|
421
|
+
"ls .git/hooks",
|
|
422
|
+
"git push -u origin feature",
|
|
423
|
+
"git push origin HEAD:refs/heads/feature",
|
|
424
|
+
"npm view pkg dist-tags",
|
|
425
|
+
"npm dist-tag ls pkg",
|
|
426
|
+
"npm run publish:dry",
|
|
427
|
+
"for f in a b; do echo $f; done",
|
|
428
|
+
"LEFTHOOK=0 npm ci && git status",
|
|
429
|
+
],
|
|
430
|
+
ask: [
|
|
431
|
+
"npm publish --access public",
|
|
432
|
+
"cd pkg && npx changeset publish",
|
|
433
|
+
"pnpm publish",
|
|
434
|
+
"npm --access=public publish",
|
|
435
|
+
"npm --registry https://registry.npmjs.org publish",
|
|
436
|
+
"pnpm --filter pkg publish",
|
|
437
|
+
"pnpm -F pkg publish",
|
|
438
|
+
"npm -g publish",
|
|
439
|
+
"yarn publish",
|
|
440
|
+
"bun publish",
|
|
441
|
+
"/usr/local/bin/npm publish",
|
|
442
|
+
"npm unpublish pkg@1.0.0",
|
|
443
|
+
"pnpm deprecate pkg@1 old",
|
|
444
|
+
"npm dist-tag add pkg@1.0.0 latest",
|
|
445
|
+
"npx lerna publish from-package",
|
|
446
|
+
"git push --force origin main",
|
|
447
|
+
"git push -f",
|
|
448
|
+
"git push -uf origin x",
|
|
449
|
+
"git push origin +main",
|
|
450
|
+
"git push --force-with-lease=main origin main",
|
|
451
|
+
"git push origin :main",
|
|
452
|
+
"git push --delete origin x",
|
|
453
|
+
"git push -d origin x",
|
|
454
|
+
"git push --mirror",
|
|
455
|
+
],
|
|
456
|
+
// decideHooked: [command, Bash input, denied?]
|
|
457
|
+
hooked: [
|
|
458
|
+
["git push origin main", {}, true],
|
|
459
|
+
["git -C repo commit -m x", { timeout: 120000 }, true],
|
|
460
|
+
["cd a && git push", { timeout: 299999 }, true],
|
|
461
|
+
["git push", { timeout: 600000 }, false],
|
|
462
|
+
["git commit -m x", { run_in_background: true }, false],
|
|
463
|
+
["git push --dry-run", {}, true],
|
|
464
|
+
["git commit --dry-run -m x", {}, false],
|
|
465
|
+
["git log -n 3", {}, false],
|
|
466
|
+
["git commit -F - <<'EOF'\nx\nEOF", { timeout: 300000 }, false],
|
|
467
|
+
["echo 'git push'", {}, false],
|
|
468
|
+
],
|
|
469
|
+
// decideEdit: [path, denied as] against EDIT_CONFIG.
|
|
470
|
+
edit: [
|
|
471
|
+
["content/a/b.md", "frozen"],
|
|
472
|
+
["./docs/../content/a.md", "frozen"],
|
|
473
|
+
["public/r/button.json", "generated"],
|
|
474
|
+
["public/r/../r/x.json", "generated"],
|
|
475
|
+
["src/button.tsx", null],
|
|
476
|
+
],
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
const EDIT_CONFIG = { frozen: ["content/**/*.md"], generated: { "public/r/**": "npm run registry:build" } };
|
|
480
|
+
|
|
481
|
+
function selfTest() {
|
|
482
|
+
const bad = [
|
|
483
|
+
...CASES.deny.filter((c) => decide(c)?.decision !== "deny").map((c) => `should deny: ${c}`),
|
|
484
|
+
...CASES.allow.filter((c) => decide(c)).map((c) => `should allow: ${c}`),
|
|
485
|
+
...CASES.ask.filter((c) => decide(c)?.decision !== "ask").map((c) => `should ask: ${c}`),
|
|
486
|
+
...CASES.hooked
|
|
487
|
+
.filter(([c, input, denied]) => Boolean(decideHooked(c, input)) !== denied)
|
|
488
|
+
.map(([c, input, denied]) => `should ${denied ? "deny" : "allow"} ${JSON.stringify(input)}: ${c}`),
|
|
489
|
+
...CASES.edit
|
|
490
|
+
.filter(([f, id]) => (decideEdit(f, EDIT_CONFIG.frozen, EDIT_CONFIG.generated)?.id ?? null) !== id)
|
|
491
|
+
.map(([f, id]) => `should ${id ? `deny as ${id}` : "allow"}: edit ${f}`),
|
|
492
|
+
];
|
|
493
|
+
process.stdout.write(
|
|
494
|
+
bad.length
|
|
495
|
+
? `${bad.join("\n")}\n${bad.length} failing\n`
|
|
496
|
+
: `ok: ${CASES.deny.length} denied, ${CASES.allow.length} allowed, ${CASES.ask.length} asked, ${CASES.hooked.length} timed, ${CASES.edit.length} edits\n`,
|
|
497
|
+
);
|
|
498
|
+
process.exit(bad.length ? 1 : 0);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** The repo's `.claude/hookset.json`: `{ "ask": [phrases], "frozen": [globs], "generated": { glob: command } }`. Missing is empty. */
|
|
502
|
+
async function repoConfig() {
|
|
503
|
+
const { readFile } = await import("node:fs/promises");
|
|
504
|
+
const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();
|
|
505
|
+
try {
|
|
506
|
+
const c = JSON.parse(await readFile(`${dir}/.claude/hookset.json`, "utf8"));
|
|
507
|
+
return {
|
|
508
|
+
dir,
|
|
509
|
+
ask: Array.isArray(c.ask) ? c.ask.map(String) : [],
|
|
510
|
+
frozen: Array.isArray(c.frozen) ? c.frozen.map(String) : [],
|
|
511
|
+
generated:
|
|
512
|
+
c.generated && typeof c.generated === "object" && !Array.isArray(c.generated)
|
|
513
|
+
? Object.fromEntries(Object.entries(c.generated).map(([g, cmd]) => [g, String(cmd)]))
|
|
514
|
+
: {},
|
|
515
|
+
};
|
|
516
|
+
} catch {
|
|
517
|
+
return { dir, ask: [], frozen: [], generated: {} };
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Imported (stop-after-3 reads `commands` from guard-bash) is not run: only the entry file acts.
|
|
522
|
+
const isMain = Boolean(process.argv[1]) && import.meta.url.endsWith(`/${process.argv[1].split(/[\\/]/).pop()}`);
|
|
523
|
+
if (isMain && process.argv.includes("--self-test")) selfTest();
|
|
524
|
+
else if (isMain) {
|
|
525
|
+
let raw = "";
|
|
526
|
+
process.stdin.on("data", (d) => (raw += d));
|
|
527
|
+
process.stdin.on("end", async () => {
|
|
528
|
+
let payload;
|
|
529
|
+
try {
|
|
530
|
+
payload = JSON.parse(raw) ?? {};
|
|
531
|
+
} catch {
|
|
532
|
+
process.exit(0);
|
|
533
|
+
}
|
|
534
|
+
const input = payload.tool_input ?? {};
|
|
535
|
+
const config = await repoConfig();
|
|
536
|
+
let hit = null;
|
|
537
|
+
if (typeof input.command === "string")
|
|
538
|
+
hit = decide(input.command, config.ask) ?? decideHooked(input.command, input);
|
|
539
|
+
else {
|
|
540
|
+
const file = input.file_path ?? input.notebook_path;
|
|
541
|
+
if (typeof file === "string") {
|
|
542
|
+
// Windows hands both paths over with backslashes: compare them with forward slashes.
|
|
543
|
+
const [f, d] = [file, config.dir].map((p) => posix.normalize(p.replaceAll("\\", "/")));
|
|
544
|
+
const rel = f.startsWith(`${d}/`) ? f.slice(d.length + 1) : f;
|
|
545
|
+
hit = decideEdit(rel, config.frozen, config.generated);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
if (!hit) process.exit(0);
|
|
549
|
+
process.stdout.write(
|
|
550
|
+
JSON.stringify({
|
|
551
|
+
hookSpecificOutput: {
|
|
552
|
+
hookEventName: "PreToolUse",
|
|
553
|
+
permissionDecision: hit.decision,
|
|
554
|
+
permissionDecisionReason: `[guard-bash:${hit.id}] ${hit.reason}`,
|
|
555
|
+
},
|
|
556
|
+
}),
|
|
557
|
+
);
|
|
558
|
+
});
|
|
559
|
+
}
|