@hasna/hooks 0.14.0 → 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 (38) hide show
  1. package/README.md +31 -11
  2. package/bin/hooks/stop-review.js +17 -9
  3. package/bin/hooks-mcp.js +741 -311
  4. package/bin/index.js +1673 -634
  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 +1813 -1178
  10. package/dist/lib/codex-safety-check.d.ts +1 -1
  11. package/dist/lib/error-events.d.ts +59 -0
  12. package/dist/lib/install-record.d.ts +136 -0
  13. package/dist/lib/manifest.d.ts +6 -0
  14. package/dist/lib/release-manifest.d.ts +162 -0
  15. package/dist/lib/store.d.ts +25 -2
  16. package/dist/openapi.d.ts +147 -0
  17. package/dist/registry-auth.d.ts +6 -1
  18. package/dist/registry-http.d.ts +2 -1
  19. package/dist/sdk/generated.d.ts +26 -0
  20. package/dist/sdk/index.js +14 -0
  21. package/hooks/codewith-native-common.ts +190 -6
  22. package/hooks/hook-signed-link-guard/README.md +46 -0
  23. package/hooks/hook-signed-link-guard/src/classify.ts +7 -3
  24. package/hooks/hook-signed-link-guard/src/jq.ts +205 -34
  25. package/hooks/hook-stop-review/README.md +5 -2
  26. package/hooks/hook-stop-review/src/jev.ts +9 -4
  27. package/hooks/hook-stop-review/src/policy.ts +7 -3
  28. package/hooks/hook-stop-review/src/runtime.ts +5 -4
  29. package/hooks/hook-trash-guard/README.md +9 -4
  30. package/hooks/hook-trash-guard/src/hook.ts +127 -10
  31. package/hooks/hook-workspace-repos-guard/src/hook.ts +27 -12
  32. package/hooks/pre-bash/README.md +47 -1
  33. package/hooks/pre-bash/src/hook.ts +168 -12
  34. package/hooks/shell-words.ts +40 -2
  35. package/package.json +3 -2
  36. package/scripts/build-release-manifest.ts +27 -0
  37. package/scripts/validate-package.ts +5 -1
  38. package/scripts/validate-release-manifest.ts +67 -0
package/README.md CHANGED
@@ -41,6 +41,7 @@ hooks install gitguard # Claude Code picks it up live; restart
41
41
  hooks install gitguard --target codex # or Codex; then review and trust it in Codex's /hooks
42
42
  hooks list --installed --target codex # what is installed for one agent
43
43
  hooks doctor # check the Claude Code installation
44
+ hooks verify # read-only: every hook, what its trust rests on, and any mismatch
44
45
  echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git reset --hard"}}' \
45
46
  | hooks run gitguard # a simulated command: prints a "block" decision, runs nothing
46
47
  ```
@@ -191,6 +192,7 @@ hooks --help
191
192
  - `hooks categories`
192
193
  - `hooks info`
193
194
  - `hooks doctor`
195
+ - `hooks verify`
194
196
  - `hooks run`
195
197
 
196
198
  ## Compact Output
@@ -453,11 +455,12 @@ hooks safety verify --target sumi --execution
453
455
  ```
454
456
 
455
457
  Hooks registered as `hooks run <hook>` do not go through the native worker, so
456
- re-registration does not cover them. When a release changes the script of such
457
- a hook, run `hooks trust <hook>` with the new CLI on every station after
458
- switching PATH to it, as "Trust model" under "Custom and remote hooks"
459
- describes. Until then, wherever an old pin exists, it refuses the new script
460
- and that hook exits 1 on every call.
458
+ re-registration does not cover them, and from 0.15.0 they need none: a bundled
459
+ hook is trusted by the release manifest of the package it ships in ("Trust
460
+ model" under "Custom and remote hooks"), so switching PATH to a new version is
461
+ the whole step. No `hooks trust` is run after an upgrade. A CLI older than
462
+ 0.15.0 still reads the pin in `hooks.lock` and refuses a changed script until
463
+ `hooks trust <hook>` is run with that CLI.
461
464
 
462
465
  `hooks safety provision --target sumi`, which the package's lifecycle script
463
466
  also runs, keeps a binding that still verifies, so it does not move Sumi to a
@@ -532,7 +535,7 @@ Codex is installed through npm, pass the platform package's native binary rather
532
535
  than its JavaScript launcher. Executable ownership, permissions, ancestry and
533
536
  bytes are checked. Supported protocol versions are 0.153.0, 0.154.0,
534
537
  0.154.0-alpha.6.1, 0.155.0, 0.155.1, 0.156.1, 0.157.0, 0.157.1, 0.158.0, 0.159.0, 0.159.2,
535
- 0.159.3, 0.160.0, 0.160.1, 0.161.0, 0.162.0, 0.162.1 and 0.163.0;
538
+ 0.159.3, 0.160.0, 0.160.1, 0.161.0, 0.162.0, 0.162.1, 0.163.0, 0.169.0 and 0.170.0;
536
539
  other versions refuse pending compatibility validation. Updating Codex can
537
540
  therefore require a compatible Hooks release before native safety verification
538
541
  and trust provisioning succeed. Keep existing hook definitions and trust intact
@@ -572,7 +575,7 @@ Codewith is deprecated. These hooks remain for existing Codewith setups; do not
572
575
 
573
576
  - `session-start` — `SessionStart` digest and additional context.
574
577
  - `prompt-guard` — `UserPromptSubmit` guard for pasted fake policy/freeze/run-this-now content.
575
- - `pre-bash` — `PreToolUse` Bash gate for staged secrets scans, scoped destructive-operation blocks, and risky-op comms checks.
578
+ - `pre-bash` — `PreToolUse` Bash gate for staged secrets scans, scoped destructive-operation blocks, and risky-op comms checks. The staged-secrets scan needs a working [gitleaks](https://github.com/gitleaks/gitleaks): without one, every `git commit` and `git push` through the hook is refused with `SECRETS SCAN UNAVAILABLE` instead of being passed unscanned. Install it with `brew install gitleaks` (or a release binary, or `go install github.com/gitleaks/gitleaks/v8@latest`); see [Prerequisites](hooks/pre-bash/README.md#prerequisites-gitleaks) for the lookup order and how to check the gate.
576
579
  - `worktree-guard` — `PreToolUse` guard for managed repos worktree boundaries and file-tool-like payloads touching protected Hasna scopes.
577
580
  - `stop-sync` — `Stop` turn-end heartbeat/evidence best effort.
578
581
  - `knowledge-context` — deterministic Knowledge context packs for `SessionStart`, `UserPromptSubmit`, and `SubagentStart`.
@@ -624,14 +627,31 @@ hooks install https://example.com/hooks/my-hook/manifest.json
624
627
 
625
628
  Custom hooks land in `~/.hasna/hooks/hooks/<name>/`. A custom hook with the same name as a bundled hook takes precedence (visible in `hooks info <name>`).
626
629
 
627
- **Trust model.** Every hook script is pinned by sha256 in `hooks.lock` in the hooks data directory (`~/.hasna/hooks/hooks.lock` unless the data directory resolves elsewhere; `HASNA_HOOKS_LOCK_PATH`, or its alias `HOOKS_LOCK_PATH`, overrides the lock path) and, in local mode, in the SQLite `hooks` table, which is checked first. `hooks run` verifies the script hash before executing; if the script changed, the run is refused and exits 1:
630
+ **Trust model.** `hooks run` hashes a hook's script before it executes it and refuses, with exit 1 (exit 2 for a bundled PreToolUse guard), when the bytes are not the trusted ones. What "trusted" rests on depends on where the hook came from, and in each case the script and its trust are written by the same step:
631
+
632
+ | Hook | Its trust is | Written by |
633
+ |---|---|---|
634
+ | Bundled (`gitguard`, `trash-guard`, …) | the package's own release manifest, `bin/release-manifest.json`: every bundled hook's version, script and sha256 | the build; installing a version unpacks scripts and manifest together, and the PATH link that selects the scripts selects their trust |
635
+ | Custom, installed with `hooks install <source>` | the hook's install record, `.hooks-install.json` in its own directory: manifest, script, their sha256 | the install, in one rename |
636
+ | Custom, placed before 0.15.0 or by hand; registry hooks from `hooks sync` | a pin in `hooks.lock` (and, in local mode, the SQLite `hooks` table, which is checked first) | the first run, `hooks sync`, `hooks update`, `hooks install <name>@<version>`, `hooks trust` |
637
+
638
+ So an upgrade needs no `hooks trust`: the new version's hooks equal the new version's manifest. A pin an older version left in `hooks.lock` for a bundled hook is not read. A bundled script that differs from its release refuses, on its first run too (before 0.15.0 a first run pinned whatever it found).
628
639
 
629
640
  ```bash
630
- hooks trust <name> # re-pin the current script content
631
- hooks update # re-register hooks and refresh pins
641
+ hooks verify # read-only: every hook, what governs it, trusted and actual sha256, its release; exit 1 on a mismatch
642
+ hooks verify --json
643
+ hooks install ./my-hook --store-only # install or update a custom hook's content and trust; no agent registration is touched
644
+ hooks trust <name> # accept the bytes on disk now, after checking them
645
+ hooks release anchor # once, by the step that installs a version (see below)
632
646
  ```
633
647
 
634
- A hook's first run writes its pin, and so do `hooks sync` (in local mode it pins every bundled hook without running any of them), `hooks update`, `hooks install <name>@<version>`, `hooks update <name>@<version>` and `hooks trust`. A station can therefore hold a pin for a hook that has never run there. After any upgrade that changes the script of a hook registered as `hooks run <hook>`, run `hooks trust <hook>` with the new CLI on every station. Run it as the same user and with the same hooks environment that the harness's `hooks run` sees: the local opt-in or registry credential, and any data directory, DB or lock path override. Otherwise it can write a pin that `hooks run` does not read. Where the hook is not pinned yet, it pins the same sha256 that the first run would have pinned, so it is harmless there.
648
+ `hooks verify` needs no credential and no local opt-in, writes nothing (no first-run pin, no repair, no store) and contacts nothing. It reads the hooks installed under the data directory, the pins in `hooks.lock` and the `hooks run` registrations in the Claude, Codex, Gemini and Qwen settings files.
649
+
650
+ **Updating a custom hook.** Install it again from its source: `hooks install <source> --store-only`. The record is committed by one rename, then `manifest.json` and the script are brought in line with it; an install that stops in between is finished by the next `hooks run` from the record. Never copy a script into `~/.hasna/hooks/hooks/<name>/` by hand: bytes no install wrote refuse until they are installed or trusted. `hooks trust <name>` remains the explicit way to accept what is on disk; for a custom hook it commits those bytes as the install record, and for a bundled hook it accepts them for the running release only.
651
+
652
+ **What the check protects against.** It detects a script that changed without its trust record changing. The record has always been writable by the same user as the script (`hooks.lock` is a 0644 file in the data directory), so a process running as that user that rewrites both is outside what this check can see; that is unchanged. For bundled hooks the manifest sits inside the package it describes, so a writer that changes a script and the manifest together is caught only where the release was anchored: `hooks release anchor` records the manifest's sha256 in `~/.hasna/hooks/release-anchors/` (0600, outside the package), once, and never moves it. With an anchor, a manifest that no longer equals it refuses every bundled hook of that package and `hooks verify` exits 1. Run `hooks release anchor` with the new CLI straight after the package manager has installed a version, and keep the installed package directory writable by its owner only. Without an anchor `hooks verify` says so.
653
+
654
+ A CLI older than 0.15.0 reads only the pins. `hooks install <source>` and `hooks trust` still write them, so a rollback finds custom hooks as it left them; for a bundled hook whose script differs between the two versions, the older CLI refuses until `hooks trust <hook>` is run with it.
635
655
 
636
656
  ### Hosted publication and station sync
637
657
 
@@ -598,6 +598,7 @@ var MAX_RESPONSE_BYTES = 16384;
598
598
  var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
599
599
  var probability = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
600
600
  var tokenCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
601
+ var isVersionedJevModel = (value) => typeof value === "string" && value.length <= 104 && /^jev-(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.exec(value)?.[0] === value;
601
602
  function buildJevRequest(envelope, options) {
602
603
  return {
603
604
  model: options.model,
@@ -610,8 +611,8 @@ function buildJevRequest(envelope, options) {
610
611
  questions: options.instruction.questions
611
612
  };
612
613
  }
613
- function parseJevAssessment(value) {
614
- if (!isRecord(value) || typeof value.model !== "string" || !/^jev-[a-zA-Z0-9._-]{1,100}$/.test(value.model) || !isRecord(value.answers) || !isRecord(value.usage))
614
+ function parseJevAssessment(value, expectedModel) {
615
+ if (!isVersionedJevModel(expectedModel) || !isRecord(value) || value.model !== expectedModel || !isRecord(value.answers) || !isRecord(value.usage))
615
616
  return null;
616
617
  const { disposition, actionable, boundary } = value.answers;
617
618
  if (Object.keys(value.answers).sort().join(",") !== "actionable,boundary,disposition" || !isRecord(disposition) || disposition.type !== "choice" || !STOP_CLASSES.includes(disposition.choice) || !probability(disposition.confidence) || !isRecord(disposition.probabilities) || !isRecord(actionable) || actionable.type !== "noul" || !probability(actionable.noul) || !isRecord(boundary) || boundary.type !== "noul" || !probability(boundary.noul) || !tokenCount(value.usage.input_tokens) || !tokenCount(value.usage.output_tokens))
@@ -637,7 +638,8 @@ function parseJevAssessment(value) {
637
638
  async function evaluateJev(envelope, options) {
638
639
  if (!options.apiKey?.trim())
639
640
  return { ok: false, reason: "credential_unavailable" };
640
- if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(options.model))
641
+ const model = options.model;
642
+ if (!isVersionedJevModel(model))
641
643
  return { ok: false, reason: "invalid_configuration" };
642
644
  const timeoutMs = options.timeoutMs ?? 8000;
643
645
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 15000)
@@ -703,7 +705,7 @@ async function evaluateJev(envelope, options) {
703
705
  } catch {
704
706
  return { ok: false, reason: "invalid_provider_response" };
705
707
  }
706
- const assessment = parseJevAssessment(decoded);
708
+ const assessment = parseJevAssessment(decoded, model);
707
709
  return assessment ? { ok: true, assessment } : { ok: false, reason: "invalid_provider_response" };
708
710
  } catch {
709
711
  return { ok: false, reason: timedOut ? "request_timeout" : "provider_unavailable" };
@@ -849,6 +851,11 @@ async function assessStop(input, options, isCurrent, admission) {
849
851
  return stop("instruction_unavailable");
850
852
  if (options.externalContentApproved !== true)
851
853
  return stop("external_content_unapproved");
854
+ const model = options.model;
855
+ if (!isVersionedJevModel(model))
856
+ return stop("invalid_configuration");
857
+ const evaluationOptions = { ...options, model };
858
+ const evaluate = options.evaluate ?? evaluateJev;
852
859
  const current = async () => {
853
860
  let timer;
854
861
  try {
@@ -866,7 +873,7 @@ async function assessStop(input, options, isCurrent, admission) {
866
873
  return stop("stale_input");
867
874
  let assessed;
868
875
  try {
869
- assessed = await (options.evaluate ?? evaluateJev)(envelope, options);
876
+ assessed = await evaluate(envelope, evaluationOptions);
870
877
  } catch {
871
878
  return { ...base, action: "unavailable", reason: "provider_unavailable" };
872
879
  }
@@ -883,7 +890,7 @@ async function assessStop(input, options, isCurrent, admission) {
883
890
  disposition: { type: "choice", choice: assessment.classification, confidence: assessment.confidence, probabilities: assessment.probabilities },
884
891
  actionable: { type: "noul", noul: assessment.actionableProbability },
885
892
  boundary: { type: "noul", noul: assessment.boundaryProbability }
886
- }, usage: { input_tokens: assessment.inputTokens, output_tokens: assessment.outputTokens } });
893
+ }, usage: { input_tokens: assessment.inputTokens, output_tokens: assessment.outputTokens } }, model);
887
894
  if (!checked)
888
895
  return { ...base, action: "unavailable", reason: "invalid_provider_response" };
889
896
  const provenance = { sourceId: options.instruction.sourceId, version: options.instruction.version, digest: options.instruction.digest };
@@ -904,7 +911,7 @@ var record2 = (value) => !!value && typeof value === "object" && !Array.isArray(
904
911
  var sha256 = (value) => createHash2("sha256").update(value).digest("hex");
905
912
  var safePath = (value) => typeof value === "string" && isAbsolute2(value) && value.length <= 4096 && !/[\u0000-\u001f]/.test(value);
906
913
  function parseRuntimeConfiguration(value) {
907
- if (!record2(value) || value.schema !== "hooks.stop-review-runtime.v1" || value.enabled !== true || typeof value.model !== "string" || !/^jev-[a-zA-Z0-9._-]{1,100}$/.test(value.model) || !record2(value.instruction) || typeof value.instruction.id !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/.test(value.instruction.id) || !Number.isSafeInteger(value.instruction.version) || value.instruction.version < 1 || typeof value.instruction.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.instruction.sha256) || !record2(value.commands) || !safePath(value.commands.instructions) || !safePath(value.commands.secrets) || typeof value.secretsReference !== "string" || value.secretsReference.length > 256 || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9_.-]*){1,12}$/.test(value.secretsReference))
914
+ if (!record2(value) || value.schema !== "hooks.stop-review-runtime.v1" || value.enabled !== true || !isVersionedJevModel(value.model) || !record2(value.instruction) || typeof value.instruction.id !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/.test(value.instruction.id) || !Number.isSafeInteger(value.instruction.version) || value.instruction.version < 1 || typeof value.instruction.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.instruction.sha256) || !record2(value.commands) || !safePath(value.commands.instructions) || !safePath(value.commands.secrets) || typeof value.secretsReference !== "string" || value.secretsReference.length > 256 || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9_.-]*){1,12}$/.test(value.secretsReference))
908
915
  return null;
909
916
  const allowed = ["schema", "enabled", "model", "instruction", "commands", "secretsReference", "harness", "codexHome", "codexSocketPath"];
910
917
  if (!Object.keys(value).every((key) => allowed.includes(key)) || Object.keys(value.instruction).sort().join(",") !== "id,sha256,version" || Object.keys(value.commands).sort().join(",") !== "instructions,secrets" || value.harness !== undefined && !["codex", "claude", "sumi", "opencode"].includes(value.harness) || value.codexHome !== undefined && !safePath(value.codexHome) || value.codexSocketPath !== undefined && !safePath(value.codexSocketPath))
@@ -1124,7 +1131,8 @@ async function runJevProviderChild(raw, env = process.env) {
1124
1131
  return evaluateJev(raw.envelope, { apiKey: env.TYPESAFE_API_KEY, model: config.model, instruction, timeoutMs: 8000 });
1125
1132
  }
1126
1133
  async function evaluateThroughSecrets(envelope, instruction, config, env, entrypoint, run = runRuntimeCommand, admission, nativeTarget) {
1127
- if (stopReviewClientContextRefused(env))
1134
+ const model = config.model;
1135
+ if (!isVersionedJevModel(model) || stopReviewClientContextRefused(env))
1128
1136
  return { ok: false, reason: "invalid_configuration" };
1129
1137
  if (!safePath(entrypoint))
1130
1138
  return { ok: false, reason: "invalid_configuration" };
@@ -1170,7 +1178,7 @@ async function evaluateThroughSecrets(envelope, instruction, config, env, entryp
1170
1178
  disposition: { type: "choice", choice: a.classification, confidence: a.confidence, probabilities: a.probabilities },
1171
1179
  actionable: { type: "noul", noul: a.actionableProbability },
1172
1180
  boundary: { type: "noul", noul: a.boundaryProbability }
1173
- }, usage: { input_tokens: a.inputTokens, output_tokens: a.outputTokens } });
1181
+ }, usage: { input_tokens: a.inputTokens, output_tokens: a.outputTokens } }, model);
1174
1182
  return assessment ? { ok: true, assessment } : { ok: false, reason: "invalid_provider_response" };
1175
1183
  }
1176
1184
  const allowed = ["credential_unavailable", "invalid_configuration", "instruction_unavailable", "claim_unavailable", "invalid_input", "request_too_large", "response_too_large", "request_timeout", "provider_unavailable", "invalid_provider_response", "credential_rejected", "provider_rate_limited", "provider_request_refused", "provider_overloaded"];