@hasna/hooks 0.12.9 → 0.12.14

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 (58) hide show
  1. package/README.md +69 -6
  2. package/bin/hooks/stop-review.js +1235 -0
  3. package/bin/hooks-mcp.js +298 -85
  4. package/bin/index.js +3309 -1086
  5. package/bin/native-readiness-entry.js +5 -1
  6. package/bin/native-safety-entry.js +27 -25
  7. package/bin/native-safety-worker.cjs +27 -25
  8. package/bin/serve.js +1362 -70
  9. package/dist/db/remote-storage.d.ts +7 -1
  10. package/dist/index.d.ts +4 -1
  11. package/dist/index.js +1665 -257
  12. package/dist/lib/codex-safety-check.d.ts +1 -1
  13. package/dist/lib/hosted-registry.d.ts +70 -0
  14. package/dist/lib/legacy-registry-artifact.d.ts +23 -0
  15. package/dist/lib/manifest.d.ts +7 -0
  16. package/dist/lib/native-safety.d.ts +1 -0
  17. package/dist/lib/native-target.d.ts +7 -0
  18. package/dist/lib/opencode-stop-plugin.d.ts +55 -0
  19. package/dist/lib/registry-artifact.d.ts +36 -0
  20. package/dist/lib/registry.d.ts +4 -0
  21. package/dist/lib/stop-review-context.d.ts +12 -0
  22. package/dist/lib/store.d.ts +4 -0
  23. package/dist/lib/sumi-stop-plugin.d.ts +129 -0
  24. package/dist/lib/sync.d.ts +10 -0
  25. package/dist/lib/transport.d.ts +1 -1
  26. package/dist/native-readiness.d.ts +1 -1
  27. package/dist/native-readiness.js +5 -1
  28. package/dist/openapi.d.ts +160 -16
  29. package/dist/opencode-stop-plugin.js +384 -0
  30. package/dist/registry-auth.d.ts +5 -0
  31. package/dist/registry-http.d.ts +4 -0
  32. package/dist/sdk/generated.d.ts +32 -12
  33. package/dist/sdk/index.d.ts +28 -5
  34. package/dist/sdk/index.js +49 -24
  35. package/dist/sdk/registry-client.d.ts +1 -1
  36. package/dist/serve.d.ts +4 -4
  37. package/dist/storage.js +33 -2
  38. package/dist/sumi-stop-plugin.js +380 -0
  39. package/hooks/hook-scanoutput/src/hook.ts +33 -3
  40. package/hooks/hook-stop-review/README.md +109 -0
  41. package/hooks/hook-stop-review/manifest.json +10 -0
  42. package/hooks/hook-stop-review/package.json +11 -0
  43. package/hooks/hook-stop-review/src/hook.ts +59 -0
  44. package/hooks/hook-stop-review/src/index.ts +3 -0
  45. package/hooks/hook-stop-review/src/jev.ts +121 -0
  46. package/hooks/hook-stop-review/src/native.ts +246 -0
  47. package/hooks/hook-stop-review/src/policy.ts +145 -0
  48. package/hooks/hook-stop-review/src/runtime.ts +309 -0
  49. package/hooks/hook-stop-review/src/types.ts +121 -0
  50. package/hooks/hook-trash-guard/src/hook.ts +96 -0
  51. package/hooks/hook-workspace-repos-guard/src/hook.ts +231 -3
  52. package/hooks/local-executors.ts +841 -0
  53. package/package.json +22 -4
  54. package/scripts/build-bundled-hooks.ts +40 -0
  55. package/scripts/validate-bundled-hooks.ts +78 -0
  56. package/scripts/validate-opencode-stop-plugin.ts +42 -0
  57. package/scripts/validate-package.ts +9 -0
  58. package/scripts/validate-sumi-stop-plugin.ts +47 -0
package/dist/index.js CHANGED
@@ -581,7 +581,7 @@ var init_redact = __esm(() => {
581
581
  ];
582
582
  });
583
583
 
584
- // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/util.js
584
+ // node_modules/zod/v3/helpers/util.js
585
585
  var util, objectUtil, ZodParsedType, getParsedType = (data) => {
586
586
  const t = typeof data;
587
587
  switch (t) {
@@ -712,7 +712,7 @@ var init_util = __esm(() => {
712
712
  ]);
713
713
  });
714
714
 
715
- // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/ZodError.js
715
+ // node_modules/zod/v3/ZodError.js
716
716
  var ZodIssueCode, quotelessJson = (obj) => {
717
717
  const json = JSON.stringify(obj, null, 2);
718
718
  return json.replace(/"([^"]+)":/g, "$1:");
@@ -833,7 +833,7 @@ var init_ZodError = __esm(() => {
833
833
  };
834
834
  });
835
835
 
836
- // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/locales/en.js
836
+ // node_modules/zod/v3/locales/en.js
837
837
  var errorMap = (issue, _ctx) => {
838
838
  let message;
839
839
  switch (issue.code) {
@@ -940,7 +940,7 @@ var init_en = __esm(() => {
940
940
  en_default = errorMap;
941
941
  });
942
942
 
943
- // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/errors.js
943
+ // node_modules/zod/v3/errors.js
944
944
  function setErrorMap(map) {
945
945
  overrideErrorMap = map;
946
946
  }
@@ -953,7 +953,7 @@ var init_errors = __esm(() => {
953
953
  overrideErrorMap = en_default;
954
954
  });
955
955
 
956
- // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
956
+ // node_modules/zod/v3/helpers/parseUtil.js
957
957
  function addIssueToContext(ctx, issueData) {
958
958
  const overrideMap = getErrorMap();
959
959
  const issue = makeIssue({
@@ -1058,10 +1058,10 @@ var init_parseUtil = __esm(() => {
1058
1058
  });
1059
1059
  });
1060
1060
 
1061
- // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/typeAliases.js
1061
+ // node_modules/zod/v3/helpers/typeAliases.js
1062
1062
  var init_typeAliases = () => {};
1063
1063
 
1064
- // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
1064
+ // node_modules/zod/v3/helpers/errorUtil.js
1065
1065
  var errorUtil;
1066
1066
  var init_errorUtil = __esm(() => {
1067
1067
  (function(errorUtil2) {
@@ -1070,7 +1070,7 @@ var init_errorUtil = __esm(() => {
1070
1070
  })(errorUtil || (errorUtil = {}));
1071
1071
  });
1072
1072
 
1073
- // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/types.js
1073
+ // node_modules/zod/v3/types.js
1074
1074
  class ParseInputLazyPath {
1075
1075
  constructor(parent, value, path, key) {
1076
1076
  this._cachedPath = [];
@@ -4421,7 +4421,7 @@ var init_types = __esm(() => {
4421
4421
  NEVER = INVALID;
4422
4422
  });
4423
4423
 
4424
- // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/external.js
4424
+ // node_modules/zod/v3/external.js
4425
4425
  var exports_external = {};
4426
4426
  __export(exports_external, {
4427
4427
  void: () => voidType,
@@ -4541,7 +4541,7 @@ var init_external = __esm(() => {
4541
4541
  init_ZodError();
4542
4542
  });
4543
4543
 
4544
- // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/index.js
4544
+ // node_modules/zod/index.js
4545
4545
  var init_zod = __esm(() => {
4546
4546
  init_external();
4547
4547
  init_external();
@@ -4566,6 +4566,56 @@ var init_config = __esm(() => {
4566
4566
  });
4567
4567
 
4568
4568
  // src/lib/semver.ts
4569
+ function parseVersion(value) {
4570
+ const coreAndPre = value.split("+")[0];
4571
+ const dash = coreAndPre.indexOf("-");
4572
+ const core = dash >= 0 ? coreAndPre.slice(0, dash) : coreAndPre;
4573
+ const pre = dash >= 0 ? coreAndPre.slice(dash + 1).split(".") : [];
4574
+ const [major, minor, patch] = core.split(".").map((part) => BigInt(part));
4575
+ return { core: [major, minor, patch], pre };
4576
+ }
4577
+ function compareVersions(a, b) {
4578
+ const pa = parseVersion(a);
4579
+ const pb = parseVersion(b);
4580
+ for (let i = 0;i < 3; i++) {
4581
+ if (pa.core[i] !== pb.core[i])
4582
+ return pa.core[i] < pb.core[i] ? -1 : 1;
4583
+ }
4584
+ const aPre = pa.pre.length > 0;
4585
+ const bPre = pb.pre.length > 0;
4586
+ if (!aPre && !bPre)
4587
+ return 0;
4588
+ if (aPre && !bPre)
4589
+ return -1;
4590
+ if (!aPre && bPre)
4591
+ return 1;
4592
+ const len = Math.max(pa.pre.length, pb.pre.length);
4593
+ for (let i = 0;i < len; i++) {
4594
+ const ai = pa.pre[i];
4595
+ const bi = pb.pre[i];
4596
+ if (ai === undefined)
4597
+ return -1;
4598
+ if (bi === undefined)
4599
+ return 1;
4600
+ if (ai === bi)
4601
+ continue;
4602
+ const aNum = /^\d+$/.test(ai);
4603
+ const bNum = /^\d+$/.test(bi);
4604
+ if (aNum && bNum) {
4605
+ const aN = BigInt(ai);
4606
+ const bN = BigInt(bi);
4607
+ if (aN === bN)
4608
+ continue;
4609
+ return aN < bN ? -1 : 1;
4610
+ }
4611
+ if (aNum)
4612
+ return -1;
4613
+ if (bNum)
4614
+ return 1;
4615
+ return ai < bi ? -1 : 1;
4616
+ }
4617
+ return 0;
4618
+ }
4569
4619
  var NUMERIC_ID = "(0|[1-9]\\d{0,15})", ALNUM_ID = "\\d*[A-Za-z-][0-9A-Za-z-]*", SEMVER_PATTERN;
4570
4620
  var init_semver = __esm(() => {
4571
4621
  SEMVER_PATTERN = new RegExp(`^${NUMERIC_ID}\\.${NUMERIC_ID}\\.${NUMERIC_ID}` + `(?:-(?:${NUMERIC_ID}|${ALNUM_ID})(?:\\.(?:${NUMERIC_ID}|${ALNUM_ID}))*)?` + `(?:\\+[0-9A-Za-z.-]+)?$`);
@@ -4587,6 +4637,7 @@ __export(exports_manifest, {
4587
4637
  customHookDir: () => customHookDir,
4588
4638
  assertContained: () => assertContained,
4589
4639
  ScriptContainmentError: () => ScriptContainmentError,
4640
+ HookIdentityError: () => HookIdentityError,
4590
4641
  HOOK_NAME_RE: () => HOOK_NAME_RE
4591
4642
  });
4592
4643
  import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync2, readdirSync as readdirSync2, realpathSync, writeFileSync } from "fs";
@@ -4662,7 +4713,10 @@ function resolveScript(manifest, manifestDir) {
4662
4713
  return { path: rel, content: readFileSync2(resolved, "utf-8") };
4663
4714
  }
4664
4715
  function customHookDir(name) {
4665
- return join5(getCustomHooksDir(), shortManifestName(name));
4716
+ const canonical = shortManifestName(name);
4717
+ if (!HOOK_NAME_RE.test(canonical))
4718
+ throw new HookIdentityError;
4719
+ return join5(getCustomHooksDir(), canonical);
4666
4720
  }
4667
4721
  function readCustomManifest(name) {
4668
4722
  const dir = customHookDir(name);
@@ -4671,11 +4725,13 @@ function readCustomManifest(name) {
4671
4725
  return;
4672
4726
  try {
4673
4727
  const manifest = parseManifest(readFileSync2(manifestPath, "utf-8"));
4728
+ if (shortManifestName(manifest.name) !== shortManifestName(name))
4729
+ throw new HookIdentityError;
4674
4730
  const script = resolveScript(manifest, dir);
4675
4731
  const scriptIsInline = isInlineScript(manifest);
4676
4732
  return { manifest, scriptPath: join5(dir, script.path), scriptContent: script.content, scriptIsInline };
4677
4733
  } catch (err) {
4678
- if (err instanceof ScriptContainmentError)
4734
+ if (err instanceof ScriptContainmentError || err instanceof HookIdentityError)
4679
4735
  throw err;
4680
4736
  return;
4681
4737
  }
@@ -4686,9 +4742,16 @@ function listCustomHooks() {
4686
4742
  return [];
4687
4743
  const results = [];
4688
4744
  for (const entry of readdirSafe(dir)) {
4689
- const parsed = readCustomManifest(entry);
4690
- if (parsed)
4691
- results.push(parsed);
4745
+ if (!HOOK_NAME_RE.test(entry))
4746
+ continue;
4747
+ try {
4748
+ const parsed = readCustomManifest(entry);
4749
+ if (parsed)
4750
+ results.push(parsed);
4751
+ } catch (error) {
4752
+ if (!(error instanceof HookIdentityError))
4753
+ throw error;
4754
+ }
4692
4755
  }
4693
4756
  return results.sort((a, b) => a.manifest.name.localeCompare(b.manifest.name));
4694
4757
  }
@@ -4716,7 +4779,7 @@ function readdirSafe(dir) {
4716
4779
  return [];
4717
4780
  }
4718
4781
  }
4719
- var HOOK_NAME_RE, manifestSchema, ScriptContainmentError;
4782
+ var HOOK_NAME_RE, manifestSchema, ScriptContainmentError, HookIdentityError;
4720
4783
  var init_manifest = __esm(() => {
4721
4784
  init_zod();
4722
4785
  init_config();
@@ -4730,6 +4793,7 @@ var init_manifest = __esm(() => {
4730
4793
  script: exports_external.string().min(1, "script must name a relative path or inline content"),
4731
4794
  script_kind: exports_external.enum(["inline", "file"]).optional(),
4732
4795
  args: exports_external.array(exports_external.string()).optional(),
4796
+ nativeTargetDispatch: exports_external.boolean().optional(),
4733
4797
  timeout_ms: exports_external.number().int().positive().optional(),
4734
4798
  env: exports_external.record(exports_external.string(), exports_external.string()).optional()
4735
4799
  });
@@ -4739,6 +4803,51 @@ var init_manifest = __esm(() => {
4739
4803
  this.name = "ScriptContainmentError";
4740
4804
  }
4741
4805
  };
4806
+ HookIdentityError = class HookIdentityError extends Error {
4807
+ constructor() {
4808
+ super("Hook name must be canonical and match its manifest identity");
4809
+ }
4810
+ };
4811
+ });
4812
+
4813
+ // src/lib/registry-artifact.ts
4814
+ import { createHash as createHash3 } from "crypto";
4815
+ function canonicalJson(value) {
4816
+ if (Array.isArray(value))
4817
+ return `[${value.map(canonicalJson).join(",")}]`;
4818
+ if (value && typeof value === "object")
4819
+ return `{${Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
4820
+ return JSON.stringify(value);
4821
+ }
4822
+ function registryDigest(value) {
4823
+ return createHash3("sha256").update(canonicalJson(value)).digest("hex");
4824
+ }
4825
+ function scriptDigest(script) {
4826
+ return createHash3("sha256").update(script).digest("hex");
4827
+ }
4828
+ function validateRegistryArtifact(value) {
4829
+ const a = value;
4830
+ const m = a?.manifest;
4831
+ const keys = new Set(["name", "version", "description", "events", "script", "script_kind", "args", "timeout_ms", "nativeTargetDispatch"]);
4832
+ if (!a || typeof a !== "object" || !m || typeof m !== "object" || Object.keys(a).some((k) => !["manifest", "script"].includes(k)) || Object.keys(m).some((k) => !keys.has(k)) || typeof m.name !== "string" || !REGISTRY_NAME.test(m.name) || m.name.startsWith("hook-") || typeof m.version !== "string" || !SEMVER_PATTERN.test(m.version) || typeof a.script !== "string" || !a.script || Buffer.byteLength(canonicalJson(a)) > REGISTRY_MAX_BYTES || m.script_kind !== "file" || m.script !== "hook.js" || !Array.isArray(m.events) || !m.events.length || m.events.length > 16 || m.events.some((e) => typeof e !== "string" || !/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(e)) || m.description !== undefined && (typeof m.description !== "string" || m.description.length > 4000) || m.args !== undefined && (!Array.isArray(m.args) || m.args.length > 32 || m.args.some((s) => typeof s !== "string" || s.length > 4096)) || m.nativeTargetDispatch !== undefined && typeof m.nativeTargetDispatch !== "boolean" || m.timeout_ms !== undefined && (!Number.isInteger(m.timeout_ms) || m.timeout_ms < 1 || m.timeout_ms > 300000)) {
4833
+ throw new RegistryError(400, "REGISTRY_ARTIFACT_INVALID");
4834
+ }
4835
+ return JSON.parse(canonicalJson(a));
4836
+ }
4837
+ var RegistryError, REGISTRY_NAME, REGISTRY_MAX_BYTES;
4838
+ var init_registry_artifact = __esm(() => {
4839
+ init_semver();
4840
+ RegistryError = class RegistryError extends Error {
4841
+ status;
4842
+ code;
4843
+ constructor(status, code) {
4844
+ super(code);
4845
+ this.status = status;
4846
+ this.code = code;
4847
+ }
4848
+ };
4849
+ REGISTRY_NAME = /^[a-z0-9][a-z0-9_-]{0,127}$/;
4850
+ REGISTRY_MAX_BYTES = 2 * 1024 * 1024;
4742
4851
  });
4743
4852
 
4744
4853
  // src/lib/store.ts
@@ -4756,18 +4865,20 @@ __export(exports_store, {
4756
4865
  removeHookFromStore: () => removeHookFromStore,
4757
4866
  readLock: () => readLock,
4758
4867
  pinInstalledHook: () => pinInstalledHook,
4868
+ markRegistryManaged: () => markRegistryManaged,
4759
4869
  listHookRecords: () => listHookRecords,
4760
4870
  getPinnedHook: () => getPinnedHook,
4761
4871
  getHookRecord: () => getHookRecord,
4762
4872
  checkScriptHash: () => checkScriptHash,
4763
4873
  LockFileError: () => LockFileError
4764
4874
  });
4765
- import { createHash as createHash3 } from "crypto";
4766
- import { existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync2, renameSync } from "fs";
4875
+ import { createHash as createHash4 } from "crypto";
4876
+ import { existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync2, renameSync, lstatSync as lstatSync3 } from "fs";
4877
+ import { join as join9 } from "path";
4767
4878
  import { readFile } from "fs/promises";
4768
4879
  import { randomBytes } from "crypto";
4769
4880
  function sha256Of(input) {
4770
- return createHash3("sha256").update(input).digest("hex");
4881
+ return createHash4("sha256").update(input).digest("hex");
4771
4882
  }
4772
4883
  async function sha256File(path) {
4773
4884
  const buf = await readFile(path);
@@ -4866,6 +4977,33 @@ function setPinnedHook(name, entry) {
4866
4977
  function getPinnedHook(name) {
4867
4978
  return readLock().hooks[name];
4868
4979
  }
4980
+ function registryManagedMarker(name) {
4981
+ return join9(getHooksDataDir(), "registry-managed", sha256Of(name) + ".json");
4982
+ }
4983
+ function markRegistryManaged(name) {
4984
+ const path = registryManagedMarker(name);
4985
+ const content = JSON.stringify({ schema: 1, name }) + `
4986
+ `;
4987
+ mkdirSync3(join9(getHooksDataDir(), "registry-managed"), { recursive: true, mode: 448 });
4988
+ try {
4989
+ writeFileSync2(path, content, { flag: "wx", mode: 384 });
4990
+ } catch (error) {
4991
+ if (error.code !== "EEXIST")
4992
+ throw error;
4993
+ }
4994
+ if (!lstatSync3(path).isFile() || readFileSync5(path, "utf8") !== content)
4995
+ throw new Error("REGISTRY_MANAGED_MARKER_INVALID");
4996
+ }
4997
+ function isRegistryManaged(name) {
4998
+ try {
4999
+ lstatSync3(registryManagedMarker(name));
5000
+ return true;
5001
+ } catch (error) {
5002
+ if (error.code === "ENOENT")
5003
+ return false;
5004
+ throw error;
5005
+ }
5006
+ }
4869
5007
  function removePinnedHook(name) {
4870
5008
  const lock = readLock();
4871
5009
  if (!(name in lock.hooks))
@@ -4896,10 +5034,33 @@ function removeHookFromStore(name) {
4896
5034
  return { removedPin, removedRecord };
4897
5035
  }
4898
5036
  function checkScriptHash(name, actual) {
5037
+ const canonical = shortManifestName(name);
5038
+ if (!HOOK_NAME_RE.test(canonical))
5039
+ return { ok: false, pinned: false, expected: "invalid-hook-name", actual, name };
5040
+ let customIdentity;
5041
+ try {
5042
+ const custom2 = readCustomManifest(name);
5043
+ customIdentity = custom2 && shortManifestName(custom2.manifest.name);
5044
+ } catch (error) {
5045
+ if (!(error instanceof HookIdentityError))
5046
+ throw error;
5047
+ return { ok: false, pinned: false, expected: "hook-manifest-identity-mismatch", actual, name };
5048
+ }
5049
+ if (isRegistryManaged(customIdentity ?? canonical))
5050
+ name = customIdentity ?? canonical;
4899
5051
  const db = storeDb();
4900
5052
  const record = db ? getHookRecord(db, name) : null;
4901
5053
  const pin2 = getPinnedHook(name);
4902
5054
  const expected = record?.sha256 ?? pin2?.sha256 ?? null;
5055
+ if (isRegistryManaged(name) && (!pin2 || !pin2.manifest_sha256)) {
5056
+ return { ok: false, pinned: false, expected: "registry-manifest-pin-required", actual, name };
5057
+ }
5058
+ if (pin2?.manifest_sha256) {
5059
+ const custom2 = readCustomManifest(name);
5060
+ if (!custom2 || registryDigest(custom2.manifest) !== pin2.manifest_sha256) {
5061
+ return { ok: false, pinned: true, expected: pin2.manifest_sha256, actual: custom2 ? registryDigest(custom2.manifest) : "missing-manifest", name };
5062
+ }
5063
+ }
4903
5064
  if (expected !== null && expected !== actual) {
4904
5065
  return { ok: false, pinned: true, expected, actual, name };
4905
5066
  }
@@ -4936,6 +5097,9 @@ async function verifyScriptHash(name, scriptPath) {
4936
5097
  }
4937
5098
  function retrustHook(name, scriptPath, version, source) {
4938
5099
  const actual = sha256Of(readFileSync5(scriptPath));
5100
+ const custom2 = isRegistryManaged(name) ? readCustomManifest(name) : undefined;
5101
+ if (isRegistryManaged(name) && !custom2)
5102
+ throw new Error("REGISTRY_MANIFEST_REQUIRED");
4939
5103
  const db = storeDb();
4940
5104
  if (db) {
4941
5105
  upsertHookRecord(db, {
@@ -4946,13 +5110,15 @@ function retrustHook(name, scriptPath, version, source) {
4946
5110
  last_verified_at: new Date().toISOString()
4947
5111
  });
4948
5112
  }
4949
- setPinnedHook(name, { version, sha256: actual, source });
5113
+ setPinnedHook(name, { version, sha256: actual, source, ...custom2 ? { manifest_sha256: registryDigest(custom2.manifest) } : {} });
4950
5114
  return { ok: true, pinned: true, expected: actual, actual, name };
4951
5115
  }
4952
5116
  var LockFileError;
4953
5117
  var init_store = __esm(() => {
4954
5118
  init_db();
4955
5119
  init_config();
5120
+ init_manifest();
5121
+ init_registry_artifact();
4956
5122
  LockFileError = class LockFileError extends Error {
4957
5123
  constructor(message) {
4958
5124
  super(message);
@@ -4975,10 +5141,10 @@ __export(exports_profiles, {
4975
5141
  createProfile: () => createProfile
4976
5142
  });
4977
5143
  import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync9, writeFileSync as writeFileSync9, readdirSync as readdirSync9, rmSync, cpSync as cpSync2 } from "fs";
4978
- import { join as join13 } from "path";
5144
+ import { join as join14 } from "path";
4979
5145
  function getProfilesDir() {
4980
- const newDir = join13(getEffectiveDataRoot(), "profiles");
4981
- const oldDir = join13(getHomeDir(), ".hooks", "profiles");
5146
+ const newDir = join14(getEffectiveDataRoot(), "profiles");
5147
+ const oldDir = join14(getHomeDir(), ".hooks", "profiles");
4982
5148
  if (!existsSync13(newDir) && existsSync13(oldDir)) {
4983
5149
  mkdirSync10(newDir, { recursive: true });
4984
5150
  cpSync2(oldDir, newDir, { recursive: true });
@@ -4992,7 +5158,7 @@ function ensureProfilesDir() {
4992
5158
  }
4993
5159
  }
4994
5160
  function profilePath(id) {
4995
- return join13(getProfilesDir(), `${id}.json`);
5161
+ return join14(getProfilesDir(), `${id}.json`);
4996
5162
  }
4997
5163
  function shortUuid() {
4998
5164
  return crypto.randomUUID().slice(0, 8);
@@ -5034,7 +5200,7 @@ function listProfiles() {
5034
5200
  const profiles = [];
5035
5201
  for (const file2 of files) {
5036
5202
  try {
5037
- const content = readFileSync9(join13(dir, file2), "utf-8");
5203
+ const content = readFileSync9(join14(dir, file2), "utf-8");
5038
5204
  profiles.push(JSON.parse(content));
5039
5205
  } catch {}
5040
5206
  }
@@ -5101,7 +5267,7 @@ var init_profiles = __esm(() => {
5101
5267
  init_app_home();
5102
5268
  });
5103
5269
 
5104
- // ../../node_modules/.bun/@hasna+contracts@1.2.2+944b86d8024e79fa/node_modules/@hasna/contracts/dist/client/transport.js
5270
+ // node_modules/@hasna/contracts/dist/client/transport.js
5105
5271
  import { isIP } from "net";
5106
5272
  import { spawnSync as spawnSync2 } from "child_process";
5107
5273
  import { closeSync as closeSync23, fstatSync as fstatSync23, openSync as openSync23, readFileSync as readFileSync22 } from "fs";
@@ -5112,7 +5278,7 @@ import { createRequire as createRequire2 } from "module";
5112
5278
  import { fileURLToPath as fileURLToPath22 } from "url";
5113
5279
  import { closeSync as closeSync6, fstatSync as fstatSync5, lstatSync as lstatSync10, openSync as openSync6, readFileSync as readFileSync10, realpathSync as realpathSync12, statSync } from "fs";
5114
5280
  import { O_NOFOLLOW, O_NONBLOCK, O_RDONLY } from "constants";
5115
- import { basename as basename8, dirname as dirname16, join as join14, relative as relative2, sep as sep4 } from "path";
5281
+ import { basename as basename8, dirname as dirname16, join as join16, relative as relative2, sep as sep4 } from "path";
5116
5282
  import { fileURLToPath as fileURLToPath4, pathToFileURL } from "url";
5117
5283
  function envToken2(name) {
5118
5284
  return name.toUpperCase().replace(/-/g, "_");
@@ -5187,7 +5353,7 @@ function o(e2, r2, t2) {
5187
5353
  }
5188
5354
  function entryPoint(directory2) {
5189
5355
  const root = realpathSync12(directory2);
5190
- const fd = openSync6(join14(root, "package.json"), O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
5356
+ const fd = openSync6(join16(root, "package.json"), O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
5191
5357
  let pkg;
5192
5358
  try {
5193
5359
  const stat2 = fstatSync5(fd);
@@ -5207,7 +5373,7 @@ function entryPoint(directory2) {
5207
5373
  if (/[\\%?#\0]/.test(target) || parts.some((part) => !part || part === "." || part === ".." || part === "node_modules")) {
5208
5374
  throw new Error("Invalid Secrets import export");
5209
5375
  }
5210
- const file2 = realpathSync12(join14(root, ...parts));
5376
+ const file2 = realpathSync12(join16(root, ...parts));
5211
5377
  const within = relative2(root, file2);
5212
5378
  if (!within || within === ".." || within.startsWith(`..${sep4}`) || !statSync(file2).isFile()) {
5213
5379
  throw new Error("Secrets import export escapes its package or is not a file");
@@ -5218,7 +5384,7 @@ function resolveInstalledSecrets(parentUrl) {
5218
5384
  let directory2 = dirname16(fileURLToPath4(parentUrl));
5219
5385
  for (;; ) {
5220
5386
  if (basename8(directory2) !== "node_modules") {
5221
- const candidate = join14(directory2, "node_modules", PACKAGE);
5387
+ const candidate = join16(directory2, "node_modules", PACKAGE);
5222
5388
  let absent = false;
5223
5389
  try {
5224
5390
  lstatSync10(candidate);
@@ -6201,9 +6367,79 @@ var init_db_writer = __esm(() => {
6201
6367
  ]);
6202
6368
  });
6203
6369
 
6370
+ // src/lib/stop-review-context.ts
6371
+ function isStopReviewContextCarrier(name) {
6372
+ return name.startsWith("HOOKS_CLIENT_");
6373
+ }
6374
+ function isCanonicalAuthority(value, app) {
6375
+ if (/[\u0000-\u001f\u007f]/.test(value))
6376
+ return false;
6377
+ const trimmed = value.trim();
6378
+ return ["", ":443"].some((port) => ["", "/", "/v1", "/v1/"].some((suffix) => trimmed === `https://api.hasna.com${port}/${app}${suffix}`));
6379
+ }
6380
+ function projectStopReviewClientContext(source, extra = {}) {
6381
+ const out = {};
6382
+ const values = (names) => names.flatMap((name) => [source[name], extra[name]]).filter((value) => value !== undefined);
6383
+ let refused2 = values([REFUSED2]).some((value) => value.trim() === "1");
6384
+ for (const [name, alias] of HOOK_CLIENT_CONFIG_PROJECTIONS) {
6385
+ const value = source[name] ?? extra[name] ?? extra[alias] ?? source[alias];
6386
+ if (value !== undefined)
6387
+ out[alias] = value;
6388
+ }
6389
+ for (const names of LOCAL_FLAGS) {
6390
+ if (values(names).some((value) => value.trim() === "1")) {
6391
+ out[names[1]] = "1";
6392
+ refused2 = true;
6393
+ }
6394
+ }
6395
+ if (values(["HASNA_HOOKS_LOCAL", "HOOKS_LOCAL"]).some((value) => value.trim() !== ""))
6396
+ refused2 = true;
6397
+ if (values(["HASNA_SECRETS_LOCAL_VAULT", "HASNA_SECRETS_DB_PATH", "OPEN_SECRETS_DB"]).some((value) => value !== ""))
6398
+ refused2 = true;
6399
+ for (const { app, name, legacy, alias } of AUTHORITY_PROJECTIONS) {
6400
+ const declared = values([name, legacy, alias]);
6401
+ if (declared.some((value) => !isCanonicalAuthority(value, app)))
6402
+ refused2 = true;
6403
+ else if (declared.length)
6404
+ out[alias] = `https://api.hasna.com/${app}`;
6405
+ const prefix3 = app.toUpperCase();
6406
+ if (values([`HASNA_${prefix3}_API_KEY_OVERRIDE`]).length)
6407
+ refused2 = true;
6408
+ const deliberate = out[`HOOKS_CLIENT_${prefix3}_API_KEY_REF`]?.trim() || out.HOOKS_CLIENT_PROFILE?.trim();
6409
+ if (!deliberate && values([`HASNA_${prefix3}_API_KEY`, `${prefix3}_API_KEY`]).length)
6410
+ refused2 = true;
6411
+ }
6412
+ if (refused2)
6413
+ out[REFUSED2] = "1";
6414
+ return out;
6415
+ }
6416
+ var APPS, REFUSED2 = "HOOKS_CLIENT_CONTEXT_REFUSED", LOCAL_FLAGS, HOOK_CLIENT_CONFIG_PROJECTIONS, AUTHORITY_PROJECTIONS;
6417
+ var init_stop_review_context = __esm(() => {
6418
+ APPS = ["hooks", "instructions", "secrets"];
6419
+ LOCAL_FLAGS = [
6420
+ ["HASNA_INSTRUCTIONS_LOCAL", "HOOKS_CLIENT_INSTRUCTIONS_LOCAL", "INSTRUCTIONS_LOCAL"],
6421
+ ["HASNA_CONFIGS_LOCAL", "HOOKS_CLIENT_CONFIGS_LOCAL", "CONFIGS_LOCAL"],
6422
+ ["HASNA_SECRETS_LOCAL", "HOOKS_CLIENT_SECRETS_LOCAL", "SECRETS_LOCAL"]
6423
+ ];
6424
+ HOOK_CLIENT_CONFIG_PROJECTIONS = [
6425
+ ["HASNA_HOME", "HOOKS_CLIENT_HOME"],
6426
+ ["HASNA_CONFIG_HOME", "HOOKS_CLIENT_CONFIG_HOME"],
6427
+ ["HASNA_PROFILE", "HOOKS_CLIENT_PROFILE"],
6428
+ ["HASNA_STATION", "HOOKS_CLIENT_STATION"],
6429
+ ...APPS.map((app) => [`HASNA_${app.toUpperCase()}_API_KEY_REF`, `HOOKS_CLIENT_${app.toUpperCase()}_API_KEY_REF`]),
6430
+ ...LOCAL_FLAGS.map(([name, alias]) => [name, alias])
6431
+ ];
6432
+ AUTHORITY_PROJECTIONS = APPS.map((app) => ({
6433
+ app,
6434
+ name: `HASNA_${app.toUpperCase()}_API_URL`,
6435
+ legacy: `${app.toUpperCase()}_API_URL`,
6436
+ alias: `HOOKS_CLIENT_${app.toUpperCase()}_AUTHORITY`
6437
+ }));
6438
+ });
6439
+
6204
6440
  // src/lib/hook-env.ts
6205
- import { dirname as dirname28, isAbsolute as isAbsolute28 } from "path";
6206
- import { existsSync as existsSync16, realpathSync as realpathSync19, statSync as statSync2 } from "fs";
6441
+ import { dirname as dirname29, isAbsolute as isAbsolute28 } from "path";
6442
+ import { existsSync as existsSync17, realpathSync as realpathSync19, statSync as statSync2 } from "fs";
6207
6443
  import { tmpdir as tmpdir2 } from "os";
6208
6444
  function isDeniedEnvName(name) {
6209
6445
  const upper = name.toUpperCase();
@@ -6251,9 +6487,9 @@ function isUnsafePathEntry(entry, home) {
6251
6487
  }
6252
6488
  function sanitizeHookPath(pathValue, home) {
6253
6489
  const baseline = PATH_BASELINE.slice();
6254
- if (process.platform === "darwin" && existsSync16("/opt/homebrew/bin"))
6490
+ if (process.platform === "darwin" && existsSync17("/opt/homebrew/bin"))
6255
6491
  baseline.push("/opt/homebrew/bin");
6256
- const bunDir = dirname28(process.execPath);
6492
+ const bunDir = dirname29(process.execPath);
6257
6493
  const seen = new Set;
6258
6494
  const out = [];
6259
6495
  for (const dir of baseline) {
@@ -6303,6 +6539,8 @@ function buildHookEnv(source, extra) {
6303
6539
  for (const [name, value] of Object.entries(merged)) {
6304
6540
  if (out[name] !== undefined)
6305
6541
  continue;
6542
+ if (isStopReviewContextCarrier(name))
6543
+ continue;
6306
6544
  if (isDeniedEnvName(name))
6307
6545
  continue;
6308
6546
  if (isInterpreterInjectionEnvName(name))
@@ -6312,10 +6550,14 @@ function buildHookEnv(source, extra) {
6312
6550
  if (value !== undefined && value !== null)
6313
6551
  out[name] = value;
6314
6552
  }
6553
+ Object.assign(out, projectStopReviewClientContext(source, extra));
6554
+ out.HOOKS_DATA_DIR = getEffectiveDataRoot({ ...source, ...extra ?? {}, HOME: out.HOME });
6315
6555
  return out;
6316
6556
  }
6317
6557
  var ALLOWLIST, INTERPRETER_INJECTION, INTERPRETER_INJECTION_PREFIXES, DENY_SUFFIXES, DENY_PREFIXES, DENY_CONTAINS, PATH_BASELINE, CONFIG_PROJECTIONS;
6318
6558
  var init_hook_env = __esm(() => {
6559
+ init_app_home();
6560
+ init_stop_review_context();
6319
6561
  ALLOWLIST = new Set(["PATH", "HOME", "LANG", "TZ", "SHELL", "TERM", "USER", "PWD"]);
6320
6562
  INTERPRETER_INJECTION = new Set([
6321
6563
  "BASH_ENV",
@@ -6376,9 +6618,9 @@ __export(exports_run, {
6376
6618
  executeVerifiedScript: () => executeVerifiedScript,
6377
6619
  HookTimeoutError: () => HookTimeoutError
6378
6620
  });
6379
- import { randomBytes as randomBytes2 } from "crypto";
6380
- import { rmSync as rmSync4, writeFileSync as writeFileSync13 } from "fs";
6381
- import { basename as basename14, dirname as dirname29, isAbsolute as isAbsolute29, join as join35 } from "path";
6621
+ import { randomBytes as randomBytes3 } from "crypto";
6622
+ import { rmSync as rmSync4, writeFileSync as writeFileSync14 } from "fs";
6623
+ import { basename as basename14, dirname as dirname30, isAbsolute as isAbsolute29, join as join37 } from "path";
6382
6624
  function extensionOf(scriptPath) {
6383
6625
  const base = basename14(scriptPath);
6384
6626
  const dot = base.lastIndexOf(".");
@@ -6447,9 +6689,9 @@ async function readPipeWithDeadline(stream, deadlineMs) {
6447
6689
  return chunks.join("");
6448
6690
  }
6449
6691
  async function executeVerifiedScript(options) {
6450
- const scriptDir = dirname29(options.scriptPath);
6692
+ const scriptDir = dirname30(options.scriptPath);
6451
6693
  const interpreter = interpreterFor(options.name, options.scriptPath, options.content);
6452
- const tempPath = join35(scriptDir, `.hooks-verified-${randomBytes2(12).toString("hex")}.${interpreter.tempExt}`);
6694
+ const tempPath = join37(scriptDir, `.hooks-verified-${randomBytes3(12).toString("hex")}.${interpreter.tempExt}`);
6453
6695
  let proc = null;
6454
6696
  let timedOut = false;
6455
6697
  const timeoutTimer = options.timeout ? setTimeout(() => {
@@ -6457,7 +6699,7 @@ async function executeVerifiedScript(options) {
6457
6699
  killGroup(proc, { leaderAlive: proc !== null && proc.exitCode === null });
6458
6700
  }, options.timeout) : null;
6459
6701
  try {
6460
- writeFileSync13(tempPath, options.content, { flag: "wx", mode: 384 });
6702
+ writeFileSync14(tempPath, options.content, { flag: "wx", mode: 384 });
6461
6703
  proc = Bun.spawn([...interpreter.command, isAbsolute29(tempPath) ? tempPath : `./${tempPath}`, ...options.args ?? []], {
6462
6704
  stdin: new Response(options.stdin),
6463
6705
  stdout: "pipe",
@@ -6625,8 +6867,39 @@ function wantsSslFor(connectionString) {
6625
6867
 
6626
6868
  class PgAdapterAsync {
6627
6869
  pool;
6628
- constructor(connectionString) {
6629
- this.pool = new pg.Pool({ connectionString, ssl: sslConfigFor(connectionString) });
6870
+ constructor(connectionString, options = {}) {
6871
+ const timeout = options.timeoutMs;
6872
+ this.pool = new pg.Pool({ connectionString, ssl: sslConfigFor(connectionString), ...timeout ? { connectionTimeoutMillis: timeout, query_timeout: timeout, statement_timeout: timeout } : {} });
6873
+ }
6874
+ async readOnlyAll(sql, ...params) {
6875
+ const client = await this.pool.connect();
6876
+ try {
6877
+ await client.query("BEGIN READ ONLY");
6878
+ return (await client.query(translatePlaceholders(sql), normalizeParams(params))).rows;
6879
+ } finally {
6880
+ try {
6881
+ await client.query("ROLLBACK");
6882
+ } finally {
6883
+ client.release();
6884
+ }
6885
+ }
6886
+ }
6887
+ async transaction(operation) {
6888
+ const client = await this.pool.connect();
6889
+ try {
6890
+ await client.query("BEGIN");
6891
+ const result = await operation({
6892
+ run: async (sql, ...params) => ({ changes: (await client.query(translatePlaceholders(sql), normalizeParams(params))).rowCount ?? 0 }),
6893
+ all: async (sql, ...params) => (await client.query(translatePlaceholders(sql), normalizeParams(params))).rows
6894
+ });
6895
+ await client.query("COMMIT");
6896
+ return result;
6897
+ } catch (error) {
6898
+ await client.query("ROLLBACK");
6899
+ throw error;
6900
+ } finally {
6901
+ client.release();
6902
+ }
6630
6903
  }
6631
6904
  async run(sql, ...params) {
6632
6905
  const result = await this.pool.query(translatePlaceholders(sql), normalizeParams(params));
@@ -7437,6 +7710,20 @@ var HOOKS = [
7437
7710
  matcher: "",
7438
7711
  tags: ["codewith", "session", "context", "conversations", "heartbeat"]
7439
7712
  },
7713
+ {
7714
+ name: "stop-review",
7715
+ bundledEntry: "bin/hooks/stop-review.js",
7716
+ displayName: "Stop Review",
7717
+ description: "Reviews turn completion against the latest user request and active goal",
7718
+ version: "0.1.0",
7719
+ category: "Agent Teams",
7720
+ event: "Stop",
7721
+ events: ["Stop"],
7722
+ nativeTargetDispatch: true,
7723
+ timeoutSeconds: 20,
7724
+ matcher: "",
7725
+ tags: ["stop", "goals", "continuity", "review"]
7726
+ },
7440
7727
  {
7441
7728
  name: "stop-sync",
7442
7729
  displayName: "Stop Sync",
@@ -7573,7 +7860,7 @@ function getHook(name) {
7573
7860
  }
7574
7861
  // src/lib/installer.ts
7575
7862
  import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync8, readdirSync as readdirSync4, realpathSync as realpathSync9, rmdirSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync7 } from "fs";
7576
- import { join as join12, dirname as dirname9, basename as basename5, resolve as resolve21 } from "path";
7863
+ import { join as join13, dirname as dirname9, basename as basename5, resolve as resolve21 } from "path";
7577
7864
  import { homedir as homedir7 } from "os";
7578
7865
  import { fileURLToPath as fileURLToPath3 } from "url";
7579
7866
 
@@ -7634,7 +7921,11 @@ var safeFailureCodes = new Set([
7634
7921
  "instructions_changed",
7635
7922
  "native_config_changed",
7636
7923
  "guard_refused",
7637
- "owner_refused"
7924
+ "owner_refused",
7925
+ "native_executable_changed",
7926
+ "runtime_changed",
7927
+ "installed_cli_changed",
7928
+ "plan_changed"
7638
7929
  ]);
7639
7930
 
7640
7931
  // src/lib/resolve.ts
@@ -7667,6 +7958,13 @@ function resolveScriptPath(name) {
7667
7958
  const custom2 = readCustomManifest(name);
7668
7959
  if (custom2)
7669
7960
  return custom2.scriptPath;
7961
+ const meta = getHook(shortManifestName(name));
7962
+ if (meta?.bundledEntry) {
7963
+ if (!/^bin\/hooks\/[a-z0-9-]+\.js$/.test(meta.bundledEntry))
7964
+ return;
7965
+ const bundle = join6(resolveBundledHooksDir(), "..", meta.bundledEntry);
7966
+ return existsSync5(bundle) ? bundle : undefined;
7967
+ }
7670
7968
  const dir = resolveHookDir(name);
7671
7969
  if (!dir)
7672
7970
  return;
@@ -7686,7 +7984,9 @@ function resolveHookMeta(name) {
7686
7984
  event: manifest.events[0] ?? "PostToolUse",
7687
7985
  events: manifest.events,
7688
7986
  matcher: "",
7689
- tags: ["custom"]
7987
+ tags: ["custom"],
7988
+ nativeTargetDispatch: manifest.nativeTargetDispatch,
7989
+ timeoutSeconds: manifest.timeout_ms === undefined ? undefined : Math.ceil(manifest.timeout_ms / 1000)
7690
7990
  };
7691
7991
  }
7692
7992
  return getHook(shortManifestName(name));
@@ -8019,7 +8319,7 @@ function retainedMementosRegistration(commands) {
8019
8319
  }
8020
8320
 
8021
8321
  // src/lib/registration.ts
8022
- var REGISTRATION_COMMAND_RE = /^(?:hooks run ([\w-]+)(?:\s+--profile\s+[\w-]+)?|hook-([\w-]+))$/;
8322
+ var REGISTRATION_COMMAND_RE = /^(?:hooks run ([\w-]+)(?:\s+--profile\s+[\w-]+)?(?:\s+--target\s+(?:claude|codex|gemini|codewith|sumi|opencode))?|hook-([\w-]+))$/;
8023
8323
  function registrationName(command) {
8024
8324
  if (typeof command !== "string")
8025
8325
  return;
@@ -8047,13 +8347,13 @@ function matchersOverlap(a, b) {
8047
8347
  init_store();
8048
8348
 
8049
8349
  // src/lib/codex-settings.ts
8050
- import { closeSync as closeSync3, existsSync as existsSync9, lstatSync as lstatSync3, mkdirSync as mkdirSync4, openSync as openSync3, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
8350
+ import { closeSync as closeSync3, existsSync as existsSync9, lstatSync as lstatSync4, mkdirSync as mkdirSync4, openSync as openSync3, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
8051
8351
  import { dirname as dirname5 } from "path";
8052
- import { createHash as createHash4, randomUUID } from "crypto";
8352
+ import { createHash as createHash5, randomUUID } from "crypto";
8053
8353
  var snapshots = new WeakMap;
8054
8354
  function current(path) {
8055
8355
  try {
8056
- const stat = lstatSync3(path);
8356
+ const stat = lstatSync4(path);
8057
8357
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1048576)
8058
8358
  throw new Error("invalid_file");
8059
8359
  return readFileSync6(path, "utf8");
@@ -8093,7 +8393,7 @@ function capturedCodexSettings(settings) {
8093
8393
  function assertSettingsPreimage(raw, expected) {
8094
8394
  if (expected === undefined)
8095
8395
  return;
8096
- if (!/^(?:absent|[a-f0-9]{64})$/.test(expected) || (raw === null ? "absent" : createHash4("sha256").update(raw).digest("hex")) !== expected) {
8396
+ if (!/^(?:absent|[a-f0-9]{64})$/.test(expected) || (raw === null ? "absent" : createHash5("sha256").update(raw).digest("hex")) !== expected) {
8097
8397
  throw new Error("Hook settings changed since planning; no settings were written.");
8098
8398
  }
8099
8399
  }
@@ -8138,15 +8438,15 @@ function writeHookSettingsPreimage(path, settings, before, beforeWrite) {
8138
8438
  import { createHash as createHash9 } from "crypto";
8139
8439
  import { existsSync as existsSync11, lstatSync as lstatSync8 } from "fs";
8140
8440
  import { homedir as homedir6 } from "os";
8141
- import { join as join11, resolve as resolve9 } from "path";
8441
+ import { join as join12, resolve as resolve9 } from "path";
8142
8442
 
8143
- // ../../node_modules/.bun/@hasna+skills@0.10.55+a00d3064559565bb/node_modules/@hasna/skills/dist/index.js
8443
+ // node_modules/@hasna/skills/dist/index.js
8144
8444
  import { existsSync as existsSync10 } from "fs";
8145
8445
  import { homedir as homedir5 } from "os";
8146
- import { join as join10, resolve as resolve4 } from "path";
8446
+ import { join as join11, resolve as resolve4 } from "path";
8147
8447
  import { homedir as pathsResolverHomedir2 } from "os";
8148
8448
  import { join as pathsResolverJoin2 } from "path";
8149
- import { createHash as createHash6 } from "crypto";
8449
+ import { createHash as createHash7 } from "crypto";
8150
8450
  import { existsSync as existsSync52, readdirSync as readdirSync3, readFileSync as readFileSync42, statSync as statSync3 } from "fs";
8151
8451
  import { join as join52, sep as sep3 } from "path";
8152
8452
  import { createHash as createHash32 } from "crypto";
@@ -8163,12 +8463,12 @@ import { isDeepStrictEqual as isDeepStrictEqual7 } from "util";
8163
8463
  import { dirname as dirname52, isAbsolute as isAbsolute5, join as join82, resolve as resolve5 } from "path";
8164
8464
  import { lstatSync as lstatSync42, readFileSync as readFileSync62, opendirSync } from "fs";
8165
8465
  import { createHash as createHash52 } from "crypto";
8166
- import { lstatSync as lstatSync5, opendirSync as opendirSync2 } from "fs";
8466
+ import { lstatSync as lstatSync52, opendirSync as opendirSync2 } from "fs";
8167
8467
  import { dirname as dirname62, isAbsolute as isAbsolute6, join as join92, resolve as resolve6 } from "path";
8168
8468
  import { createHash as createHash62 } from "crypto";
8169
8469
  import { closeSync as closeSync22, constants as constants22, fstatSync as fstatSync22, lstatSync as lstatSync6, openSync as openSync22, readSync as readSync2 } from "fs";
8170
8470
  import { dirname as dirname7, isAbsolute as isAbsolute7, resolve as resolve7 } from "path";
8171
- import { createHash as createHash7 } from "crypto";
8471
+ import { createHash as createHash72 } from "crypto";
8172
8472
  import { lstatSync as lstatSync7, readlinkSync } from "fs";
8173
8473
  import { dirname as dirname8, isAbsolute as isAbsolute8, join as join102, parse as parse2, resolve as resolve8, sep as sep32 } from "path";
8174
8474
  import { createHash as createHash8 } from "crypto";
@@ -8177,12 +8477,12 @@ import { basename as basename9, dirname as dirname18, isAbsolute as isAbsolute19
8177
8477
  import { isAbsolute as isAbsolute18, join as join30, resolve as resolve17 } from "path";
8178
8478
  import { createRequire } from "module";
8179
8479
 
8180
- // ../contracts/dist/kernel-lock.js
8181
- import { createHash as createHash5 } from "crypto";
8480
+ // node_modules/@hasna/skills/node_modules/@hasna/contracts/dist/kernel-lock.js
8481
+ import { createHash as createHash6 } from "crypto";
8182
8482
  import { fileURLToPath as fileURLToPath2 } from "url";
8183
8483
  import { spawn, spawnSync } from "child_process";
8184
- import { closeSync as closeSync4, constants as constants3, fstatSync as fstatSync3, lstatSync as lstatSync4, openSync as openSync4, readFileSync as readFileSync7, realpathSync as realpathSync4 } from "fs";
8185
- import { dirname as dirname6, join as join9, parse, relative, resolve as resolve3, sep as sep2 } from "path";
8484
+ import { closeSync as closeSync4, constants as constants3, fstatSync as fstatSync3, lstatSync as lstatSync5, openSync as openSync4, readFileSync as readFileSync7, realpathSync as realpathSync4 } from "fs";
8485
+ import { dirname as dirname6, join as join10, parse, relative, resolve as resolve3, sep as sep2 } from "path";
8186
8486
  class KernelLockError extends Error {
8187
8487
  code = "KERNEL_LOCK_UNAVAILABLE";
8188
8488
  constructor(reason) {
@@ -8205,7 +8505,7 @@ function darwinAcls(entries, deadline) {
8205
8505
  refused("unsafe ACL helper path");
8206
8506
  fd = openSync4(helper, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
8207
8507
  const info = fstatSync3(fd);
8208
- if (!info.isFile() || info.nlink !== 1 || info.uid !== 0 && info.uid !== process.getuid() || (info.mode & 18) !== 0 || (info.mode & 73) === 0 || info.size > 1048576 || createHash5("sha256").update(readFileSync7(fd)).digest("hex") !== DARWIN_HELPER_SHA256 || !sameEntry(info, lstatSync4(helper)))
8508
+ if (!info.isFile() || info.nlink !== 1 || info.uid !== 0 && info.uid !== process.getuid() || (info.mode & 18) !== 0 || (info.mode & 73) === 0 || info.size > 1048576 || createHash6("sha256").update(readFileSync7(fd)).digest("hex") !== DARWIN_HELPER_SHA256 || !sameEntry(info, lstatSync5(helper)))
8209
8509
  refused("ACL helper integrity check failed");
8210
8510
  const result = spawnSync(helper, entries.flatMap(([path, stat]) => [path, String(stat.dev), String(stat.ino)]), {
8211
8511
  env: { LANG: "C" },
@@ -8215,7 +8515,7 @@ function darwinAcls(entries, deadline) {
8215
8515
  timeout: timeout(deadline - performance.now()),
8216
8516
  killSignal: "SIGKILL"
8217
8517
  });
8218
- if (result.error || result.signal || !sameEntry(info, lstatSync4(helper)))
8518
+ if (result.error || result.signal || !sameEntry(info, lstatSync5(helper)))
8219
8519
  refused("ACL helper failed");
8220
8520
  if (result.status === 76)
8221
8521
  refused("unsafe lock ACL");
@@ -8243,7 +8543,7 @@ function sameEntry(a, b) {
8243
8543
  }
8244
8544
  function statOptional(path) {
8245
8545
  try {
8246
- return lstatSync4(path);
8546
+ return lstatSync5(path);
8247
8547
  } catch (error) {
8248
8548
  if (error.code === "ENOENT")
8249
8549
  return;
@@ -8261,7 +8561,7 @@ function canonicalRoot(root) {
8261
8561
  const parts = relative(cursor, requested).split(sep2).filter(Boolean);
8262
8562
  for (const part of ["", ...parts]) {
8263
8563
  if (part)
8264
- cursor = join9(cursor, part);
8564
+ cursor = join10(cursor, part);
8265
8565
  const info = statOptional(cursor);
8266
8566
  if (!info)
8267
8567
  refused("existing lock root is required");
@@ -8318,10 +8618,10 @@ class KernelLock {
8318
8618
  let fd;
8319
8619
  try {
8320
8620
  const rootPath = canonicalRoot(root);
8321
- this.#path = join9(rootPath, key + LOCK_SUFFIX);
8322
- this.#legacyPath = join9(rootPath, `${key}.lock`);
8621
+ this.#path = join10(rootPath, key + LOCK_SUFFIX);
8622
+ this.#legacyPath = join10(rootPath, `${key}.lock`);
8323
8623
  for (let path = rootPath;; path = dirname6(path)) {
8324
- const info = lstatSync4(path);
8624
+ const info = lstatSync5(path);
8325
8625
  const stickyParent = path !== rootPath && info.uid === 0 && (info.mode & 512) !== 0;
8326
8626
  if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== process.getuid() && info.uid !== 0 || (info.mode & 18) !== 0 && !stickyParent || path === rootPath && info.uid !== process.getuid())
8327
8627
  refused("unsafe lock directory");
@@ -8370,11 +8670,11 @@ class KernelLock {
8370
8670
  try {
8371
8671
  this.#checkLegacy();
8372
8672
  for (const [path, initial] of this.#directories) {
8373
- const current22 = lstatSync4(path);
8673
+ const current22 = lstatSync5(path);
8374
8674
  if (!sameEntry(initial, current22) || current22.mode !== initial.mode || current22.uid !== initial.uid || current22.isSymbolicLink())
8375
8675
  refused("lock directory changed");
8376
8676
  }
8377
- const current2 = lstatSync4(this.#path), descriptor = fstatSync3(this.#fd);
8677
+ const current2 = lstatSync5(this.#path), descriptor = fstatSync3(this.#fd);
8378
8678
  this.#checkFile(current2);
8379
8679
  this.#checkFile(descriptor);
8380
8680
  if (!sameEntry(current2, this.#opened) || !sameEntry(descriptor, this.#opened))
@@ -8388,7 +8688,7 @@ class KernelLock {
8388
8688
  refused("lock ACL changed");
8389
8689
  }
8390
8690
  for (const [path, initial] of [...this.#directories, [this.#path, current2]]) {
8391
- const after = lstatSync4(path);
8691
+ const after = lstatSync5(path);
8392
8692
  if (!sameEntry(initial, after) || after.mode !== initial.mode || after.uid !== initial.uid)
8393
8693
  refused("lock identity changed during ACL inspection");
8394
8694
  }
@@ -8508,7 +8808,7 @@ class KernelLock {
8508
8808
  }
8509
8809
  }
8510
8810
 
8511
- // ../../node_modules/.bun/@hasna+skills@0.10.55+a00d3064559565bb/node_modules/@hasna/skills/dist/index.js
8811
+ // node_modules/@hasna/skills/dist/index.js
8512
8812
  import { execFileSync } from "child_process";
8513
8813
  import { createHash as createHash12 } from "crypto";
8514
8814
  import { accessSync, constants as constants6, lstatSync as lstatSync12, readFileSync as readFileSync11, realpathSync as realpathSync32, statSync as statSync7 } from "fs";
@@ -15403,7 +15703,7 @@ function effectiveHome() {
15403
15703
  return process.env["HOME"] || process.env["USERPROFILE"] || homedir5() || "/tmp";
15404
15704
  }
15405
15705
  function legacyDataRoot() {
15406
- return join10(effectiveHome(), ".hasna", "skills");
15706
+ return join11(effectiveHome(), ".hasna", "skills");
15407
15707
  }
15408
15708
  function resolverDataRoot(home = effectiveHome(), env) {
15409
15709
  return dataDir2({ app: "skills", home, env });
@@ -15412,7 +15712,7 @@ function adoptResolverDataRoot2(resolved, env = process.env) {
15412
15712
  const dataOverride = env.HASNA_DATA_HOME;
15413
15713
  if (typeof dataOverride === "string" && dataOverride.trim().length > 0)
15414
15714
  return true;
15415
- return existsSync10(join10(resolved, DEFAULT_SQLITE_FILENAME)) || existsSync10(join10(resolved, GLOBAL_CONFIG_FILENAME));
15715
+ return existsSync10(join11(resolved, DEFAULT_SQLITE_FILENAME)) || existsSync10(join11(resolved, GLOBAL_CONFIG_FILENAME));
15416
15716
  }
15417
15717
  function exactDataRoot() {
15418
15718
  for (const key of [DATA_DIR_ENV, HASNA_SKILLS_HOME_ENV, SKILLS_HOME_ENV]) {
@@ -15646,7 +15946,7 @@ function* bundleHashParts(files) {
15646
15946
  yield new TextEncoder().encode("\x00");
15647
15947
  }
15648
15948
  function hashBundleFiles(files) {
15649
- const hash = createHash6(CONTENT_HASH_ALGORITHM);
15949
+ const hash = createHash7(CONTENT_HASH_ALGORITHM);
15650
15950
  for (const part of bundleHashParts(files))
15651
15951
  hash.update(part);
15652
15952
  return hash.digest("hex");
@@ -16937,7 +17237,7 @@ function need3(value, message) {
16937
17237
  function safe(path) {
16938
17238
  need3(typeof path === "string" && path.length <= AGENT_POLICY_LIMITS.pathCharacters && isAbsolute6(path) && resolve6(path) === path && !path.includes("\x00"), "Expected a canonical absolute discovery directory path");
16939
17239
  for (let cursor = path;; cursor = dirname62(cursor)) {
16940
- need3(!lstatSync5(cursor, { throwIfNoEntry: false })?.isSymbolicLink(), "Refusing symlink native discovery directory");
17240
+ need3(!lstatSync52(cursor, { throwIfNoEntry: false })?.isSymbolicLink(), "Refusing symlink native discovery directory");
16941
17241
  if (dirname62(cursor) === cursor)
16942
17242
  break;
16943
17243
  }
@@ -16949,7 +17249,7 @@ function capture(path, budget2, excludedRoots, omittedRoots = [], rows) {
16949
17249
  safe(path);
16950
17250
  if (omittedRoots.some((root2) => path === root2 || path.startsWith(root2 + "/")))
16951
17251
  return { path, sha256: null };
16952
- const root = lstatSync5(path, { throwIfNoEntry: false });
17252
+ const root = lstatSync52(path, { throwIfNoEntry: false });
16953
17253
  if (!root)
16954
17254
  return { path, sha256: null };
16955
17255
  need3(root.isDirectory(), "Unsupported native discovery directory input");
@@ -16971,7 +17271,7 @@ function capture(path, budget2, excludedRoots, omittedRoots = [], rows) {
16971
17271
  if (omittedRoots.includes(child2))
16972
17272
  continue;
16973
17273
  need3(child2.length <= AGENT_POLICY_LIMITS.pathCharacters, "Native discovery directory path limit exceeded");
16974
- const stat = lstatSync5(child2);
17274
+ const stat = lstatSync52(child2);
16975
17275
  need3(stat.isFile() || stat.isDirectory(), "Refusing symlink or special native discovery directory member");
16976
17276
  const row = JSON.stringify([childRelative, stat.isDirectory() ? "directory" : "file"]) + `
16977
17277
  `;
@@ -16982,7 +17282,7 @@ function capture(path, budget2, excludedRoots, omittedRoots = [], rows) {
16982
17282
  if (stat.isDirectory() && !excludedRoots.includes(child2))
16983
17283
  walk(child2, childRelative, stat, depth + 1);
16984
17284
  }
16985
- need3(same(before, lstatSync5(current2, { throwIfNoEntry: false })), "Native discovery directory changed while reading");
17285
+ need3(same(before, lstatSync52(current2, { throwIfNoEntry: false })), "Native discovery directory changed while reading");
16986
17286
  }
16987
17287
  walk(path, "", root, 0);
16988
17288
  safe(path);
@@ -17211,7 +17511,7 @@ function hashDiscoveryPathFile(path, budget2, changes) {
17211
17511
  const after = trace(path);
17212
17512
  if (JSON.stringify(before.rows) !== JSON.stringify(after.rows) || before.file !== after.file)
17213
17513
  throw new Error("Discovery path input changed during read");
17214
- return createHash7("sha256").update(JSON.stringify({ version: 1, path, rows: before.rows, content })).digest("hex");
17514
+ return createHash72("sha256").update(JSON.stringify({ version: 1, path, rows: before.rows, content })).digest("hex");
17215
17515
  }
17216
17516
  var CLAUDE_PLUGIN_MANIFEST_LIMITS = Object.freeze({ bytes: 1024 * 1024, depth: 32, nodes: 65536, stringCharacters: 16384 });
17217
17517
  function requireValue(value, reason2) {
@@ -21131,14 +21431,14 @@ function validatePluginTarget(value) {
21131
21431
  }
21132
21432
  pluginNeed(["2.1.274", "2.1.276"].includes(value.native.version), "Plugin admission requires a certified Claude command-source runtime (2.1.274 or 2.1.276)");
21133
21433
  }
21134
- function canonicalJson(value) {
21434
+ function canonicalJson2(value) {
21135
21435
  return JSON.stringify(value, (_key, item) => pluginObject(item) ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
21136
21436
  }
21137
21437
  function canonicalTarget(target) {
21138
- return JSON.parse(canonicalJson({ ...target, registrations: [...target.registrations].sort((a, b) => canonicalJson(a) < canonicalJson(b) ? -1 : canonicalJson(a) > canonicalJson(b) ? 1 : 0) }));
21438
+ return JSON.parse(canonicalJson2({ ...target, registrations: [...target.registrations].sort((a, b) => canonicalJson2(a) < canonicalJson2(b) ? -1 : canonicalJson2(a) > canonicalJson2(b) ? 1 : 0) }));
21139
21439
  }
21140
21440
  function bindingId(binding) {
21141
- return pluginHash(canonicalJson({ ...binding, target: canonicalTarget(binding.target) }));
21441
+ return pluginHash(canonicalJson2({ ...binding, target: canonicalTarget(binding.target) }));
21142
21442
  }
21143
21443
  function selectedIdentity(selection) {
21144
21444
  return { slug: selection.slug, version: selection.version, bundleDigest: selection.bundleDigest };
@@ -21153,10 +21453,10 @@ function planIdentity(plan) {
21153
21453
  return { schemaVersion: 3, binding: plan.binding, bindingId: plan.bindingId, profileRevision: plan.profileRevision, selection: routingIdentity(plan.selection), payloadSelections: plan.payloadSelections.map(routingIdentity), manifest: plan.manifest, originalTreeDigest: plan.originalTreeDigest, projectionTreeDigest: plan.projectionTreeDigest, files: plan.files, removed: plan.removed, sourceCommand: plan.sourceCommand, evidenceDigest: plan.evidenceDigest };
21154
21454
  }
21155
21455
  function identityDigest(plan) {
21156
- return `sha256:${pluginHash(canonicalJson(planIdentity(plan)))}`;
21456
+ return `sha256:${pluginHash(canonicalJson2(planIdentity(plan)))}`;
21157
21457
  }
21158
21458
  function observedEvidenceDigest(observation) {
21159
- return `sha256:${pluginHash(canonicalJson(observation))}`;
21459
+ return `sha256:${pluginHash(canonicalJson2(observation))}`;
21160
21460
  }
21161
21461
  function validatePrincipal(value) {
21162
21462
  pluginKeys(value, ["userId", "accountId", "role"]);
@@ -21189,7 +21489,7 @@ function validateObservedSelection(value) {
21189
21489
  function validateRoutingIdentity(value) {
21190
21490
  pluginKeys(value, ["slug", "version", "bundleDigest", "aliases", "triggers"]);
21191
21491
  validateObservedSelection({ ...value, authority: "https://example.com/skills/v1", workspaceId: "validation", profileRevision: "validation" });
21192
- pluginNeed(canonicalJson(value) === canonicalJson(routingIdentity(value)), "Plugin routing identity is not canonical");
21492
+ pluginNeed(canonicalJson2(value) === canonicalJson2(routingIdentity(value)), "Plugin routing identity is not canonical");
21193
21493
  }
21194
21494
  function validateWitnesses(value, empty = false) {
21195
21495
  pluginNeed(Array.isArray(value) && (empty || value.length > 0) && value.length <= PLUGIN_PROJECTION_LIMITS.files, "Invalid plugin file witnesses");
@@ -21235,7 +21535,7 @@ function validatePlan(value) {
21235
21535
  const mapped = new Map;
21236
21536
  for (const mapping of value.manifest.payloads) {
21237
21537
  const prior = mapped.get(mapping.target.slug);
21238
- pluginNeed(!prior || canonicalJson(prior) === canonicalJson(mapping.target), "Plugin mappings disagree about a canonical payload");
21538
+ pluginNeed(!prior || canonicalJson2(prior) === canonicalJson2(mapping.target), "Plugin mappings disagree about a canonical payload");
21239
21539
  mapped.set(mapping.target.slug, mapping.target);
21240
21540
  const removed = value.removed.find((item) => item.path === mapping.path);
21241
21541
  pluginNeed(removed && mapping.sourceDigest === `sha256:${pluginHash(JSON.stringify(normalizedWitnesses([removed])))}`, "Plugin mapped source differs from its removed witness");
@@ -21244,7 +21544,7 @@ function validatePlan(value) {
21244
21544
  let previous = "";
21245
21545
  for (const selection of value.payloadSelections) {
21246
21546
  validateRoutingIdentity(selection);
21247
- pluginNeed(selection.slug > previous && selection.slug !== value.selection.slug && canonicalJson(selectedIdentity(selection)) === canonicalJson(mapped.get(selection.slug)), "Plugin payload selection differs from its canonical mapping");
21547
+ pluginNeed(selection.slug > previous && selection.slug !== value.selection.slug && canonicalJson2(selectedIdentity(selection)) === canonicalJson2(mapped.get(selection.slug)), "Plugin payload selection differs from its canonical mapping");
21248
21548
  previous = selection.slug;
21249
21549
  }
21250
21550
  pluginKeys(value.observation, ["principal", "profileRevision", "integration", "payloads"]);
@@ -21256,9 +21556,9 @@ function validatePlan(value) {
21256
21556
  for (let index = 0;index < observed.length; index++) {
21257
21557
  const selection = observed[index];
21258
21558
  validateRoutingIdentity(selection);
21259
- pluginNeed(canonicalJson(selection) === canonicalJson(selected[index]), "Plugin observed routing selection differs from its identity");
21559
+ pluginNeed(canonicalJson2(selection) === canonicalJson2(selected[index]), "Plugin observed routing selection differs from its identity");
21260
21560
  }
21261
- pluginNeed(value.profileRevision === value.observation.profileRevision && canonicalJson(binding.principal) === canonicalJson(value.observation.principal), "Plugin observed profile or principal differs from its approved identity");
21561
+ pluginNeed(value.profileRevision === value.observation.profileRevision && canonicalJson2(binding.principal) === canonicalJson2(value.observation.principal), "Plugin observed profile or principal differs from its approved identity");
21262
21562
  validateResolvedProfile({ profileId: binding.profileId, authority: binding.authority, workspaceId: binding.workspaceId, profileRevision: value.profileRevision, selections: observed.map((selection) => ({ ...selection, authority: binding.authority, workspaceId: binding.workspaceId, profileRevision: value.profileRevision })) }, binding.authority);
21263
21563
  const plan = value;
21264
21564
  pluginNeed(observedEvidenceDigest(plan.observation) === plan.evidenceDigest, "Plugin receipt observed evidence changed");
@@ -21295,7 +21595,7 @@ function readPluginAdmissionReceipt(storeRoot, id, digest) {
21295
21595
  receipt.plan.removed = normalizedWitnesses(receipt.plan.removed);
21296
21596
  pluginNeed(receipt.plan.bindingId === id && receipt.plan.planDigest === digest, "Plugin receipt identity differs from its filename");
21297
21597
  const binding = readPluginBinding(storeRoot, id);
21298
- pluginNeed(canonicalJson(binding) === canonicalJson(receipt.plan.binding) && receipt.plan.sourceCommand === pluginResolverCommand(binding), "Plugin receipt binding changed");
21598
+ pluginNeed(canonicalJson2(binding) === canonicalJson2(receipt.plan.binding) && receipt.plan.sourceCommand === pluginResolverCommand(binding), "Plugin receipt binding changed");
21299
21599
  pluginNeed(receipt.materializedPath === join30(storeRoot, "objects", id, digest.slice(7)), "Plugin receipt points outside its immutable materialization");
21300
21600
  pluginText(receipt.admittedAt, 64);
21301
21601
  pluginNeed(Number.isFinite(Date.parse(receipt.admittedAt)), "Invalid plugin admission time");
@@ -42793,7 +43093,7 @@ function claudeSkillsUsage(before, home) {
42793
43093
  }
42794
43094
  if (events2.length)
42795
43095
  evidence.push(`Skills-managed hook entries in ${events2.join(", ")}`);
42796
- const bridge = join11(home, ".claude", "skills", "skills-cli", "SKILL.md");
43096
+ const bridge = join12(home, ".claude", "skills", "skills-cli", "SKILL.md");
42797
43097
  let bridgePresent;
42798
43098
  try {
42799
43099
  bridgePresent = lstatSync8(bridge, { throwIfNoEntry: false }) !== undefined;
@@ -42807,7 +43107,7 @@ function claudeSkillsUsage(before, home) {
42807
43107
  function skillsPolicyLocations(dataDir3) {
42808
43108
  const state = (path) => existsSync11(path) ? "present" : "absent";
42809
43109
  if (dataDir3 !== undefined)
42810
- return [`${join11(resolve9(dataDir3), "agent-policy.json")} (explicit data directory, absent)`];
43110
+ return [`${join12(resolve9(dataDir3), "agent-policy.json")} (explicit data directory, absent)`];
42811
43111
  const env = process.env, home = env.HOME || env.USERPROFILE || homedir6() || "/tmp", searched = [];
42812
43112
  let selected = false;
42813
43113
  for (const key of ["HASNA_SKILLS_DIR", "HASNA_SKILLS_HOME", "SKILLS_HOME"]) {
@@ -42818,13 +43118,13 @@ function skillsPolicyLocations(dataDir3) {
42818
43118
  searched.push(`$${key} (unset)`);
42819
43119
  else {
42820
43120
  selected = true;
42821
- searched.push(`$${key} -> ${join11(resolve9(value), "agent-policy.json")} (selected, absent)`);
43121
+ searched.push(`$${key} -> ${join12(resolve9(value), "agent-policy.json")} (selected, absent)`);
42822
43122
  }
42823
43123
  }
42824
43124
  const override = env.HASNA_DATA_HOME;
42825
- const base = typeof override === "string" && override.length > 0 ? override : process.platform === "darwin" ? join11(home, "Library", "Application Support", "Hasna") : join11(home, ".local", "share", "hasna");
42826
- const xdg = join11(base, "skills"), xdgPolicy = join11(xdg, "agent-policy.json");
42827
- const adopted = typeof override === "string" && override.trim().length > 0 || existsSync11(join11(xdg, "server.db")) || existsSync11(join11(xdg, "config.json"));
43125
+ const base = typeof override === "string" && override.length > 0 ? override : process.platform === "darwin" ? join12(home, "Library", "Application Support", "Hasna") : join12(home, ".local", "share", "hasna");
43126
+ const xdg = join12(base, "skills"), xdgPolicy = join12(xdg, "agent-policy.json");
43127
+ const adopted = typeof override === "string" && override.trim().length > 0 || existsSync11(join12(xdg, "server.db")) || existsSync11(join12(xdg, "config.json"));
42828
43128
  if (selected)
42829
43129
  searched.push(`${xdgPolicy} (not consulted, ${state(xdgPolicy)})`);
42830
43130
  else if (adopted) {
@@ -42832,7 +43132,7 @@ function skillsPolicyLocations(dataDir3) {
42832
43132
  searched.push(`${xdgPolicy} (selected, absent)`);
42833
43133
  } else
42834
43134
  searched.push(`${xdgPolicy} (not selected: the directory holds no server.db or config.json and HASNA_DATA_HOME is unset; ${state(xdgPolicy)})`);
42835
- const legacy = join11(home, ".hasna", "skills", "agent-policy.json");
43135
+ const legacy = join12(home, ".hasna", "skills", "agent-policy.json");
42836
43136
  searched.push(selected ? `${legacy} (not consulted, ${state(legacy)})` : `${legacy} (selected, absent)`);
42837
43137
  return searched;
42838
43138
  }
@@ -42850,7 +43150,7 @@ function planCoordinatedClaudeSettings(before, replacement, options) {
42850
43150
  if (!plan) {
42851
43151
  const usage = claudeSkillsUsage(before, options.home);
42852
43152
  if (usage.length)
42853
- throw new ClaudeSettingsRefusal("skills_policy_unresolved", `Skills manages ${join11(options.home, ".claude", "settings.json")} (${usage.join("; ")}), but no Skills agent policy resolved, ` + "so Hooks cannot coordinate this change and wrote nothing. Locations searched, in Skills resolution order: " + skillsPolicyLocations(options.dataDir).map((location, index) => `${index + 1}) ${location}`).join("; ") + ". Run hooks with the environment that selects the Skills data directory (for example HASNA_SKILLS_DIR), " + "or repair the integration with `skills hook install`.");
43153
+ throw new ClaudeSettingsRefusal("skills_policy_unresolved", `Skills manages ${join12(options.home, ".claude", "settings.json")} (${usage.join("; ")}), but no Skills agent policy resolved, ` + "so Hooks cannot coordinate this change and wrote nothing. Locations searched, in Skills resolution order: " + skillsPolicyLocations(options.dataDir).map((location, index) => `${index + 1}) ${location}`).join("; ") + ". Run hooks with the environment that selects the Skills data directory (for example HASNA_SKILLS_DIR), " + "or repair the integration with `skills hook install`.");
42854
43154
  }
42855
43155
  return plan;
42856
43156
  }
@@ -42863,9 +43163,33 @@ function coordinateClaudeSettings(before, replacement, options, beforeWrite) {
42863
43163
  return true;
42864
43164
  }
42865
43165
 
43166
+ // src/lib/native-target.ts
43167
+ var HOOK_RUN_TARGETS = ["claude", "codex", "gemini", "codewith", "sumi", "opencode"];
43168
+ function isHookRunTarget(value) {
43169
+ return typeof value === "string" && HOOK_RUN_TARGETS.includes(value);
43170
+ }
43171
+ function nativeTargetArgs(dispatch, target, args = []) {
43172
+ if (target !== undefined && !isHookRunTarget(target))
43173
+ throw new Error("Invalid --target; expected claude, codex, gemini, codewith, sumi, or opencode");
43174
+ if (!dispatch)
43175
+ return [...args];
43176
+ if (!isHookRunTarget(target))
43177
+ throw new Error("This hook requires --target from its native registration");
43178
+ if (args.some((arg) => arg === "--harness" || arg.startsWith("--harness=")))
43179
+ throw new Error("nativeTargetDispatch owns the --harness argument; remove it from manifest args");
43180
+ return [...args, "--harness", target];
43181
+ }
43182
+ function nativeTargetCommandSuffix(dispatch, target) {
43183
+ if (!dispatch)
43184
+ return "";
43185
+ if (!isHookRunTarget(target))
43186
+ throw new Error("Native registration requires a supported target");
43187
+ return ` --target ${target}`;
43188
+ }
43189
+
42866
43190
  // src/lib/installer.ts
42867
43191
  var __dirname2 = dirname9(fileURLToPath3(import.meta.url));
42868
- var HOOKS_DIR = existsSync12(join12(__dirname2, "..", "..", "hooks", "hook-gitguard")) ? join12(__dirname2, "..", "..", "hooks") : join12(__dirname2, "..", "hooks");
43192
+ var HOOKS_DIR = existsSync12(join13(__dirname2, "..", "..", "hooks", "hook-gitguard")) ? join13(__dirname2, "..", "..", "hooks") : join13(__dirname2, "..", "hooks");
42869
43193
  function normalizeHookName(name) {
42870
43194
  return name.startsWith("hook-") ? name : `hook-${name}`;
42871
43195
  }
@@ -42953,18 +43277,18 @@ function getSettingsPath(scope = "global", target = "claude", codewithConfigPath
42953
43277
  return globalOverride;
42954
43278
  const dir = getTargetSettingsDir(target);
42955
43279
  if (target === "codex")
42956
- return join12(scope === "project" ? process.cwd() : homedir7(), dir, "hooks.json");
43280
+ return join13(scope === "project" ? process.cwd() : homedir7(), dir, "hooks.json");
42957
43281
  if (scope === "project") {
42958
- return target === "codewith" ? join12(process.cwd(), dir, "config.toml") : join12(process.cwd(), dir, "settings.json");
43282
+ return target === "codewith" ? join13(process.cwd(), dir, "config.toml") : join13(process.cwd(), dir, "settings.json");
42959
43283
  }
42960
- return target === "codewith" ? join12(homedir7(), dir, "config.toml") : join12(homedir7(), dir, "settings.json");
43284
+ return target === "codewith" ? join13(homedir7(), dir, "config.toml") : join13(homedir7(), dir, "settings.json");
42961
43285
  }
42962
43286
  function getHookPath(name) {
42963
43287
  const shortName = shortHookName(name);
42964
43288
  const resolved = resolveHookDir(shortName);
42965
43289
  if (resolved)
42966
43290
  return resolved;
42967
- return join12(HOOKS_DIR, normalizeHookName(shortName));
43291
+ return join13(HOOKS_DIR, normalizeHookName(shortName));
42968
43292
  }
42969
43293
  function hookExists(name) {
42970
43294
  return existsSync12(getHookPath(name));
@@ -43011,10 +43335,10 @@ function unreadableSettingsRefusal(settings, path) {
43011
43335
  function settingsIdentity(path) {
43012
43336
  if (existsSync12(path))
43013
43337
  return realpathSync9(path);
43014
- return existsSync12(dirname9(path)) ? join12(realpathSync9(dirname9(path)), basename5(path)) : resolve21(path);
43338
+ return existsSync12(dirname9(path)) ? join13(realpathSync9(dirname9(path)), basename5(path)) : resolve21(path);
43015
43339
  }
43016
43340
  function coordinatesWithSkills(path, target) {
43017
- return target === "claude" && settingsIdentity(path) === settingsIdentity(join12(homedir7(), ".claude/settings.json"));
43341
+ return target === "claude" && settingsIdentity(path) === settingsIdentity(join13(homedir7(), ".claude/settings.json"));
43018
43342
  }
43019
43343
  function planClaudeSettingsWrite(before, after, scope = "global") {
43020
43344
  if (coordinatesWithSkills(getSettingsPath(scope, "claude"), "claude"))
@@ -43125,7 +43449,7 @@ function buildCodewithTomlFragment(name, profile, mementos) {
43125
43449
  if (!meta3)
43126
43450
  throw new Error(`Hook '${shortName}' not found`);
43127
43451
  validateMementosRegistration(shortName, mementos);
43128
- const command = isNativeSafetyName(shortName) ? installedNativeSafetyCommand(shortName) : (profile ? `hooks run ${shortName} --profile ${profile}` : `hooks run ${shortName}`) + mementosCommandSuffix(mementos);
43452
+ const command = isNativeSafetyName(shortName) ? installedNativeSafetyCommand(shortName) : (profile ? `hooks run ${shortName} --profile ${profile}` : `hooks run ${shortName}`) + nativeTargetCommandSuffix(meta3.nativeTargetDispatch, "codewith") + mementosCommandSuffix(mementos);
43129
43453
  const matcher = codewithMatcher(meta3.matcher);
43130
43454
  const fragments = [];
43131
43455
  for (const event of getHookEvents(meta3)) {
@@ -43423,7 +43747,7 @@ function registerHook(name, scope = "global", target = "claude", profile, mement
43423
43747
  }
43424
43748
  }
43425
43749
  const retained = name === "mementos-context" && mementos === undefined ? retainedMementosRegistration(Object.values(settings.hooks).flatMap((groups) => Array.isArray(groups) ? groups.flatMap((group) => Array.isArray(group.hooks) ? group.hooks.map((hook) => hook.command).filter((command) => typeof command === "string") : []) : [])) : undefined;
43426
- const hookCommand = readiness ? installedNativeReadinessCommand(target) : isNativeSafetyName(name) ? installedNativeSafetyCommand(name) : (profile ? `hooks run ${name} --profile ${profile}` : `hooks run ${name}`) + mementosCommandSuffix(mementos ?? retained);
43750
+ const hookCommand = readiness ? installedNativeReadinessCommand(target) : isNativeSafetyName(name) ? installedNativeSafetyCommand(name) : (profile ? `hooks run ${name} --profile ${profile}` : `hooks run ${name}`) + nativeTargetCommandSuffix(meta3.nativeTargetDispatch, target) + mementosCommandSuffix(mementos ?? retained);
43427
43751
  if (target === "codex" || target === "claude" && (isNativeSafetyName(name) || readiness)) {
43428
43752
  const positions = [];
43429
43753
  for (const [event, groups] of Object.entries(settings.hooks)) {
@@ -43627,12 +43951,12 @@ function removeStoreDirFailClosed(dir) {
43627
43951
  const entries = readdirSync4(dir, { withFileTypes: true });
43628
43952
  for (const entry of entries) {
43629
43953
  if (entry.isDirectory()) {
43630
- removeStoreDirFailClosed(join12(dir, entry.name));
43954
+ removeStoreDirFailClosed(join13(dir, entry.name));
43631
43955
  }
43632
43956
  }
43633
43957
  for (const entry of entries) {
43634
43958
  if (!entry.isDirectory()) {
43635
- unlinkSync2(join12(dir, entry.name));
43959
+ unlinkSync2(join13(dir, entry.name));
43636
43960
  }
43637
43961
  }
43638
43962
  rmdirSync(dir);
@@ -43704,9 +44028,9 @@ function uninstallHook(name, scope = "global", target = "claude") {
43704
44028
  };
43705
44029
  }
43706
44030
  // src/index.ts
44031
+ import { readFileSync as readFileSync25 } from "fs";
43707
44032
  init_profiles();
43708
44033
  init_config();
43709
- import { existsSync as existsSync17, readFileSync as readFileSync25 } from "fs";
43710
44034
 
43711
44035
  // src/lib/transport.ts
43712
44036
  init_transport();
@@ -43847,10 +44171,10 @@ init_manifest();
43847
44171
  init_config();
43848
44172
  init_manifest();
43849
44173
  import { existsSync as existsSync14, mkdirSync as mkdirSync12, mkdtempSync, readFileSync as readFileSync14, rmSync as rmSync2 } from "fs";
43850
- import { join as join16 } from "path";
44174
+ import { join as join24 } from "path";
43851
44175
  import { tmpdir } from "os";
43852
44176
  function manifestAt(dir) {
43853
- const path = join16(dir, "manifest.json");
44177
+ const path = join24(dir, "manifest.json");
43854
44178
  if (!existsSync14(path))
43855
44179
  return;
43856
44180
  try {
@@ -43873,8 +44197,8 @@ function writeFromManifest(manifest, srcDir, source, kind) {
43873
44197
  return { name, version: manifest.version, kind, source, dir, scriptPath };
43874
44198
  }
43875
44199
  async function cloneToTemp(gitUrl) {
43876
- const tmp = mkdtempSync(join16(tmpdir(), "hooks-install-"));
43877
- const proc = Bun.spawn(["git", "clone", "--depth", "1", "--quiet", gitUrl, join16(tmp, "repo")], {
44200
+ const tmp = mkdtempSync(join24(tmpdir(), "hooks-install-"));
44201
+ const proc = Bun.spawn(["git", "clone", "--depth", "1", "--quiet", gitUrl, join24(tmp, "repo")], {
43878
44202
  stdout: "pipe",
43879
44203
  stderr: "pipe"
43880
44204
  });
@@ -43887,7 +44211,7 @@ async function cloneToTemp(gitUrl) {
43887
44211
  rmSync2(tmp, { recursive: true, force: true });
43888
44212
  throw new Error(`git clone failed (${exitCode}): ${stderr.trim()}`);
43889
44213
  }
43890
- return join16(tmp, "repo");
44214
+ return join24(tmp, "repo");
43891
44215
  }
43892
44216
  function isGitUrl(value) {
43893
44217
  return value.startsWith("git@") || value.startsWith("ssh://") || value.startsWith("file://") || value.endsWith(".git");
@@ -43945,11 +44269,14 @@ async function installManifestUrl(url2) {
43945
44269
  return { name, version: manifest.version, kind: "url", source: url2, dir, scriptPath };
43946
44270
  }
43947
44271
  // src/lib/sync.ts
43948
- import { createHash as createHash11 } from "crypto";
43949
- import { readFileSync as readFileSync16 } from "fs";
44272
+ init_config();
44273
+ import { createHash as createHash11, randomUUID as randomUUID4 } from "crypto";
44274
+ import { readFileSync as readFileSync16, lstatSync as lstatSync11, mkdirSync as mkdirSync13, writeFileSync as writeFileSync10, accessSync as accessSync2, constants as constants5, existsSync as existsSync15 } from "fs";
44275
+ import { dirname as dirname21, join as join26, resolve as resolve23, sep as sep9 } from "path";
43950
44276
  init_db();
43951
44277
  init_store();
43952
44278
  init_manifest();
44279
+ init_registry_artifact();
43953
44280
  function sha256OfText(text3) {
43954
44281
  return createHash11("sha256").update(text3).digest("hex");
43955
44282
  }
@@ -43995,22 +44322,27 @@ async function fetchJson(base, path, apiKey, opts) {
43995
44322
  const body = await res.json();
43996
44323
  if (opts?.withHeader) {
43997
44324
  body[opts.withHeader] = res.headers.get("x-hook-sha256");
44325
+ body._bundleHeaderSha = res.headers.get("x-hook-bundle-sha256");
43998
44326
  }
43999
44327
  return body;
44000
44328
  }
44001
- async function fetchRemoteState(apiUrl, apiKey) {
44002
- const catalog = await fetchJson(apiUrl, "/api/v1/catalog", apiKey);
44003
- const remoteLock = await fetchJson(apiUrl, "/api/v1/lock", apiKey);
44329
+ async function fetchRemoteState(apiUrl, apiKey, options = {}) {
44330
+ const catalog = await fetchJson(apiUrl, "/v1/catalog", apiKey);
44331
+ const remoteLock = await fetchJson(apiUrl, "/v1/lock" + (options.selectionProfile ? "?profile=" + encodeURIComponent(options.selectionProfile) : ""), apiKey);
44004
44332
  if (!catalog.hooks || !Array.isArray(catalog.hooks)) {
44005
44333
  throw new Error("remote catalog is malformed: missing hooks array");
44006
44334
  }
44007
44335
  if (!remoteLock.hooks || typeof remoteLock.hooks !== "object") {
44008
44336
  throw new Error("remote lock is malformed: missing hooks map");
44009
44337
  }
44338
+ if (options.expectedRevision !== undefined && remoteLock.revision !== options.expectedRevision)
44339
+ throw new Error("REGISTRY_SELECTION_PRECONDITION_FAILED: selection revision changed");
44340
+ if (remoteLock.profile && (!Number.isSafeInteger(remoteLock.revision) || remoteLock.revision < 1 || options.selectionProfile && remoteLock.profile !== options.selectionProfile))
44341
+ throw new Error("REGISTRY_SELECTION_INVALID");
44010
44342
  return { catalog: catalog.hooks, remoteLock };
44011
44343
  }
44012
- function classifyRemotePin(pin2, remoteVersion, remoteSha) {
44013
- const pinnedLocally = pin2 !== undefined && pin2.version === remoteVersion && pin2.sha256 === remoteSha;
44344
+ function classifyRemotePin(pin2, remoteVersion, remoteSha, remoteBundle) {
44345
+ const pinnedLocally = pin2 !== undefined && pin2.version === remoteVersion && pin2.sha256 === remoteSha && (!remoteBundle || pin2.bundle_sha256 === remoteBundle);
44014
44346
  if (pinnedLocally)
44015
44347
  return "unchanged";
44016
44348
  if (pin2 !== undefined && pin2.pinned === true && pin2.version !== remoteVersion)
@@ -44032,14 +44364,25 @@ function computeDiff(catalog, remoteLock) {
44032
44364
  diff.skipped.push(entry.name);
44033
44365
  continue;
44034
44366
  }
44035
- if (remotePin.version !== entry.version) {
44367
+ if (!remoteLock.profile && remotePin.version !== entry.version) {
44036
44368
  throw new Error(`remote registry is ambiguous for '${entry.name}': lock pins ${remotePin.version} but catalog latest is ${entry.version}. ` + `Fix the registry (or its lock) before syncing \u2014 nothing was changed.`);
44037
44369
  }
44038
- diff[classifyRemotePin(pin2, remotePin.version, remotePin.sha256)].push(entry.name);
44370
+ let classification = classifyRemotePin(pin2, remotePin.version, remotePin.sha256, remotePin.bundle_sha256);
44371
+ if (classification === "unchanged" && remotePin.bundle_sha256 && pin2?.version === remotePin.version) {
44372
+ const custom3 = readCustomManifest(entry.name);
44373
+ if (!custom3 || !pin2.manifest_sha256 || registryDigest(custom3.manifest) !== pin2.manifest_sha256 || sha256OfPath(custom3.scriptPath) !== remotePin.sha256)
44374
+ classification = "updated";
44375
+ }
44376
+ diff[classification].push(entry.name);
44039
44377
  } else {
44040
44378
  diff[classifyRemotePin(pin2, entry.version, entry.sha256)].push(entry.name);
44041
44379
  }
44042
44380
  }
44381
+ if (remoteLock?.profile) {
44382
+ const names = new Set(catalog.map((entry) => entry.name));
44383
+ if (Object.keys(remoteLock.hooks).some((name) => !names.has(name)))
44384
+ throw new Error("REGISTRY_SELECTION_ARTIFACT_MISSING");
44385
+ }
44043
44386
  return diff;
44044
44387
  }
44045
44388
  async function planSync(options = {}) {
@@ -44048,8 +44391,8 @@ async function planSync(options = {}) {
44048
44391
  });
44049
44392
  if (transport.mode === "remote" && transport.authority) {
44050
44393
  const { origin } = transport.authority;
44051
- const { catalog, remoteLock } = await fetchRemoteState(origin, transport.authority);
44052
- return { apiUrl: origin, dryRun: options.dryRun ?? false, diff: computeDiff(catalog, remoteLock) };
44394
+ const { catalog, remoteLock } = await fetchRemoteState(origin, transport.authority, options);
44395
+ return { apiUrl: origin, dryRun: options.dryRun ?? false, diff: computeDiff(catalog, remoteLock), ...remoteLock.profile ? { selection: { profile: remoteLock.profile, revision: remoteLock.revision } } : {} };
44053
44396
  }
44054
44397
  const diff = computeDiff(collectBundledCatalog(), null);
44055
44398
  return { apiUrl: null, dryRun: options.dryRun ?? false, diff };
@@ -44077,11 +44420,75 @@ async function syncHooks(options = {}) {
44077
44420
  return plan;
44078
44421
  }
44079
44422
  const { origin } = transport.authority;
44080
- const { catalog, remoteLock } = await fetchRemoteState(origin, transport.authority);
44423
+ const guardedOptions = { ...options, ...plan.selection ? { selectionProfile: plan.selection.profile, expectedRevision: plan.selection.revision } : {} };
44424
+ const { catalog, remoteLock } = await fetchRemoteState(origin, transport.authority, guardedOptions);
44081
44425
  const diff = computeDiff(catalog, remoteLock);
44082
44426
  const staged = await stageSyncArtifacts(origin, transport.authority, [...diff.added, ...diff.updated], remoteLock);
44427
+ if (remoteLock.profile) {
44428
+ const current2 = (await fetchRemoteState(origin, transport.authority, guardedOptions)).remoteLock;
44429
+ if (registryDigest(current2) !== registryDigest(remoteLock))
44430
+ throw new Error("REGISTRY_SELECTION_PRECONDITION_FAILED: selection changed during staging");
44431
+ }
44083
44432
  await commitSyncArtifacts(staged, origin, remoteLock);
44084
- return { apiUrl: origin, dryRun: false, diff };
44433
+ return { apiUrl: origin, dryRun: false, diff, ...remoteLock.profile ? { selection: { profile: remoteLock.profile, revision: remoteLock.revision } } : {} };
44434
+ }
44435
+ function prepareRegistryCommit(staged) {
44436
+ if (!staged.length)
44437
+ return;
44438
+ const originals = new Map;
44439
+ const inspectFile = (path) => {
44440
+ try {
44441
+ if (!lstatSync11(path).isFile())
44442
+ throw new Error("REGISTRY_SYNC_DESTINATION_INVALID");
44443
+ accessSync2(path, constants5.W_OK);
44444
+ originals.set(path, readFileSync16(path));
44445
+ } catch (error61) {
44446
+ if (error61.code !== "ENOENT")
44447
+ throw error61;
44448
+ }
44449
+ };
44450
+ for (const item of staged) {
44451
+ const root = resolve23(customHookDir(item.name));
44452
+ const script = resolve23(root, item.scriptRel);
44453
+ if (script !== root && !script.startsWith(root + sep9))
44454
+ throw new ScriptContainmentError(script, root, item.scriptRel);
44455
+ const manifest = join26(root, "manifest.json");
44456
+ if (script === manifest || script === root)
44457
+ throw new Error("REGISTRY_SYNC_DESTINATION_INVALID");
44458
+ for (let path = dirname21(script);; path = dirname21(path)) {
44459
+ try {
44460
+ if (!lstatSync11(path).isDirectory())
44461
+ throw new Error("REGISTRY_SYNC_DESTINATION_INVALID");
44462
+ accessSync2(path, constants5.W_OK);
44463
+ } catch (error61) {
44464
+ if (error61.code !== "ENOENT")
44465
+ throw error61;
44466
+ }
44467
+ if (path === root)
44468
+ break;
44469
+ }
44470
+ if (existsSync15(root))
44471
+ assertContained(script, root, item.scriptRel);
44472
+ inspectFile(script);
44473
+ inspectFile(manifest);
44474
+ }
44475
+ inspectFile(getLockPath());
44476
+ if (originals.size) {
44477
+ const recovery = join26(getHooksDataDir(), "registry-preservation", randomUUID4());
44478
+ mkdirSync13(recovery, { recursive: true, mode: 448 });
44479
+ const receipt = [];
44480
+ for (const [target, bytes] of originals) {
44481
+ const path = join26(recovery, `${receipt.length}.original`);
44482
+ writeFileSync10(path, bytes, { flag: "wx", mode: 384 });
44483
+ if (!readFileSync16(path).equals(bytes))
44484
+ throw new Error("REGISTRY_PRESERVATION_READBACK_FAILED");
44485
+ receipt.push({ target, preserved: path, sha256: createHash11("sha256").update(bytes).digest("hex"), readback: true });
44486
+ }
44487
+ writeFileSync10(join26(recovery, "receipt.json"), JSON.stringify(receipt, null, 2) + `
44488
+ `, { flag: "wx", mode: 384 });
44489
+ }
44490
+ for (const item of staged)
44491
+ markRegistryManaged(item.name);
44085
44492
  }
44086
44493
  async function stageSyncArtifacts(apiUrl, apiKey, names, remoteLock) {
44087
44494
  const staged = [];
@@ -44089,10 +44496,18 @@ async function stageSyncArtifacts(apiUrl, apiKey, names, remoteLock) {
44089
44496
  const entry = remoteLock.hooks[name];
44090
44497
  if (!entry)
44091
44498
  continue;
44092
- const artifact = await fetchJson(apiUrl, `/api/v1/hooks/${encodeURIComponent(name)}/${encodeURIComponent(entry.version)}`, apiKey);
44499
+ const artifact = await fetchJson(apiUrl, `/v1/hooks/${encodeURIComponent(name)}/${encodeURIComponent(entry.version)}`, apiKey);
44093
44500
  if (!artifact.manifest || typeof artifact.script !== "string") {
44094
44501
  throw new Error(`artifact for '${name}@${entry.version}' is malformed`);
44095
44502
  }
44503
+ if (shortManifestName(artifact.manifest.name) !== name)
44504
+ throw new Error("REGISTRY_ARTIFACT_IDENTITY_MISMATCH");
44505
+ if (entry.bundle_sha256) {
44506
+ const canonical8 = validateRegistryArtifact(artifact);
44507
+ if (registryDigest(canonical8) !== entry.bundle_sha256)
44508
+ throw new Error("REGISTRY_BUNDLE_DIGEST_MISMATCH");
44509
+ } else if (remoteLock.profile)
44510
+ throw new Error("REGISTRY_BUNDLE_DIGEST_MISSING");
44096
44511
  const actualSha = sha256OfText(artifact.script);
44097
44512
  if (actualSha !== entry.sha256) {
44098
44513
  throw new Error(`sha256 mismatch for '${name}@${entry.version}': lock says ${entry.sha256}, artifact has ${actualSha}`);
@@ -44116,6 +44531,7 @@ async function stageSyncArtifacts(apiUrl, apiKey, names, remoteLock) {
44116
44531
  }
44117
44532
  async function commitSyncArtifacts(staged, apiUrl, remoteLock) {
44118
44533
  const db = isLocalStoreRefused() ? null : getDb();
44534
+ prepareRegistryCommit(staged);
44119
44535
  for (const item of staged) {
44120
44536
  const entry = remoteLock.hooks[item.name];
44121
44537
  if (!entry)
@@ -44132,7 +44548,7 @@ async function commitSyncArtifacts(staged, apiUrl, remoteLock) {
44132
44548
  const entry = remoteLock.hooks[item.name];
44133
44549
  if (!entry)
44134
44550
  continue;
44135
- lock.hooks[item.name] = { version: entry.version, sha256: entry.sha256, source: entry.source ?? "remote" };
44551
+ lock.hooks[item.name] = { version: entry.version, sha256: entry.sha256, source: entry.source ?? "remote", manifest_sha256: registryDigest(item.manifest), ...entry.bundle_sha256 ? { bundle_sha256: entry.bundle_sha256 } : {} };
44136
44552
  }
44137
44553
  writeLock(lock);
44138
44554
  if (!db)
@@ -44159,16 +44575,16 @@ async function commitSyncArtifacts(staged, apiUrl, remoteLock) {
44159
44575
  }
44160
44576
  }
44161
44577
  async function fetchPinnedHook(name, version2, apiUrl, apiKey) {
44162
- const remoteLock = await fetchJson(apiUrl, "/api/v1/lock", apiKey);
44578
+ const remoteLock = await fetchJson(apiUrl, "/v1/lock", apiKey);
44163
44579
  const entry = remoteLock.hooks?.[name];
44164
44580
  if (!entry) {
44165
44581
  throw new Error(`Hook '${name}' is not in the remote registry lock`);
44166
44582
  }
44167
44583
  const isLatest = entry.version === version2;
44168
- if (!isLatest && !(entry.versions ?? []).includes(version2)) {
44584
+ if (!remoteLock.profile && !isLatest && !(entry.versions ?? []).includes(version2)) {
44169
44585
  throw new Error(`Hook '${name}' version ${version2} is not in the remote registry (available: ${[entry.version, ...entry.versions ?? []].join(", ")})`);
44170
44586
  }
44171
- const artifact = await fetchJson(apiUrl, `/api/v1/hooks/${encodeURIComponent(name)}/${encodeURIComponent(version2)}`, apiKey, { withHeader: "_headerSha" });
44587
+ const artifact = await fetchJson(apiUrl, `/v1/hooks/${encodeURIComponent(name)}/${encodeURIComponent(version2)}`, apiKey, { withHeader: "_headerSha" });
44172
44588
  if (!artifact.manifest || typeof artifact.script !== "string") {
44173
44589
  throw new Error(`artifact for '${name}@${version2}' is malformed`);
44174
44590
  }
@@ -44179,6 +44595,13 @@ async function fetchPinnedHook(name, version2, apiUrl, apiKey) {
44179
44595
  if (artifact.manifest.version !== version2) {
44180
44596
  throw new Error(`artifact for '${name}@${version2}' declares a different version ('${artifact.manifest.version}')`);
44181
44597
  }
44598
+ const bundleSha = isLatest ? entry.bundle_sha256 : artifact._bundleHeaderSha;
44599
+ if (bundleSha) {
44600
+ const canonical8 = validateRegistryArtifact({ manifest: artifact.manifest, script: artifact.script });
44601
+ if (registryDigest(canonical8) !== bundleSha)
44602
+ throw new Error("REGISTRY_BUNDLE_DIGEST_MISMATCH");
44603
+ } else if (remoteLock.profile)
44604
+ throw new Error("REGISTRY_BUNDLE_DIGEST_MISSING");
44182
44605
  const actualSha = sha256OfText(artifact.script);
44183
44606
  let expectedSha = entry.sha256;
44184
44607
  if (!isLatest) {
@@ -44193,13 +44616,14 @@ async function fetchPinnedHook(name, version2, apiUrl, apiKey) {
44193
44616
  }
44194
44617
  const manifest = parseManifest(JSON.stringify({ ...artifact.manifest, name: shortManifestName(artifact.manifest.name || name) }));
44195
44618
  const scriptRel = scriptRelFor(manifest);
44619
+ prepareRegistryCommit([{ name, version: version2, sha256: expectedSha, source: entry.source ?? "remote", manifest, scriptContent: artifact.script, scriptRel }]);
44196
44620
  writeCustomHook(name, manifest, artifact.script, scriptRel);
44197
44621
  const scriptPath = resolveScriptPath(name);
44198
44622
  const actual = await sha256File(scriptPath);
44199
44623
  if (actual !== expectedSha) {
44200
44624
  throw new Error(`sha256 mismatch after write for '${name}@${version2}': expected ${expectedSha}, on disk ${actual}`);
44201
44625
  }
44202
- setPinnedHook(name, { version: version2, sha256: expectedSha, source: entry.source ?? "remote", pinned: true });
44626
+ setPinnedHook(name, { version: version2, sha256: expectedSha, source: entry.source ?? "remote", pinned: true, manifest_sha256: registryDigest(manifest), ...bundleSha ? { bundle_sha256: bundleSha } : {} });
44203
44627
  if (!isLocalStoreRefused()) {
44204
44628
  upsertHookRecord(getDb(), {
44205
44629
  name,
@@ -44256,7 +44680,7 @@ async function installPinnedFromBundled(name, version2) {
44256
44680
  init_manifest();
44257
44681
  init_store();
44258
44682
  import { readFileSync as readFileSync17 } from "fs";
44259
- import { dirname as dirname21, join as join24 } from "path";
44683
+ import { dirname as dirname23, join as join27 } from "path";
44260
44684
  import { fileURLToPath as fileURLToPath5 } from "url";
44261
44685
 
44262
44686
  // src/lib/secure-compare.ts
@@ -44279,7 +44703,7 @@ function buildOpenApiDocument(version2) {
44279
44703
  info: {
44280
44704
  title: "Hooks Registry API",
44281
44705
  version: version2,
44282
- description: "Local registry HTTP API for @hasna/hooks: catalog, lock, and artifact reads are open; publishing (PUT /api/v1/hooks) requires the API key (authorization: Bearer or x-api-key)."
44706
+ description: "Authenticated hosted registry for @hasna/hooks: immutable executable artifacts and version-guarded selection profiles. Canonical /v1 routes require PostgreSQL; legacy /api/v1 self-hosted routes remain compatible."
44283
44707
  },
44284
44708
  servers: [{ url: "/" }],
44285
44709
  paths: {
@@ -44301,7 +44725,7 @@ function buildOpenApiDocument(version2) {
44301
44725
  },
44302
44726
  "/ready": {
44303
44727
  get: {
44304
- summary: "Readiness probe \u2014 the hooks.lock store is readable",
44728
+ summary: "Readiness probe \u2014 hosted registry tables are readable",
44305
44729
  operationId: "getReady",
44306
44730
  responses: {
44307
44731
  "200": {
@@ -44355,10 +44779,11 @@ function buildOpenApiDocument(version2) {
44355
44779
  }
44356
44780
  }
44357
44781
  },
44358
- "/api/v1/catalog": {
44782
+ "/v1/catalog": {
44359
44783
  get: {
44360
44784
  summary: "List the full hook catalog with versions and sha256",
44361
44785
  operationId: "getCatalog",
44786
+ security: [{ apiKey: [] }],
44362
44787
  responses: {
44363
44788
  "200": {
44364
44789
  description: "Catalog entries",
@@ -44371,10 +44796,12 @@ function buildOpenApiDocument(version2) {
44371
44796
  }
44372
44797
  }
44373
44798
  },
44374
- "/api/v1/lock": {
44799
+ "/v1/lock": {
44375
44800
  get: {
44376
44801
  summary: "Read the published hooks.lock with per-hook versions",
44377
44802
  operationId: "getLock",
44803
+ parameters: [{ name: "profile", in: "query", required: false, schema: { type: "string", default: "fleet" } }],
44804
+ security: [{ apiKey: [] }],
44378
44805
  responses: {
44379
44806
  "200": {
44380
44807
  description: "The lock file",
@@ -44387,10 +44814,11 @@ function buildOpenApiDocument(version2) {
44387
44814
  }
44388
44815
  }
44389
44816
  },
44390
- "/api/v1/hooks/{name}/{version}": {
44817
+ "/v1/hooks/{name}/{version}": {
44391
44818
  get: {
44392
44819
  summary: "Fetch one hook's manifest and script",
44393
44820
  operationId: "getHookArtifact",
44821
+ security: [{ apiKey: [] }],
44394
44822
  parameters: [
44395
44823
  { name: "name", in: "path", required: true, schema: { type: "string" } },
44396
44824
  { name: "version", in: "path", required: true, schema: { type: "string" } }
@@ -44399,6 +44827,7 @@ function buildOpenApiDocument(version2) {
44399
44827
  "200": {
44400
44828
  description: "Hook artifact; x-hook-sha256 header carries the script hash",
44401
44829
  headers: {
44830
+ "x-hook-bundle-sha256": { description: "SHA256 of canonical manifest and script", schema: { type: "string" } },
44402
44831
  "x-hook-sha256": {
44403
44832
  description: "sha256 of the served script, the same value the lock pins",
44404
44833
  schema: { type: "string" }
@@ -44419,7 +44848,7 @@ function buildOpenApiDocument(version2) {
44419
44848
  }
44420
44849
  },
44421
44850
  "404": {
44422
- description: "Hook not found locally",
44851
+ description: "Exact published version not found",
44423
44852
  content: {
44424
44853
  "application/json": {
44425
44854
  schema: { $ref: "#/components/schemas/HooksError" }
@@ -44429,9 +44858,26 @@ function buildOpenApiDocument(version2) {
44429
44858
  }
44430
44859
  }
44431
44860
  },
44432
- "/api/v1/hooks": {
44861
+ "/v1/selections/{profile}": {
44862
+ get: {
44863
+ summary: "Read one exact hosted selection profile",
44864
+ operationId: "getSelection",
44865
+ parameters: [{ name: "profile", in: "path", required: true, schema: { type: "string" } }],
44866
+ security: [{ apiKey: [] }],
44867
+ responses: { "200": { description: "Current exact selection", content: { "application/json": { schema: { $ref: "#/components/schemas/HooksLock" } } } } }
44868
+ },
44869
+ put: {
44870
+ summary: "Append a selection revision under its exact predecessor guard",
44871
+ operationId: "putSelection",
44872
+ parameters: [{ name: "profile", in: "path", required: true, schema: { type: "string" } }],
44873
+ security: [{ apiKey: [] }],
44874
+ requestBody: { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/HooksSelectionRequest" } } } },
44875
+ responses: { "200": { description: "Accepted or idempotently reconciled selection", content: { "application/json": { schema: { $ref: "#/components/schemas/HooksLock" } } } }, "409": { description: "Stale revision or mismatched artifact digest" } }
44876
+ }
44877
+ },
44878
+ "/v1/hooks": {
44433
44879
  put: {
44434
- summary: "Publish/retrust a hook (requires the API key)",
44880
+ summary: "Publish an immutable executable artifact (requires the API key)",
44435
44881
  operationId: "putHook",
44436
44882
  requestBody: {
44437
44883
  required: true,
@@ -44443,7 +44889,7 @@ function buildOpenApiDocument(version2) {
44443
44889
  },
44444
44890
  responses: {
44445
44891
  "200": {
44446
- description: "Hook retrusted and pin updated",
44892
+ description: "Immutable artifact accepted or identical prior publication reconciled",
44447
44893
  content: {
44448
44894
  "application/json": {
44449
44895
  schema: { $ref: "#/components/schemas/HooksPublishResponse" }
@@ -44475,7 +44921,7 @@ function buildOpenApiDocument(version2) {
44475
44921
  }
44476
44922
  },
44477
44923
  "409": {
44478
- description: "Version mismatch with the local store",
44924
+ description: "Conflicting bytes for an existing name and version",
44479
44925
  content: {
44480
44926
  "application/json": {
44481
44927
  schema: { $ref: "#/components/schemas/HooksError" }
@@ -44519,6 +44965,7 @@ function buildOpenApiDocument(version2) {
44519
44965
  name: { type: "string" },
44520
44966
  version: { type: "string" },
44521
44967
  sha256: { type: "string" },
44968
+ bundle_sha256: { type: "string" },
44522
44969
  events: { type: "array", items: { type: "string" } },
44523
44970
  description: { type: "string" },
44524
44971
  source: {
@@ -44543,6 +44990,7 @@ function buildOpenApiDocument(version2) {
44543
44990
  properties: {
44544
44991
  version: { type: "string" },
44545
44992
  sha256: { type: "string" },
44993
+ bundle_sha256: { type: "string" },
44546
44994
  source: { type: "string" },
44547
44995
  pinned: {
44548
44996
  type: "boolean",
@@ -44556,6 +45004,8 @@ function buildOpenApiDocument(version2) {
44556
45004
  additionalProperties: false,
44557
45005
  required: ["hooks"],
44558
45006
  properties: {
45007
+ profile: { type: "string" },
45008
+ revision: { type: "integer" },
44559
45009
  hooks: {
44560
45010
  type: "object",
44561
45011
  additionalProperties: { $ref: "#/components/schemas/HooksLockEntry" }
@@ -44565,14 +45015,15 @@ function buildOpenApiDocument(version2) {
44565
45015
  HooksManifest: {
44566
45016
  type: "object",
44567
45017
  additionalProperties: false,
44568
- required: ["name", "version", "events", "script"],
45018
+ required: ["name", "version", "events", "script", "script_kind"],
44569
45019
  properties: {
45020
+ nativeTargetDispatch: { type: "boolean", description: "Pass the trusted installed target through the Hooks runner" },
44570
45021
  name: { type: "string" },
44571
45022
  version: { type: "string" },
44572
45023
  description: { type: "string" },
44573
45024
  events: { type: "array", items: { type: "string" } },
44574
- script: { type: "string" },
44575
- script_kind: { type: "string", enum: ["inline", "file"] },
45025
+ script: { type: "string", enum: ["hook.js"] },
45026
+ script_kind: { type: "string", enum: ["file"] },
44576
45027
  args: { type: "array", items: { type: "string" } },
44577
45028
  timeout_ms: { type: "number" }
44578
45029
  }
@@ -44595,10 +45046,16 @@ function buildOpenApiDocument(version2) {
44595
45046
  HooksPublishRequest: {
44596
45047
  type: "object",
44597
45048
  additionalProperties: false,
44598
- required: ["name"],
45049
+ required: ["manifest", "script"],
45050
+ properties: { manifest: { $ref: "#/components/schemas/HooksManifest" }, script: { type: "string" } }
45051
+ },
45052
+ HooksSelectionRequest: {
45053
+ type: "object",
45054
+ additionalProperties: false,
45055
+ required: ["expected_revision", "hooks"],
44599
45056
  properties: {
44600
- name: { type: "string" },
44601
- version: { type: "string" }
45057
+ expected_revision: { type: "integer", minimum: 0 },
45058
+ hooks: { type: "object", additionalProperties: { type: "object", additionalProperties: false, required: ["version", "bundle_sha256"], properties: { version: { type: "string" }, bundle_sha256: { type: "string", pattern: "^[a-f0-9]{64}$" } } } }
44602
45059
  }
44603
45060
  },
44604
45061
  HooksPublishResponse: {
@@ -44607,6 +45064,7 @@ function buildOpenApiDocument(version2) {
44607
45064
  required: ["ok", "hook"],
44608
45065
  properties: {
44609
45066
  ok: { type: "boolean" },
45067
+ idempotent: { type: "boolean" },
44610
45068
  hook: {
44611
45069
  type: "object",
44612
45070
  additionalProperties: false,
@@ -44614,7 +45072,8 @@ function buildOpenApiDocument(version2) {
44614
45072
  properties: {
44615
45073
  name: { type: "string" },
44616
45074
  version: { type: "string" },
44617
- sha256: { type: "string" }
45075
+ sha256: { type: "string" },
45076
+ bundle_sha256: { type: "string" }
44618
45077
  }
44619
45078
  }
44620
45079
  }
@@ -44626,12 +45085,948 @@ function buildOpenApiDocument(version2) {
44626
45085
 
44627
45086
  // src/serve.ts
44628
45087
  init_semver();
45088
+
45089
+ // src/lib/hosted-registry.ts
45090
+ init_semver();
45091
+ init_registry_artifact();
45092
+
45093
+ // src/lib/legacy-registry-artifact.ts
45094
+ init_registry_artifact();
45095
+ init_semver();
45096
+ function validateLegacyArtifact(wire, name, version2, expectedScript) {
45097
+ try {
45098
+ const value = JSON.parse(wire), manifest = value?.manifest;
45099
+ if (!REGISTRY_NAME.test(name) || !SEMVER_PATTERN.test(version2) || Buffer.byteLength(wire) > REGISTRY_MAX_BYTES || !manifest || typeof manifest !== "object" || Array.isArray(manifest) || manifest.name !== name || manifest.version !== version2 || typeof value.script !== "string" || !value.script || scriptDigest(value.script) !== expectedScript)
45100
+ throw new Error;
45101
+ return value;
45102
+ } catch {
45103
+ throw new RegistryError(400, "REGISTRY_LEGACY_ARTIFACT_INVALID");
45104
+ }
45105
+ }
45106
+ function validateLegacyCatalog(value) {
45107
+ const row = value;
45108
+ if (!row || typeof row !== "object" || Array.isArray(row) || typeof row.name !== "string" || !REGISTRY_NAME.test(row.name) || typeof row.version !== "string" || !SEMVER_PATTERN.test(row.version) || typeof row.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(row.sha256) || !Array.isArray(row.versions) || row.versions.length !== 1 || row.versions[0] !== row.version || typeof row.source !== "string" || row.description !== undefined && typeof row.description !== "string" || row.events !== undefined && (!Array.isArray(row.events) || row.events.some((e2) => typeof e2 !== "string")))
45109
+ throw new RegistryError(400, "REGISTRY_LEGACY_CATALOG_INVALID");
45110
+ return row;
45111
+ }
45112
+ function readLegacyRegistryRow(row) {
45113
+ try {
45114
+ if (row.artifact_format !== "legacy-raw-v1" || scriptDigest(row.artifact_json) !== row.bundle_sha256 || !row.catalog_json || !row.catalog_sha256)
45115
+ throw new Error;
45116
+ const catalog = validateLegacyCatalog(JSON.parse(row.catalog_json));
45117
+ if (registryDigest(catalog) !== row.catalog_sha256 || catalog.name !== row.name || catalog.version !== row.version || catalog.sha256 !== row.script_sha256)
45118
+ throw new Error;
45119
+ const artifact = validateLegacyArtifact(row.artifact_json, row.name, row.version, row.script_sha256);
45120
+ return { artifact, catalog };
45121
+ } catch {
45122
+ throw new RegistryError(503, "REGISTRY_LEGACY_INTEGRITY_FAILED");
45123
+ }
45124
+ }
45125
+
45126
+ // src/lib/hosted-registry.ts
45127
+ class PgRegistryStore {
45128
+ db;
45129
+ constructor(db) {
45130
+ this.db = db;
45131
+ }
45132
+ async ready() {
45133
+ await this.db.all("SELECT name, artifact_format, catalog_json, catalog_sha256 FROM hooks_registry_versions LIMIT 0");
45134
+ await this.db.all("SELECT profile FROM hooks_registry_selections LIMIT 0");
45135
+ await this.db.all("SELECT export_sha256 FROM hooks_registry_legacy_imports LIMIT 0");
45136
+ }
45137
+ async versions() {
45138
+ return await this.db.all("SELECT name, version, bundle_sha256, script_sha256, artifact_json, artifact_format, catalog_json, catalog_sha256 FROM hooks_registry_versions ORDER BY name, version");
45139
+ }
45140
+ async version(name, version2) {
45141
+ return (await this.db.all("SELECT name, version, bundle_sha256, script_sha256, artifact_json, artifact_format, catalog_json, catalog_sha256 FROM hooks_registry_versions WHERE name = ? AND version = ?", name, version2))[0] ?? null;
45142
+ }
45143
+ async insertVersion(row) {
45144
+ return (await this.db.run("INSERT INTO hooks_registry_versions (name,version,bundle_sha256,script_sha256,artifact_json) VALUES (?,?,?,?,?) ON CONFLICT (name,version) DO NOTHING", row.name, row.version, row.bundle_sha256, row.script_sha256, row.artifact_json)).changes === 1;
45145
+ }
45146
+ async selection(profile) {
45147
+ const row = (await this.db.all("SELECT selection_json, selection_sha256 FROM hooks_registry_selections WHERE profile = ? ORDER BY revision DESC LIMIT 1", profile))[0];
45148
+ if (!row)
45149
+ return null;
45150
+ const selection = JSON.parse(row.selection_json);
45151
+ if (registryDigest(selection) !== row.selection_sha256)
45152
+ throw new RegistryError(503, "REGISTRY_SELECTION_INTEGRITY_FAILED");
45153
+ return selection;
45154
+ }
45155
+ async insertSelection(selection, expectedRevision) {
45156
+ return (await this.db.run(`INSERT INTO hooks_registry_selections (profile,revision,selection_json,selection_sha256)
45157
+ SELECT ?,?,?,? WHERE COALESCE((SELECT MAX(revision) FROM hooks_registry_selections WHERE profile = ?),0) = ?
45158
+ ON CONFLICT (profile,revision) DO NOTHING`, selection.profile, selection.revision, canonicalJson(selection), registryDigest(selection), selection.profile, expectedRevision)).changes === 1;
45159
+ }
45160
+ }
45161
+
45162
+ class HostedRegistry {
45163
+ store;
45164
+ constructor(store) {
45165
+ this.store = store;
45166
+ }
45167
+ async ready() {
45168
+ await this.store.ready?.();
45169
+ }
45170
+ async publish(value) {
45171
+ const artifact = validateRegistryArtifact(value), { name, version: version2 } = artifact.manifest;
45172
+ const row = { name, version: version2, bundle_sha256: registryDigest(artifact), script_sha256: scriptDigest(artifact.script), artifact_json: canonicalJson(artifact) };
45173
+ const inserted = await this.store.insertVersion(row);
45174
+ if (!inserted) {
45175
+ const previous = await this.store.version(name, version2);
45176
+ if (!previous || previous.artifact_format === "legacy-raw-v1" || previous.artifact_json !== row.artifact_json || previous.bundle_sha256 !== row.bundle_sha256)
45177
+ throw new RegistryError(409, "REGISTRY_VERSION_CONFLICT");
45178
+ }
45179
+ return { ok: true, idempotent: !inserted, hook: { name, version: version2, sha256: row.script_sha256, bundle_sha256: row.bundle_sha256, source: "hosted" } };
45180
+ }
45181
+ async artifact(name, version2) {
45182
+ const row = await this.store.version(name, version2);
45183
+ if (!row)
45184
+ throw new RegistryError(404, "REGISTRY_VERSION_NOT_FOUND");
45185
+ if (row.artifact_format === "legacy-raw-v1")
45186
+ throw new RegistryError(409, "REGISTRY_LEGACY_ARTIFACT_NOT_PORTABLE");
45187
+ const artifact = validateRegistryArtifact(JSON.parse(row.artifact_json));
45188
+ if (artifact.manifest.name !== name || artifact.manifest.version !== version2 || registryDigest(artifact) !== row.bundle_sha256 || scriptDigest(artifact.script) !== row.script_sha256)
45189
+ throw new RegistryError(503, "REGISTRY_ARTIFACT_INTEGRITY_FAILED");
45190
+ return { artifact, row };
45191
+ }
45192
+ async artifactWire(name, version2) {
45193
+ const row = await this.store.version(name, version2);
45194
+ if (!row)
45195
+ throw new RegistryError(404, "REGISTRY_VERSION_NOT_FOUND");
45196
+ if (row.artifact_format === "legacy-raw-v1") {
45197
+ readLegacyRegistryRow(row);
45198
+ return { body: row.artifact_json, row, format: "legacy-raw-v1", portable: false };
45199
+ }
45200
+ const valid2 = await this.artifact(name, version2);
45201
+ return { body: valid2.row.artifact_json, row: valid2.row, format: "portable-v1", portable: true };
45202
+ }
45203
+ async catalog() {
45204
+ const rows = await this.store.versions(), groups = new Map;
45205
+ for (const row of rows)
45206
+ groups.set(row.name, [...groups.get(row.name) ?? [], row]);
45207
+ return { hooks: [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, versions]) => {
45208
+ versions.sort((a, b) => compareVersions(b.version, a.version) || b.version.localeCompare(a.version));
45209
+ const row = versions[0];
45210
+ if (row.artifact_format === "legacy-raw-v1") {
45211
+ const { catalog } = readLegacyRegistryRow(row);
45212
+ return { ...catalog, name, version: row.version, sha256: row.script_sha256, bundle_sha256: row.bundle_sha256, source: "hosted", format: "legacy-raw-v1", portable: false, versions: versions.map((v) => v.version) };
45213
+ }
45214
+ const artifact = validateRegistryArtifact(JSON.parse(row.artifact_json));
45215
+ if (artifact.manifest.name !== name || artifact.manifest.version !== row.version || registryDigest(artifact) !== row.bundle_sha256 || scriptDigest(artifact.script) !== row.script_sha256)
45216
+ throw new RegistryError(503, "REGISTRY_ARTIFACT_INTEGRITY_FAILED");
45217
+ return { name, version: row.version, sha256: row.script_sha256, bundle_sha256: row.bundle_sha256, description: artifact.manifest.description ?? "", events: artifact.manifest.events, source: "hosted", format: "portable-v1", portable: true, versions: versions.map((v) => v.version) };
45218
+ }) };
45219
+ }
45220
+ async selection(profile) {
45221
+ if (!REGISTRY_NAME.test(profile))
45222
+ throw new RegistryError(400, "REGISTRY_PROFILE_INVALID");
45223
+ const selection = await this.store.selection(profile);
45224
+ if (!selection)
45225
+ throw new RegistryError(404, "REGISTRY_SELECTION_NOT_FOUND");
45226
+ return selection;
45227
+ }
45228
+ async select(profile, value) {
45229
+ const body = value;
45230
+ if (!REGISTRY_NAME.test(profile) || !body || !Number.isSafeInteger(body.expected_revision) || body.expected_revision < 0 || body.expected_revision >= 2147483647 || !body.hooks || typeof body.hooks !== "object" || Array.isArray(body.hooks) || Object.keys(body).some((k) => !["expected_revision", "hooks"].includes(k)) || Object.keys(body.hooks).length > 256)
45231
+ throw new RegistryError(400, "REGISTRY_SELECTION_INVALID");
45232
+ const hooks = {};
45233
+ for (const [name, pin2] of Object.entries(body.hooks)) {
45234
+ if (!REGISTRY_NAME.test(name) || !pin2 || typeof pin2 !== "object" || Object.keys(pin2).some((k) => !["version", "bundle_sha256"].includes(k)) || typeof pin2.version !== "string" || typeof pin2.bundle_sha256 !== "string" || !/^[a-f0-9]{64}$/.test(pin2.bundle_sha256))
45235
+ throw new RegistryError(400, "REGISTRY_SELECTION_INVALID");
45236
+ const { row } = await this.artifact(name, pin2.version);
45237
+ if (pin2.bundle_sha256 !== row.bundle_sha256)
45238
+ throw new RegistryError(409, "REGISTRY_SELECTION_DIGEST_MISMATCH");
45239
+ hooks[name] = { version: row.version, sha256: row.script_sha256, bundle_sha256: row.bundle_sha256, source: "hosted" };
45240
+ }
45241
+ const next = { profile, revision: body.expected_revision + 1, hooks };
45242
+ if (await this.store.insertSelection(next, body.expected_revision))
45243
+ return next;
45244
+ const current2 = await this.store.selection(profile);
45245
+ if (current2 && canonicalJson(current2) === canonicalJson(next))
45246
+ return current2;
45247
+ throw new RegistryError(409, "REGISTRY_SELECTION_PRECONDITION_FAILED");
45248
+ }
45249
+ }
45250
+
45251
+ // src/registry-http.ts
45252
+ init_registry_artifact();
45253
+
45254
+ // node_modules/@hasna/contracts/dist/auth/index.js
45255
+ import { createHash as createHash13, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
45256
+ var MAX_TENANT_ID_LENGTH = 64;
45257
+ var TENANT_ID_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${MAX_TENANT_ID_LENGTH - 1}}$`);
45258
+ var UUID_HEX = "[0-9a-fA-F]";
45259
+ var UUID_PATTERN = new RegExp(`^\\{?(?:${UUID_HEX}{8}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{12}|${UUID_HEX}{32})\\}?$`);
45260
+ function isValidTenantId(value) {
45261
+ return typeof value === "string" && TENANT_ID_PATTERN.test(value);
45262
+ }
45263
+ function isUuidTenantId(value) {
45264
+ return typeof value === "string" && UUID_PATTERN.test(value);
45265
+ }
45266
+ function canonicalizeTenantId(value) {
45267
+ if (!isUuidTenantId(value))
45268
+ return value;
45269
+ const hex3 = value.replace(/[{}-]/g, "").toLowerCase();
45270
+ return `${hex3.slice(0, 8)}-${hex3.slice(8, 12)}-${hex3.slice(12, 16)}-${hex3.slice(16, 20)}-${hex3.slice(20)}`;
45271
+ }
45272
+ function normalizeTenantId(value) {
45273
+ const trimmed = typeof value === "string" ? value.trim() : "";
45274
+ const canonical8 = canonicalizeTenantId(trimmed);
45275
+ if (!isValidTenantId(canonical8)) {
45276
+ throw new Error(`Invalid tenant id '${value}'. Expected 1-${MAX_TENANT_ID_LENGTH} characters matching ${TENANT_ID_PATTERN} (a UUID, ULID, slug, or prefixed id).`);
45277
+ }
45278
+ return canonical8;
45279
+ }
45280
+ function tenantIdsEqual(left, right) {
45281
+ const canonical8 = (value) => {
45282
+ if (typeof value !== "string")
45283
+ return null;
45284
+ const folded = canonicalizeTenantId(value.trim());
45285
+ return isValidTenantId(folded) ? folded : null;
45286
+ };
45287
+ const a = canonical8(left);
45288
+ const b = canonical8(right);
45289
+ return a !== null && b !== null && a === b;
45290
+ }
45291
+ function ownTenantId(source) {
45292
+ return Object.hasOwn(source, "tid") ? source.tid : undefined;
45293
+ }
45294
+ var API_KEY_TOKEN_VERSION = 1;
45295
+ var API_KEY_NAMESPACE = "hasna";
45296
+ var API_KEY_TOKEN_PATTERN = /^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/;
45297
+ var TOKEN_PATTERN = API_KEY_TOKEN_PATTERN;
45298
+ var DEFAULT_API_KEY_TTL_SECONDS = 90 * 24 * 60 * 60;
45299
+ function ownAgentClaim(source) {
45300
+ return Object.hasOwn(source, "agent") && typeof source.agent === "string" ? source.agent : null;
45301
+ }
45302
+ function ownScopesClaim(source) {
45303
+ return Object.hasOwn(source, "scopes") && Array.isArray(source.scopes) ? source.scopes : null;
45304
+ }
45305
+ function ownOption(options, name) {
45306
+ return Object.hasOwn(options, name) ? options[name] : undefined;
45307
+ }
45308
+ var typedArrayPrototype2 = Object.getPrototypeOf(Uint8Array.prototype);
45309
+ var intrinsicViewBuffer = Object.getOwnPropertyDescriptor(typedArrayPrototype2, "buffer").get;
45310
+ var intrinsicViewByteOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype2, "byteOffset").get;
45311
+ var intrinsicViewByteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype2, "byteLength").get;
45312
+ var intrinsicDataViewBuffer = Object.getOwnPropertyDescriptor(DataView.prototype, "buffer").get;
45313
+ var intrinsicDataViewByteOffset = Object.getOwnPropertyDescriptor(DataView.prototype, "byteOffset").get;
45314
+ var intrinsicDataViewByteLength = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get;
45315
+ function viewWindow(view) {
45316
+ try {
45317
+ return [
45318
+ intrinsicViewBuffer.call(view),
45319
+ intrinsicViewByteOffset.call(view),
45320
+ intrinsicViewByteLength.call(view)
45321
+ ];
45322
+ } catch {
45323
+ return [
45324
+ intrinsicDataViewBuffer.call(view),
45325
+ intrinsicDataViewByteOffset.call(view),
45326
+ intrinsicDataViewByteLength.call(view)
45327
+ ];
45328
+ }
45329
+ }
45330
+ function toBuffer(secret) {
45331
+ if (typeof secret === "string")
45332
+ return Buffer.from(secret.trim(), "utf8");
45333
+ if (ArrayBuffer.isView(secret)) {
45334
+ const [store, byteOffset, byteLength] = viewWindow(secret);
45335
+ return Buffer.from(store, byteOffset, byteLength);
45336
+ }
45337
+ return Buffer.from(secret);
45338
+ }
45339
+ function hmac(signingSecret, message) {
45340
+ return createHmac("sha256", toBuffer(signingSecret)).update(message, "utf8").digest();
45341
+ }
45342
+ function apiKeyPrefix(app) {
45343
+ return `${API_KEY_NAMESPACE}_${app}_`;
45344
+ }
45345
+ function parseApiKey(token) {
45346
+ if (typeof token !== "string")
45347
+ return null;
45348
+ const match = TOKEN_PATTERN.exec(token);
45349
+ if (!match)
45350
+ return null;
45351
+ const [, app, body, sig] = match;
45352
+ if (!app || !body || !sig)
45353
+ return null;
45354
+ let claims;
45355
+ try {
45356
+ claims = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
45357
+ } catch {
45358
+ return null;
45359
+ }
45360
+ if (typeof claims !== "object" || claims === null || typeof claims.kid !== "string" || typeof claims.app !== "string" || ownScopesClaim(claims) === null) {
45361
+ return null;
45362
+ }
45363
+ const claimedTid = ownTenantId(claims);
45364
+ if (claimedTid !== undefined && !isValidTenantId(claimedTid)) {
45365
+ return null;
45366
+ }
45367
+ return { app, body, sig, claims };
45368
+ }
45369
+ function verifyApiKeyToken(token, options) {
45370
+ const optSigningSecret = ownOption(options, "signingSecret");
45371
+ const optExpectedApp = ownOption(options, "expectedApp");
45372
+ const optNowMs = ownOption(options, "nowMs");
45373
+ const optLeewaySeconds = ownOption(options, "leewaySeconds");
45374
+ const optRequiredScopes = ownOption(options, "requiredScopes");
45375
+ const optRequireTenant = ownOption(options, "requireTenant");
45376
+ const optExpectedTid = ownOption(options, "expectedTid");
45377
+ const parsed = parseApiKey(token);
45378
+ if (!parsed) {
45379
+ return { ok: false, reason: "malformed", message: "Token is malformed." };
45380
+ }
45381
+ const { app, body, sig, claims } = parsed;
45382
+ if (claims.v !== API_KEY_TOKEN_VERSION) {
45383
+ return { ok: false, reason: "unsupported_version", message: `Unsupported token version ${claims.v}.` };
45384
+ }
45385
+ if (claims.app !== app) {
45386
+ return { ok: false, reason: "app_mismatch", message: "Token prefix app does not match claims." };
45387
+ }
45388
+ if (optExpectedApp !== undefined && app !== optExpectedApp) {
45389
+ return { ok: false, reason: "app_mismatch", message: `Token is for app '${app}', expected '${optExpectedApp}'.` };
45390
+ }
45391
+ const expected = hmac(optSigningSecret, `${apiKeyPrefix(app)}${body}`);
45392
+ let provided;
45393
+ try {
45394
+ provided = Buffer.from(sig, "base64url");
45395
+ } catch {
45396
+ return { ok: false, reason: "bad_signature", message: "Signature is not valid base64url." };
45397
+ }
45398
+ if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
45399
+ return { ok: false, reason: "bad_signature", message: "Signature verification failed." };
45400
+ }
45401
+ const agent = ownAgentClaim(claims);
45402
+ const now = Math.floor((optNowMs ?? Date.now()) / 1000);
45403
+ const leeway = optLeewaySeconds ?? 0;
45404
+ if (typeof claims.iat === "number" && now + leeway < claims.iat) {
45405
+ return { ok: false, reason: "not_yet_valid", message: "Token is not yet valid.", agent };
45406
+ }
45407
+ if (claims.exp !== null && typeof claims.exp === "number" && now - leeway >= claims.exp) {
45408
+ return { ok: false, reason: "expired", message: "Token has expired.", agent };
45409
+ }
45410
+ const verifiedTid = ownTenantId(claims);
45411
+ const tid = verifiedTid === undefined ? null : canonicalizeTenantId(verifiedTid);
45412
+ const tenantRequired = Boolean(optRequireTenant) || optExpectedTid !== undefined;
45413
+ if (tenantRequired && tid === null) {
45414
+ return {
45415
+ ok: false,
45416
+ reason: "tenant_required",
45417
+ message: "Token carries no tenant id ('tid') and this service requires one.",
45418
+ kid: claims.kid,
45419
+ tid: null,
45420
+ agent
45421
+ };
45422
+ }
45423
+ if (optExpectedTid !== undefined && !tenantIdsEqual(tid, optExpectedTid)) {
45424
+ const expectationIsWellFormed = typeof optExpectedTid === "string" && isValidTenantId(optExpectedTid.trim());
45425
+ return {
45426
+ ok: false,
45427
+ reason: "tenant_mismatch",
45428
+ message: expectationIsWellFormed ? "Token is for a different tenant than the one this service accepts." : "Token tenant cannot be checked: the expected tenant id is not a valid tenant id.",
45429
+ kid: claims.kid,
45430
+ tid,
45431
+ agent
45432
+ };
45433
+ }
45434
+ if (optRequiredScopes && optRequiredScopes.length > 0) {
45435
+ const granted = ownScopesClaim(claims) ?? [];
45436
+ const satisfies = (required2) => granted.some((g) => {
45437
+ if (g === "*")
45438
+ return true;
45439
+ const gi = g.indexOf(":");
45440
+ const ri = required2.indexOf(":");
45441
+ if (gi < 0 || ri < 0)
45442
+ return false;
45443
+ const gApp = g.slice(0, gi);
45444
+ const gAction = g.slice(gi + 1);
45445
+ const rApp = required2.slice(0, ri);
45446
+ const rAction = required2.slice(ri + 1);
45447
+ return (gApp === "*" || gApp === rApp) && (gAction === "*" || gAction === rAction);
45448
+ });
45449
+ for (const required2 of optRequiredScopes) {
45450
+ if (!satisfies(required2)) {
45451
+ return { ok: false, reason: "insufficient_scope", message: `Missing required scope '${required2}'.`, agent };
45452
+ }
45453
+ }
45454
+ }
45455
+ return { ok: true, claims, kid: claims.kid, app, tid, agent };
45456
+ }
45457
+ var DEFAULT_API_KEYS_TABLE = "api_keys";
45458
+ var API_KEY_ISSUANCE_PENDING_REASON = "credential_delivery_pending";
45459
+ function createTableSql(table) {
45460
+ return `CREATE TABLE IF NOT EXISTS ${table} (
45461
+ kid TEXT PRIMARY KEY,
45462
+ app TEXT NOT NULL,
45463
+ agent TEXT,
45464
+ scopes JSONB NOT NULL,
45465
+ token_hash TEXT NOT NULL UNIQUE,
45466
+ issued_at TIMESTAMPTZ NOT NULL,
45467
+ expires_at TIMESTAMPTZ,
45468
+ revoked_at TIMESTAMPTZ,
45469
+ revoked_reason TEXT,
45470
+ last_used_at TIMESTAMPTZ,
45471
+ created_by TEXT,
45472
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
45473
+ )`;
45474
+ }
45475
+ function apiKeyMigrations(table = DEFAULT_API_KEYS_TABLE) {
45476
+ return [
45477
+ { id: `hasna_auth_0001_${table}`, sql: createTableSql(table) },
45478
+ {
45479
+ id: `hasna_auth_0002_${table}_indexes`,
45480
+ sql: `CREATE INDEX IF NOT EXISTS ${table}_app_idx ON ${table} (app);
45481
+ CREATE INDEX IF NOT EXISTS ${table}_token_hash_idx ON ${table} (token_hash);`
45482
+ },
45483
+ {
45484
+ id: `hasna_auth_0003_${table}_tenant`,
45485
+ sql: `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS tid TEXT;
45486
+ CREATE INDEX IF NOT EXISTS ${table}_tid_idx ON ${table} (tid);`
45487
+ }
45488
+ ];
45489
+ }
45490
+ function toIso(value) {
45491
+ if (value === null || value === undefined)
45492
+ return null;
45493
+ if (value instanceof Date)
45494
+ return value.toISOString();
45495
+ return new Date(String(value)).toISOString();
45496
+ }
45497
+ function parseScopes(value) {
45498
+ if (Array.isArray(value))
45499
+ return value.map((v) => String(v));
45500
+ if (typeof value === "string") {
45501
+ try {
45502
+ const parsed = JSON.parse(value);
45503
+ return Array.isArray(parsed) ? parsed.map((v) => String(v)) : [];
45504
+ } catch {
45505
+ return [];
45506
+ }
45507
+ }
45508
+ return [];
45509
+ }
45510
+ function rowToRecord(row) {
45511
+ const tid = ownTenantId(row);
45512
+ const agentValue = Object.hasOwn(row, "agent") ? row.agent : null;
45513
+ return {
45514
+ kid: String(row.kid),
45515
+ app: String(row.app),
45516
+ agent: agentValue === null || agentValue === undefined ? null : String(agentValue),
45517
+ tid: tid === null || tid === undefined ? null : String(tid),
45518
+ scopes: parseScopes(row.scopes),
45519
+ tokenHash: String(row.token_hash),
45520
+ issuedAt: toIso(row.issued_at) ?? new Date(0).toISOString(),
45521
+ expiresAt: toIso(row.expires_at),
45522
+ revokedAt: toIso(row.revoked_at),
45523
+ revokedReason: row.revoked_reason === null || row.revoked_reason === undefined ? null : String(row.revoked_reason),
45524
+ lastUsedAt: toIso(row.last_used_at),
45525
+ createdBy: row.created_by === null || row.created_by === undefined ? null : String(row.created_by)
45526
+ };
45527
+ }
45528
+
45529
+ class ApiKeyStore {
45530
+ client;
45531
+ table;
45532
+ constructor(client, options = {}) {
45533
+ this.client = client;
45534
+ this.table = options.table ?? DEFAULT_API_KEYS_TABLE;
45535
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(this.table)) {
45536
+ throw new Error(`Invalid api-keys table name '${this.table}'.`);
45537
+ }
45538
+ }
45539
+ migrations() {
45540
+ return apiKeyMigrations(this.table);
45541
+ }
45542
+ async ensureSchema() {
45543
+ for (const migration of this.migrations()) {
45544
+ await this.client.execute(migration.sql);
45545
+ }
45546
+ }
45547
+ async insert(input2) {
45548
+ await this.insertWithLifecycle(input2, null, null);
45549
+ }
45550
+ async insertWithLifecycle(input2, revokedAt, revokedReason) {
45551
+ const tid = ownTenantId(input2);
45552
+ const agent = ownAgentClaim(input2);
45553
+ await this.client.execute(`INSERT INTO ${this.table}
45554
+ (kid, app, agent, tid, scopes, token_hash, issued_at, expires_at, created_by, revoked_at, revoked_reason)
45555
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10, $11)`, [
45556
+ input2.kid,
45557
+ input2.app,
45558
+ agent,
45559
+ tid === undefined || tid === null ? null : normalizeTenantId(tid),
45560
+ JSON.stringify(input2.scopes),
45561
+ input2.tokenHash,
45562
+ input2.issuedAt.toISOString(),
45563
+ input2.expiresAt ? input2.expiresAt.toISOString() : null,
45564
+ input2.createdBy ?? null,
45565
+ revokedAt,
45566
+ revokedReason
45567
+ ]);
45568
+ }
45569
+ mintedInput(minted, createdBy) {
45570
+ const claims = minted.claims;
45571
+ return {
45572
+ kid: minted.kid,
45573
+ app: claims.app,
45574
+ agent: ownAgentClaim(claims),
45575
+ tid: ownTenantId(claims) ?? null,
45576
+ scopes: claims.scopes,
45577
+ tokenHash: minted.tokenHash,
45578
+ issuedAt: new Date(claims.iat * 1000),
45579
+ expiresAt: claims.exp === null ? null : new Date(claims.exp * 1000),
45580
+ createdBy: createdBy ?? null
45581
+ };
45582
+ }
45583
+ async insertMinted(minted, createdBy) {
45584
+ await this.insert(this.mintedInput(minted, createdBy));
45585
+ }
45586
+ async insertMintedPending(minted, createdBy, atMs = Date.now()) {
45587
+ await this.insertWithLifecycle(this.mintedInput(minted, createdBy), new Date(atMs).toISOString(), API_KEY_ISSUANCE_PENDING_REASON);
45588
+ }
45589
+ async activatePending(kid, tokenHash) {
45590
+ const row = await this.client.get(`UPDATE ${this.table}
45591
+ SET revoked_at = NULL, revoked_reason = NULL
45592
+ WHERE kid = $1
45593
+ AND revoked_at IS NOT NULL
45594
+ AND revoked_reason = $2
45595
+ AND token_hash = $3
45596
+ RETURNING kid`, [kid, API_KEY_ISSUANCE_PENDING_REASON, tokenHash]);
45597
+ if (row)
45598
+ return true;
45599
+ const active = await this.client.get(`SELECT kid FROM ${this.table}
45600
+ WHERE kid = $1
45601
+ AND token_hash = $2
45602
+ AND revoked_at IS NULL
45603
+ AND revoked_reason IS NULL`, [kid, tokenHash]);
45604
+ return active !== null;
45605
+ }
45606
+ async findByKid(kid) {
45607
+ const row = await this.client.get(`SELECT * FROM ${this.table} WHERE kid = $1`, [kid]);
45608
+ return row ? rowToRecord(row) : null;
45609
+ }
45610
+ async findByTokenHash(tokenHash) {
45611
+ const row = await this.client.get(`SELECT * FROM ${this.table} WHERE token_hash = $1`, [tokenHash]);
45612
+ return row ? rowToRecord(row) : null;
45613
+ }
45614
+ isRevoked = async (kid) => {
45615
+ const row = await this.client.get(`SELECT revoked_at FROM ${this.table} WHERE kid = $1`, [kid]);
45616
+ if (!row)
45617
+ return false;
45618
+ return row.revoked_at !== null && row.revoked_at !== undefined;
45619
+ };
45620
+ async status(kid, nowMs = Date.now()) {
45621
+ const record4 = await this.findByKid(kid);
45622
+ if (!record4)
45623
+ return "unknown";
45624
+ if (record4.revokedAt)
45625
+ return "revoked";
45626
+ if (record4.expiresAt && new Date(record4.expiresAt).getTime() <= nowMs)
45627
+ return "expired";
45628
+ return "active";
45629
+ }
45630
+ keyStatus = async (kid) => {
45631
+ return this.status(kid);
45632
+ };
45633
+ statusChecker() {
45634
+ return async (kid) => {
45635
+ const status = await this.status(kid);
45636
+ return status !== "active";
45637
+ };
45638
+ }
45639
+ async revoke(kid, reason2, atMs = Date.now(), options = {}) {
45640
+ const params = [kid, new Date(atMs).toISOString(), reason2 ?? null];
45641
+ let scope = "";
45642
+ if (options.app !== undefined) {
45643
+ params.push(options.app);
45644
+ scope = ` AND app = $${params.length}`;
45645
+ }
45646
+ const row = await this.client.get(`UPDATE ${this.table}
45647
+ SET revoked_at = COALESCE(revoked_at, $2), revoked_reason = COALESCE(revoked_reason, $3)
45648
+ WHERE kid = $1${scope}
45649
+ RETURNING kid`, params);
45650
+ return row !== null;
45651
+ }
45652
+ async touchLastUsed(kid, atMs = Date.now()) {
45653
+ await this.client.execute(`UPDATE ${this.table} SET last_used_at = $2 WHERE kid = $1`, [
45654
+ kid,
45655
+ new Date(atMs).toISOString()
45656
+ ]);
45657
+ }
45658
+ async list(options = {}) {
45659
+ const clauses = [];
45660
+ const params = [];
45661
+ if (options.app) {
45662
+ params.push(options.app);
45663
+ clauses.push(`app = $${params.length}`);
45664
+ }
45665
+ const tid = ownTenantId(options);
45666
+ if (tid !== undefined) {
45667
+ params.push(normalizeTenantId(tid));
45668
+ clauses.push(`tid = $${params.length}`);
45669
+ }
45670
+ if (!options.includeRevoked) {
45671
+ clauses.push("revoked_at IS NULL");
45672
+ }
45673
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
45674
+ const rows = await this.client.many(`SELECT * FROM ${this.table} ${where} ORDER BY issued_at DESC`, params);
45675
+ return rows.map(rowToRecord);
45676
+ }
45677
+ async revokedKids() {
45678
+ const rows = await this.client.many(`SELECT kid FROM ${this.table} WHERE revoked_at IS NOT NULL`);
45679
+ return rows.map((row) => String(row.kid));
45680
+ }
45681
+ }
45682
+ function readHeader(source, name) {
45683
+ const lower = name.toLowerCase();
45684
+ if (typeof source === "function") {
45685
+ return source(name) ?? source(lower) ?? null;
45686
+ }
45687
+ if (typeof Headers !== "undefined" && source instanceof Headers) {
45688
+ return source.get(name);
45689
+ }
45690
+ const record4 = source;
45691
+ const value = record4[name] ?? record4[lower] ?? record4[name.toUpperCase()];
45692
+ if (Array.isArray(value))
45693
+ return value[0] ?? null;
45694
+ return value ?? null;
45695
+ }
45696
+ function extractToken(source, headerName = "x-api-key", scheme = "Bearer") {
45697
+ const direct = readHeader(source, headerName);
45698
+ if (direct && direct.trim().length > 0)
45699
+ return direct.trim();
45700
+ const authz = readHeader(source, "authorization");
45701
+ if (authz) {
45702
+ const prefix3 = `${scheme} `;
45703
+ if (authz.toLowerCase().startsWith(prefix3.toLowerCase())) {
45704
+ const token = authz.slice(prefix3.length).trim();
45705
+ if (token.length > 0)
45706
+ return token;
45707
+ }
45708
+ }
45709
+ return null;
45710
+ }
45711
+ function ownOption2(bag, name) {
45712
+ return Object.hasOwn(bag, name) ? bag[name] : undefined;
45713
+ }
45714
+ function verifyApiKey(options) {
45715
+ const optionApp = ownOption2(options, "app");
45716
+ const optionSigningSecret = ownOption2(options, "signingSecret");
45717
+ const optionExpectedTid = ownOption2(options, "expectedTid");
45718
+ const optionRequiredScopes = ownOption2(options, "requiredScopes");
45719
+ const optionRequireTenant = ownOption2(options, "requireTenant");
45720
+ const optionLeewaySeconds = ownOption2(options, "leewaySeconds");
45721
+ const audit = ownOption2(options, "audit");
45722
+ const headerName = ownOption2(options, "headerName") ?? "x-api-key";
45723
+ const scheme = ownOption2(options, "scheme") ?? "Bearer";
45724
+ const clock = ownOption2(options, "nowMs") ?? (() => Date.now());
45725
+ if (!optionApp)
45726
+ throw new Error("verifyApiKey requires an 'app' slug.");
45727
+ if (!optionSigningSecret) {
45728
+ throw new Error("verifyApiKey requires a 'signingSecret'. Set it from HASNA_<APP>_API_SIGNING_KEY.");
45729
+ }
45730
+ if (optionExpectedTid !== undefined && !isValidTenantId(optionExpectedTid)) {
45731
+ throw new Error(`verifyApiKey received an invalid 'expectedTid': '${optionExpectedTid}'.`);
45732
+ }
45733
+ const app = optionApp;
45734
+ const signingSecret = optionSigningSecret;
45735
+ const ownKeyStatus = ownOption2(options, "keyStatus");
45736
+ const ownIsRevoked = ownOption2(options, "isRevoked");
45737
+ const allowUnregistered = ownOption2(options, "allowUnregisteredKeys") === true;
45738
+ if (ownKeyStatus && ownIsRevoked) {
45739
+ throw new Error("verifyApiKey received both 'keyStatus' and 'isRevoked'. Supply exactly one \u2014 " + "letting one silently win would hide which check is actually guarding the service. " + "Use 'keyStatus' (store.keyStatus); drop 'isRevoked'.");
45740
+ }
45741
+ if (!ownKeyStatus && !allowUnregistered) {
45742
+ throw new Error(ownIsRevoked ? "verifyApiKey was given only 'isRevoked', which cannot refuse a key this service has " + "no record of: it returns false both for an active key and for one that was never " + "registered, so an unregistered key is irrevocable. Wire 'keyStatus: store.keyStatus' " + "(or 'isRevoked: store.statusChecker()'), or set 'allowUnregisteredKeys: true' to " + "accept that risk explicitly." : "verifyApiKey requires a key-status hook. Without one this service performs NO " + "revocation check and cannot turn any of its keys off. Wire " + "'keyStatus: store.keyStatus', or set 'allowUnregisteredKeys: true' to declare that " + "this service intentionally cannot revoke keys.");
45743
+ }
45744
+ async function emit(event) {
45745
+ if (!audit)
45746
+ return;
45747
+ try {
45748
+ await audit(event);
45749
+ } catch {}
45750
+ }
45751
+ async function authenticate(headers, context2 = {}) {
45752
+ const method = ownOption2(context2, "method") ?? null;
45753
+ const path = ownOption2(context2, "path") ?? null;
45754
+ const requiredScopes = [
45755
+ ...optionRequiredScopes ?? [],
45756
+ ...ownOption2(context2, "requiredScopes") ?? []
45757
+ ];
45758
+ const at = new Date(clock()).toISOString();
45759
+ const perCallTid = ownOption2(context2, "expectedTid");
45760
+ const expectedTid = perCallTid !== undefined ? perCallTid : optionExpectedTid;
45761
+ if (perCallTid !== undefined && optionExpectedTid !== undefined && !tenantIdsEqual(perCallTid, optionExpectedTid)) {
45762
+ await emit({ outcome: "deny", app, kid: null, tid: null, reason: "tenant_mismatch", scopesRequired: requiredScopes, method, path, status: 403, at });
45763
+ return {
45764
+ ok: false,
45765
+ status: 403,
45766
+ reason: "tenant_mismatch",
45767
+ message: "This route addresses a tenant other than the one this service is pinned to."
45768
+ };
45769
+ }
45770
+ const token = extractToken(headers, headerName, scheme);
45771
+ if (!token) {
45772
+ const decision = {
45773
+ ok: false,
45774
+ status: 401,
45775
+ reason: "missing_token",
45776
+ message: `Missing API key. Send it as '${headerName}: <key>' or 'Authorization: ${scheme} <key>'.`
45777
+ };
45778
+ await emit({ outcome: "deny", app, kid: null, tid: null, reason: "missing_token", scopesRequired: requiredScopes, method, path, status: 401, at });
45779
+ return decision;
45780
+ }
45781
+ const verified = verifyApiKeyToken(token, {
45782
+ signingSecret,
45783
+ expectedApp: app,
45784
+ nowMs: clock(),
45785
+ ...optionLeewaySeconds !== undefined ? { leewaySeconds: optionLeewaySeconds } : {},
45786
+ ...optionRequireTenant !== undefined ? { requireTenant: optionRequireTenant } : {},
45787
+ ...expectedTid !== undefined ? { expectedTid } : {},
45788
+ requiredScopes
45789
+ });
45790
+ if (!verified.ok) {
45791
+ const status = verified.reason === "insufficient_scope" || verified.reason === "tenant_mismatch" || verified.reason === "tenant_required" ? 403 : 401;
45792
+ await emit({
45793
+ outcome: "deny",
45794
+ app,
45795
+ kid: ownOption2(verified, "kid") ?? null,
45796
+ tid: ownTenantId(verified) ?? null,
45797
+ ...Object.hasOwn(verified, "agent") ? { agent: verified.agent } : {},
45798
+ reason: verified.reason,
45799
+ scopesRequired: requiredScopes,
45800
+ method,
45801
+ path,
45802
+ status,
45803
+ at
45804
+ });
45805
+ return { ok: false, status, reason: verified.reason, message: verified.message };
45806
+ }
45807
+ if (ownKeyStatus) {
45808
+ let status;
45809
+ try {
45810
+ status = await ownKeyStatus(verified.kid);
45811
+ } catch {
45812
+ await emit({ outcome: "deny", app, kid: verified.kid, tid: verified.tid, agent: verified.agent, reason: "status_unavailable", scopesRequired: requiredScopes, method, path, status: 503, at });
45813
+ return {
45814
+ ok: false,
45815
+ status: 503,
45816
+ reason: "status_unavailable",
45817
+ message: "Could not verify API key status. Try again shortly."
45818
+ };
45819
+ }
45820
+ if (status !== "active") {
45821
+ const known = status === "revoked" || status === "expired" || status === "unknown";
45822
+ if (!(status === "unknown" && allowUnregistered)) {
45823
+ const reason2 = status === "revoked" || status === "expired" ? status : "unknown_key";
45824
+ const message = reason2 === "unknown_key" ? known ? "API key is not registered with this service." : "API key status could not be recognized." : status === "expired" ? "API key has expired." : "API key has been revoked.";
45825
+ await emit({ outcome: "deny", app, kid: verified.kid, tid: verified.tid, agent: verified.agent, reason: reason2, scopesRequired: requiredScopes, method, path, status: 401, at });
45826
+ return { ok: false, status: 401, reason: reason2, message };
45827
+ }
45828
+ }
45829
+ } else if (ownIsRevoked) {
45830
+ let revoked;
45831
+ try {
45832
+ revoked = await ownIsRevoked(verified.kid);
45833
+ } catch {
45834
+ await emit({ outcome: "deny", app, kid: verified.kid, tid: verified.tid, agent: verified.agent, reason: "status_unavailable", scopesRequired: requiredScopes, method, path, status: 503, at });
45835
+ return {
45836
+ ok: false,
45837
+ status: 503,
45838
+ reason: "status_unavailable",
45839
+ message: "Could not verify API key status. Try again shortly."
45840
+ };
45841
+ }
45842
+ if (revoked) {
45843
+ await emit({ outcome: "deny", app, kid: verified.kid, tid: verified.tid, agent: verified.agent, reason: "revoked", scopesRequired: requiredScopes, method, path, status: 401, at });
45844
+ return { ok: false, status: 401, reason: "revoked", message: "API key has been revoked." };
45845
+ }
45846
+ }
45847
+ const principal = {
45848
+ kid: verified.kid,
45849
+ app: verified.app,
45850
+ scopes: verified.claims.scopes,
45851
+ agent: verified.agent,
45852
+ tid: verified.tid,
45853
+ claims: verified.claims
45854
+ };
45855
+ await emit({ outcome: "allow", app, kid: verified.kid, tid: verified.tid, agent: verified.agent, reason: null, scopesRequired: requiredScopes, method, path, status: 200, at });
45856
+ return { ok: true, status: 200, principal };
45857
+ }
45858
+ return { authenticate, app };
45859
+ }
45860
+ function envToken3(name) {
45861
+ return name.toUpperCase().replace(/-/g, "_");
45862
+ }
45863
+ var MAX_FLEET_TOKEN_TTL_SECONDS = 24 * 60 * 60;
45864
+ function signingSecretEnvKeys(app) {
45865
+ return [`HASNA_${envToken3(app)}_API_SIGNING_KEY`, "HASNA_API_SIGNING_KEY"];
45866
+ }
45867
+
45868
+ class SigningSecretError extends Error {
45869
+ attempted;
45870
+ constructor(message, attempted) {
45871
+ super(message);
45872
+ this.name = "SigningSecretError";
45873
+ this.attempted = Object.freeze([...attempted]);
45874
+ }
45875
+ }
45876
+ function signingSecretHasSurroundingWhitespace(value) {
45877
+ return value !== value.trim();
45878
+ }
45879
+ function resolveSigningSecret(app, env, options = {}) {
45880
+ const keys = options.envName ? [options.envName] : signingSecretEnvKeys(app);
45881
+ for (const key of keys) {
45882
+ const raw = env[key];
45883
+ if (raw === undefined)
45884
+ continue;
45885
+ const value = raw.trim();
45886
+ if (!value)
45887
+ continue;
45888
+ return { value, source: key, trimmed: signingSecretHasSurroundingWhitespace(raw) };
45889
+ }
45890
+ throw new SigningSecretError(`No signing secret found. Set ${keys.join(" or ")} (openssl rand -hex 32).`, keys);
45891
+ }
45892
+
45893
+ // src/registry-auth.ts
45894
+ init_registry_artifact();
45895
+ function createRegistryVerifier(signingSecret, keyStatus) {
45896
+ return verifyApiKey({ app: "hooks", signingSecret, keyStatus });
45897
+ }
45898
+ function hasRegistrySigningConfiguration() {
45899
+ return process.env.HASNA_HOOKS_API_SIGNING_KEY !== undefined || process.env.HASNA_API_SIGNING_KEY !== undefined;
45900
+ }
45901
+ var keyStore;
45902
+ function registryKeyStatus() {
45903
+ if (!keyStore) {
45904
+ const url2 = getStorageDatabaseUrl();
45905
+ if (!url2)
45906
+ throw new RegistryError(503, "REGISTRY_DATABASE_REQUIRED");
45907
+ const db = new PgAdapterAsync(url2, { timeoutMs: 5000 });
45908
+ const client = {
45909
+ many: async (sql, params) => await db.all(sql, ...params ?? []),
45910
+ get: async (sql, params) => (await db.all(sql, ...params ?? []))[0] ?? null,
45911
+ execute: async () => {
45912
+ throw new Error("REGISTRY_AUTH_READ_ONLY");
45913
+ }
45914
+ };
45915
+ keyStore = new ApiKeyStore(client);
45916
+ }
45917
+ return keyStore.keyStatus;
45918
+ }
45919
+ async function authenticateRegistryRequest(request, verifier) {
45920
+ const auth = verifier ?? createRegistryVerifier(resolveSigningSecret("hooks", process.env, process.env.HASNA_HOOKS_API_SIGNING_KEY !== undefined ? { envName: "HASNA_HOOKS_API_SIGNING_KEY" } : {}).value, registryKeyStatus());
45921
+ const decision = await auth.authenticate(request.headers, {
45922
+ method: request.method,
45923
+ path: new URL(request.url).pathname,
45924
+ requiredScopes: [request.method === "GET" ? "hooks:read" : "hooks:write"]
45925
+ });
45926
+ if (!decision.ok)
45927
+ throw new RegistryError(decision.status, "REGISTRY_AUTH_" + decision.reason.toUpperCase());
45928
+ }
45929
+
45930
+ // src/registry-http.ts
45931
+ init_local_opt_in();
45932
+ var serverRegistry;
45933
+ function configuredRegistry() {
45934
+ if (serverRegistry)
45935
+ return serverRegistry;
45936
+ if (getStorageBackend() !== "postgresql")
45937
+ throw new RegistryError(503, "REGISTRY_DATABASE_REQUIRED");
45938
+ const url2 = getStorageDatabaseUrl();
45939
+ if (!url2)
45940
+ throw new RegistryError(503, "REGISTRY_DATABASE_REQUIRED");
45941
+ serverRegistry = new HostedRegistry(new PgRegistryStore(new PgAdapterAsync(url2, { timeoutMs: 5000 })));
45942
+ return serverRegistry;
45943
+ }
45944
+ async function registryReady() {
45945
+ try {
45946
+ await configuredRegistry().ready();
45947
+ return true;
45948
+ } catch {
45949
+ return false;
45950
+ }
45951
+ }
45952
+ function json2(body, status = 200, headers = {}) {
45953
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } });
45954
+ }
45955
+ async function boundedJson2(request) {
45956
+ if (!request.body)
45957
+ throw new RegistryError(400, "REGISTRY_BODY_REQUIRED");
45958
+ const reader = request.body.getReader(), chunks = [];
45959
+ let length = 0;
45960
+ for (;; ) {
45961
+ const next = await reader.read();
45962
+ if (next.done)
45963
+ break;
45964
+ length += next.value.byteLength;
45965
+ if (length > REGISTRY_MAX_BYTES) {
45966
+ await reader.cancel();
45967
+ throw new RegistryError(413, "REGISTRY_BODY_TOO_LARGE");
45968
+ }
45969
+ chunks.push(next.value);
45970
+ }
45971
+ try {
45972
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
45973
+ } catch {
45974
+ throw new RegistryError(400, "REGISTRY_JSON_INVALID");
45975
+ }
45976
+ }
45977
+ async function handleRegistryRequest(request, key, registry2) {
45978
+ try {
45979
+ if (hasRegistrySigningConfiguration())
45980
+ await authenticateRegistryRequest(request);
45981
+ else {
45982
+ if (!isHooksLocalOptIn())
45983
+ throw new RegistryError(503, "REGISTRY_SIGNING_CONFIGURATION_REQUIRED");
45984
+ if (!key)
45985
+ throw new RegistryError(503, "REGISTRY_AUTH_NOT_CONFIGURED");
45986
+ const bearer = request.headers.get("authorization") ?? "";
45987
+ const supplied = bearer.startsWith("Bearer ") ? bearer.slice(7) : request.headers.get("x-api-key") ?? "";
45988
+ if (!secureEqual(supplied, key))
45989
+ throw new RegistryError(401, "REGISTRY_UNAUTHORIZED");
45990
+ }
45991
+ const url2 = new URL(request.url), path = url2.pathname.replace(/^\/api\/v1(?=\/|$)/, "/v1");
45992
+ const owner2 = registry2 ?? configuredRegistry();
45993
+ if (path === "/v1/catalog" && request.method === "GET")
45994
+ return json2(await owner2.catalog());
45995
+ if (path === "/v1/lock" && request.method === "GET")
45996
+ return json2(await owner2.selection(url2.searchParams.get("profile") ?? "fleet"));
45997
+ if (path === "/v1/hooks" && request.method === "PUT")
45998
+ return json2(await owner2.publish(await boundedJson2(request)));
45999
+ const artifact = /^\/v1\/hooks\/([^/]+)\/([^/]+)$/.exec(path);
46000
+ if (artifact && request.method === "GET") {
46001
+ const { body, row, format, portable } = await owner2.artifactWire(decodeURIComponent(artifact[1]), decodeURIComponent(artifact[2]));
46002
+ return new Response(body, { status: 200, headers: { "content-type": "application/json", "cache-control": "no-store", "x-hook-sha256": row.script_sha256, "x-hook-bundle-sha256": row.bundle_sha256, "x-hook-artifact-format": format, "x-hook-portable": String(portable) } });
46003
+ }
46004
+ const selection = /^\/v1\/selections\/([^/]+)$/.exec(path);
46005
+ if (selection) {
46006
+ const profile = decodeURIComponent(selection[1]);
46007
+ if (request.method === "GET")
46008
+ return json2(await owner2.selection(profile));
46009
+ if (request.method === "PUT")
46010
+ return json2(await owner2.select(profile, await boundedJson2(request)));
46011
+ }
46012
+ return json2({ error: "REGISTRY_ROUTE_NOT_FOUND" }, 404);
46013
+ } catch (error61) {
46014
+ if (error61 instanceof RegistryError)
46015
+ return json2({ error: error61.code }, error61.status);
46016
+ if (error61 instanceof URIError)
46017
+ return json2({ error: "REGISTRY_PATH_INVALID" }, 400);
46018
+ return json2({ error: "REGISTRY_STORAGE_UNAVAILABLE" }, 503);
46019
+ }
46020
+ }
46021
+
46022
+ // src/serve.ts
46023
+ init_local_opt_in();
44629
46024
  var DEFAULT_SERVE_PORT = 39428;
44630
46025
  var SERVE_HOST = "127.0.0.1";
44631
46026
  var SERVE_SERVICE_NAME = "hooks-registry";
44632
46027
  function packageVersion() {
44633
46028
  try {
44634
- const pkgPath = join24(dirname21(fileURLToPath5(import.meta.url)), "..", "package.json");
46029
+ const pkgPath = join27(dirname23(fileURLToPath5(import.meta.url)), "..", "package.json");
44635
46030
  return JSON.parse(readFileSync17(pkgPath, "utf-8")).version || "0.0.0";
44636
46031
  } catch {
44637
46032
  return "0.0.0";
@@ -44685,7 +46080,8 @@ async function artifactFor(name, version2) {
44685
46080
  script: custom3 ? custom3.manifest.script : `src/hook.ts`,
44686
46081
  script_kind: custom3?.manifest.script_kind,
44687
46082
  args: custom3?.manifest.args,
44688
- timeout_ms: custom3?.manifest.timeout_ms
46083
+ timeout_ms: custom3?.manifest.timeout_ms,
46084
+ nativeTargetDispatch: custom3?.manifest.nativeTargetDispatch ?? resolved.meta.nativeTargetDispatch
44689
46085
  };
44690
46086
  const script = await Bun.file(resolved.scriptPath).text();
44691
46087
  return { manifest, script };
@@ -44698,7 +46094,7 @@ function authorized(req, apiKey) {
44698
46094
  return secureEqual(header.slice("Bearer ".length), apiKey);
44699
46095
  return secureEqual(req.headers.get("x-api-key") ?? "", apiKey);
44700
46096
  }
44701
- function json2(body, status = 200, headers = {}) {
46097
+ function json3(body, status = 200, headers = {}) {
44702
46098
  return new Response(JSON.stringify(body), {
44703
46099
  status,
44704
46100
  headers: { "content-type": "application/json", ...headers }
@@ -44706,25 +46102,38 @@ function json2(body, status = 200, headers = {}) {
44706
46102
  }
44707
46103
  function handleServeRequest(req, apiKey) {
44708
46104
  const url2 = new URL(req.url);
46105
+ let localSelected = false;
46106
+ try {
46107
+ localSelected = !getStorageDatabaseUrl() && !hasRegistrySigningConfiguration() && getStorageBackend() === "sqlite" && selectsHooksLocalStore();
46108
+ } catch {}
46109
+ if (url2.pathname.startsWith("/v1/") && localSelected) {
46110
+ url2.pathname = "/api" + url2.pathname;
46111
+ return handleServeRequest(new Request(url2, req), apiKey);
46112
+ }
46113
+ if (url2.pathname.startsWith("/v1/") || url2.pathname.startsWith("/api/v1/") && !localSelected) {
46114
+ return handleRegistryRequest(req, apiKey);
46115
+ }
44709
46116
  if (url2.pathname === "/health" && req.method === "GET") {
44710
- return Promise.resolve(json2({ status: "ok", name: SERVE_SERVICE_NAME }));
46117
+ return Promise.resolve(json3({ status: "ok", name: SERVE_SERVICE_NAME }));
44711
46118
  }
44712
46119
  if (url2.pathname === "/ready" && req.method === "GET") {
46120
+ if (!localSelected)
46121
+ return registryReady().then((ready) => json3({ status: ready ? "ready" : "not-ready", name: SERVE_SERVICE_NAME }, ready ? 200 : 503));
44713
46122
  try {
44714
46123
  readLock();
44715
- return Promise.resolve(json2({ status: "ready", name: SERVE_SERVICE_NAME }));
46124
+ return Promise.resolve(json3({ status: "ready", name: SERVE_SERVICE_NAME }));
44716
46125
  } catch {
44717
- return Promise.resolve(json2({ status: "not-ready", name: SERVE_SERVICE_NAME }, 503));
46126
+ return Promise.resolve(json3({ status: "not-ready", name: SERVE_SERVICE_NAME }, 503));
44718
46127
  }
44719
46128
  }
44720
46129
  if (url2.pathname === "/version" && req.method === "GET") {
44721
- return Promise.resolve(json2({ version: packageVersion() }));
46130
+ return Promise.resolve(json3({ version: packageVersion() }));
44722
46131
  }
44723
46132
  if (url2.pathname === "/openapi.json" && req.method === "GET") {
44724
- return Promise.resolve(json2(buildOpenApiDocument(packageVersion())));
46133
+ return Promise.resolve(json3(buildOpenApiDocument(packageVersion())));
44725
46134
  }
44726
46135
  if (url2.pathname === "/api/v1/catalog" && req.method === "GET") {
44727
- return buildCatalog().then((catalog) => json2({ hooks: catalog }));
46136
+ return buildCatalog().then((catalog) => json3({ hooks: catalog }));
44728
46137
  }
44729
46138
  if (url2.pathname === "/api/v1/lock" && req.method === "GET") {
44730
46139
  return buildCatalog().then((catalog) => {
@@ -44736,7 +46145,7 @@ function handleServeRequest(req, apiKey) {
44736
46145
  for (const [name, pin2] of Object.entries(lock.hooks)) {
44737
46146
  hooks[name] = { ...pin2, versions: byVersion[name] ?? [pin2.version] };
44738
46147
  }
44739
- return json2({ hooks });
46148
+ return json3({ hooks });
44740
46149
  });
44741
46150
  }
44742
46151
  const artifactMatch = /^\/api\/v1\/hooks\/([\w-]+)\/([0-9A-Za-z.%+_-]+)$/.exec(url2.pathname);
@@ -44748,37 +46157,37 @@ function handleServeRequest(req, apiKey) {
44748
46157
  name = decodeURIComponent(rawName);
44749
46158
  version2 = decodeURIComponent(rawVersion);
44750
46159
  } catch {
44751
- return Promise.resolve(json2({ error: "invalid URL encoding" }, 400));
46160
+ return Promise.resolve(json3({ error: "invalid URL encoding" }, 400));
44752
46161
  }
44753
46162
  if (!SEMVER_PATTERN.test(version2)) {
44754
- return Promise.resolve(json2({ error: `invalid semver version '${version2}'` }, 400));
46163
+ return Promise.resolve(json3({ error: `invalid semver version '${version2}'` }, 400));
44755
46164
  }
44756
46165
  return artifactFor(name, version2).then(async (artifact) => {
44757
46166
  if (!artifact)
44758
- return json2({ error: `Hook '${name}@${version2}' not found locally` }, 404);
46167
+ return json3({ error: `Hook '${name}@${version2}' not found locally` }, 404);
44759
46168
  const resolved = resolveHook(name);
44760
46169
  const sha6 = resolved ? await sha256File(resolved.scriptPath) : artifact.manifest.name;
44761
- return json2(artifact, 200, { "x-hook-sha256": sha6 });
46170
+ return json3(artifact, 200, { "x-hook-sha256": sha6 });
44762
46171
  });
44763
46172
  }
44764
46173
  if (url2.pathname === "/api/v1/hooks" && req.method === "PUT") {
44765
46174
  if (!authorized(req, apiKey)) {
44766
- return Promise.resolve(json2({ error: "unauthorized: valid API key required to publish" }, 401));
46175
+ return Promise.resolve(json3({ error: "unauthorized: valid API key required to publish" }, 401));
44767
46176
  }
44768
46177
  return req.json().then((body) => {
44769
46178
  const name = body.name ?? "";
44770
46179
  const version2 = body.version ?? "";
44771
46180
  const resolved = resolveHook(name);
44772
46181
  if (!resolved)
44773
- return json2({ error: `Hook '${name}' not found in local store` }, 404);
46182
+ return json3({ error: `Hook '${name}' not found in local store` }, 404);
44774
46183
  if (version2 && version2 !== resolved.version) {
44775
- return json2({ error: `Version mismatch: local '${name}' is ${resolved.version}, requested ${version2}` }, 409);
46184
+ return json3({ error: `Version mismatch: local '${name}' is ${resolved.version}, requested ${version2}` }, 409);
44776
46185
  }
44777
46186
  const check2 = retrustHook(name, resolved.scriptPath, resolved.version, "serve");
44778
- return json2({ ok: true, hook: { name, version: resolved.version, sha256: check2.actual } });
44779
- }, () => json2({ error: "invalid JSON body" }, 400));
46187
+ return json3({ ok: true, hook: { name, version: resolved.version, sha256: check2.actual } });
46188
+ }, () => json3({ error: "invalid JSON body" }, 400));
44780
46189
  }
44781
- return Promise.resolve(json2({ error: "Not Found" }, 404));
46190
+ return Promise.resolve(json3({ error: "Not Found" }, 404));
44782
46191
  }
44783
46192
  function resolveServeOptions(options) {
44784
46193
  const envPort = process.env.PORT?.trim();
@@ -44877,16 +46286,16 @@ async function provisionCloudflareResources(options) {
44877
46286
  return result;
44878
46287
  }
44879
46288
  // src/lib/codex-safety-trust.ts
44880
- import { createHash as createHash19, randomUUID as randomUUID4 } from "crypto";
44881
- import { constants as constants15, closeSync as closeSync17, fsyncSync as fsyncSync4, fstatSync as fstatSync15, lstatSync as lstatSync21, mkdirSync as mkdirSync14, openSync as openSync17, readFileSync as readFileSync21, realpathSync as realpathSync16, writeFileSync as writeFileSync11 } from "fs";
44882
- import { dirname as dirname25, isAbsolute as isAbsolute24, join as join27, relative as relative3 } from "path";
46289
+ import { createHash as createHash26, randomUUID as randomUUID6 } from "crypto";
46290
+ import { constants as constants17, closeSync as closeSync17, fsyncSync as fsyncSync4, fstatSync as fstatSync15, lstatSync as lstatSync26, mkdirSync as mkdirSync15, openSync as openSync17, readFileSync as readFileSync21, realpathSync as realpathSync16, writeFileSync as writeFileSync12 } from "fs";
46291
+ import { dirname as dirname26, isAbsolute as isAbsolute24, join as join33, relative as relative3 } from "path";
44883
46292
  import { homedir as homedir9 } from "os";
44884
46293
 
44885
46294
  // src/lib/codex-safety-check.ts
44886
46295
  import { spawn as spawn2, execFile as execFile2 } from "child_process";
44887
- import { createHash as createHash13 } from "crypto";
44888
- import { constants as constants10, openSync as openSync15, closeSync as closeSync15, fstatSync as fstatSync10, lstatSync as lstatSync19, readFileSync as readFileSync19, realpathSync as realpathSync15 } from "fs";
44889
- import { dirname as dirname24, isAbsolute as isAbsolute15, resolve as resolve24 } from "path";
46296
+ import { createHash as createHash19 } from "crypto";
46297
+ import { constants as constants15, openSync as openSync15, closeSync as closeSync15, fstatSync as fstatSync10, lstatSync as lstatSync21, readFileSync as readFileSync19, realpathSync as realpathSync15 } from "fs";
46298
+ import { dirname as dirname25, isAbsolute as isAbsolute15, resolve as resolve25 } from "path";
44890
46299
  import { promisify } from "util";
44891
46300
 
44892
46301
  // src/lib/native-child-env.ts
@@ -44933,9 +46342,9 @@ function nativeChildEnv(source, explicit = {}, inherit = () => false) {
44933
46342
 
44934
46343
  // src/native-safety.ts
44935
46344
  import { execFile } from "child_process";
44936
- import { closeSync as closeSync10, constants as constants5, existsSync as existsSync15, fstatSync as fstatSync6, fsyncSync, linkSync, lstatSync as lstatSync11, mkdirSync as mkdirSync13, openSync as openSync10, readFileSync as readFileSync18, realpathSync as realpathSync14, renameSync as renameSync4, unlinkSync as unlinkSync6, writeFileSync as writeFileSync10 } from "fs";
46345
+ import { closeSync as closeSync10, constants as constants10, existsSync as existsSync16, fstatSync as fstatSync6, fsyncSync, linkSync, lstatSync as lstatSync19, mkdirSync as mkdirSync14, openSync as openSync10, readFileSync as readFileSync18, realpathSync as realpathSync14, renameSync as renameSync4, unlinkSync as unlinkSync6, writeFileSync as writeFileSync11 } from "fs";
44937
46346
  import { homedir as homedir8 } from "os";
44938
- import { dirname as dirname23, isAbsolute as isAbsolute11, join as join26, resolve as resolve23 } from "path";
46347
+ import { dirname as dirname24, isAbsolute as isAbsolute11, join as join28, resolve as resolve24 } from "path";
44939
46348
  class NativeSafetyError extends Error {
44940
46349
  code;
44941
46350
  reason;
@@ -44949,19 +46358,19 @@ class NativeSafetyError extends Error {
44949
46358
  var executionSchema = "hasna.hooks.execution.v1";
44950
46359
  var owner2 = (uid2) => uid2 === 0 || uid2 === process.getuid?.();
44951
46360
  function safeDirectory(path) {
44952
- for (let cursor = path;; cursor = dirname23(cursor)) {
44953
- const stat2 = lstatSync11(cursor);
46361
+ for (let cursor = path;; cursor = dirname24(cursor)) {
46362
+ const stat2 = lstatSync19(cursor);
44954
46363
  if (!stat2.isDirectory() || !owner2(stat2.uid) || stat2.mode & 18)
44955
46364
  throw new NativeSafetyError("binding_invalid");
44956
- if (dirname23(cursor) === cursor)
46365
+ if (dirname24(cursor) === cursor)
44957
46366
  return;
44958
46367
  }
44959
46368
  }
44960
46369
  function canonicalHome(home) {
44961
- if (!isAbsolute11(home) || home.includes("\x00") || realpathSync14(home) !== resolve23(home))
46370
+ if (!isAbsolute11(home) || home.includes("\x00") || realpathSync14(home) !== resolve24(home))
44962
46371
  throw new NativeSafetyError("binding_invalid");
44963
46372
  safeDirectory(home);
44964
- return resolve23(home);
46373
+ return resolve24(home);
44965
46374
  }
44966
46375
  function parseRecord(text3, home) {
44967
46376
  const record4 = JSON.parse(text3);
@@ -45013,7 +46422,7 @@ async function verifyNativeSafetyCommand(command, home = homedir8(), guard = "tr
45013
46422
  const binding = nativeSafetyCommandBinding(command);
45014
46423
  if (binding?.name !== guard || binding.home !== home)
45015
46424
  throw new NativeSafetyError("binding_invalid");
45016
- const root = join26(home, ".hasna", "repos", "clones"), probe = join26(root, ".hasna-workspace-repos-verification-only");
46425
+ const root = join28(home, ".hasna", "repos", "clones"), probe = join28(root, ".hasna-workspace-repos-verification-only");
45017
46426
  const verdict2 = await evaluateRecord({
45018
46427
  hook_event_name: "PreToolUse",
45019
46428
  tool_name: "Bash",
@@ -45031,7 +46440,7 @@ async function verifyNativeSafetyCommand(command, home = homedir8(), guard = "tr
45031
46440
  }
45032
46441
 
45033
46442
  // src/lib/codex-safety-check.ts
45034
- var SUPPORTED_CODEX_SAFETY_VERSIONS = ["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", "codex-cli 0.161.0"];
46443
+ var SUPPORTED_CODEX_SAFETY_VERSIONS = ["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", "codex-cli 0.161.0", "codex-cli 0.162.0"];
45035
46444
  var versions = new Set(SUPPORTED_CODEX_SAFETY_VERSIONS);
45036
46445
 
45037
46446
  class CodexSafetyError extends Error {
@@ -45046,7 +46455,7 @@ function need8(condition, code2) {
45046
46455
  if (!condition)
45047
46456
  throw new CodexSafetyError(code2);
45048
46457
  }
45049
- var digest3 = (bytes) => createHash13("sha256").update(bytes).digest("hex");
46458
+ var digest3 = (bytes) => createHash19("sha256").update(bytes).digest("hex");
45050
46459
  function nativeHeader(bytes) {
45051
46460
  if (bytes.length < 64 || !["arm64", "x64"].includes(process.arch))
45052
46461
  return false;
@@ -45065,13 +46474,13 @@ function executable2(command) {
45065
46474
  need8(found, "native_unavailable");
45066
46475
  try {
45067
46476
  const path = realpathSync15(found);
45068
- for (let parent = dirname24(path);; parent = dirname24(parent)) {
45069
- const stat2 = lstatSync19(parent);
46477
+ for (let parent = dirname25(path);; parent = dirname25(parent)) {
46478
+ const stat2 = lstatSync21(parent);
45070
46479
  need8(stat2.isDirectory() && [0, process.getuid?.()].includes(stat2.uid) && !(stat2.mode & 18), "native_unsafe_executable");
45071
- if (parent === dirname24(parent))
46480
+ if (parent === dirname25(parent))
45072
46481
  break;
45073
46482
  }
45074
- const fd = openSync15(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
46483
+ const fd = openSync15(path, constants15.O_RDONLY | constants15.O_NOFOLLOW | constants15.O_NONBLOCK);
45075
46484
  try {
45076
46485
  const stat2 = fstatSync10(fd);
45077
46486
  need8(stat2.isFile() && [0, process.getuid?.()].includes(stat2.uid) && !(stat2.mode & 18) && !!(stat2.mode & 64) && stat2.size <= 256000000, "native_unsafe_executable");
@@ -45210,9 +46619,9 @@ function supportedDiscoveryWarnings(hooks, warnings) {
45210
46619
  const sources = new Set(hooks.map((hook) => JSON.stringify([hook?.source, hook?.sourcePath])));
45211
46620
  for (const hook of hooks) {
45212
46621
  const path = hook?.sourcePath;
45213
- if (typeof path !== "string" || path.length > 4096 || !isAbsolute15(path) || path !== resolve24(dirname24(path), "hooks.json") || !["user", "project"].includes(hook.source))
46622
+ if (typeof path !== "string" || path.length > 4096 || !isAbsolute15(path) || path !== resolve25(dirname25(path), "hooks.json") || !["user", "project"].includes(hook.source))
45214
46623
  continue;
45215
- const toml = resolve24(dirname24(path), "config.toml");
46624
+ const toml = resolve25(dirname25(path), "config.toml");
45216
46625
  if (sources.has(JSON.stringify([hook.source, toml]))) {
45217
46626
  allowed.add(`loading hooks from both ${path} and ${toml}; prefer a single representation for this layer`);
45218
46627
  }
@@ -45296,7 +46705,7 @@ function need10(value, code2 = "native_changed") {
45296
46705
  if (!value)
45297
46706
  throw new CodexTrustError(code2);
45298
46707
  }
45299
- var sha6 = (value) => createHash19("sha256").update(value).digest("hex");
46708
+ var sha6 = (value) => createHash26("sha256").update(value).digest("hex");
45300
46709
  function canonical8(value) {
45301
46710
  if (Array.isArray(value))
45302
46711
  return "[" + value.map(canonical8).join(",") + "]";
@@ -45328,16 +46737,16 @@ function mergedConfiguration(value) {
45328
46737
  return canonical8(copy);
45329
46738
  }
45330
46739
  function safeDirectory2(path) {
45331
- for (let p = path;; p = dirname25(p)) {
45332
- const s = lstatSync21(p);
46740
+ for (let p = path;; p = dirname26(p)) {
46741
+ const s = lstatSync26(p);
45333
46742
  need10(s.isDirectory() && [0, process.getuid?.()].includes(s.uid) && !(s.mode & 18), "preimage_unsafe");
45334
- if (dirname25(p) === p)
46743
+ if (dirname26(p) === p)
45335
46744
  return;
45336
46745
  }
45337
46746
  }
45338
46747
  function readPrivate(path) {
45339
- safeDirectory2(dirname25(path));
45340
- const fd = openSync17(path, constants15.O_RDONLY | constants15.O_NOFOLLOW | constants15.O_NONBLOCK);
46748
+ safeDirectory2(dirname26(path));
46749
+ const fd = openSync17(path, constants17.O_RDONLY | constants17.O_NOFOLLOW | constants17.O_NONBLOCK);
45341
46750
  try {
45342
46751
  const s = fstatSync15(fd);
45343
46752
  need10(s.isFile() && s.uid === process.getuid?.() && !(s.mode & 63) && s.size <= 4194304, "preimage_unsafe");
@@ -45349,7 +46758,7 @@ function readPrivate(path) {
45349
46758
  }
45350
46759
  }
45351
46760
  function syncDirectory(path) {
45352
- const fd = openSync17(path, constants15.O_RDONLY | constants15.O_DIRECTORY | constants15.O_NOFOLLOW);
46761
+ const fd = openSync17(path, constants17.O_RDONLY | constants17.O_DIRECTORY | constants17.O_NOFOLLOW);
45353
46762
  try {
45354
46763
  fsyncSync4(fd);
45355
46764
  } finally {
@@ -45357,14 +46766,14 @@ function syncDirectory(path) {
45357
46766
  }
45358
46767
  }
45359
46768
  function exclusive(path, bytes) {
45360
- const fd = openSync17(path, constants15.O_CREAT | constants15.O_EXCL | constants15.O_WRONLY | constants15.O_NOFOLLOW, 384);
46769
+ const fd = openSync17(path, constants17.O_CREAT | constants17.O_EXCL | constants17.O_WRONLY | constants17.O_NOFOLLOW, 384);
45361
46770
  try {
45362
- writeFileSync11(fd, bytes);
46771
+ writeFileSync12(fd, bytes);
45363
46772
  fsyncSync4(fd);
45364
46773
  } finally {
45365
46774
  closeSync17(fd);
45366
46775
  }
45367
- syncDirectory(dirname25(path));
46776
+ syncDirectory(dirname26(path));
45368
46777
  }
45369
46778
  async function inspect(rpc, home, cwd, readiness = false, selected = "trash-guard") {
45370
46779
  const observed = await readCodexSafety(rpc, home, cwd, { includeLayers: true, requireReady: false, readiness, guard: selected });
@@ -45445,21 +46854,21 @@ async function applyTrust(options, dependencies = {}) {
45445
46854
  const expectedGuard = expectedDiscovery.data[0].hooks.find((h) => h.key === before.guard.key);
45446
46855
  expectedGuard.enabled = true;
45447
46856
  expectedGuard.trustStatus = "trusted";
45448
- operationId = randomUUID4();
46857
+ operationId = randomUUID6();
45449
46858
  let directory2 = home;
45450
46859
  for (const part of [".hasna", "hooks", "native", selected.readiness ? "codex-readiness-trust" : (selected.guard ?? "trash-guard") === "trash-guard" ? "codex-trash-trust" : "codex-" + selected.guard + "-trust", operationId]) {
45451
- directory2 = join27(directory2, part);
46860
+ directory2 = join33(directory2, part);
45452
46861
  try {
45453
- mkdirSync14(directory2, { mode: 448 });
45454
- syncDirectory(dirname25(directory2));
46862
+ mkdirSync15(directory2, { mode: 448 });
46863
+ syncDirectory(dirname26(directory2));
45455
46864
  } catch (error61) {
45456
46865
  if (error61.code !== "EEXIST")
45457
46866
  throw error61;
45458
46867
  }
45459
46868
  safeDirectory2(directory2);
45460
46869
  }
45461
- exclusive(join27(directory2, "config.before"), before.before);
45462
- exclusive(join27(directory2, "intent.json"), JSON.stringify({ operationId, plan: before.plan, configSHA256: sha6(before.before) }) + `
46870
+ exclusive(join33(directory2, "config.before"), before.before);
46871
+ exclusive(join33(directory2, "intent.json"), JSON.stringify({ operationId, plan: before.plan, configSHA256: sha6(before.before) }) + `
45463
46872
  `);
45464
46873
  journal = directory2;
45465
46874
  need10(sha6(readPrivate(before.canonicalPath)) === sha6(before.before));
@@ -45487,7 +46896,7 @@ async function applyTrust(options, dependencies = {}) {
45487
46896
  nativeAdoptionVerified: false,
45488
46897
  unrelatedConfigurationPreserved: true
45489
46898
  };
45490
- exclusive(join27(directory2, "receipt.json"), JSON.stringify(receipt) + `
46899
+ exclusive(join33(directory2, "receipt.json"), JSON.stringify(receipt) + `
45491
46900
  `);
45492
46901
  return receipt;
45493
46902
  } catch (error61) {
@@ -45500,7 +46909,7 @@ async function applyTrust(options, dependencies = {}) {
45500
46909
  if (!journal)
45501
46910
  throw new CodexTrustError("trust_refused", undefined, refusal3);
45502
46911
  try {
45503
- exclusive(join27(journal, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, planDigest: selected.expectedPlanDigest, refusal: refusal3 }) + `
46912
+ exclusive(join33(journal, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, planDigest: selected.expectedPlanDigest, refusal: refusal3 }) + `
45504
46913
  `);
45505
46914
  } catch {
45506
46915
  throw new CodexTrustError("trust_outcome_uncertain", operationId);
@@ -45513,9 +46922,9 @@ async function applyTrust(options, dependencies = {}) {
45513
46922
  var planCodexSafetyTrust = (options = {}, dependencies = {}) => planTrust({ ...options, readiness: false }, dependencies);
45514
46923
  var applyCodexSafetyTrust = (options, dependencies = {}) => applyTrust({ ...options, readiness: false }, dependencies);
45515
46924
  // src/lib/claude-safety-check.ts
45516
- import { constants as constants17, closeSync as closeSync18, fstatSync as fstatSync17, lstatSync as lstatSync26, openSync as openSync18, readFileSync as readFileSync23, realpathSync as realpathSync17 } from "fs";
45517
- import { createHash as createHash26 } from "crypto";
45518
- import { dirname as dirname26, isAbsolute as isAbsolute26, join as join28, resolve as resolve25 } from "path";
46925
+ import { constants as constants18, closeSync as closeSync18, fstatSync as fstatSync17, lstatSync as lstatSync28, openSync as openSync18, readFileSync as readFileSync23, realpathSync as realpathSync17 } from "fs";
46926
+ import { createHash as createHash28 } from "crypto";
46927
+ import { dirname as dirname27, isAbsolute as isAbsolute26, join as join35, resolve as resolve26 } from "path";
45519
46928
  import { homedir as homedir10 } from "os";
45520
46929
  class ClaudeSafetyError extends Error {
45521
46930
  code;
@@ -45529,17 +46938,17 @@ function need11(value, code2) {
45529
46938
  if (!value)
45530
46939
  throw new ClaudeSafetyError(code2);
45531
46940
  }
45532
- var sha8 = (value) => createHash26("sha256").update(value).digest("hex");
46941
+ var sha8 = (value) => createHash28("sha256").update(value).digest("hex");
45533
46942
  function read3(path) {
45534
46943
  try {
45535
46944
  const resolved = realpathSync17(path);
45536
- for (let parent = dirname26(resolved);; parent = dirname26(parent)) {
45537
- const s = lstatSync26(parent);
46945
+ for (let parent = dirname27(resolved);; parent = dirname27(parent)) {
46946
+ const s = lstatSync28(parent);
45538
46947
  need11(s.isDirectory() && [0, process.getuid?.()].includes(s.uid) && !(s.mode & 18), "settings_unsafe");
45539
- if (dirname26(parent) === parent)
46948
+ if (dirname27(parent) === parent)
45540
46949
  break;
45541
46950
  }
45542
- const fd = openSync18(resolved, constants17.O_RDONLY | constants17.O_NOFOLLOW | constants17.O_NONBLOCK);
46951
+ const fd = openSync18(resolved, constants18.O_RDONLY | constants18.O_NOFOLLOW | constants18.O_NONBLOCK);
45543
46952
  try {
45544
46953
  const s = fstatSync17(fd);
45545
46954
  need11(s.isFile() && [0, process.getuid?.()].includes(s.uid) && !(s.mode & 18) && s.size <= 1048576, "settings_unsafe");
@@ -45560,11 +46969,11 @@ function read3(path) {
45560
46969
  async function verifyClaudeSafetyConfiguration(options = {}, dependencies = {}) {
45561
46970
  const home = realpathSync17(options.home ?? homedir10()), cwd = realpathSync17(options.cwd ?? process.cwd());
45562
46971
  const paths = [
45563
- options.userSettingsPath ?? join28(home, ".claude/settings.json"),
45564
- join28(cwd, ".claude/settings.json"),
45565
- options.localSettingsPath ?? join28(cwd, ".claude/settings.local.json")
46972
+ options.userSettingsPath ?? join35(home, ".claude/settings.json"),
46973
+ join35(cwd, ".claude/settings.json"),
46974
+ options.localSettingsPath ?? join35(cwd, ".claude/settings.local.json")
45566
46975
  ];
45567
- need11(paths.every((path) => isAbsolute26(path) && resolve25(path) === path), "settings_unsafe");
46976
+ need11(paths.every((path) => isAbsolute26(path) && resolve26(path) === path), "settings_unsafe");
45568
46977
  const inspect2 = () => [...new Set(paths)].map(read3);
45569
46978
  const before = inspect2(), unique = [...new Map(before.filter((file2) => file2.resolved !== null).map((file2) => [file2.resolved, file2])).values()];
45570
46979
  const guards = [];
@@ -45623,9 +47032,9 @@ async function verifyClaudeSafetyConfiguration(options = {}, dependencies = {})
45623
47032
  };
45624
47033
  }
45625
47034
  // src/lib/native-safety-registration.ts
45626
- import { createHash as createHash28, randomUUID as randomUUID6 } from "crypto";
45627
- import { constants as constants18, closeSync as closeSync19, fstatSync as fstatSync18, fsyncSync as fsyncSync7, lstatSync as lstatSync28, mkdirSync as mkdirSync15, openSync as openSync19, readFileSync as readFileSync24, realpathSync as realpathSync18, writeFileSync as writeFileSync12 } from "fs";
45628
- import { basename as basename12, dirname as dirname27, isAbsolute as isAbsolute27, join as join33, relative as relative7, resolve as resolve26 } from "path";
47035
+ import { createHash as createHash30, randomUUID as randomUUID7 } from "crypto";
47036
+ import { constants as constants19, closeSync as closeSync19, fstatSync as fstatSync18, fsyncSync as fsyncSync7, lstatSync as lstatSync29, mkdirSync as mkdirSync16, openSync as openSync19, readFileSync as readFileSync24, realpathSync as realpathSync18, writeFileSync as writeFileSync13 } from "fs";
47037
+ import { basename as basename12, dirname as dirname28, isAbsolute as isAbsolute27, join as join36, relative as relative7, resolve as resolve27 } from "path";
45629
47038
  import { homedir as homedir11 } from "os";
45630
47039
  class NativeRegistrationError extends Error {
45631
47040
  code;
@@ -45643,7 +47052,7 @@ var need12 = (value, code2) => {
45643
47052
  if (!value)
45644
47053
  throw new NativeRegistrationError(code2);
45645
47054
  };
45646
- var sha9 = (value) => createHash28("sha256").update(value).digest("hex");
47055
+ var sha9 = (value) => createHash30("sha256").update(value).digest("hex");
45647
47056
  function canonical10(value) {
45648
47057
  if (Array.isArray(value))
45649
47058
  return "[" + value.map(canonical10).join(",") + "]";
@@ -45652,10 +47061,10 @@ function canonical10(value) {
45652
47061
  return JSON.stringify(value);
45653
47062
  }
45654
47063
  function safeDirectory3(path) {
45655
- for (let p = path;; p = dirname27(p)) {
45656
- const s = lstatSync28(p);
47064
+ for (let p = path;; p = dirname28(p)) {
47065
+ const s = lstatSync29(p);
45657
47066
  need12(s.isDirectory() && [0, process.getuid?.()].includes(s.uid) && !(s.mode & 18), "settings_unsafe");
45658
- if (dirname27(p) === p)
47067
+ if (dirname28(p) === p)
45659
47068
  return;
45660
47069
  }
45661
47070
  }
@@ -45667,39 +47076,39 @@ function read5(path) {
45667
47076
  if (error61.code !== "ENOENT")
45668
47077
  throw new NativeRegistrationError("settings_unsafe");
45669
47078
  try {
45670
- lstatSync28(path);
47079
+ lstatSync29(path);
45671
47080
  throw new NativeRegistrationError("settings_unsafe");
45672
47081
  } catch (missing2) {
45673
47082
  if (missing2.code !== "ENOENT")
45674
47083
  throw missing2;
45675
47084
  }
45676
- let ancestor = dirname27(path);
47085
+ let ancestor = dirname28(path);
45677
47086
  const suffix = [basename12(path)];
45678
47087
  for (;; ) {
45679
47088
  try {
45680
- resolved = join33(realpathSync18(ancestor), ...suffix);
47089
+ resolved = join36(realpathSync18(ancestor), ...suffix);
45681
47090
  break;
45682
47091
  } catch (missing2) {
45683
- if (missing2.code !== "ENOENT" || dirname27(ancestor) === ancestor || suffix.length >= 64)
47092
+ if (missing2.code !== "ENOENT" || dirname28(ancestor) === ancestor || suffix.length >= 64)
45684
47093
  throw new NativeRegistrationError("settings_unsafe");
45685
47094
  try {
45686
- lstatSync28(ancestor);
47095
+ lstatSync29(ancestor);
45687
47096
  throw new NativeRegistrationError("settings_unsafe");
45688
47097
  } catch (absent) {
45689
47098
  if (absent.code !== "ENOENT")
45690
47099
  throw absent;
45691
47100
  }
45692
47101
  suffix.unshift(basename12(ancestor));
45693
- ancestor = dirname27(ancestor);
47102
+ ancestor = dirname28(ancestor);
45694
47103
  }
45695
47104
  }
45696
47105
  safeDirectory3(realpathSync18(ancestor));
45697
47106
  return { resolved, raw: null, sha256: "absent" };
45698
47107
  }
45699
- safeDirectory3(dirname27(resolved));
47108
+ safeDirectory3(dirname28(resolved));
45700
47109
  let fd;
45701
47110
  try {
45702
- fd = openSync19(resolved, constants18.O_RDONLY | constants18.O_NOFOLLOW | constants18.O_NONBLOCK);
47111
+ fd = openSync19(resolved, constants19.O_RDONLY | constants19.O_NOFOLLOW | constants19.O_NONBLOCK);
45703
47112
  } catch (error61) {
45704
47113
  if (error61.code === "ENOENT")
45705
47114
  return { resolved, raw: null, sha256: "absent" };
@@ -45785,11 +47194,11 @@ function inspect2(options) {
45785
47194
  need12(options?.target === "codex" || options?.target === "claude", "input_invalid");
45786
47195
  need12(options.readiness ? options.guard === "trash-guard" : isNativeSafetyName(options.guard), "input_invalid");
45787
47196
  const home = realpathSync18(homedir11()), path = getSettingsPath("global", options.target);
45788
- need12(isAbsolute27(path) && resolve26(path) === path, "input_invalid");
47197
+ need12(isAbsolute27(path) && resolve27(path) === path, "input_invalid");
45789
47198
  const nativeHome = options.target === "codex" ? process.env.CODEX_HOME : process.env.CLAUDE_CONFIG_DIR;
45790
47199
  if (nativeHome !== undefined) {
45791
47200
  need12(nativeHome.length > 0 && isAbsolute27(nativeHome), "input_invalid");
45792
- const selectedNative = read5(resolve26(nativeHome, options.target === "codex" ? "hooks.json" : "settings.json"));
47201
+ const selectedNative = read5(resolve27(nativeHome, options.target === "codex" ? "hooks.json" : "settings.json"));
45793
47202
  need12(read5(path).resolved === selectedNative.resolved, "input_invalid");
45794
47203
  }
45795
47204
  const before = read5(path), inside = relative7(home, before.resolved);
@@ -45823,7 +47232,7 @@ function inspect2(options) {
45823
47232
  return { home, before, preview: preview2, plan };
45824
47233
  }
45825
47234
  function syncDirectory2(path) {
45826
- const fd = openSync19(path, constants18.O_RDONLY | constants18.O_DIRECTORY | constants18.O_NOFOLLOW);
47235
+ const fd = openSync19(path, constants19.O_RDONLY | constants19.O_DIRECTORY | constants19.O_NOFOLLOW);
45827
47236
  try {
45828
47237
  fsyncSync7(fd);
45829
47238
  } finally {
@@ -45831,14 +47240,14 @@ function syncDirectory2(path) {
45831
47240
  }
45832
47241
  }
45833
47242
  function exclusive2(path, bytes) {
45834
- const fd = openSync19(path, constants18.O_CREAT | constants18.O_EXCL | constants18.O_WRONLY | constants18.O_NOFOLLOW, 384);
47243
+ const fd = openSync19(path, constants19.O_CREAT | constants19.O_EXCL | constants19.O_WRONLY | constants19.O_NOFOLLOW, 384);
45835
47244
  try {
45836
- writeFileSync12(fd, bytes);
47245
+ writeFileSync13(fd, bytes);
45837
47246
  fsyncSync7(fd);
45838
47247
  } finally {
45839
47248
  closeSync19(fd);
45840
47249
  }
45841
- syncDirectory2(dirname27(path));
47250
+ syncDirectory2(dirname28(path));
45842
47251
  }
45843
47252
  function refusalOf(error61) {
45844
47253
  const code2 = error61?.code;
@@ -45846,7 +47255,7 @@ function refusalOf(error61) {
45846
47255
  }
45847
47256
  function refuseApply(directory2, operationId, planDigest, refusal3) {
45848
47257
  try {
45849
- exclusive2(join33(directory2, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, planDigest, refusal: refusal3 }) + `
47258
+ exclusive2(join36(directory2, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, planDigest, refusal: refusal3 }) + `
45850
47259
  `);
45851
47260
  } catch {
45852
47261
  throw new NativeRegistrationError("apply_outcome_uncertain", operationId);
@@ -45887,13 +47296,13 @@ async function applyRegistration(options, dependencies = {}) {
45887
47296
  need12(before.plan.planDigest === plan.planDigest, "settings_changed");
45888
47297
  if (plan.action === "unchanged")
45889
47298
  return { ok: true, changed: false, ...plan };
45890
- const operationId = randomUUID6();
47299
+ const operationId = randomUUID7();
45891
47300
  let directory2 = before.home;
45892
47301
  for (const part of [".hasna", "hooks", "native", selected.readiness ? "trash-readiness-registration" : selected.guard === "trash-guard" ? "trash-registration" : selected.guard + "-registration", operationId]) {
45893
- directory2 = join33(directory2, part);
47302
+ directory2 = join36(directory2, part);
45894
47303
  try {
45895
- mkdirSync15(directory2, { mode: 448 });
45896
- syncDirectory2(dirname27(directory2));
47304
+ mkdirSync16(directory2, { mode: 448 });
47305
+ syncDirectory2(dirname28(directory2));
45897
47306
  } catch (error61) {
45898
47307
  if (error61.code !== "EEXIST")
45899
47308
  throw new NativeRegistrationError("settings_unsafe");
@@ -45901,8 +47310,8 @@ async function applyRegistration(options, dependencies = {}) {
45901
47310
  safeDirectory3(directory2);
45902
47311
  }
45903
47312
  if (before.before.raw !== null)
45904
- exclusive2(join33(directory2, "settings.before"), before.before.raw);
45905
- exclusive2(join33(directory2, "intent.json"), JSON.stringify({ operationId, plan }) + `
47313
+ exclusive2(join36(directory2, "settings.before"), before.before.raw);
47314
+ exclusive2(join36(directory2, "intent.json"), JSON.stringify({ operationId, plan }) + `
45906
47315
  `);
45907
47316
  let writeMayHaveStarted = false;
45908
47317
  const beforeWrite = () => {
@@ -45931,7 +47340,7 @@ async function applyRegistration(options, dependencies = {}) {
45931
47340
  ...selected.readiness ? { readinessRunnerVerified: true } : {},
45932
47341
  nativeAdoptionVerified: false
45933
47342
  };
45934
- exclusive2(join33(directory2, "receipt.json"), JSON.stringify(receipt) + `
47343
+ exclusive2(join36(directory2, "receipt.json"), JSON.stringify(receipt) + `
45935
47344
  `);
45936
47345
  return receipt;
45937
47346
  } catch (error61) {
@@ -45962,9 +47371,8 @@ async function runHook(name, input2, options = {}) {
45962
47371
  const resolvedMeta = custom3 ? undefined : getHook(name);
45963
47372
  if (!custom3 && !resolvedMeta)
45964
47373
  throw new Error(`Hook '${name}' not found`);
45965
- const hookScript = getHookPath(name) + "/src/hook.ts";
45966
- const resolvedScript = custom3?.scriptPath;
45967
- const script = resolvedScript ?? (existsSync17(hookScript) ? hookScript : undefined);
47374
+ const dispatchArgs = nativeTargetArgs(custom3?.manifest.nativeTargetDispatch ?? resolvedMeta?.nativeTargetDispatch, options.target, custom3?.manifest.args);
47375
+ const script = resolveScriptPath(name);
45968
47376
  if (!script)
45969
47377
  throw new Error(`Hook script not found: ${name}`);
45970
47378
  const { sha256Of: sha256Of2, checkScriptHash: checkScriptHash2 } = await Promise.resolve().then(() => (init_store(), exports_store));
@@ -45998,7 +47406,7 @@ async function runHook(name, input2, options = {}) {
45998
47406
  name,
45999
47407
  scriptPath: script,
46000
47408
  content,
46001
- args: custom3?.manifest.args ?? [],
47409
+ args: dispatchArgs,
46002
47410
  env: custom3?.manifest.env,
46003
47411
  stdin: JSON.stringify(hookInput),
46004
47412
  timeout: effectiveTimeout ?? undefined