@hasna/hooks 0.12.3 → 0.12.5

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.
@@ -1,8 +1,30 @@
1
+ /** A definite refusal raised before any Claude settings byte is written.
2
+ * `settings_unreadable` (raised by the installer's writer, also for Gemini
3
+ * settings): the file exists but was not read and parsed as a JSON object. */
4
+ export declare class ClaudeSettingsRefusal extends Error {
5
+ readonly code: "skills_policy_unresolved" | "settings_unreadable";
6
+ constructor(code: "skills_policy_unresolved" | "settings_unreadable", message: string);
7
+ }
8
+ /** Skills is in use for the Claude settings under `home` when at least one holds:
9
+ * 1. the current settings text has a hook handler (`hooks.<event>[].hooks[].command`,
10
+ * or a flat `hooks.<event>[].command`) matching SKILLS_HOOK_COMMAND; or
11
+ * 2. the Skills Claude bridge `<home>/.claude/skills/skills-cli/SKILL.md` exists,
12
+ * as any file type. A lookup error other than ENOENT/ENOTDIR counts as present.
13
+ * Returns the evidence found; an empty list means Skills is genuinely absent. */
14
+ export declare function claudeSkillsUsage(before: string | null, home: string): string[];
15
+ /** Every location the bundled Skills package (@hasna/skills 0.10.28, `getDataRoot`)
16
+ * considers for `agent-policy.json`, in its resolution order, with the outcome
17
+ * at each. Only called after Skills found no policy at the selected location. */
18
+ export declare function skillsPolicyLocations(dataDir?: string): string[];
1
19
  /** The owning Skills writer commits Claude settings and discovery together.
2
- * A missing policy permits ordinary standalone installation. Any other refusal
3
- * propagates before settings are written; it never selects a fallback writer.
20
+ * A missing policy permits ordinary standalone installation only while Skills is
21
+ * genuinely absent (`claudeSkillsUsage`). When Skills is in use but its policy
22
+ * cannot be resolved, it refuses with `skills_policy_unresolved` and writes
23
+ * nothing. Any other refusal propagates before settings are written; it never
24
+ * selects a fallback writer. `beforeWrite` runs once, immediately before the
25
+ * coordinated write starts.
4
26
  */
5
27
  export declare function coordinateClaudeSettings(before: string | null, replacement: string, options: {
6
28
  home: string;
7
29
  dataDir?: string;
8
- }): boolean;
30
+ }, beforeWrite?: () => void): boolean;
@@ -1,7 +1,7 @@
1
1
  import { verifyNativeSafetyCommand } from "../native-safety.js";
2
2
  /** Exact `codex --version` outputs whose app-server protocol was measured
3
3
  * against the real native binary. Anything else refuses as native_unsupported. */
4
- export declare const SUPPORTED_CODEX_SAFETY_VERSIONS: readonly ["codex-cli 0.153.0", "codex-cli 0.154.0", "codex-cli 0.154.0-alpha.6.1", "codex-cli 0.155.0", "codex-cli 0.155.1", "codex-cli 0.156.1", "codex-cli 0.157.0", "codex-cli 0.157.1", "codex-cli 0.158.0", "codex-cli 0.159.0", "codex-cli 0.159.2", "codex-cli 0.159.3", "codex-cli 0.160.0"];
4
+ export declare const SUPPORTED_CODEX_SAFETY_VERSIONS: readonly ["codex-cli 0.153.0", "codex-cli 0.154.0", "codex-cli 0.154.0-alpha.6.1", "codex-cli 0.155.0", "codex-cli 0.155.1", "codex-cli 0.156.1", "codex-cli 0.157.0", "codex-cli 0.157.1", "codex-cli 0.158.0", "codex-cli 0.159.0", "codex-cli 0.159.2", "codex-cli 0.159.3", "codex-cli 0.160.0", "codex-cli 0.160.1"];
5
5
  export type CodexSafetyCode = "native_unavailable" | "native_unsafe_executable" | "native_executable_required" | "native_unsupported" | "native_failed" | "native_discovery_failed" | "hooks_disabled" | "guard_missing" | "guard_ambiguous" | "guard_definition_invalid" | "guard_disabled" | "guard_untrusted" | "guard_changed" | "guard_failed";
6
6
  export declare class CodexSafetyError extends Error {
7
7
  readonly code: CodexSafetyCode;
@@ -1,9 +1,16 @@
1
1
  import { connectCodexSafety, type CodexSafetyOptions } from "./codex-safety-check.js";
2
2
  import { verifyNativeSafetyCommand } from "../native-safety.js";
3
3
  export declare class CodexTrustError extends Error {
4
- readonly code: "input_invalid" | "native_changed" | "native_config_invalid" | "preimage_unsafe" | "trust_outcome_uncertain";
4
+ readonly code: "input_invalid" | "native_changed" | "native_config_invalid" | "preimage_unsafe" | "trust_refused" | "trust_outcome_uncertain";
5
5
  readonly operationId?: string | undefined;
6
- constructor(code: "input_invalid" | "native_changed" | "native_config_invalid" | "preimage_unsafe" | "trust_outcome_uncertain", operationId?: string | undefined);
6
+ readonly refusal?: {
7
+ code: string;
8
+ message: string;
9
+ } | undefined;
10
+ constructor(code: "input_invalid" | "native_changed" | "native_config_invalid" | "preimage_unsafe" | "trust_refused" | "trust_outcome_uncertain", operationId?: string | undefined, refusal?: {
11
+ code: string;
12
+ message: string;
13
+ } | undefined);
7
14
  }
8
15
  interface Dependencies {
9
16
  connect?: typeof connectCodexSafety;
@@ -2,6 +2,9 @@ export declare function readCodexSettings(path: string): Record<string, any>;
2
2
  /** Preserve the exact read version. Never write trust state or config.toml. */
3
3
  export declare function capturedCodexSettings(settings: Record<string, any>): string | null;
4
4
  export declare function assertSettingsPreimage(raw: string | null, expected?: string): void;
5
- export declare function writeCodexSettings(path: string, settings: Record<string, any>, expectedSha256?: string): void;
6
- /** Shared standalone writer. Managed Claude settings still use Skills. */
7
- export declare function writeHookSettingsPreimage(path: string, settings: Record<string, any>, before: string | null): void;
5
+ export declare function writeCodexSettings(path: string, settings: Record<string, any>, expectedSha256?: string, beforeWrite?: () => void): void;
6
+ /** Shared standalone writer. Managed Claude settings still use Skills.
7
+ * `beforeWrite` runs once, after every predecessor check and immediately before
8
+ * the replacement is renamed over `path`; a failure before it is a definite
9
+ * refusal that left `path` unchanged. */
10
+ export declare function writeHookSettingsPreimage(path: string, settings: Record<string, any>, before: string | null, beforeWrite?: () => void): void;
@@ -28,6 +28,8 @@ export interface InstallResult {
28
28
  applied?: boolean;
29
29
  note?: string;
30
30
  configPath?: string;
31
+ /** Stable refusal code, when the failure carries one (e.g. skills_policy_unresolved). */
32
+ code?: string;
31
33
  }
32
34
  export interface InstallOptions {
33
35
  /** Optional exact predecessor for a planned native safety registration. */
@@ -46,6 +48,12 @@ export interface InstallOptions {
46
48
  codewithMode?: CodewithInstallMode;
47
49
  /** Explicit Codewith config path for the direct-write mode and tests. */
48
50
  codewithConfigPath?: string;
51
+ /**
52
+ * Single JSON-settings target only: runs once, immediately before the
53
+ * selected writer may change the settings file. A failure reported before it
54
+ * runs is a definite refusal that left the settings unchanged.
55
+ */
56
+ beforeWrite?: () => void;
49
57
  }
50
58
  export declare function getSettingsPath(scope?: Scope, target?: SingleTarget, codewithConfigPath?: string): string;
51
59
  export declare function getHookPath(name: string): string;
@@ -80,7 +88,7 @@ export declare function previewNativeReadinessRegistration(target: "codex" | "cl
80
88
  after: string;
81
89
  command: string;
82
90
  };
83
- export declare function installNativeReadinessRegistration(target: "codex" | "claude", expectedSettingsSha256: string): {
91
+ export declare function installNativeReadinessRegistration(target: "codex" | "claude", expectedSettingsSha256: string, beforeWrite?: () => void): {
84
92
  success: boolean;
85
93
  };
86
94
  export declare function installHooks(names: string[], options?: InstallOptions): InstallResult[];
@@ -1,8 +1,14 @@
1
1
  import { verifyNativeSafetyCommand } from "../native-safety.js";
2
+ /** The definite cause of an apply that stopped before its writer could change the target. */
3
+ export interface RegistrationRefusal {
4
+ code: string;
5
+ message: string;
6
+ }
2
7
  export declare class NativeRegistrationError extends Error {
3
- readonly code: "input_invalid" | "settings_unsafe" | "settings_invalid" | "settings_changed" | "hooks_disabled" | "registration_conflict" | "guard_failed" | "apply_outcome_uncertain";
8
+ readonly code: "input_invalid" | "settings_unsafe" | "settings_invalid" | "settings_changed" | "hooks_disabled" | "registration_conflict" | "guard_failed" | "apply_refused" | "apply_outcome_uncertain";
4
9
  readonly operationId?: string | undefined;
5
- constructor(code: "input_invalid" | "settings_unsafe" | "settings_invalid" | "settings_changed" | "hooks_disabled" | "registration_conflict" | "guard_failed" | "apply_outcome_uncertain", operationId?: string | undefined);
10
+ readonly refusal?: RegistrationRefusal | undefined;
11
+ constructor(code: "input_invalid" | "settings_unsafe" | "settings_invalid" | "settings_changed" | "hooks_disabled" | "registration_conflict" | "guard_failed" | "apply_refused" | "apply_outcome_uncertain", operationId?: string | undefined, refusal?: RegistrationRefusal | undefined);
6
12
  }
7
13
  export interface NativeRegistrationOptions {
8
14
  target: "codex" | "claude";
@@ -55,11 +55,14 @@ export declare function readNativeSafetyRegistration(home?: string): {
55
55
  export declare function nativeSafetyBindingIntegrityReason(home?: string): string | undefined;
56
56
  /** Register only the bundled composite guard. Updates preserve the exact prior
57
57
  * record and require its digest. A lock coordinates package-owned writers; an
58
- * unexpected preimage or a retained interrupted lock requires reconciliation. */
58
+ * unexpected preimage or a retained interrupted lock requires reconciliation.
59
+ * `beforeWrite` runs once, after the last predecessor check and immediately
60
+ * before the record is replaced; a failure before it left the record unchanged. */
59
61
  export declare function registerNativeSafety(options?: {
60
62
  home?: string;
61
63
  expectedSHA256?: string;
62
64
  command?: string;
65
+ beforeWrite?: () => void;
63
66
  }): {
64
67
  ok: true;
65
68
  changed: boolean;
@@ -301,8 +301,10 @@ function registerNativeSafety(options = {}) {
301
301
  if (before) {
302
302
  if (hash(readOwned(path)) !== before.sha256)
303
303
  throw new NativeSafetyError("binding_changed");
304
+ options.beforeWrite?.();
304
305
  renameSync(temporary, path);
305
306
  } else {
307
+ options.beforeWrite?.();
306
308
  linkSync(temporary, path);
307
309
  unlinkSync(temporary);
308
310
  }
@@ -1,6 +1,6 @@
1
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync, writeSync } from "fs";
2
- import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "path";
3
- import { homedir, tmpdir } from "os";
1
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync, writeSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
3
+ import { homedir, tmpdir } from "node:os";
4
4
 
5
5
  export interface CodewithHookInput {
6
6
  session_id?: string;
@@ -66,7 +66,10 @@ export async function run(): Promise<void> {
66
66
  if (!("continue" in verdict && verdict.continue === true)) respond(verdict);
67
67
  }
68
68
 
69
+ // Standalone run only. No top-level await: the CommonJS native safety worker
70
+ // (scripts/build-native-worker.ts) bundles this module, and its parser refuses
71
+ // top-level await even where import.meta.main=false makes the block dead.
72
+ // A rejected run still exits non-zero, as an awaited one did.
69
73
  if (import.meta.main) {
70
- await run();
71
- process.exit(0);
74
+ void run().then(() => process.exit(0));
72
75
  }
@@ -2,10 +2,12 @@
2
2
  * Signed-link shapes in text.
3
3
  *
4
4
  * The same shape the in-process harness redaction uses for this class: an
5
- * absolute http(s) URL whose query or fragment carries a capability-class
6
- * parameter. The measured signed action links carry `expires`, `pr_number`,
7
- * `repository`, `return_to` and `signature`; `signature` is the discriminating
8
- * parameter, and the other capability names below are the same class.
5
+ * absolute http(s) URL that carries a capability — a capability-class query or
6
+ * fragment parameter, or a capability carried in the path of a measured
7
+ * provider class. The measured signed action links carry `expires`,
8
+ * `pr_number`, `repository`, `return_to` and `signature`; `signature` is the
9
+ * discriminating parameter, and the other capability names below are the same
10
+ * class.
9
11
  *
10
12
  * A match is replaced by the URL's origin plus `/[redacted signed link]`, so a
11
13
  * reader keeps the host for diagnosis and nothing else. The matched text is
@@ -23,6 +25,31 @@ export const SIGNED_LINK_PARAMS: readonly string[] = [
23
25
  "token",
24
26
  ];
25
27
 
28
+ /**
29
+ * Anchored, provider-scoped path-borne capability classes.
30
+ *
31
+ * Some providers put the whole proof in the URL path, so a parameter scan
32
+ * reports their capability links clean (HP659: a Stripe Connect account
33
+ * onboarding link reached a transcript through browser tool-result metadata).
34
+ * Each entry names one measured provider class: the exact host plus the path
35
+ * shape that carries the token. A generic "long path" heuristic would flag
36
+ * ordinary links, so extend this table only with a class that was measured.
37
+ * Do not fetch a link to test it.
38
+ *
39
+ * This mirrors the scanner's table in @hasna/secrets (`signed-urls.ts`), so a
40
+ * link one Hasna component redacts is a link the other recognizes.
41
+ */
42
+ export const PATH_CAPABILITY_CLASSES: ReadonlyArray<{ hostname: string; path: RegExp }> = [
43
+ {
44
+ // Stripe Connect account-onboarding links: /setup/<letter>/<token> and the
45
+ // documented /setup/c/acct_<id>/<token> form. The onboarding token is the
46
+ // capability and the link is the account's entry point; nothing in the
47
+ // query marks it.
48
+ hostname: "connect.stripe.com",
49
+ path: /^\/setup\/[a-z]\/(?:acct_[A-Za-z0-9]+\/)?[^/?#]+\/?$/i,
50
+ },
51
+ ];
52
+
26
53
  /** Cheap pre-filter: any absolute URL. (A keyword pre-filter would miss percent- or entity-encoded names.) */
27
54
  const HINT = /https?:\/\//i;
28
55
 
@@ -75,13 +102,41 @@ export function hasSignatureParameter(url: string): boolean {
75
102
  return false;
76
103
  }
77
104
 
105
+ /**
106
+ * True when a URL's path carries a capability of an anchored, provider-scoped
107
+ * class (see `PATH_CAPABILITY_CLASSES`). The host and path shape are the whole
108
+ * rule: an ordinary URL, the bare provider origin, a host that merely ends with
109
+ * the provider name, and the same path shape on another host are all untouched.
110
+ * Separators are decoded first, exactly as the parameter check does, so a JSON
111
+ * `\u003f` (`?`) or `\u0026` (`&`) straight after the token cannot push the
112
+ * token out of the matched path segment.
113
+ */
114
+ export function hasPathBorneCapability(url: string): boolean {
115
+ let parsed: URL;
116
+ try { parsed = new URL(decodeSeparators(url)); } catch { return false; }
117
+ const hostname = parsed.hostname.replace(/\.$/, "").toLowerCase();
118
+ for (const klass of PATH_CAPABILITY_CLASSES) {
119
+ if (hostname === klass.hostname && klass.path.test(parsed.pathname)) return true;
120
+ }
121
+ return false;
122
+ }
123
+
124
+ /**
125
+ * True when a URL carries a capability: a signature-class query or fragment
126
+ * parameter, or an anchored path-borne class. The count and the redaction share
127
+ * this predicate, so the two cannot disagree.
128
+ */
129
+ export function carriesCapability(url: string): boolean {
130
+ return hasSignatureParameter(url) || hasPathBorneCapability(url);
131
+ }
132
+
78
133
  /** Number of signed-link URLs in `text`. */
79
134
  export function countSignedLinks(text: string): number {
80
135
  if (typeof text !== "string" || !text || !HINT.test(text)) return 0;
81
136
  let count = 0;
82
137
  for (const match of text.matchAll(URL_PATTERN)) {
83
138
  const url = match[0].replace(TRAILING_PUNCTUATION, "");
84
- if (hasSignatureParameter(url)) count++;
139
+ if (carriesCapability(url)) count++;
85
140
  }
86
141
  return count;
87
142
  }
@@ -92,7 +147,7 @@ export function redactSignedLinks(text: string): string {
92
147
  return text.replace(URL_PATTERN, (match) => {
93
148
  const trailing = match.match(TRAILING_PUNCTUATION)?.[0] ?? "";
94
149
  const url = trailing ? match.slice(0, -trailing.length) : match;
95
- if (!hasSignatureParameter(url)) return match;
150
+ if (!carriesCapability(url)) return match;
96
151
  const origin = url.match(/^https?:\/\/[^/?#]+/i)?.[0];
97
152
  return origin ? `${origin}/${REDACTION_MARKER}${trailing}` : `${REDACTION_MARKER}${trailing}`;
98
153
  });
@@ -4,13 +4,26 @@ Claude Code PostToolUse hook, installed as `hooks run signed-link-output`
4
4
  (matcher `Bash`, `WebFetch` and MCP tools). It is the backstop behind the
5
5
  `signed-link-guard` PreToolUse guard.
6
6
 
7
- When a tool result contains a signed-link URL — an absolute `http(s)` URL whose
8
- query or fragment carries `signature`, `sig`, `x-amz-signature`,
9
- `x-goog-signature`, `x-ms-signature`, `hmac` or `token` — it returns the two
10
- fields below. Separators are recognised in their encoded forms too: `&amp;`
11
- (also repeated, `&amp;amp;`), `&#38;`, `&#x26;`, the JSON escape `\u0026` and
12
- percent-encoded parameter names. A result with no such link gets no output at
13
- all, however large it is.
7
+ When a tool result contains a capability link it returns the two fields below.
8
+ Two shapes are recognised:
9
+
10
+ - an absolute `http(s)` URL whose query or fragment carries `signature`, `sig`,
11
+ `x-amz-signature`, `x-goog-signature`, `x-ms-signature`, `hmac` or `token`;
12
+ separators are recognised in their encoded forms too: `&amp;` (also repeated,
13
+ `&amp;amp;`), `&#38;`, `&#x26;`, the JSON escape `\u0026` and percent-encoded
14
+ parameter names.
15
+ - an absolute `http(s)` URL of an anchored, provider-scoped path-borne class:
16
+ the exact provider host plus the measured path shape that carries the token.
17
+ The measured class is the Stripe Connect account-onboarding link
18
+ (`connect.stripe.com/setup/<letter>/<token>`, including the documented
19
+ `connect.stripe.com/setup/c/acct_<id>/<token>` form), the shape that reached
20
+ a transcript through browser tool-result metadata in HP659. The table mirrors
21
+ the scanner's in `@hasna/secrets` (`signed-urls.ts`).
22
+
23
+ Every string of the tool result is walked, so a capability in nested metadata —
24
+ for example a browser tool result's `_meta.browser_use.url` — is redacted like
25
+ one in ordinary output text. A result with no such link gets no output at all,
26
+ however large it is.
14
27
 
15
28
  - `hookSpecificOutput.updatedToolOutput`: the same tool result with each such
16
29
  URL replaced by `<origin>/[redacted signed link]`. Keys, order and
@@ -23,10 +36,26 @@ It never blocks, and it never prints, logs or stores a matched URL.
23
36
 
24
37
  ## What it can and cannot do
25
38
 
26
- - Output replacement depends on the running Claude Code build. The 2.1.285
39
+ - Output replacement depends on the running harness. Claude Code's 2.1.285
27
40
  build accepts `updatedToolOutput` on PostToolUse for every tool, checks it
28
41
  against the tool's output schema, and uses the original output (with a hook
29
42
  error) when the check fails. Older builds may ignore or reject the field.
43
+ - Codex has no output rewrite: that is a native capability limit on Codex, not
44
+ a configuration toggle. Stock Codex 0.160.0, stable 0.160.1 and shipped Hoshi
45
+ 0.5.2 share the same relevant hook schema, parser, event and core consumers.
46
+ The rewrite field this hook emits, `updatedToolOutput`, is not in Codex's
47
+ PostToolUse output schema, so Codex rejects that response as unknown and the
48
+ hook fails open: the redaction does not apply and the notice sent with it is
49
+ dropped. Codex's own rewrite field, `updatedMCPToolOutput`, is parsed but
50
+ explicitly unsupported (the hook run is marked Failed, `should_block` stays
51
+ false, and `additionalContext` is dropped); an async hook preserves the
52
+ context only. A notice-only response (`additionalContext` without a rewrite
53
+ field, as this hook returns when the copy bound prevents a rewrite) is
54
+ accepted, so the notice can still reach the model on Codex; the link is never
55
+ rewritten there. The controls Codex does support are `decision: block` with a
56
+ non-empty reason, or exit 2 — they reject the model-facing result after
57
+ execution, but they do not rewrite the payload and do not remove prior
58
+ transcript exposure. Codex-side wiring is a harness-owned follow-up.
30
59
  - It runs after the tool has run. The command already executed, the terminal
31
60
  may already have shown the output, and files the command or the harness
32
61
  wrote (including a spill file for large output) keep the link. Whether the
@@ -34,8 +63,12 @@ It never blocks, and it never prints, logs or stores a matched URL.
34
63
  - PostToolUse hooks run in parallel on the original output and the last
35
64
  rewrite wins, so another rewriting hook can undo this one. This hook returns
36
65
  a rewrite only when it changed something.
37
- - A URL that carries its capability in the path, with no capability-named
38
- parameter, is not recognised.
66
+ - A path-borne capability is recognised only for the anchored, measured
67
+ provider classes in `PATH_CAPABILITY_CLASSES` (currently
68
+ `connect.stripe.com` with `^/setup/<letter>/(acct_<id>/)?<token>/?$`). A
69
+ token in the path of an unmeasured provider class is not recognised until
70
+ that class is measured and added; a generic "long path" heuristic would flag
71
+ ordinary links.
39
72
  - Output larger than its copy bound (1,000,000 JSON nodes or 2,000 levels
40
73
  deep) is still scanned for links; when one is found the notice is added but
41
74
  the output is not rewritten, because a partial copy would change the
@@ -4,8 +4,11 @@
4
4
  * PostToolUse hook: signed-link-output (Claude Code)
5
5
  *
6
6
  * The second layer behind signed-link-guard. When a tool result contains a
7
- * signed-link URL (an absolute URL whose query or fragment carries a
8
- * capability-class parameter such as `signature`), this hook:
7
+ * capability link — an absolute URL whose query or fragment carries a
8
+ * capability-class parameter such as `signature`, or a URL of an anchored,
9
+ * provider-scoped path-borne class such as the Stripe Connect onboarding link
10
+ * (`connect.stripe.com/setup/<letter>/<token>`, including the documented
11
+ * `connect.stripe.com/setup/c/acct_<id>/<token>` form) — this hook:
9
12
  *
10
13
  * 1. returns `hookSpecificOutput.updatedToolOutput`: the same tool result
11
14
  * with each such URL replaced by `<origin>/[redacted signed link]`, and
@@ -46,8 +46,8 @@
46
46
  * command that contains a delete-verb word and stays silent otherwise.
47
47
  */
48
48
 
49
- import { homedir } from "os";
50
- import { isAbsolute, join, normalize, resolve, sep } from "path";
49
+ import { homedir } from "node:os";
50
+ import { isAbsolute, join, normalize, resolve, sep } from "node:path";
51
51
  import { BINARY_FAILURES, findTrashBinary, inspectTrashBinary, type TrashBinaryInspection } from "./binary.js";
52
52
  export { findTrashBinary, inspectTrashBinary } from "./binary.js";
53
53
  import {
@@ -1297,7 +1297,10 @@ export async function run(): Promise<void> {
1297
1297
  }
1298
1298
  }
1299
1299
 
1300
+ // Standalone run only. No top-level await: the CommonJS native safety worker
1301
+ // (scripts/build-native-worker.ts) bundles this module, and its parser refuses
1302
+ // top-level await even where import.meta.main=false makes the block dead.
1303
+ // A rejected run still exits non-zero, as an awaited one did.
1300
1304
  if (import.meta.main) {
1301
- await run();
1302
- process.exit(0);
1305
+ void run().then(() => process.exit(0));
1303
1306
  }
@@ -51,9 +51,9 @@
51
51
  * or evaluation error so a guard defect cannot wedge the agent.
52
52
  */
53
53
 
54
- import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, statSync } from "fs";
55
- import { homedir } from "os";
56
- import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from "path";
54
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, statSync } from "node:fs";
55
+ import { homedir } from "node:os";
56
+ import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
57
57
  import {
58
58
  commandWordIndex,
59
59
  decodeWord,
@@ -1213,7 +1213,10 @@ export async function run(): Promise<void> {
1213
1213
  }
1214
1214
  }
1215
1215
 
1216
+ // Standalone run only. No top-level await: the CommonJS native safety worker
1217
+ // (scripts/build-native-worker.ts) bundles this module, and its parser refuses
1218
+ // top-level await even where import.meta.main=false makes the block dead.
1219
+ // A rejected run still exits non-zero, as an awaited one did.
1216
1220
  if (import.meta.main) {
1217
- await run();
1218
- process.exit(0);
1221
+ void run().then(() => process.exit(0));
1219
1222
  }
@@ -0,0 +1,75 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute } from "node:path";
3
+ import { evaluate as evaluateTrash, findTrashBinary, inspectTrashBinary, scanCommand } from "./hook-trash-guard/src/hook";
4
+ import { evaluate as evaluateRepos } from "./hook-workspace-repos-guard/src/hook";
5
+ import { evaluate as evaluateSignedLinks } from "./hook-signed-link-guard/src/hook";
6
+ import type { CodewithHookInput, CodewithHookOutput } from "./codewith-native-common";
7
+
8
+ // The native safety composite: trash-guard, workspace-repos-guard and
9
+ // signed-link-guard judged together for one capability name. Both the v1 entry
10
+ // (hooks/native-safety-entry.ts) and the v2 worker (hooks/native-safety-worker.ts)
11
+ // call it, so one guard decision has one implementation. It reads no stdin,
12
+ // writes no stdout and never exits: the caller owns the process.
13
+
14
+ export type NativeSafetyCompositeGuard = "trash-guard" | "workspace-repos-guard";
15
+
16
+ /** Refuses an unknown capability name exactly as the v1 entry always has. */
17
+ export function assertCompositeGuard(guard: unknown): asserts guard is NativeSafetyCompositeGuard {
18
+ if (guard !== "trash-guard" && guard !== "workspace-repos-guard") throw new Error("Invalid safety capability");
19
+ }
20
+
21
+ /**
22
+ * Judge one PreToolUse input for `guard`. Returns the exact text the v1 entry
23
+ * writes to stdout (`{"verdict":null}` or `{"verdict":{hookSpecificOutput}}`),
24
+ * and throws where the v1 entry exits non-zero.
25
+ */
26
+ export function evaluateComposite(guard: string, inputText: string): string {
27
+ assertCompositeGuard(guard);
28
+ const name = guard;
29
+ const input = JSON.parse(inputText) as CodewithHookInput;
30
+ if (!input || Array.isArray(input) || input.hook_event_name !== "PreToolUse" || typeof input.tool_name !== "string"
31
+ || !input.tool_input || typeof input.tool_input !== "object" || Array.isArray(input.tool_input)
32
+ || typeof input.cwd !== "string" || !isAbsolute(input.cwd)) throw new Error("Invalid safety input");
33
+ if (input.tool_name === "Bash" && typeof input.tool_input.command !== "string") throw new Error("Invalid shell input");
34
+ // Claude Code's Monitor runs a shell command and streams its stdout to the
35
+ // model; a websocket Monitor carries `ws` and no command.
36
+ if (input.tool_name === "Monitor" && input.tool_input.command !== undefined && typeof input.tool_input.command !== "string") throw new Error("Invalid monitor input");
37
+ const requestedExecution = (input as CodewithHookInput & { hasna_execution?: { schema: string; agent: string } }).hasna_execution;
38
+ if (requestedExecution !== undefined && (!requestedExecution || Object.keys(requestedExecution).sort().join() !== "agent,schema"
39
+ || requestedExecution.schema !== "hasna.hooks.execution.v1" || typeof requestedExecution.agent !== "string"
40
+ || !/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/.test(requestedExecution.agent))) throw new Error("Invalid execution capability");
41
+ const execution = requestedExecution === undefined ? undefined : {
42
+ runtime: process.execPath, home: homedir(), path: process.env.PATH!, agent: requestedExecution.agent,
43
+ };
44
+ if (execution && (!isAbsolute(execution.runtime) || !execution.path)) throw new Error("Invalid bound execution context");
45
+ if (["apply_patch", "ApplyPatch", "functions.apply_patch"].includes(input.tool_name)) {
46
+ if (input.tool_input.command !== undefined && input.tool_input.patch !== undefined && input.tool_input.command !== input.tool_input.patch) throw new Error("Conflicting patch aliases");
47
+ const patch = input.tool_input.command ?? input.tool_input.patch;
48
+ if (typeof patch !== "string") throw new Error("Invalid patch input");
49
+ input.tool_input = { ...input.tool_input, command: patch, patch };
50
+ }
51
+ // Every guard judges a Monitor command exactly as it judges the same Bash command.
52
+ const monitor = input.tool_name === "Monitor";
53
+ const shellCommand = input.tool_name === "Bash" || (monitor && typeof input.tool_input.command === "string");
54
+ const evaluated: CodewithHookInput = monitor && shellCommand ? { ...input, tool_name: "Bash" } : input;
55
+ const deny = (reason: string) => ({ hookSpecificOutput: { hookEventName: "PreToolUse" as const, permissionDecision: "deny" as const, permissionDecisionReason: reason } });
56
+ const repos = evaluateRepos(evaluated).output;
57
+ // Every shell command, whatever the capability name: the guard reaches each
58
+ // registration of this entry. Its refusal outranks a Trash rewrite, because an
59
+ // allowed rewrite would also run the composite gh read.
60
+ const signedLinks = evaluateSignedLinks(evaluated);
61
+ const handoff = shellCommand && scanCommand(evaluated.tool_input!.command as string, { home: homedir(), cwd: input.cwd }).handoffHits.length > 0;
62
+ let trash: CodewithHookOutput = name === "trash-guard" && (!monitor || shellCommand)
63
+ ? evaluateTrash(evaluated, { home: homedir(), cwd: input.cwd, findTrash: findTrashBinary, inspectTrash: inspectTrashBinary, execution }) : { continue: true };
64
+ // A Trash rewrite is proven only for Bash. Under Monitor the deletion is
65
+ // refused rather than rewritten: a rewrite the harness dropped would run the
66
+ // raw command.
67
+ if (monitor && trash.hookSpecificOutput?.permissionDecision === "allow") {
68
+ trash = deny("[trash-guard] A deletion inside a Monitor command is refused; run it with the Bash tool, where it is redirected into trash.");
69
+ }
70
+ const verdict: CodewithHookOutput = repos.decision === "block" ? deny(repos.reason!)
71
+ : signedLinks.hookSpecificOutput ? signedLinks
72
+ : handoff ? deny("[workspace-repos-guard] Deletion under a protected repository checkout is refused.")
73
+ : trash;
74
+ return JSON.stringify({ verdict: "continue" in verdict ? null : verdict });
75
+ }
@@ -1,57 +1,11 @@
1
- import { homedir } from "node:os";
2
- import { isAbsolute } from "node:path";
3
- import { evaluate as evaluateTrash, findTrashBinary, inspectTrashBinary, scanCommand } from "./hook-trash-guard/src/hook";
4
- import { evaluate as evaluateRepos } from "./hook-workspace-repos-guard/src/hook";
5
- import { evaluate as evaluateSignedLinks } from "./hook-signed-link-guard/src/hook";
6
- import type { CodewithHookInput, CodewithHookOutput } from "./codewith-native-common";
1
+ import { assertCompositeGuard, evaluateComposite } from "./native-safety-composite";
7
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.
8
7
  // Bundled with import.meta.main=false, so the original standalone run wrappers
9
8
  // cannot swallow exceptions or emit a second response. Only this entry runs.
10
9
  const name = process.argv[1];
11
- if (name !== "trash-guard" && name !== "workspace-repos-guard") throw new Error("Invalid safety capability");
12
- const input = JSON.parse(await Bun.stdin.text()) as CodewithHookInput;
13
- if (!input || Array.isArray(input) || input.hook_event_name !== "PreToolUse" || typeof input.tool_name !== "string"
14
- || !input.tool_input || typeof input.tool_input !== "object" || Array.isArray(input.tool_input)
15
- || typeof input.cwd !== "string" || !isAbsolute(input.cwd)) throw new Error("Invalid safety input");
16
- if (input.tool_name === "Bash" && typeof input.tool_input.command !== "string") throw new Error("Invalid shell input");
17
- // Claude Code's Monitor runs a shell command and streams its stdout to the
18
- // model; a websocket Monitor carries `ws` and no command.
19
- if (input.tool_name === "Monitor" && input.tool_input.command !== undefined && typeof input.tool_input.command !== "string") throw new Error("Invalid monitor input");
20
- const requestedExecution = (input as CodewithHookInput & { hasna_execution?: { schema: string; agent: string } }).hasna_execution;
21
- if (requestedExecution !== undefined && (!requestedExecution || Object.keys(requestedExecution).sort().join() !== "agent,schema"
22
- || requestedExecution.schema !== "hasna.hooks.execution.v1" || typeof requestedExecution.agent !== "string"
23
- || !/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/.test(requestedExecution.agent))) throw new Error("Invalid execution capability");
24
- const execution = requestedExecution === undefined ? undefined : {
25
- runtime: process.execPath, home: homedir(), path: process.env.PATH!, agent: requestedExecution.agent,
26
- };
27
- if (execution && (!isAbsolute(execution.runtime) || !execution.path)) throw new Error("Invalid bound execution context");
28
- if (["apply_patch", "ApplyPatch", "functions.apply_patch"].includes(input.tool_name)) {
29
- if (input.tool_input.command !== undefined && input.tool_input.patch !== undefined && input.tool_input.command !== input.tool_input.patch) throw new Error("Conflicting patch aliases");
30
- const patch = input.tool_input.command ?? input.tool_input.patch;
31
- if (typeof patch !== "string") throw new Error("Invalid patch input");
32
- input.tool_input = { ...input.tool_input, command: patch, patch };
33
- }
34
- // Every guard judges a Monitor command exactly as it judges the same Bash command.
35
- const monitor = input.tool_name === "Monitor";
36
- const shellCommand = input.tool_name === "Bash" || (monitor && typeof input.tool_input.command === "string");
37
- const evaluated: CodewithHookInput = monitor && shellCommand ? { ...input, tool_name: "Bash" } : input;
38
- const deny = (reason: string) => ({ hookSpecificOutput: { hookEventName: "PreToolUse" as const, permissionDecision: "deny" as const, permissionDecisionReason: reason } });
39
- const repos = evaluateRepos(evaluated).output;
40
- // Every shell command, whatever the capability name: the guard reaches each
41
- // registration of this entry. Its refusal outranks a Trash rewrite, because an
42
- // allowed rewrite would also run the composite gh read.
43
- const signedLinks = evaluateSignedLinks(evaluated);
44
- const handoff = shellCommand && scanCommand(evaluated.tool_input!.command as string, { home: homedir(), cwd: input.cwd }).handoffHits.length > 0;
45
- let trash: CodewithHookOutput = name === "trash-guard" && (!monitor || shellCommand)
46
- ? evaluateTrash(evaluated, { home: homedir(), cwd: input.cwd, findTrash: findTrashBinary, inspectTrash: inspectTrashBinary, execution }) : { continue: true };
47
- // A Trash rewrite is proven only for Bash. Under Monitor the deletion is
48
- // refused rather than rewritten: a rewrite the harness dropped would run the
49
- // raw command.
50
- if (monitor && trash.hookSpecificOutput?.permissionDecision === "allow") {
51
- trash = deny("[trash-guard] A deletion inside a Monitor command is refused; run it with the Bash tool, where it is redirected into trash.");
52
- }
53
- const verdict: CodewithHookOutput = repos.decision === "block" ? deny(repos.reason!)
54
- : signedLinks.hookSpecificOutput ? signedLinks
55
- : handoff ? deny("[workspace-repos-guard] Deletion under a protected repository checkout is refused.")
56
- : trash;
57
- process.stdout.write(JSON.stringify({ verdict: "continue" in verdict ? null : verdict }));
10
+ assertCompositeGuard(name);
11
+ process.stdout.write(evaluateComposite(name, await Bun.stdin.text()));
@@ -0,0 +1,19 @@
1
+ import { evaluateComposite } from "./native-safety-composite";
2
+
3
+ // The native safety worker, ABI v2 (docs/adr/0001-stable-native-safety-launcher.md
4
+ // section 3.4). scripts/build-native-worker.ts bundles it into
5
+ // bin/native-safety-worker.cjs: CommonJS for Node's module shape, requiring only
6
+ // node: builtins, with no top-level await and no top-level side effects. It reads
7
+ // no stdin, writes no stdout and never exits; the loader that evaluates the
8
+ // verified bundle owns the process.
9
+
10
+ /** Replaced at build time with the package.json version; never set at run time. */
11
+ declare const HASNA_HOOKS_NATIVE_SAFETY_WORKER_VERSION: string;
12
+
13
+ export const abi = 2;
14
+ export const version: string = HASNA_HOOKS_NATIVE_SAFETY_WORKER_VERSION;
15
+
16
+ /** The v1 entry's exact stdout text for this input; throws where the v1 entry exits non-zero. */
17
+ export function evaluate(guard: string, inputText: string): string {
18
+ return evaluateComposite(guard, inputText);
19
+ }