@hasna/hooks 0.13.2 → 0.14.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.
Files changed (41) hide show
  1. package/README.md +30 -15
  2. package/bin/hooks/stop-review.js +53 -17
  3. package/bin/hooks-mcp.js +4787 -1415
  4. package/bin/index.js +5250 -2337
  5. package/bin/native-safety-entry.js +15 -37
  6. package/bin/native-safety-worker.cjs +38 -36
  7. package/bin/serve.js +34 -11
  8. package/dist/index.js +4970 -1579
  9. package/dist/lib/claude-skills-coordination.d.ts +1 -1
  10. package/dist/lib/codex-safety-trust.d.ts +2 -2
  11. package/dist/lib/native-safety-registration.d.ts +2 -2
  12. package/dist/lib/native-safety.d.ts +1 -1
  13. package/dist/lib/registry.d.ts +3 -1
  14. package/dist/native-safety.d.ts +4 -2
  15. package/dist/native-safety.js +21 -2
  16. package/dist/sdk/index.js +9 -53
  17. package/hooks/hook-job-folder-guard/README.md +61 -0
  18. package/hooks/hook-job-folder-guard/package.json +12 -0
  19. package/hooks/hook-job-folder-guard/src/classify.ts +398 -0
  20. package/hooks/hook-job-folder-guard/src/hook.ts +96 -0
  21. package/hooks/hook-protected-delete-guard/README.md +114 -0
  22. package/hooks/hook-protected-delete-guard/package.json +12 -0
  23. package/hooks/hook-protected-delete-guard/src/hook.ts +539 -0
  24. package/hooks/hook-signed-link-guard/src/classify.ts +41 -2
  25. package/hooks/hook-stop-review/README.md +16 -0
  26. package/hooks/hook-stop-review/manifest.json +1 -1
  27. package/hooks/hook-stop-review/package.json +1 -1
  28. package/hooks/hook-stop-review/src/hook.ts +1 -1
  29. package/hooks/hook-stop-review/src/native.ts +44 -8
  30. package/hooks/hook-stop-review/src/policy.ts +20 -8
  31. package/hooks/hook-stop-review/src/runtime.ts +16 -13
  32. package/hooks/hook-stop-review/src/types.ts +12 -2
  33. package/hooks/hook-trash-guard/README.md +130 -13
  34. package/hooks/hook-trash-guard/src/hook.ts +518 -71
  35. package/hooks/local-executors.ts +33 -0
  36. package/hooks/native-safety-composite.ts +19 -8
  37. package/package.json +3 -3
  38. package/scripts/build-native-entry.ts +123 -0
  39. package/scripts/build-native-worker.ts +11 -4
  40. package/scripts/validate-package.ts +8 -2
  41. package/hooks/native-safety-entry.ts +0 -11
@@ -719,6 +719,39 @@ export interface ShellProgram {
719
719
  export const ansiPlain = (text: string): string =>
720
720
  text.replace(/\$'(?:[^'\\]|\\[\s\S])*'/g, (word) => word.replace(/\\[\s\S]/g, (pair) => (pair === "\\'" ? "\\x27" : pair)));
721
721
 
722
+ /**
723
+ * ansiPlain, with a `$'…'` word read from every `$'` in `text` rather than in one
724
+ * pass from the left (HO-00222). A `$'` that bash does not read as ANSI-C (inside
725
+ * quotes, in a comment or a here-document body) starts a word in that pass which
726
+ * runs to the opening quote of a real `$'it\'s'`, so the real word was never
727
+ * respelled. A word can hold another `$'` only as its closing quote, so the words
728
+ * cover the text at most about twice. A stray `$'` can only respell more than
729
+ * bash would, so callers read this beside ansiPlain, never instead of it.
730
+ */
731
+ export function ansiPlainEvery(text: string): string {
732
+ const word = /\$'(?:[^'\\]|\\[\s\S])*'/y;
733
+ const found = new Set<number>();
734
+ for (let at = text.indexOf("$'"); at >= 0; at = text.indexOf("$'", at + 1)) {
735
+ word.lastIndex = at;
736
+ const match = word.exec(text);
737
+ if (!match) continue;
738
+ const end = at + match[0].length - 1;
739
+ for (let i = at + 2; i < end; i++) {
740
+ if (text[i] !== "\\") continue;
741
+ if (text[i + 1] === "'") found.add(i);
742
+ i++;
743
+ }
744
+ }
745
+ if (found.size === 0) return text;
746
+ let out = "";
747
+ let from = 0;
748
+ for (const at of [...found].sort((a, b) => a - b)) {
749
+ out += `${text.slice(from, at)}\\x27`;
750
+ from = at + 2;
751
+ }
752
+ return out + text.slice(from);
753
+ }
754
+
722
755
  export function shellProgram(raw: string[], index: number, decodeName: (raw: string) => string | null = literalWord): ShellProgram | null {
723
756
  if (index < 0 || index >= raw.length) return null;
724
757
  const name = baseName(decodeName(raw[index]) ?? "");
@@ -1,22 +1,25 @@
1
1
  import { homedir } from "node:os";
2
2
  import { isAbsolute } from "node:path";
3
- import { evaluate as evaluateTrash, findTrashBinary, inspectTrashBinary, scanCommand } from "./hook-trash-guard/src/hook";
3
+ import { evaluate as evaluateTrash, findTrashBinary, HANDOFF_REFUSED, inspectTrashBinary, scanCommand } from "./hook-trash-guard/src/hook";
4
4
  import { evaluate as evaluateRepos } from "./hook-workspace-repos-guard/src/hook";
5
+ import { guard as evaluateProtectedDelete } from "./hook-protected-delete-guard/src/hook";
5
6
  import { readWithLegacyQuotes } from "./local-executors";
6
7
  import { evaluate as evaluateSignedLinks } from "./hook-signed-link-guard/src/hook";
7
8
  import type { CodewithHookInput, CodewithHookOutput } from "./codewith-native-common";
8
9
 
9
10
  // The native safety composite: trash-guard, workspace-repos-guard and
10
- // signed-link-guard judged together for one capability name. Both the v1 entry
11
- // (hooks/native-safety-entry.ts) and the v2 worker (hooks/native-safety-worker.ts)
12
- // call it, so one guard decision has one implementation. It reads no stdin,
13
- // writes no stdout and never exits: the caller owns the process.
11
+ // signed-link-guard judged together for one capability name, and
12
+ // protected-delete-guard judged on its own under its name. The v2 worker
13
+ // (hooks/native-safety-worker.ts) calls it, and the v1 entry carries that worker
14
+ // (scripts/build-native-entry.ts), so one guard decision has one
15
+ // implementation. It reads no stdin, writes no stdout and never exits: the
16
+ // caller owns the process.
14
17
 
15
- export type NativeSafetyCompositeGuard = "trash-guard" | "workspace-repos-guard";
18
+ export type NativeSafetyCompositeGuard = "trash-guard" | "workspace-repos-guard" | "protected-delete-guard";
16
19
 
17
20
  /** Refuses an unknown capability name exactly as the v1 entry always has. */
18
21
  export function assertCompositeGuard(guard: unknown): asserts guard is NativeSafetyCompositeGuard {
19
- if (guard !== "trash-guard" && guard !== "workspace-repos-guard") throw new Error("Invalid safety capability");
22
+ if (guard !== "trash-guard" && guard !== "workspace-repos-guard" && guard !== "protected-delete-guard") throw new Error("Invalid safety capability");
20
23
  }
21
24
 
22
25
  /**
@@ -54,6 +57,14 @@ export function evaluateComposite(guard: string, inputText: string): string {
54
57
  const shellCommand = input.tool_name === "Bash" || (monitor && typeof input.tool_input.command === "string");
55
58
  const evaluated: CodewithHookInput = monitor && shellCommand ? { ...input, tool_name: "Bash" } : input;
56
59
  const deny = (reason: string) => ({ hookSpecificOutput: { hookEventName: "PreToolUse" as const, permissionDecision: "deny" as const, permissionDecisionReason: reason } });
60
+ // protected-delete-guard judges by its own class and nothing else: it only
61
+ // denies, it looks for no trash binary, and the checkout rules and the
62
+ // signed-link guard stay with the registrations that carry them, so switching
63
+ // this one off changes nothing but its own refusals.
64
+ if (name === "protected-delete-guard") {
65
+ const own = evaluateProtectedDelete(evaluated, { home: homedir(), cwd: input.cwd, env: process.env });
66
+ return JSON.stringify({ verdict: own.hookSpecificOutput?.permissionDecision === "deny" ? own : null });
67
+ }
57
68
  const repos = evaluateRepos(evaluated).output;
58
69
  // Every shell command, whatever the capability name: the guard reaches each
59
70
  // registration of this entry. Its refusal outranks a Trash rewrite, because an
@@ -73,7 +84,7 @@ export function evaluateComposite(guard: string, inputText: string): string {
73
84
  }
74
85
  const verdict: CodewithHookOutput = repos.decision === "block" ? deny(repos.reason!)
75
86
  : signedLinks.hookSpecificOutput ? signedLinks
76
- : handoff ? deny("[workspace-repos-guard] Deletion under a protected repository checkout is refused.")
87
+ : handoff ? deny(HANDOFF_REFUSED)
77
88
  : trash;
78
89
  return JSON.stringify({ verdict: "continue" in verdict ? null : verdict });
79
90
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hasna/hooks",
3
- "version": "0.13.2",
3
+ "version": "0.14.0",
4
4
  "description": "Open source hooks library for AI coding agents - Install safety, quality, and automation hooks with a single command",
5
5
  "type": "module",
6
6
  "bin": {
@@ -53,7 +53,7 @@
53
53
  "postinstall": "node scripts/ensure-profiles-dir.mjs",
54
54
  "scan:artifact": "bun scripts/artifact-scan.ts",
55
55
  "prepack": "bun run build && bun run scan:artifact",
56
- "build:native-safety": "bun build ./hooks/native-safety-entry.ts --outdir ./bin --target bun --minify --define import.meta.main=false && bun build ./src/native-safety.ts --outdir ./dist --target bun && bun run build:native-readiness",
56
+ "build:native-safety": "bun scripts/build-native-entry.ts && bun build ./src/native-safety.ts --outdir ./dist --target bun && bun run build:native-readiness",
57
57
  "build:native-readiness": "bun build ./hooks/native-readiness-entry.ts --outdir ./bin --target node --format=cjs && bun build ./src/native-readiness.ts --outdir ./dist --target bun",
58
58
  "build:native-safety-worker": "bun scripts/build-native-worker.ts",
59
59
  "build:bundled-hooks": "bun scripts/build-bundled-hooks.ts",
@@ -87,7 +87,7 @@
87
87
  "@hasna/contracts": "~1.2.1"
88
88
  },
89
89
  "dependencies": {
90
- "@hasna/skills": "0.10.78",
90
+ "@hasna/skills": "0.10.100",
91
91
  "@hasna/events": "^0.1.16",
92
92
  "@hasna/secrets": "0.4.2",
93
93
  "@modelcontextprotocol/sdk": "1.31.0",
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Build the v1 native safety entry, bin/native-safety-entry.js (HO-00144).
4
+ *
5
+ * The v1 supervisor (src/lib/native-safety.ts, the current template and the
6
+ * frozen previous one the Sumi guard record keeps) reads the file a
7
+ * registration pins, checks its sha256 and passes its bytes to Bun as ONE
8
+ * `--eval` argument. Linux refuses a single argument of 131,072 bytes or more
9
+ * (MAX_ARG_STRLEN with 4 KiB pages), and the guard code alone is close to that.
10
+ *
11
+ * So the entry carries the v2 worker (scripts/build-native-worker.ts: the same
12
+ * bundle as bin/native-safety-worker.cjs) deflated and base64-encoded. When it
13
+ * runs, it inflates those bytes, refuses unless their sha256 equals the one
14
+ * written into the entry, evaluates exactly those bytes as a CommonJS function
15
+ * body with a `require` that serves only `node:` builtins (the v2 loader's
16
+ * shape, ADR 0001 section 3.3), and writes `evaluate(argv[1], stdin)` to
17
+ * stdout. Its contract with the supervisor is the v1 entry's: the capability
18
+ * name in argv[1], the hook input on stdin, one JSON write to stdout, and a
19
+ * non-zero exit on any failure.
20
+ *
21
+ * The supervisor's digest covers the deflated bytes and inflating is
22
+ * deterministic, so the code that runs is still fixed by the pinned digest.
23
+ * This raises the v1 ceiling, it does not remove it: the entry itself must stay
24
+ * below the argument limit, and the build refuses one that does not. The v2
25
+ * launcher (ADR 0001), which reads the worker from its file, has no such limit.
26
+ *
27
+ * Usage: bun scripts/build-native-entry.ts [--outfile <path>]
28
+ */
29
+ import { createHash } from "node:crypto";
30
+ import { mkdirSync, writeFileSync } from "node:fs";
31
+ import { dirname, join, resolve } from "node:path";
32
+ import { deflateRawSync, inflateRawSync } from "node:zlib";
33
+ import { bundleNativeSafetyWorker } from "./build-native-worker";
34
+
35
+ export const ENTRY_OUTFILE = "bin/native-safety-entry.js";
36
+ /** Linux's single exec argument limit with 4 KiB pages; the entry must stay below it. */
37
+ export const ENTRY_ARGUMENT_LIMIT = 131_072;
38
+
39
+ /**
40
+ * The entry's exact text for a deflated, base64-encoded worker and the worker's sha256.
41
+ *
42
+ * The first line must be the `// @bun` pragma that `bun build` writes. Without
43
+ * it Bun transpiles an `--eval` source this large and caches the result under
44
+ * `$HOME/.bun/install/cache`: the guard would write into the home it guards,
45
+ * and a later call could run that cached code instead of the bytes the
46
+ * supervisor verified. With it, Bun runs the text as written, so the entry is
47
+ * an ES module and uses `import`, not `require`.
48
+ */
49
+ function entryText(packed: string, sha256: string): string {
50
+ return `// @bun
51
+ // @hasna/hooks native safety entry for the v1 supervisor: the v2 worker (bin/native-safety-worker.cjs), deflated. See scripts/build-native-entry.ts.
52
+ import { inflateRawSync } from "node:zlib";
53
+ import { createHash } from "node:crypto";
54
+ import { builtinModules, createRequire } from "node:module";
55
+ const builtins = new Set(builtinModules), load = createRequire("/");
56
+ const source = inflateRawSync(Buffer.from("${packed}", "base64"));
57
+ if (createHash("sha256").update(source).digest("hex") !== "${sha256}") throw new Error("native safety worker digest mismatch");
58
+ const worker = { exports: {} };
59
+ const workerRequire = (specifier) => {
60
+ if (typeof specifier === "string" && /^node:[a-z][a-z0-9_]*(?:[/][a-z][a-z0-9_]*)*$/.test(specifier) && builtins.has(specifier.slice(5))) return load(specifier);
61
+ throw new Error("native safety worker may require only node: builtins");
62
+ };
63
+ new Function("module", "exports", "require", source.toString("utf8"))(worker, worker.exports, workerRequire);
64
+ if (worker.exports.abi !== 2 || typeof worker.exports.evaluate !== "function") throw new Error("native safety worker ABI mismatch");
65
+ process.stdout.write(worker.exports.evaluate(process.argv[1], await Bun.stdin.text()));
66
+ `;
67
+ }
68
+
69
+ /** The entry that carries `workerSource`. Pure: the same worker gives the same entry. */
70
+ export function nativeSafetyEntrySource(workerSource: string): string {
71
+ const bytes = Buffer.from(workerSource, "utf8");
72
+ return entryText(deflateRawSync(bytes, { level: 9 }).toString("base64"), createHash("sha256").update(bytes).digest("hex"));
73
+ }
74
+
75
+ /**
76
+ * The worker bytes an entry carries, or undefined when `entry` is not exactly
77
+ * an entry this script writes: the wrapper text must match byte for byte, and
78
+ * the inflated bytes must match the sha256 written into it.
79
+ */
80
+ export function nativeSafetyEntryWorker(entry: string): Buffer | undefined {
81
+ const parts = /\nconst source = inflateRawSync\(Buffer\.from\("([A-Za-z0-9+/]*={0,2})", "base64"\)\);\nif \(createHash\("sha256"\)\.update\(source\)\.digest\("hex"\) !== "([0-9a-f]{64})"\)/.exec(entry);
82
+ if (!parts || entryText(parts[1]!, parts[2]!) !== entry) return undefined;
83
+ try {
84
+ const source = inflateRawSync(Buffer.from(parts[1]!, "base64"));
85
+ return createHash("sha256").update(source).digest("hex") === parts[2] ? source : undefined;
86
+ } catch { return undefined; }
87
+ }
88
+
89
+ export interface NativeSafetyEntryBuild { outfile: string; bytes: number; sha256: string; workerBytes: number; workerSHA256: string; version: string }
90
+
91
+ /** Bundle the worker, wrap it and write the entry. Writes nothing when the worker check or the size check fails. */
92
+ export async function buildNativeSafetyEntry(options: { packageDir?: string; outfile?: string } = {}): Promise<NativeSafetyEntryBuild> {
93
+ const packageDir = resolve(options.packageDir ?? join(import.meta.dir, ".."));
94
+ const outfile = resolve(packageDir, options.outfile ?? ENTRY_OUTFILE);
95
+ const { source, version } = await bundleNativeSafetyWorker(packageDir);
96
+ const entry = nativeSafetyEntrySource(source);
97
+ const bytes = Buffer.byteLength(entry);
98
+ if (bytes >= ENTRY_ARGUMENT_LIMIT) throw new Error(`native safety entry is ${bytes} bytes; one exec argument holds at most ${ENTRY_ARGUMENT_LIMIT - 1}`);
99
+ mkdirSync(dirname(outfile), { recursive: true });
100
+ // A new file is never group- or world-writable, whatever the umask: the supervisor's pin check refuses such a file.
101
+ writeFileSync(outfile, entry, { mode: 0o644 });
102
+ return {
103
+ outfile, bytes, sha256: createHash("sha256").update(entry).digest("hex"),
104
+ workerBytes: Buffer.byteLength(source), workerSHA256: createHash("sha256").update(source).digest("hex"), version,
105
+ };
106
+ }
107
+
108
+ if (import.meta.main) {
109
+ const args = process.argv.slice(2);
110
+ let outfile: string | undefined;
111
+ if (args.length === 2 && args[0] === "--outfile" && args[1]) outfile = resolve(args[1]);
112
+ else if (args.length !== 0) {
113
+ console.error("usage: bun scripts/build-native-entry.ts [--outfile <path>]");
114
+ process.exit(2);
115
+ }
116
+ try {
117
+ const built = await buildNativeSafetyEntry({ outfile });
118
+ console.log(`native-safety-entry.js ${built.version}: ${built.bytes} bytes (worker ${built.workerBytes} bytes, sha256 ${built.workerSHA256}), sha256 ${built.sha256} -> ${built.outfile}`);
119
+ } catch (error) {
120
+ console.error(error instanceof Error ? error.message : String(error));
121
+ process.exit(1);
122
+ }
123
+ }
@@ -107,10 +107,9 @@ export function workerBundleProblems(source: string): string[] {
107
107
 
108
108
  export interface NativeSafetyWorkerBuild { outfile: string; bytes: number; sha256: string; version: string }
109
109
 
110
- /** Bundle, check and write the worker. Writes nothing when a check fails. */
111
- export async function buildNativeSafetyWorker(options: { packageDir?: string; outfile?: string } = {}): Promise<NativeSafetyWorkerBuild> {
112
- const packageDir = resolve(options.packageDir ?? join(import.meta.dir, ".."));
113
- const outfile = resolve(packageDir, options.outfile ?? WORKER_OUTFILE);
110
+ /** Bundle and check the worker without writing it. Throws when a check fails. */
111
+ export async function bundleNativeSafetyWorker(packageDir: string = join(import.meta.dir, "..")): Promise<{ source: string; version: string }> {
112
+ packageDir = resolve(packageDir);
114
113
  const version: unknown = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8")).version;
115
114
  if (typeof version !== "string" || !/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) throw new Error("package.json has no valid version for the native safety worker");
116
115
  const result = await Bun.build({
@@ -128,6 +127,14 @@ export async function buildNativeSafetyWorker(options: { packageDir?: string; ou
128
127
  const source = await result.outputs[0]!.text();
129
128
  const problems = workerBundleProblems(source);
130
129
  if (problems.length > 0) throw new Error(`native safety worker bundle refused:\n${problems.map((problem) => ` - ${problem}`).join("\n")}`);
130
+ return { source, version };
131
+ }
132
+
133
+ /** Bundle, check and write the worker. Writes nothing when a check fails. */
134
+ export async function buildNativeSafetyWorker(options: { packageDir?: string; outfile?: string } = {}): Promise<NativeSafetyWorkerBuild> {
135
+ const packageDir = resolve(options.packageDir ?? join(import.meta.dir, ".."));
136
+ const outfile = resolve(packageDir, options.outfile ?? WORKER_OUTFILE);
137
+ const { source, version } = await bundleNativeSafetyWorker(packageDir);
131
138
  mkdirSync(dirname(outfile), { recursive: true });
132
139
  // A new file is never group- or world-writable, whatever the umask: the launcher's pin check refuses such a worker.
133
140
  writeFileSync(outfile, source, { mode: 0o644 });
@@ -3,6 +3,7 @@ import { existsSync } from "node:fs";
3
3
  import { chmod, copyFile, mkdtemp, mkdir, readFile, realpath, rm, symlink, writeFile } from "node:fs/promises";
4
4
  import { dirname, join } from "node:path";
5
5
  import { validatePackedBundledHooks } from "./validate-bundled-hooks";
6
+ import { ENTRY_ARGUMENT_LIMIT, nativeSafetyEntryWorker } from "./build-native-entry";
6
7
 
7
8
  type PackageJson = {
8
9
  name: string;
@@ -275,10 +276,15 @@ console.log("packed Hooks accepts codex-settings-v6 and refuses unknown mode wit
275
276
  async function validatePackedNativeSafety(packageDir: string, smokeDir: string): Promise<void> {
276
277
  const worker = join(packageDir, "bin/native-safety-entry.js");
277
278
  const bytes = await readFile(worker);
278
- // The supervisor passes the worker as one `--eval` argument; Linux refuses a
279
+ // The supervisor passes the entry as one `--eval` argument; Linux refuses a
279
280
  // single argument over 32 pages (131,072 bytes with 4 KiB pages), and every
280
281
  // command would then fail to launch. Check it before the launch smoke tests.
281
- if (bytes.length >= 131_072) throw new Error(`Packed native worker is ${bytes.length} bytes; one exec argument holds at most 131072`);
282
+ if (bytes.length >= ENTRY_ARGUMENT_LIMIT) throw new Error(`Packed native entry is ${bytes.length} bytes; one exec argument holds at most ${ENTRY_ARGUMENT_LIMIT - 1}`);
283
+ // The entry carries the v2 worker deflated (scripts/build-native-entry.ts).
284
+ // Both lanes must run the same guard code, so it must carry exactly the
285
+ // packed bin/native-safety-worker.cjs.
286
+ const carried = nativeSafetyEntryWorker(bytes.toString("utf8"));
287
+ if (!carried || !carried.equals(await readFile(join(packageDir, "bin/native-safety-worker.cjs")))) throw new Error("Packed native entry does not carry the packed bin/native-safety-worker.cjs");
282
288
  const home = join(smokeDir, "native-safety-home");
283
289
  await mkdir(home, { mode: 0o700 });
284
290
  const settings = join(home, ".codex", "hooks.json");
@@ -1,11 +0,0 @@
1
- import { assertCompositeGuard, evaluateComposite } from "./native-safety-composite";
2
-
3
- // The v1 native safety entry: a thin wrapper over the composite. Its contract is
4
- // fixed by the v1 supervisor (src/lib/native-safety.ts): the capability name is
5
- // argv[1], the hook input is stdin, the verdict is one JSON write to stdout, and
6
- // any failure exits non-zero.
7
- // Bundled with import.meta.main=false, so the original standalone run wrappers
8
- // cannot swallow exceptions or emit a second response. Only this entry runs.
9
- const name = process.argv[1];
10
- assertCompositeGuard(name);
11
- process.stdout.write(evaluateComposite(name, await Bun.stdin.text()));