@hasna/hooks 0.13.2 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +30 -15
  2. package/bin/hooks/stop-review.js +53 -17
  3. package/bin/hooks-mcp.js +4787 -1415
  4. package/bin/index.js +5250 -2337
  5. package/bin/native-safety-entry.js +15 -37
  6. package/bin/native-safety-worker.cjs +38 -36
  7. package/bin/serve.js +34 -11
  8. package/dist/index.js +4970 -1579
  9. package/dist/lib/claude-skills-coordination.d.ts +1 -1
  10. package/dist/lib/codex-safety-trust.d.ts +2 -2
  11. package/dist/lib/native-safety-registration.d.ts +2 -2
  12. package/dist/lib/native-safety.d.ts +1 -1
  13. package/dist/lib/registry.d.ts +3 -1
  14. package/dist/native-safety.d.ts +4 -2
  15. package/dist/native-safety.js +21 -2
  16. package/dist/sdk/index.js +9 -53
  17. package/hooks/hook-job-folder-guard/README.md +61 -0
  18. package/hooks/hook-job-folder-guard/package.json +12 -0
  19. package/hooks/hook-job-folder-guard/src/classify.ts +398 -0
  20. package/hooks/hook-job-folder-guard/src/hook.ts +96 -0
  21. package/hooks/hook-protected-delete-guard/README.md +114 -0
  22. package/hooks/hook-protected-delete-guard/package.json +12 -0
  23. package/hooks/hook-protected-delete-guard/src/hook.ts +539 -0
  24. package/hooks/hook-signed-link-guard/src/classify.ts +41 -2
  25. package/hooks/hook-stop-review/README.md +16 -0
  26. package/hooks/hook-stop-review/manifest.json +1 -1
  27. package/hooks/hook-stop-review/package.json +1 -1
  28. package/hooks/hook-stop-review/src/hook.ts +1 -1
  29. package/hooks/hook-stop-review/src/native.ts +44 -8
  30. package/hooks/hook-stop-review/src/policy.ts +20 -8
  31. package/hooks/hook-stop-review/src/runtime.ts +16 -13
  32. package/hooks/hook-stop-review/src/types.ts +12 -2
  33. package/hooks/hook-trash-guard/README.md +130 -13
  34. package/hooks/hook-trash-guard/src/hook.ts +518 -71
  35. package/hooks/local-executors.ts +33 -0
  36. package/hooks/native-safety-composite.ts +19 -8
  37. package/package.json +3 -3
  38. package/scripts/build-native-entry.ts +123 -0
  39. package/scripts/build-native-worker.ts +11 -4
  40. package/scripts/validate-package.ts +8 -2
  41. package/hooks/native-safety-entry.ts +0 -11
@@ -13,7 +13,7 @@ export declare class ClaudeSettingsRefusal extends Error {
13
13
  * as any file type. A lookup error other than ENOENT/ENOTDIR counts as present.
14
14
  * Returns the evidence found; an empty list means Skills is genuinely absent. */
15
15
  export declare function claudeSkillsUsage(before: string | null, home: string): string[];
16
- /** Every location the bundled Skills package (@hasna/skills 0.10.78, `getDataRoot`)
16
+ /** Every location the bundled Skills package (@hasna/skills 0.10.100, `getDataRoot`)
17
17
  * considers for `agent-policy.json`, in its resolution order, with the outcome
18
18
  * at each. Only called after Skills found no policy at the selected location. */
19
19
  export declare function skillsPolicyLocations(dataDir?: string): string[];
@@ -49,7 +49,7 @@ export declare const applyCodexSafetyTrust: (options: CodexSafetyTrustOptions &
49
49
  unrelatedConfigurationPreserved: boolean;
50
50
  readinessRunnerVerified?: boolean | undefined;
51
51
  guardVerified: boolean;
52
- guard?: "workspace-repos-guard" | undefined;
52
+ guard?: "workspace-repos-guard" | "protected-delete-guard" | undefined;
53
53
  ok: boolean;
54
54
  changed: boolean;
55
55
  operationId: string;
@@ -84,7 +84,7 @@ export declare const applyCodexReadinessTrust: (options: CodexSafetyOptions & {
84
84
  unrelatedConfigurationPreserved: boolean;
85
85
  readinessRunnerVerified?: boolean | undefined;
86
86
  guardVerified: boolean;
87
- guard?: "workspace-repos-guard" | undefined;
87
+ guard?: "workspace-repos-guard" | "protected-delete-guard" | undefined;
88
88
  ok: boolean;
89
89
  changed: boolean;
90
90
  operationId: string;
@@ -69,7 +69,7 @@ export declare const applyNativeSafetyRegistration: (options: NativeRegistration
69
69
  nativeAdoptionVerified: boolean;
70
70
  readinessRunnerVerified?: boolean | undefined;
71
71
  guardVerified: boolean;
72
- guard?: "workspace-repos-guard" | undefined;
72
+ guard?: "workspace-repos-guard" | "protected-delete-guard" | undefined;
73
73
  ok: boolean;
74
74
  changed: boolean;
75
75
  operationId: `${string}-${string}-${string}-${string}-${string}`;
@@ -103,7 +103,7 @@ export declare const applyNativeReadinessRegistration: (options: NativeReadiness
103
103
  nativeAdoptionVerified: boolean;
104
104
  readinessRunnerVerified?: boolean | undefined;
105
105
  guardVerified: boolean;
106
- guard?: "workspace-repos-guard" | undefined;
106
+ guard?: "workspace-repos-guard" | "protected-delete-guard" | undefined;
107
107
  ok: boolean;
108
108
  changed: boolean;
109
109
  operationId: `${string}-${string}-${string}-${string}-${string}`;
@@ -1,4 +1,4 @@
1
- export type NativeSafetyName = "trash-guard" | "workspace-repos-guard";
1
+ export type NativeSafetyName = "trash-guard" | "workspace-repos-guard" | "protected-delete-guard";
2
2
  export interface NativeSafetyBinding {
3
3
  name: NativeSafetyName;
4
4
  runtime: string;
@@ -51,7 +51,9 @@ export interface HookMeta {
51
51
  /**
52
52
  * Timeout (seconds) written into the agent's settings entry for this hook.
53
53
  * The harness default is 600s, and a TIMED-OUT HOOK DOES NOT BLOCK: a guard
54
- * that needs a verdict on stdout must declare a timeout it can meet.
54
+ * that needs a verdict on stdout must declare a timeout it can meet. Claude
55
+ * registrations of the native safety guards also set onFailure "block", so
56
+ * their timeout refuses the call (HO-00191); other hooks keep the default.
55
57
  */
56
58
  timeoutSeconds?: number;
57
59
  }
@@ -93,8 +93,10 @@ export declare function evaluateNativeSafetyForExecution(event: NativeSafetyEven
93
93
  * trash-guard must rewrite the removal into Trash. workspace-repos-guard never
94
94
  * rewrites, so its probe is a removal below the protected clones root, which it
95
95
  * refuses from the path alone: the exact deny proves the pinned runtime and
96
- * worker, the worker's execution and its classification. Neither probe runs the
97
- * removal, and neither path is created. */
96
+ * worker, the worker's execution and its classification. protected-delete-guard
97
+ * never rewrites either: its probes are a removal of the home's `~/.ssh`, which
98
+ * it must refuse, and of an ordinary name in the home, which it must let pass.
99
+ * No probe runs the removal, and no path is created. */
98
100
  export declare function verifyNativeSafetyCommand(command: string, home?: string, guard?: NativeSafetyName): Promise<void>;
99
101
  export declare function verifyNativeSafetyRegistration(home?: string): Promise<{
100
102
  path: string;
@@ -12,7 +12,7 @@ import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readF
12
12
  import { dirname, isAbsolute, join } from "path";
13
13
  import { homedir } from "os";
14
14
  function isNativeSafetyName(name) {
15
- return name === "trash-guard" || name === "workspace-repos-guard";
15
+ return name === "trash-guard" || name === "workspace-repos-guard" || name === "protected-delete-guard";
16
16
  }
17
17
  var NATIVE_SAFETY_RUNTIME_KEY_SOURCE = String.raw`((s) => {
18
18
  const parts = [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs, s.birthtimeNs];
@@ -542,9 +542,28 @@ async function evaluateRecord(event, record, signal, executionAgent) {
542
542
  throw new NativeSafetyError("guard_failed");
543
543
  }
544
544
  async function verifyNativeSafetyCommand(command, home = homedir2(), guard = "trash-guard") {
545
- if (guard !== "trash-guard" && guard !== "workspace-repos-guard")
545
+ if (guard !== "trash-guard" && guard !== "workspace-repos-guard" && guard !== "protected-delete-guard")
546
546
  throw new NativeSafetyError("input_invalid");
547
547
  home = canonicalHome(home);
548
+ if (guard === "protected-delete-guard") {
549
+ const binding = nativeSafetyCommandBinding(command);
550
+ if (binding?.name !== guard || binding.home !== home)
551
+ throw new NativeSafetyError("binding_invalid");
552
+ const record2 = { schema: "hasna.hooks.native-safety.v1", harness: "sumi", command };
553
+ const removal = (path) => ({
554
+ hook_event_name: "PreToolUse",
555
+ tool_name: "Bash",
556
+ cwd: home,
557
+ tool_input: { command: "rm -rf -- '" + path.replaceAll("'", "'\\''") + "'" }
558
+ });
559
+ const refused = await evaluateRecord(removal(join2(home, ".ssh")), record2);
560
+ if (refused.decision !== "deny" || !refused.reason.startsWith("[protected-delete-guard] "))
561
+ throw new NativeSafetyError("guard_failed", refused.decision === "deny" ? refused.reason.slice(0, 512) : undefined);
562
+ const ordinary = await evaluateRecord(removal(join2(home, ".hasna-protected-delete-verification-only")), record2);
563
+ if (ordinary.decision !== "continue")
564
+ throw new NativeSafetyError("guard_failed", ordinary.decision === "deny" ? ordinary.reason.slice(0, 512) : undefined);
565
+ return;
566
+ }
548
567
  if (guard === "workspace-repos-guard") {
549
568
  const binding = nativeSafetyCommandBinding(command);
550
569
  if (binding?.name !== guard || binding.home !== home)
package/dist/sdk/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- // ../contracts/dist/client/transport.js
2
+ // node_modules/@hasna/contracts/dist/client/transport.js
3
3
  import { isIP } from "net";
4
4
  import { spawnSync } from "child_process";
5
5
  import { closeSync as closeSync2, fstatSync as fstatSync2, openSync as openSync2, readFileSync as readFileSync2 } from "fs";
@@ -311,14 +311,11 @@ function readCredentialFile(path, apiKeyKeys, pointerKey) {
311
311
  return values[0] === undefined ? null : { apiKey: values[0] };
312
312
  }
313
313
  var CREDENTIAL_SHAPED_KEY = /(?:^|_)(?:API_KEY|KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH)(?:_|$)/;
314
- function appConfigDiskValue(name, env, keys, profile = null) {
315
- if (profile !== null && !SAFE_PROFILE.test(profile)) {
316
- throw new CredentialResolutionError(name, "The selected configuration profile is invalid.", ["profile"]);
317
- }
314
+ function appConfigDiskValue(name, env, keys) {
318
315
  const wanted = keys.filter((key) => !CREDENTIAL_SHAPED_KEY.test(key));
319
316
  if (wanted.length === 0)
320
317
  return null;
321
- for (const path of profileDiskSources(name, env, profile)) {
318
+ for (const path of credentialDiskSources(name, env)) {
322
319
  const parsed = readAppConfigFile(path);
323
320
  if (!parsed)
324
321
  continue;
@@ -842,16 +839,7 @@ class ClientTransportConfigurationError extends Error {
842
839
  this.sources = Object.freeze([...sources]);
843
840
  }
844
841
  }
845
-
846
- class ClientCredentialMissingError extends ClientTransportConfigurationError {
847
- authorityConfigured;
848
- constructor(name, message, sources, authorityConfigured) {
849
- super(name, message, sources);
850
- this.authorityConfigured = authorityConfigured;
851
- this.name = "ClientCredentialMissingError";
852
- }
853
- }
854
- function resolveClientAuthoritySnapshot(name, env = process.env, options = {}) {
842
+ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
855
843
  env = snapshotClientEnvironment(name, env);
856
844
  const keys = clientTransportEnvKeys(name);
857
845
  const definedUrlEntries = keys.apiUrlKeys.filter((key) => Object.prototype.hasOwnProperty.call(env, key) && env[key] !== undefined).map((key) => ({ key, raw: String(env[key]) }));
@@ -864,20 +852,12 @@ function resolveClientAuthoritySnapshot(name, env = process.env, options = {}) {
864
852
  throw new ClientTransportConfigurationError(name, `${controlledUrl.key} contains ASCII control characters.`, [controlledUrl.key]);
865
853
  }
866
854
  const usableUrlEntries = definedUrlEntries.map((entry) => ({ key: entry.key, value: entry.raw.trim() }));
867
- const normalizedAuthority = (entry) => {
868
- try {
869
- return toV1BaseUrl(entry.value);
870
- } catch {
871
- throw new ClientTransportConfigurationError(name, `Invalid API URL from ${entry.key}; use an absolute HTTPS URL or exact loopback HTTP authority without credentials, query or fragment.`, [entry.key]);
872
- }
873
- };
874
- if (usableUrlEntries.length > 1 && new Set(usableUrlEntries.map(normalizedAuthority)).size > 1) {
875
- throw new ClientTransportConfigurationError(name, `${usableUrlEntries.map((entry) => entry.key).join(" and ")} disagree; client authority aliases must select the same versioned API authority or only one may be set.`, usableUrlEntries.map((entry) => entry.key));
855
+ if (usableUrlEntries.length > 1 && new Set(usableUrlEntries.map((entry) => entry.value)).size > 1) {
856
+ throw new ClientTransportConfigurationError(name, `${usableUrlEntries.map((entry) => entry.key).join(" and ")} disagree; client authority aliases must be identical or only one may be set.`, usableUrlEntries.map((entry) => entry.key));
876
857
  }
877
858
  const envUrlHit = usableUrlEntries[0] ?? null;
878
859
  const keychainUrlHit = keychainConfigValue(name, env, options.credentials?.keychain);
879
- const profile = options.bindUnpairedCredentialsToFleet ? options.credentials?.profile?.trim() || env.HASNA_PROFILE?.trim() || null : null;
880
- const diskConfigUrlHit = appConfigDiskValue(name, env, keys.apiUrlKeys, profile);
860
+ const diskConfigUrlHit = appConfigDiskValue(name, env, keys.apiUrlKeys);
881
861
  if (diskConfigUrlHit?.unusable) {
882
862
  throw new ClientTransportConfigurationError(name, `${diskConfigUrlHit.key} in ${diskConfigUrlHit.path} is declared but blank or malformed; public clients require a valid HTTPS service authority.`, [diskConfigUrlHit.path]);
883
863
  }
@@ -887,23 +867,10 @@ function resolveClientAuthoritySnapshot(name, env = process.env, options = {}) {
887
867
  ...diskConfigUrlHit ? [{ key: diskConfigUrlHit.path, value: diskConfigUrlHit.value.trim() }] : []
888
868
  ];
889
869
  const configuredUrl = urlCandidates[0] ?? null;
890
- const normalizedUrls = urlCandidates.map(normalizedAuthority);
891
- const divergentUrls = urlCandidates.filter((_, index) => normalizedUrls[index] !== normalizedUrls[0]);
870
+ const divergentUrls = urlCandidates.filter((candidate) => candidate.value !== configuredUrl?.value);
892
871
  if (configuredUrl && divergentUrls.length > 0) {
893
872
  throw new ClientTransportConfigurationError(name, `${configuredUrl.key} and ${divergentUrls.map((candidate) => candidate.key).join(" and ")} select different service authorities; refusing to send a credential written for one authority to the other.`, urlCandidates.map((candidate) => candidate.key));
894
873
  }
895
- if (configuredUrl && options.bindUnpairedCredentialsToFleet) {
896
- try {
897
- toV1BaseUrl(configuredUrl.value);
898
- } catch (error) {
899
- throw new ClientTransportConfigurationError(name, `Invalid API URL from ${configuredUrl.key}: ${error instanceof Error ? error.message : String(error)}`, [configuredUrl.key]);
900
- }
901
- }
902
- return { keys, configuredUrl, envUrlHit, keychainUrlHit, diskConfigUrlHit };
903
- }
904
- function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
905
- env = snapshotClientEnvironment(name, env);
906
- const { keys, configuredUrl, envUrlHit, keychainUrlHit, diskConfigUrlHit } = resolveClientAuthoritySnapshot(name, env, options);
907
874
  const warnings = [];
908
875
  if (configuredUrl && !envUrlHit) {
909
876
  warnings.push(`No ${keys.apiUrlKeys[0]} in the environment; the server URL in ${configuredUrl.key} was used, so this client connects to the server. ` + `Keep that entry aligned with the intended service authority.`);
@@ -913,10 +880,7 @@ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
913
880
  const diskHint = credentialDiskSourcesForMessage(name, env);
914
881
  const lead = configuredUrl ? `${configuredUrl.key} selects the HTTP server for '${name}', but no API key could be resolved` : `${keys.apiUrlKeys[0]} is not set and no API key could be resolved for '${name}'; a credential is required before the default fleet gateway authority applies`;
915
882
  warnings.push(`${lead}; refusing to create an unauthenticated client \u2014 public clients never fall back to SQLite or another local store. ` + `Looked in the Keychain (macOS only), then for a credential file at ${diskHint}, then for ${keys.apiKeyKeys[0]} in the environment.`);
916
- const sources = [configuredUrl?.key ?? keys.apiUrlKeys[0]];
917
- if (options.bindUnpairedCredentialsToFleet)
918
- throw new ClientCredentialMissingError(name, warnings.join(" "), sources, configuredUrl !== null);
919
- throw new ClientTransportConfigurationError(name, warnings.join(" "), sources);
883
+ throw new ClientTransportConfigurationError(name, warnings.join(" "), [configuredUrl?.key ?? keys.apiUrlKeys[0]]);
920
884
  }
921
885
  if (credential.warning)
922
886
  warnings.push(credential.warning);
@@ -939,14 +903,6 @@ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
939
903
  const message = error instanceof Error ? error.message : String(error);
940
904
  throw new ClientTransportConfigurationError(name, `Invalid API URL from ${apiUrlSource}: ${message}`, [apiUrlSource]);
941
905
  }
942
- if (options.bindUnpairedCredentialsToFleet && baseUrl !== toV1BaseUrl(defaultFleetGatewayBaseUrl(name))) {
943
- const pairedDisk = diskConfigUrlHit?.path === credential.source && (credential.tier === "disk" || credential.tier === "profile" || credential.tier === "pointer");
944
- const pairedKeychain = credential.tier === "keychain" && keychainUrlHit?.source === credential.source.replace(".api-key@", ".api-url@");
945
- const deliberatePair = envUrlHit !== null && (credential.tier === "argument" || credential.tier === "override");
946
- if (!pairedDisk && !pairedKeychain && !deliberatePair) {
947
- throw new ClientTransportConfigurationError(name, "An unpaired legacy credential is bound to the fleet gateway. Configure a stored authority/credential pair or an explicit API key override for the intended authority; no credential was sent.");
948
- }
949
- }
950
906
  return {
951
907
  resolution: {
952
908
  transport: "http",
@@ -0,0 +1,61 @@
1
+ # Job Folder Guard
2
+
3
+ A Claude Code `PreToolUse` hook that adds a notice to the model's context when a tool call writes to, or uses, a
4
+ harness job folder, and names the session's Scratchpad folder instead. Stage 1 of HO-00190: it never blocks.
5
+
6
+ Why: background sessions are told to keep temporary files in `$CLAUDE_JOB_DIR/tmp`. Under Switcher that folder is in
7
+ `~/.hasna/switcher/state/<...>/jobs/<id>/tmp/`. Job folders are removed with their session, outside Trash, so work kept
8
+ there is lost without a record. Scratch belongs in `~/.hasna/scratchpad/scratch/<session-id>/` (rules
9
+ `global-hosted-app-authority` and `global-scratch-is-transient`).
10
+
11
+ ## Install
12
+
13
+ ```
14
+ hooks install job-folder-guard
15
+ ```
16
+
17
+ It registers on `PreToolUse` with the matcher `^(Write|Edit|MultiEdit|NotebookEdit|Bash)$` and a 5-second timeout.
18
+ Codex is not covered in this stage: its tools have other names, and its sessions are not told to use a job folder.
19
+
20
+ ## What counts as a job folder
21
+
22
+ - `<any path>/jobs/<id>/tmp/` and anything below it;
23
+ - anything in `~/.claude/jobs/<id>/`, `$CLAUDE_CONFIG_DIR/jobs/<id>/` or `~/.hasna/switcher/state/<...>/jobs/<id>/`;
24
+ - anything in `$CLAUDE_JOB_DIR` (expanded when the hook's environment has it; otherwise the variable itself counts).
25
+
26
+ The harness's own `state.json` and `timeline.jsonl`, directly in `jobs/<id>/`, are excluded. Paths are read as
27
+ written: `~`, `$HOME` and `${HOME}` are expanded and a relative path is resolved against the tool call's `cwd`. Other
28
+ variables, globs and symlinks are not followed, and the file system is never touched.
29
+
30
+ ## What it reads
31
+
32
+ - `Write`, `Edit`, `MultiEdit`: `file_path`; `NotebookEdit`: `notebook_path`. A job folder there is a write.
33
+ - `Bash`: a small lexer reads the command, handling quotes, backslashes and comments. It skips heredoc bodies, and
34
+ reads command substitutions, backquotes and subshells as commands of their own. These count as writes: redirect
35
+ targets (`>`, `>>`, `>|`, `&>`, `&>>`, `<>`, `>& FILE`), `tee`'s files, the destination of `cp`, `mv`, `install` and
36
+ `ln` (or their `-t`/`--target-directory`), `install -d`'s directories, and the operands of `mkdir` and `touch`.
37
+ Leading assignments and the wrappers `env`, `sudo`, `timeout`, `nice`, `stdbuf`, `exec`, `nohup`, `command`,
38
+ `builtin` and `time` are skipped. Any other word naming a job folder counts as a use: a program's argument, the
39
+ program itself, an input redirect, an assignment's value, or an `--option=value`.
40
+
41
+ It does not see a `cd` inside the command, other variables, or files the programs it runs write themselves.
42
+
43
+ ## Output
44
+
45
+ Nothing, when there is nothing to say. Otherwise:
46
+
47
+ ```json
48
+ { "hookSpecificOutput": { "hookEventName": "PreToolUse", "additionalContext": "[job-folder-guard] This writes to ..." } }
49
+ ```
50
+
51
+ There is no `permissionDecision`, so the user's permission flow and every other hook's verdict are unchanged. The
52
+ notice names the first write, or else the first use. The path is shown as written, with control and
53
+ direction-override characters removed and a cut at 200 characters. The session id is used only when it is a plain id
54
+ (`[A-Za-z0-9][A-Za-z0-9._-]{0,127}`); otherwise the folder reads `<session-id>`. Any error in classification is
55
+ silence: a notice must never stand in the way of a tool call.
56
+
57
+ ## Stages
58
+
59
+ Stage 1, this hook: a notice only. Stage 2 would refuse such writes with the same text; it comes only on Engineering's
60
+ word, after 48 hours of stage 1, as its own reviewed change. The native safety entry is not used, because it accepts
61
+ only a deny.
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "job-folder-guard",
3
+ "version": "0.1.0",
4
+ "description": "PreToolUse Job Folder Guard hook for @hasna/hooks",
5
+ "type": "module",
6
+ "main": "./src/hook.ts",
7
+ "scripts": {
8
+ "typecheck": "tsc --noEmit"
9
+ },
10
+ "author": "Hasna",
11
+ "license": "Apache-2.0"
12
+ }