@hasna/hooks 0.14.1 → 0.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.
Files changed (37) hide show
  1. package/README.md +30 -10
  2. package/bin/hooks/stop-review.js +17 -9
  3. package/bin/hooks-mcp.js +741 -311
  4. package/bin/index.js +1669 -632
  5. package/bin/native-safety-entry.js +2 -2
  6. package/bin/native-safety-worker.cjs +36 -34
  7. package/bin/release-manifest.json +297 -0
  8. package/bin/serve.js +577 -151
  9. package/dist/index.js +1809 -1176
  10. package/dist/lib/error-events.d.ts +59 -0
  11. package/dist/lib/install-record.d.ts +136 -0
  12. package/dist/lib/manifest.d.ts +6 -0
  13. package/dist/lib/release-manifest.d.ts +162 -0
  14. package/dist/lib/store.d.ts +25 -2
  15. package/dist/openapi.d.ts +147 -0
  16. package/dist/registry-auth.d.ts +6 -1
  17. package/dist/registry-http.d.ts +2 -1
  18. package/dist/sdk/generated.d.ts +26 -0
  19. package/dist/sdk/index.js +14 -0
  20. package/hooks/codewith-native-common.ts +190 -6
  21. package/hooks/hook-signed-link-guard/README.md +46 -0
  22. package/hooks/hook-signed-link-guard/src/classify.ts +7 -3
  23. package/hooks/hook-signed-link-guard/src/jq.ts +205 -34
  24. package/hooks/hook-stop-review/README.md +5 -2
  25. package/hooks/hook-stop-review/src/jev.ts +9 -4
  26. package/hooks/hook-stop-review/src/policy.ts +7 -3
  27. package/hooks/hook-stop-review/src/runtime.ts +5 -4
  28. package/hooks/hook-trash-guard/README.md +9 -4
  29. package/hooks/hook-trash-guard/src/hook.ts +127 -10
  30. package/hooks/hook-workspace-repos-guard/src/hook.ts +27 -12
  31. package/hooks/pre-bash/README.md +47 -1
  32. package/hooks/pre-bash/src/hook.ts +168 -12
  33. package/hooks/shell-words.ts +40 -2
  34. package/package.json +3 -2
  35. package/scripts/build-release-manifest.ts +27 -0
  36. package/scripts/validate-package.ts +5 -1
  37. package/scripts/validate-release-manifest.ts +67 -0
@@ -82,6 +82,7 @@ import {
82
82
  OPTIONAL,
83
83
  REFUSE,
84
84
  VALUE,
85
+ WATCH_SPEC,
85
86
  WRAPPER_SPECS,
86
87
  expandBraces,
87
88
  splitsOrMoves,
@@ -144,9 +145,11 @@ export const OBSERVED_REFUSALS: ReadonlySet<string> = new Set([...Object.values(
144
145
  /**
145
146
  * Commands whose own argument string is a shell command we cannot rewrite in
146
147
  * place. When one of these is in command position and the command mentions a
147
- * delete verb, the command is refused rather than guessed at.
148
+ * delete verb, the command is refused rather than guessed at. `watch` runs a
149
+ * command line (watchCommandLine); it is one of these only where that line
150
+ * cannot be read (HO-00242).
148
151
  */
149
- const OPAQUE_COMMANDS = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "eval", "source", ".", "su", "runuser", "env"]);
152
+ const OPAQUE_COMMANDS = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "eval", "source", ".", "su", "runuser", "env", "watch"]);
150
153
 
151
154
  /** Wrapper commands whose real command follows them (with their value-taking options). */
152
155
  const WRAPPERS: Record<string, string[]> = {
@@ -1636,6 +1639,26 @@ export function strictCommandIndex(segment: Segment): number | null {
1636
1639
  return found.index < 0 ? -1 : kept[found.index];
1637
1640
  }
1638
1641
 
1642
+ /**
1643
+ * The command line the `watch` at `index` of `segment` runs (HO-00242): the
1644
+ * words after its own options (WATCH_SPEC; nested `watch` words too), decoded
1645
+ * and joined with spaces as watch joins them before `sh -c` runs them. "" when
1646
+ * it runs nothing; null when a word expands at runtime or an option cannot be
1647
+ * read, so the line is unknown. Redirections are the shell's, not watch's.
1648
+ */
1649
+ export function watchCommandLine(segment: Segment, index: number): string | null {
1650
+ const words: ShellWord[] = [];
1651
+ for (let at = index; at < segment.words.length; at++) {
1652
+ if (segment.redirects.has(at)) continue;
1653
+ const raw = segment.words[at].text;
1654
+ if (expandsWord(raw)) return null;
1655
+ words.push({ text: decodeCommandWord(raw), opaque: false });
1656
+ }
1657
+ const found = unwrapCommand(words, { watch: WATCH_SPEC });
1658
+ if (found === null) return null;
1659
+ return found.index < 0 ? "" : words.slice(found.index).map((word) => word.text).join(" ");
1660
+ }
1661
+
1639
1662
  /**
1640
1663
  * Where a `cd` leaves the shell, read with bash's grammar (HO-00185): options first (`-L`, `-P`, `-e`, alone or
1641
1664
  * combined, the ones bash accepts on Linux), then `--`, then the directory; `cd` with no operand goes home. Before
@@ -1701,6 +1724,9 @@ function readDirectoryChange(segment: Segment, index: number, cwd: string, ctx:
1701
1724
  return target === null ? unknown : { kind: "cd", cwd: target };
1702
1725
  }
1703
1726
 
1727
+ const WATCH_REASON =
1728
+ "`watch` runs its command again and again, so a delete in it cannot be redirected into trash. Run the delete once, as `rm -- <path>` (intercepted and redirected into trash).";
1729
+
1704
1730
  /** What the command whose word is at `index` of `segment` does. */
1705
1731
  function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanContext): Reading {
1706
1732
  const verb = commandName(segment.words[index].text);
@@ -1819,6 +1845,21 @@ function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanCo
1819
1845
  }
1820
1846
  if (verb === "xargs") return launchedRefusal(segment, index, cwd, ctx) ?? { kind: "none" };
1821
1847
 
1848
+ // watch reruns the command line it runs (watchCommandLine), so a delete or a
1849
+ // refused form in that line is refused: rewritten, it would run again and
1850
+ // again (HO-00242). The line is scanned as a command of its own, sharing the
1851
+ // depth that bounds substitution bodies; a line that cannot be read, or one
1852
+ // past that depth, keeps the command-string refusal below (OPAQUE_COMMANDS).
1853
+ if (verb === "watch" && ctx.depth < 3) {
1854
+ const line = watchCommandLine(segment, index);
1855
+ if (line !== null) {
1856
+ const inner = line ? scanCommand(line, { cwd, home: ctx.home, depth: ctx.depth + 1 }) : null;
1857
+ const live = inner !== null && (inner.rmHits.length + inner.refusals.length + inner.handoffHits.length + inner.protectedHits.length > 0
1858
+ || (!inner.trustworthy && mentionsDeleteVerb(line)));
1859
+ return live ? { kind: "refuse", reason: WATCH_REASON } : { kind: "none" };
1860
+ }
1861
+ }
1862
+
1822
1863
  // `flock <file> -c <string>` runs the string through a shell: as the shared
1823
1864
  // reading sees it (`flock`) and as the strict one does (`-c`, the word after
1824
1865
  // the lock file).
@@ -1974,6 +2015,8 @@ interface ScanOptions {
1974
2015
  depth?: number;
1975
2016
  /** Called for each delete the scan reads exactly (ObservedDelete), in substitution bodies too. */
1976
2017
  observe?: DeleteObserver;
2018
+ /** The readings this call has scanned, by text (HO-00233): each respelled reading is scanned once per call. */
2019
+ scanned?: Map<string, ScanResult>;
1977
2020
  }
1978
2021
 
1979
2022
  const CASE_WORD_RE = /(^|[^A-Za-z0-9_.-])(case|esac)(?![A-Za-z0-9_.-])/;
@@ -2002,25 +2045,99 @@ export function blankComments(command: string): string {
2002
2045
  * on them was trusted and missed. That spelling moves offsets, so what it finds is kept and the command is not trusted:
2003
2046
  * refused, never rewritten. The words are found in one pass from the left (ansiPlain) and, beside that, from every
2004
2047
  * `$'` (ansiPlainEvery), because a `$'` bash does not read as ANSI-C can start a word that hides the real one
2005
- * (HO-00222).
2048
+ * (HO-00222), and as bash reads them (ansiPlainBash), because that reading of every `$'` also respelled an escaped
2049
+ * `\$'a\'`, whose quote then never closed (HO-00233). The readings of readings often repeat, so each text is scanned
2050
+ * once per call; the same text and options give the same result.
2006
2051
  */
2007
2052
  export function scanCommand(command: string, options: ScanOptions): ScanResult {
2008
- const kept = scanReading(command, options);
2053
+ const scanned = options.scanned ?? new Map<string, ScanResult>();
2054
+ const known = scanned.get(command);
2055
+ if (known) return known;
2056
+ const within = { ...options, scanned };
2057
+ const kept = scanReading(command, within);
2009
2058
  const blanked = blankComments(command);
2010
- let result = blanked === command ? kept : unionReadings(kept, scanReading(blanked, options));
2059
+ let result = blanked === command ? kept : unionReadings(kept, scanReading(blanked, within));
2011
2060
  for (const plain of ansiReadings(command)) {
2012
- const spelled = scanCommand(plain, options);
2061
+ const spelled = scanCommand(plain, within);
2013
2062
  const found = spelled.rmHits.length + spelled.handoffHits.length + spelled.refusals.length + spelled.protectedHits.length > 0;
2014
2063
  if (found) result = { ...unionReadings(result, spelled), trustworthy: false };
2015
2064
  }
2065
+ scanned.set(command, result);
2016
2066
  return result;
2017
2067
  }
2018
2068
 
2019
- /** The respelled readings of `command` (ansiPlain, then ansiPlainEvery) that differ from it and from each other. */
2069
+ /**
2070
+ * ansiPlain, with `\'` respelled only inside the `$'…'` words bash reads as ANSI-C (HO-00233). The text is read from
2071
+ * the left as bash reads it, following backslashes, single and double quotes, `$(…)` and backquotes inside double
2072
+ * quotes, comments and here-document bodies. So a `$'` that is escaped (`\$'`), the second `$` of `$$`, quoted, in a
2073
+ * comment or in a here-document body starts no word. ansiPlainEvery respells such a `$'` too, and where its string
2074
+ * ends in a backslash (`\$'a\'` is a backslash then the closing quote in bash) the quote stayed open in that reading,
2075
+ * so a delete after a real `$'it\'s'` was hidden from every reading. The lexer's double-quote and substitution scanners
2076
+ * can't be used here: they end `$'it\'s'` at its escaped quote. Callers read this beside the other readings, never
2077
+ * instead of them.
2078
+ */
2079
+ export function ansiPlainBash(text: string): string {
2080
+ let out = "";
2081
+ let i = 0;
2082
+ let pending: HeredocMarker[] = [];
2083
+ // Reads to the `close` that ends this context: `"`, the `)` of `$(`, a backquote, or "" for the end of the text.
2084
+ const read = (close: string): void => {
2085
+ let depth = 0;
2086
+ while (i < text.length) {
2087
+ const c = text[i];
2088
+ const next = text[i + 1];
2089
+ let end = i + 1;
2090
+ if (c === "\\") end = i + 2;
2091
+ else if (c === close && (close !== ")" || depth-- === 0)) {
2092
+ out += c;
2093
+ i++;
2094
+ return;
2095
+ } else if (close === '"') {
2096
+ if (c === "`" || (c === "$" && next === "(" && text[i + 2] !== "(")) {
2097
+ end = c === "`" ? i + 1 : i + 2;
2098
+ out += text.slice(i, end);
2099
+ i = end;
2100
+ read(c === "`" ? "`" : ")");
2101
+ continue;
2102
+ }
2103
+ } else if (c === "$" && next === "'") {
2104
+ const word = /\$'(?:[^'\\]|\\[\s\S])*'?/y;
2105
+ word.lastIndex = i;
2106
+ const found = (word.exec(text) as RegExpExecArray)[0];
2107
+ out += found.replace(/\\[\s\S]/g, (pair) => (pair === "\\'" ? "\\x27" : pair));
2108
+ i += found.length;
2109
+ continue;
2110
+ } else if (c === "$" && next === "$") end = i + 2;
2111
+ else if (c === "$" && next === "(" && text[i + 2] === "(") end = scanParenAt(text, i + 1);
2112
+ else if (c === "'") end = scanSingleAt(text, i);
2113
+ else if (c === '"') {
2114
+ out += c;
2115
+ i++;
2116
+ read('"');
2117
+ continue;
2118
+ } else if (c === "(") depth++;
2119
+ else if (c === "#" && (i === 0 || /[\s;&|()<>]/.test(text[i - 1]))) end = text.indexOf("\n", i);
2120
+ else if (c === "<" && next === "<") {
2121
+ const marker = heredocMarkerAt(text, i);
2122
+ if (marker) pending.push(marker);
2123
+ end = marker ? marker.end : i + 2;
2124
+ } else if (c === "\n" && pending.length > 0) {
2125
+ end = skipHeredocBodies(text, i, pending);
2126
+ pending = [];
2127
+ }
2128
+ if (end < 0) end = text.length;
2129
+ out += text.slice(i, end);
2130
+ i = end;
2131
+ }
2132
+ };
2133
+ read("");
2134
+ return out;
2135
+ }
2136
+
2137
+ /** The respelled readings of `command` (ansiPlain, ansiPlainEvery, ansiPlainBash) that differ from it and each other. */
2020
2138
  function ansiReadings(command: string): string[] {
2021
- const plain = ansiPlain(command);
2022
- const every = ansiPlainEvery(command);
2023
- return [plain, every].filter((reading, index, all) => reading !== command && all.indexOf(reading) === index);
2139
+ const readings = [ansiPlain(command), ansiPlainEvery(command), ansiPlainBash(command)];
2140
+ return readings.filter((reading, index, all) => reading !== command && all.indexOf(reading) === index);
2024
2141
  }
2025
2142
 
2026
2143
  function unionReadings(kept: ScanResult, other: ScanResult): ScanResult {
@@ -40,9 +40,10 @@
40
40
  * command can run it (see dataHeredocs): its words are then never resolved
41
41
  * against the cwd, and only protected paths it names explicitly count.
42
42
  * Wrapper commands (timeout, env, nice, nohup, command, exec, builtin,
43
- * stdbuf, time, ionice, setsid) and their own arguments are skipped before
44
- * the command and its operands are read (see unwrapCommand); arguments they
45
- * cannot be parsed from fail closed. A Trash capture is read the way
43
+ * stdbuf, time, ionice, setsid, caffeinate, chronic, unbuffer) and their own
44
+ * arguments are skipped before the command and its operands are read (see
45
+ * unwrapCommand); arguments they cannot be parsed from fail closed. watch's
46
+ * command line is read as the command it is (see watchCommandLine). A Trash capture is read the way
46
47
  * @hasna/trash parses it, with options before, between or after its paths
47
48
  * until `--` (see trashOperands). A quoted command list that the `;`, `&&`,
48
49
  * `||` and newline split cuts (`ssh host 'a; trash --version'`) is read as
@@ -72,6 +73,7 @@ import {
72
73
  heredocMarkerAt,
73
74
  lexCommand,
74
75
  mentionsDeleteVerb,
76
+ watchCommandLine,
75
77
  type HeredocMarker,
76
78
  } from "../../hook-trash-guard/src/hook";
77
79
  import {
@@ -462,7 +464,7 @@ function expandsAtRuntime(raw: string): boolean {
462
464
  * stronger of the two readings stands, and a wrapper whose arguments the
463
465
  * strict model cannot parse falls back to the opaque reading.
464
466
  */
465
- function segmentOperation(segment: string): Operation {
467
+ function segmentOperation(segment: string, depth = 0): Operation {
466
468
  const trimmed = segment.trim();
467
469
  if (!trimmed) return "read";
468
470
  // A destructive local executor counts wherever it hides: in a substitution
@@ -472,7 +474,7 @@ function segmentOperation(segment: string): Operation {
472
474
  // Preserve conservative classification where the shell body is opaque.
473
475
  if (!parsed.trustworthy || parsed.substitutions.length || /\$\{[^}]*[|;()]|[<>]\(/.test(trimmed)) return opaqueOperation(trimmed);
474
476
  const operations = parsed.segments.flatMap((part): Operation[] => {
475
- const operation = partOperation(part);
477
+ const operation = partOperation(part, depth);
476
478
  // Brace expansion comes before every other expansion, so a brace word
477
479
  // can supply the command word or shift a wrapper's arguments
478
480
  // (`nice -n {5,rm} -rf build` runs rm). The expanded words are read as
@@ -483,20 +485,20 @@ function segmentOperation(segment: string): Operation {
483
485
  if (expanded.every((words, k) => words !== null && words.length === 1 && words[0] === raws[k])) return [operation];
484
486
  if (expanded.some((words) => words === null)) return [operation, opaqueOperation(raws.join(" "))];
485
487
  const relexed = lexCommand(expanded.flatMap((words) => words ?? []).join(" "));
486
- return [operation, ...(relexed.trustworthy ? relexed.segments.map(partOperation) : [opaqueOperation(raws.join(" "))])];
488
+ return [operation, ...(relexed.trustworthy ? relexed.segments.map((segment) => partOperation(segment, depth)) : [opaqueOperation(raws.join(" "))])];
487
489
  });
488
490
  return strongest(...operations);
489
491
  }
490
492
 
491
493
  /** The operation of one lexed simple command, read by both command-position models. */
492
- function partOperation(part: ReturnType<typeof lexCommand>["segments"][number]): Operation {
494
+ function partOperation(part: ReturnType<typeof lexCommand>["segments"][number], depth = 0): Operation {
493
495
  const kept = part.words.map((word, at) => ({ word, at })).filter(({ at }) => !part.redirects.has(at));
494
496
  const index = commandWordIndex(part);
495
- const shared = index < 0 ? "read" : commandOperation(part, index);
497
+ const shared = index < 0 ? "read" : commandOperation(part, index, depth);
496
498
  const strict = unwrapCommand(kept.map(({ word }) => strictWord(word.text)));
497
499
  if (strict === null) return strongest(shared, opaqueOperation(kept.map(({ word }) => decodeWord(word.text)).join(" ")));
498
500
  if (strict.index < 0 || kept[strict.index].at === index) return shared;
499
- return strongest(shared, commandOperation(part, kept[strict.index].at));
501
+ return strongest(shared, commandOperation(part, kept[strict.index].at, depth));
500
502
  }
501
503
 
502
504
  /**
@@ -625,8 +627,14 @@ function hidesDestructiveExecutor(text: string, depth = 0): boolean {
625
627
  return (bodies ?? lexed.substitutions).some((body) => hidesDestructiveExecutor(body, depth + 1));
626
628
  }
627
629
 
628
- /** The operation of the command whose word is at `index` of `part`. */
629
- function commandOperation(part: ReturnType<typeof lexCommand>["segments"][number], index: number): Operation {
630
+ /** How many watch command lines inside one another are read (HO-00242), as trash-guard reads substitution bodies. */
631
+ const WATCH_DEPTH = 3;
632
+
633
+ /**
634
+ * The operation of the command whose word is at `index` of `part`. `depth`
635
+ * counts the watch command lines read on the way here (at most WATCH_DEPTH).
636
+ */
637
+ function commandOperation(part: ReturnType<typeof lexCommand>["segments"][number], index: number, depth = 0): Operation {
630
638
  // A command that runs a destructive program or option value locally (awk
631
639
  // system(), perl -e, ssh ProxyCommand, sed e, …) is a delete here, whatever
632
640
  // its own command word would otherwise read as.
@@ -666,7 +674,14 @@ function commandOperation(part: ReturnType<typeof lexCommand>["segments"][number
666
674
  // opaque reading below.
667
675
  if (tool === "find" && !kept.some((word) => expandsAtRuntime(word.text)) && !words.some((word) => FIND_ACTIONS.has(word))) return "read";
668
676
  if (tool === "env" && mentionsDeleteVerb(envSplitCommandText(words))) return "delete";
669
- if (["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "eval", "source", ".", "su", "runuser", "env", "xargs", "find", "busybox", "toybox"].includes(tool ?? "")) {
677
+ // watch runs a command line (watchCommandLine, HO-00242): it is read as the
678
+ // command it is. A line that cannot be read, or one past WATCH_DEPTH, keeps
679
+ // the opaque reading below.
680
+ if (tool === "watch" && depth < WATCH_DEPTH) {
681
+ const line = watchCommandLine(part, index);
682
+ if (line !== null) return line ? segmentOperation(line, depth + 1) : "read";
683
+ }
684
+ if (["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "eval", "source", ".", "su", "runuser", "env", "xargs", "find", "busybox", "toybox", "watch"].includes(tool ?? "")) {
670
685
  return opaqueOperation(words.join(" "));
671
686
  }
672
687
  if (["mkdir", "mkfile", "touch", "mv", "cp", "ln", "tee", "install", "dd", "rsync", "scp", "truncate"].includes(tool ?? "")) return "write";
@@ -2,7 +2,53 @@
2
2
 
3
3
  Codewith-native hook installed as `hooks run pre-bash`.
4
4
 
5
- This hook is OSS-safe: optional Hasna CLIs are best-effort and missing CLIs fail open with concise warnings. Security gates only fail closed when a guarded commit/push scan runs successfully and finds possible secrets.
5
+ This hook is OSS-safe: optional Hasna CLIs are best-effort and missing CLIs fail open with concise warnings. The staged-secrets scan is the exception, and it fails closed in both directions: it refuses a `git commit` or `git push` when gitleaks finds possible secrets, and equally when gitleaks is missing or could not reach a verdict. A scan that did not run must not read as a clean scan.
6
+
7
+ ## Prerequisites: gitleaks
8
+
9
+ A working [gitleaks](https://github.com/gitleaks/gitleaks) is a prerequisite for
10
+ every `git commit` and `git push` that goes through this hook. The hook runs
11
+ `gitleaks git --staged --no-banner --redact --report-format json --report-path - .`
12
+ from the top of the work tree the git command runs in. Without a gitleaks it can
13
+ run, the commit or push is refused — fail closed, not fail open.
14
+
15
+ Install it with any of:
16
+
17
+ ```bash
18
+ brew install gitleaks # macOS / Homebrew
19
+ go install github.com/gitleaks/gitleaks/v8@latest # any platform with Go
20
+ # or a release binary: https://github.com/gitleaks/gitleaks/releases
21
+ ```
22
+
23
+ Lookup order: `PATH` first, then the retained runtime
24
+ `~/.hasna/runtimes/gitleaks/<version>/` (newest `X.Y.Z` first), then
25
+ `~/.local/bin`, `/opt/homebrew/bin`, `/usr/local/bin` and `/usr/bin`. The
26
+ fallbacks exist because a harness can start a hook with a bare `env -i PATH=…`
27
+ that holds neither `~/.local/bin` nor Homebrew, and an installed gitleaks then
28
+ still has to be found.
29
+
30
+ What the scan answers:
31
+
32
+ - scanned and clean → `{"continue":true, …}` with `secretsScan=clean` in
33
+ `hookSpecificOutput.additionalContext`;
34
+ - scanned and possible secrets found → `{"decision":"block","reason":…}`, with the
35
+ finding details redacted;
36
+ - gitleaks missing → `{"decision":"block","reason":"SECRETS SCAN UNAVAILABLE: …"}`,
37
+ and the commit or push is refused;
38
+ - gitleaks present but no verdict (it exited with anything other than 0 or 1, or
39
+ exited 1 without a JSON report), or the git command's work tree could not be
40
+ resolved → `{"decision":"block","reason":"SECRETS SCAN INCONCLUSIVE: …"}`, also
41
+ refused.
42
+
43
+ Check the gate end to end without committing, from inside a git work tree:
44
+
45
+ ```bash
46
+ echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git commit -m x"}}' | hooks run pre-bash
47
+ ```
48
+
49
+ `PRE_BASH_GITLEAKS_FALLBACK_DIRS` overrides the search list *after* `PATH`
50
+ (colon-separated; an empty value disables the fallbacks). It exists so the
51
+ unavailable case can be tested on a machine where gitleaks is installed.
6
52
 
7
53
  It also blocks scoped destructive shell operations such as recursive `rm`,
8
54
  `rsync --delete`, destructive `find`, and destructive `git clean` / `git reset
@@ -1,7 +1,9 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
+ import { readdirSync, statSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
3
6
  import {
4
- commandExists,
5
7
  classifyDangerousOperation,
6
8
  gitCommandInfo,
7
9
  getCommand,
@@ -21,20 +23,161 @@ interface SessionDigest {
21
23
  warnings: string[];
22
24
  }
23
25
 
24
- async function runStagedSecretsScan(cwd: string): Promise<{ block: boolean; reason?: string; warning?: string }> {
25
- if (!commandExists("gitleaks")) {
26
- return { block: false, warning: "gitleaks unavailable; staged secrets scan skipped fail-open." };
26
+ function isExecutableFile(path: string): boolean {
27
+ try {
28
+ const stat = statSync(path);
29
+ return stat.isFile() && (stat.mode & 0o100) !== 0;
30
+ } catch {
31
+ return false;
32
+ }
33
+ }
34
+
35
+ function defaultFallbackDirs(home: string): string[] {
36
+ const runtimes = join(home, ".hasna", "runtimes", "gitleaks");
37
+ let versions: string[] = [];
38
+ try {
39
+ versions = readdirSync(runtimes)
40
+ .filter((name) => /^\d+\.\d+\.\d+$/.test(name))
41
+ .sort((a, b) => {
42
+ const left = a.split(".").map(Number);
43
+ const right = b.split(".").map(Number);
44
+ for (let i = 0; i < 3; i += 1) if (left[i] !== right[i]) return right[i] - left[i];
45
+ return 0;
46
+ });
47
+ } catch {
48
+ versions = [];
49
+ }
50
+ return [
51
+ ...versions.map((version) => join(runtimes, version)),
52
+ join(home, ".local/bin"),
53
+ "/opt/homebrew/bin",
54
+ "/usr/local/bin",
55
+ "/usr/bin",
56
+ ];
57
+ }
58
+
59
+ /**
60
+ * The guard runs under a bare `env -i PATH=…` on some harnesses, and that PATH holds
61
+ * neither ~/.local/bin nor /opt/homebrew/bin — so a gitleaks that is installed and
62
+ * working is invisible to a PATH-only lookup. PATH still wins when it has one; after it,
63
+ * the retained per-version runtime and the fixed install locations are checked, newest
64
+ * runtime first, so the scan does not depend on which PATH the caller was given.
65
+ *
66
+ * `fallbackDirs` is the search list after PATH, injectable so a test can prove the
67
+ * unavailable case on a machine that has gitleaks installed. `PRE_BASH_GITLEAKS_FALLBACK_DIRS`
68
+ * carries it across the process boundary: unset keeps the default list, an empty value
69
+ * means no fallbacks at all.
70
+ */
71
+ export function findGitleaks(
72
+ env: NodeJS.ProcessEnv = process.env,
73
+ fallbackDirs?: string[],
74
+ ): string | null {
75
+ for (const dir of (env.PATH || "").split(":")) {
76
+ if (!dir) continue;
77
+ const candidate = join(dir, "gitleaks");
78
+ if (isExecutableFile(candidate)) return candidate;
79
+ }
80
+ const home = env.HOME || homedir();
81
+ const dirs = fallbackDirs ?? defaultFallbackDirs(home);
82
+ for (const dir of dirs) {
83
+ if (!dir) continue;
84
+ if (isExecutableFile(join(dir, "gitleaks"))) return join(dir, "gitleaks");
85
+ }
86
+ return null;
87
+ }
88
+
89
+ function findGitleaksForProcess(env: NodeJS.ProcessEnv = process.env): string | null {
90
+ const override = env.PRE_BASH_GITLEAKS_FALLBACK_DIRS;
91
+ const fallbackDirs = override === undefined ? undefined : override.split(":").filter(Boolean);
92
+ return findGitleaks(env, fallbackDirs);
93
+ }
94
+
95
+ /**
96
+ * What the staged-secret scan actually did. A command that was never scanned
97
+ * must not look like a command that was scanned and found clean: `status`
98
+ * separates those, `scanned` says whether gitleaks reached a verdict at all,
99
+ * and a skip carries the reason it could not.
100
+ */
101
+ type StagedSecretsScan =
102
+ | { status: "clean"; scanned: true }
103
+ | { status: "secrets"; scanned: true; reason: string }
104
+ | { status: "skipped"; scanned: false; code: "gitleaks-unavailable" | "gitleaks-inconclusive"; detail: string };
105
+
106
+ /**
107
+ * gitleaks writes its findings as JSON on stdout. It uses exit 1 both for leaks and for
108
+ * fatal errors, so the report — not the exit code alone — decides which happened.
109
+ */
110
+ function isGitleaksReport(stdout: string): boolean {
111
+ const text = stdout.trim();
112
+ if (!text) return false;
113
+ try {
114
+ const parsed = JSON.parse(text);
115
+ return typeof parsed === "object" && parsed !== null;
116
+ } catch {
117
+ return false;
118
+ }
119
+ }
120
+
121
+ async function runStagedSecretsScan(targetCwd: string, targetCertain: boolean): Promise<StagedSecretsScan> {
122
+ if (!targetCertain) {
123
+ return {
124
+ status: "skipped",
125
+ scanned: false,
126
+ code: "gitleaks-inconclusive",
127
+ detail: "the folder this git command runs in could not be determined, so there is no known work tree to scan.",
128
+ };
129
+ }
130
+
131
+ const gitleaks = findGitleaksForProcess();
132
+ if (!gitleaks) {
133
+ return {
134
+ status: "skipped",
135
+ scanned: false,
136
+ code: "gitleaks-unavailable",
137
+ detail: "gitleaks is not installed, so this git command was NOT scanned for staged secrets.",
138
+ };
139
+ }
140
+
141
+ // gitleaks answers a folder that is not a repository with an error on stderr, an empty
142
+ // report on stdout and exit 0 — which a caller reading only the exit code would record as
143
+ // clean. Resolve the work tree first: no work tree, no scan, no clean verdict. Running
144
+ // from the top level also makes a subfolder cwd scan the whole repository rather than
145
+ // only that subfolder.
146
+ const top = await runCommand(["git", "-C", targetCwd, "rev-parse", "--show-toplevel"], { timeoutMs: 5_000 });
147
+ const topLevel = top.stdout.trim();
148
+ if (top.exitCode !== 0 || !topLevel) {
149
+ return {
150
+ status: "skipped",
151
+ scanned: false,
152
+ code: "gitleaks-inconclusive",
153
+ detail: `git could not resolve a work tree for ${targetCwd}${top.exitCode ? ` (git rev-parse exited ${top.exitCode})` : ""}, so this git command was NOT scanned for staged secrets.`,
154
+ };
27
155
  }
28
156
 
29
157
  const result = await runCommand([
30
- "gitleaks", "git", "--staged", "--no-banner", "--redact", "--report-format", "json", "--report-path", "-", ".",
31
- ], { cwd, timeoutMs: 15_000 });
158
+ gitleaks, "git", "--staged", "--no-banner", "--redact", "--report-format", "json", "--report-path", "-", ".",
159
+ ], { cwd: topLevel, timeoutMs: 15_000 });
32
160
 
33
- if (result.exitCode === 0) return { block: false };
161
+ if (result.exitCode === 0) return { status: "clean", scanned: true };
34
162
  if (result.exitCode === 1) {
35
- return { block: true, reason: redactGitleaksOutput(result.stdout, result.stderr) };
163
+ if (!isGitleaksReport(result.stdout)) {
164
+ // Ada's NO-GO N7: a fatal error that exits 1 must not be reported as «found
165
+ // possible credential(s)». No report, no finding.
166
+ return {
167
+ status: "skipped",
168
+ scanned: false,
169
+ code: "gitleaks-inconclusive",
170
+ detail: "gitleaks exited 1 without a report, so this git command was NOT scanned for staged secrets.",
171
+ };
172
+ }
173
+ return { status: "secrets", scanned: true, reason: redactGitleaksOutput(result.stdout, result.stderr) };
36
174
  }
37
- return { block: false, warning: `gitleaks scan did not complete cleanly (exit ${result.exitCode ?? "unknown"}${result.timedOut ? ", timed out" : ""}); fail-open.` };
175
+ return {
176
+ status: "skipped",
177
+ scanned: false,
178
+ code: "gitleaks-inconclusive",
179
+ detail: `gitleaks exited ${result.exitCode ?? "unknown"}${result.timedOut ? " (timed out)" : ""} without a verdict, so this git command was NOT scanned for staged secrets.`,
180
+ };
38
181
  }
39
182
 
40
183
  function riskyCommsBlock(): string | null {
@@ -61,12 +204,25 @@ export async function evaluate(input: CodewithHookInput): Promise<{ output: Reco
61
204
 
62
205
  const gitInfo = gitCommandInfo(command, cwd);
63
206
 
207
+ // The scan's own outcome travels as TEXT inside the documented answer: the
208
+ // Codex 0.166 pre-tool-use output schema sets additionalProperties false at
209
+ // the top level and inside hookSpecificOutput, so a bespoke field would make
210
+ // every answer — the block included — invalid there. A stable
211
+ // `secretsScan=<state>` prefix keeps it machine-readable without adding a
212
+ // field any target rejects.
64
213
  if (gitInfo) {
65
- const scan = await runStagedSecretsScan(gitInfo.targetCwd);
66
- if (scan.warning) warnings.push(scan.warning);
67
- if (scan.block) {
214
+ const scan = await runStagedSecretsScan(gitInfo.targetCwd, gitInfo.targetCertain !== false);
215
+ if (scan.status === "skipped") {
216
+ // Fail closed (Ada's ruling, 04.11): a scan that did not run is not a
217
+ // clean scan. The git command is refused with a reason naming why, and
218
+ // the answer uses only the documented decision and reason fields.
219
+ return { output: { decision: "block", reason: `${scan.code === "gitleaks-unavailable" ? "SECRETS SCAN UNAVAILABLE" : "SECRETS SCAN INCONCLUSIVE"}: ${scan.detail} This git commit or push is refused until the staged-secrets scan can run.` }, warnings };
220
+ }
221
+ if (scan.status === "secrets") {
222
+ // The block is the answer: the documented decision and reason carry it.
68
223
  return { output: { decision: "block", reason: scan.reason }, warnings };
69
224
  }
225
+ warnings.push("secretsScan=clean");
70
226
  }
71
227
 
72
228
  if (isRiskyOperation(command)) {
@@ -229,8 +229,9 @@ const DURATION = /^(?:\d+(?:\.\d*)?|\.\d+)[smhd]?$/;
229
229
  * option whose value is the rest of the word or the next word, and a long
230
230
  * option may be abbreviated to a unique prefix. The option lists are
231
231
  * complete, so an abbreviation that is unique here is unique in the tool.
232
- * sudo and doas are not modelled: their own options are richer, and the
233
- * shared command-position walk keeps reading them.
232
+ * caffeinate, chronic and unbuffer are modelled from their own sources (see
233
+ * each entry). sudo and doas are not modelled: their own options are richer,
234
+ * and the shared command-position walk keeps reading them.
234
235
  */
235
236
  export const WRAPPER_SPECS: Record<string, WrapperSpec> = {
236
237
  timeout: {
@@ -261,6 +262,41 @@ export const WRAPPER_SPECS: Record<string, WrapperSpec> = {
261
262
  long: { class: VALUE, classdata: VALUE, ignore: FLAG, pid: REFUSE, pgid: REFUSE, uid: REFUSE, ...HELP_LONG },
262
263
  },
263
264
  setsid: { short: { c: FLAG, f: FLAG, w: FLAG, h: REFUSE, V: REFUSE }, long: { ctty: FLAG, fork: FLAG, wait: FLAG, ...HELP_LONG } },
265
+ // Launchers that exec the words after their options as a command, without a
266
+ // shell (HO-00242). As with trash-guard's flock, they are modelled for this
267
+ // strict reading only, not in trash-guard's shared command-position walk:
268
+ // both guards read the command at both positions, and the walk's other
269
+ // readers (signed-link-guard, heredoc bodies, cd placement) keep main's
270
+ // reading.
271
+ //
272
+ // macOS caffeinate: getopt("mdhisut:w:") in Apple's PowerManagement source,
273
+ // where options end at the first non-option word; -h prints its usage and
274
+ // exits.
275
+ caffeinate: { short: { m: FLAG, d: FLAG, h: REFUSE, i: FLAG, s: FLAG, u: FLAG, t: VALUE, w: VALUE }, long: {} },
276
+ // moreutils chronic: Getopt::Std getopts("ev"), whose result it ignores, so
277
+ // an unknown option is dropped and the command still runs, and so does one
278
+ // after --help or --version. Neither is modelled: the reading fails closed.
279
+ chronic: { short: { e: FLAG, v: FLAG }, long: { ...HELP_LONG } },
280
+ // expect's unbuffer: `-p` as its first word only. Every other word goes to
281
+ // expect's spawn, whose own options (-ignore, -open, -pty, ...) are not
282
+ // modelled, so the reading fails closed on them. A `-p` after the first word
283
+ // is read as unbuffer's too, which reads a command where spawn may run none.
284
+ unbuffer: { short: { p: FLAG }, long: {} },
285
+ };
286
+
287
+ /**
288
+ * watch's own options (procps-ng 4.0.4: getopt_long "+bCced::ghq:n:prtwvx"),
289
+ * which end at the first non-option word. watch is not a wrapper: it joins
290
+ * the words after them with spaces and runs that line with `sh -c` (with -x,
291
+ * as a command), so the guards read that line as a command of its own
292
+ * (watchCommandLine in hook-trash-guard). -h and -v print and exit.
293
+ */
294
+ export const WATCH_SPEC: WrapperSpec = {
295
+ short: { b: FLAG, C: FLAG, c: FLAG, e: FLAG, d: OPTIONAL, g: FLAG, q: VALUE, n: VALUE, p: FLAG, r: FLAG, t: FLAG, w: FLAG, x: FLAG, h: REFUSE, v: REFUSE },
296
+ long: {
297
+ color: FLAG, "no-color": FLAG, differences: OPTIONAL, interval: VALUE, beep: FLAG, errexit: FLAG, chgexit: FLAG, equexit: VALUE,
298
+ exec: FLAG, precise: FLAG, "no-rerun": FLAG, "no-title": FLAG, "no-wrap": FLAG, help: REFUSE, version: REFUSE,
299
+ },
264
300
  };
265
301
 
266
302
  /** Shell reserved words that may precede the command word. */
@@ -322,6 +358,8 @@ function skipWrapperArguments(spec: WrapperSpec, words: ShellWord[], at: number)
322
358
  }
323
359
  break;
324
360
  }
361
+ // getopt's optional argument (`d::`): the rest of the word, never the next word.
362
+ if (option.arg === "optional") break;
325
363
  }
326
364
  at++;
327
365
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hasna/hooks",
3
- "version": "0.14.1",
3
+ "version": "0.15.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": {
@@ -41,7 +41,7 @@
41
41
  "main": "./dist/index.js",
42
42
  "types": "./dist/index.d.ts",
43
43
  "scripts": {
44
- "build": "rm -rf dist bin && bun build ./src/cli/index.tsx --outdir ./bin --target bun --external pg --external ink --external react --external chalk --external conf --external @modelcontextprotocol/sdk --external zod && bun build ./src/serve.ts --outdir ./bin --target bun --external pg && bun build ./src/mcp/hooks-mcp.ts --outdir ./bin --target bun --external pg --external chalk --external conf --external @modelcontextprotocol/sdk --external zod && bun build ./src/sdk/index.ts --outdir ./dist/sdk --target bun && bun build ./src/index.ts ./src/storage.ts --outdir ./dist --target bun --external pg && bun run build:native-safety && bun run build:native-safety-worker && bun run build:bundled-hooks && bun run build:sumi-stop-plugin && bun run build:opencode-stop-plugin && bun run build:types",
44
+ "build": "rm -rf dist bin && bun build ./src/cli/index.tsx --outdir ./bin --target bun --external pg --external ink --external react --external chalk --external conf --external @modelcontextprotocol/sdk --external zod && bun build ./src/serve.ts --outdir ./bin --target bun --external pg && bun build ./src/mcp/hooks-mcp.ts --outdir ./bin --target bun --external pg --external chalk --external conf --external @modelcontextprotocol/sdk --external zod && bun build ./src/sdk/index.ts --outdir ./dist/sdk --target bun && bun build ./src/index.ts ./src/storage.ts --outdir ./dist --target bun --external pg && bun run build:native-safety && bun run build:native-safety-worker && bun run build:bundled-hooks && bun run build:release-manifest && bun run build:sumi-stop-plugin && bun run build:opencode-stop-plugin && bun run build:types",
45
45
  "build:types": "tsc -p tsconfig.build.json",
46
46
  "generate:sdk": "bun run scripts/generate-sdk.ts",
47
47
  "verify:generated": "bun run scripts/verify-generated-artifacts.ts",
@@ -57,6 +57,7 @@
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",
60
+ "build:release-manifest": "bun scripts/build-release-manifest.ts",
60
61
  "build:sumi-stop-plugin": "bun build ./src/lib/sumi-stop-plugin.ts --outdir ./dist --target node",
61
62
  "build:opencode-stop-plugin": "bun build ./src/lib/opencode-stop-plugin.ts --outdir ./dist --target node"
62
63
  },