@astrasyncai/verification-gateway 5.10.0 → 5.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +4 -0
  2. package/dist/adapters/express.d.mts +1 -1
  3. package/dist/adapters/express.d.ts +1 -1
  4. package/dist/adapters/express.js +359 -30
  5. package/dist/adapters/express.js.map +1 -1
  6. package/dist/adapters/express.mjs +359 -30
  7. package/dist/adapters/express.mjs.map +1 -1
  8. package/dist/adapters/mcp.d.mts +5 -1
  9. package/dist/adapters/mcp.d.ts +5 -1
  10. package/dist/adapters/mcp.js +168 -41
  11. package/dist/adapters/mcp.js.map +1 -1
  12. package/dist/adapters/mcp.mjs +168 -41
  13. package/dist/adapters/mcp.mjs.map +1 -1
  14. package/dist/adapters/nextjs.d.mts +1 -1
  15. package/dist/adapters/nextjs.d.ts +1 -1
  16. package/dist/adapters/nextjs.js +352 -13
  17. package/dist/adapters/nextjs.js.map +1 -1
  18. package/dist/adapters/nextjs.mjs +352 -13
  19. package/dist/adapters/nextjs.mjs.map +1 -1
  20. package/dist/adapters/sdk.d.mts +9 -1
  21. package/dist/adapters/sdk.d.ts +9 -1
  22. package/dist/adapters/sdk.js +100 -8
  23. package/dist/adapters/sdk.js.map +1 -1
  24. package/dist/adapters/sdk.mjs +100 -8
  25. package/dist/adapters/sdk.mjs.map +1 -1
  26. package/dist/agent/index.js +1 -1
  27. package/dist/agent/index.js.map +1 -1
  28. package/dist/agent/index.mjs +1 -1
  29. package/dist/agent/index.mjs.map +1 -1
  30. package/dist/bin/astrasync-claude-hook.js +805 -16
  31. package/dist/bin/astrasync-codex-hook.js +805 -16
  32. package/dist/bin/astrasync-guard.js +894 -71
  33. package/dist/bin/astrasync.js +951 -74
  34. package/dist/browser/background.js +284 -7
  35. package/dist/browser/background.js.map +1 -1
  36. package/dist/browser/background.mjs +284 -7
  37. package/dist/browser/background.mjs.map +1 -1
  38. package/dist/cli/index.d.mts +8 -8
  39. package/dist/cli/index.d.ts +8 -8
  40. package/dist/cli/index.js +22 -64
  41. package/dist/cli/index.js.map +1 -1
  42. package/dist/cli/index.mjs +22 -64
  43. package/dist/cli/index.mjs.map +1 -1
  44. package/dist/codex/index.d.mts +5 -0
  45. package/dist/codex/index.d.ts +5 -0
  46. package/dist/codex/index.js +821 -24
  47. package/dist/codex/index.js.map +1 -1
  48. package/dist/codex/index.mjs +823 -26
  49. package/dist/codex/index.mjs.map +1 -1
  50. package/dist/cursor/extension.d.mts +9 -2
  51. package/dist/cursor/extension.d.ts +9 -2
  52. package/dist/cursor/extension.js +787 -11
  53. package/dist/cursor/extension.js.map +1 -1
  54. package/dist/cursor/extension.mjs +789 -11
  55. package/dist/cursor/extension.mjs.map +1 -1
  56. package/dist/edge-config.d.mts +1 -1
  57. package/dist/edge-config.d.ts +1 -1
  58. package/dist/edge-config.js +1 -1
  59. package/dist/edge-config.js.map +1 -1
  60. package/dist/edge-config.mjs +1 -1
  61. package/dist/edge-config.mjs.map +1 -1
  62. package/dist/edge-core/index.d.mts +128 -13
  63. package/dist/edge-core/index.d.ts +128 -13
  64. package/dist/edge-core/index.js +337 -55
  65. package/dist/edge-core/index.js.map +1 -1
  66. package/dist/edge-core/index.mjs +334 -55
  67. package/dist/edge-core/index.mjs.map +1 -1
  68. package/dist/enrolment-store-8DyaIOLe.d.mts +26 -0
  69. package/dist/enrolment-store-8DyaIOLe.d.ts +26 -0
  70. package/dist/gateway/gateway.js +284 -7
  71. package/dist/gateway/gateway.js.map +1 -1
  72. package/dist/gateway/gateway.mjs +284 -7
  73. package/dist/gateway/gateway.mjs.map +1 -1
  74. package/dist/git-trigger/git-hooks.d.mts +1 -1
  75. package/dist/git-trigger/git-hooks.d.ts +1 -1
  76. package/dist/index.d.mts +215 -5
  77. package/dist/index.d.ts +215 -5
  78. package/dist/index.js +3756 -80
  79. package/dist/index.js.map +1 -1
  80. package/dist/index.mjs +3748 -80
  81. package/dist/index.mjs.map +1 -1
  82. package/dist/platform-signatures.js +4 -1
  83. package/dist/platform-signatures.js.map +1 -1
  84. package/dist/platform-signatures.mjs +4 -1
  85. package/dist/platform-signatures.mjs.map +1 -1
  86. package/dist/registration/index.js +1 -1
  87. package/dist/registration/index.js.map +1 -1
  88. package/dist/registration/index.mjs +1 -1
  89. package/dist/registration/index.mjs.map +1 -1
  90. package/dist/transport/index.js +1 -1
  91. package/dist/transport/index.js.map +1 -1
  92. package/dist/transport/index.mjs +1 -1
  93. package/dist/transport/index.mjs.map +1 -1
  94. package/dist/{types-CTmUpNpS.d.mts → types-BCkwBA84.d.mts} +12 -0
  95. package/dist/{types-CTmUpNpS.d.ts → types-BCkwBA84.d.ts} +12 -0
  96. package/dist/{types-CtFXmDzm.d.ts → types-C_b4QTyO.d.ts} +18 -0
  97. package/dist/{types-DQrn_kei.d.mts → types-DlshIIR-.d.mts} +18 -0
  98. package/dist/ui/index.d.mts +1 -1
  99. package/dist/ui/index.d.ts +1 -1
  100. package/dist/verify.d.mts +35 -4
  101. package/dist/verify.d.ts +35 -4
  102. package/dist/verify.js +130 -16
  103. package/dist/verify.js.map +1 -1
  104. package/dist/verify.mjs +129 -16
  105. package/dist/verify.mjs.map +1 -1
  106. package/package.json +1 -1
@@ -279,7 +279,8 @@ var CodexAdapter = class {
279
279
  };
280
280
 
281
281
  // src/codex/hook.ts
282
- import { join as join3 } from "path";
282
+ import { homedir as homedir3 } from "os";
283
+ import { join as join5 } from "path";
283
284
 
284
285
  // src/gateway/types.ts
285
286
  var HIGH_RISK_COMMANDS = [
@@ -4005,7 +4006,7 @@ function getTrustLevel(score) {
4005
4006
  }
4006
4007
 
4007
4008
  // src/version.ts
4008
- var SDK_VERSION = "5.10.0";
4009
+ var SDK_VERSION = "5.12.0";
4009
4010
 
4010
4011
  // src/http.ts
4011
4012
  var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
@@ -4032,6 +4033,14 @@ function getCachedWellKnownUrls(apiBaseUrl) {
4032
4033
  return cache.get(apiBaseUrl)?.data;
4033
4034
  }
4034
4035
 
4036
+ // src/failure-posture.ts
4037
+ var REJECTED_IDENTITY_DIMENSIONS = /* @__PURE__ */ new Set([
4038
+ "identity.invalid_agent_id",
4039
+ "identity.unknown_agent",
4040
+ "agent.lookup"
4041
+ ]);
4042
+ var UNKNOWN_AGENT_GUIDANCE = "Register your agent with AstraSync (or, inside an MCP host, add the AstraSync MCP connector for keyless, human-approved registration), then present the canonical ASTRA-* id issued after owner approval.";
4043
+
4035
4044
  // src/verify.ts
4036
4045
  var DEFAULT_CONFIG = {
4037
4046
  apiBaseUrl: "https://astrasync.ai/api",
@@ -4243,11 +4252,44 @@ function createGuidanceResponse(_config, reason, options = {}) {
4243
4252
  // coercing the absent recommendation to a policy 'deny'. Misconfig is
4244
4253
  // deterministic and intentionally NOT marked retryable.
4245
4254
  ...isApiError && { retryable: true },
4255
+ ...options.httpStatus !== void 0 && { httpStatus: options.httpStatus },
4256
+ ...options.retryAfterMs !== void 0 && { retryAfterMs: options.retryAfterMs },
4246
4257
  correlationId: options.correlationId,
4247
4258
  attemptId: options.attemptId,
4248
4259
  verifiedAt: /* @__PURE__ */ new Date()
4249
4260
  };
4250
4261
  }
4262
+ async function readJsonSafe(response) {
4263
+ try {
4264
+ const parsed = await response.json();
4265
+ return parsed && typeof parsed === "object" ? parsed : {};
4266
+ } catch {
4267
+ return {};
4268
+ }
4269
+ }
4270
+ function rejectedIdentityGuidance(failures) {
4271
+ const f = failures?.find((x) => REJECTED_IDENTITY_DIMENSIONS.has(x.dimension));
4272
+ if (!f) return void 0;
4273
+ if (f.dimension === "agent.lookup") {
4274
+ return `The presented agent identifier is not registered with AstraSync. ${UNKNOWN_AGENT_GUIDANCE}`;
4275
+ }
4276
+ return f.guidance ? `${f.message} ${f.guidance}` : f.message;
4277
+ }
4278
+ var MAX_RETRY_AFTER_MS = 15 * 60 * 1e3;
4279
+ function parseRetryAfterMs(response) {
4280
+ const raw = response.headers?.get?.("retry-after");
4281
+ if (!raw) return void 0;
4282
+ const trimmed = raw.trim();
4283
+ let ms;
4284
+ if (/^\d+(\.\d+)?$/.test(trimmed)) {
4285
+ ms = Number(trimmed) * 1e3;
4286
+ } else {
4287
+ const at = Date.parse(trimmed);
4288
+ if (Number.isNaN(at)) return void 0;
4289
+ ms = at - Date.now();
4290
+ }
4291
+ return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, Math.round(ms)));
4292
+ }
4251
4293
  async function callVerifyAccessAPI(config, request) {
4252
4294
  const { credentials, ...requestData } = request;
4253
4295
  const body = {
@@ -4304,7 +4346,8 @@ async function callVerifyAccessAPI(config, request) {
4304
4346
  body: JSON.stringify(body),
4305
4347
  signal: AbortSignal.timeout(config.verifyTimeoutMs ?? 1e4)
4306
4348
  });
4307
- const data = await response.json();
4349
+ const data = await readJsonSafe(response);
4350
+ const retryAfterMs = parseRetryAfterMs(response);
4308
4351
  if (response.status === 410) {
4309
4352
  return {
4310
4353
  success: true,
@@ -4342,6 +4385,23 @@ async function callVerifyAccessAPI(config, request) {
4342
4385
  }
4343
4386
  };
4344
4387
  }
4388
+ if (response.status === 404 && credentials.astraId && (data?.error === "AGENT_NOT_FOUND" || typeof data?.message === "string" && /agent/i.test(data.message))) {
4389
+ return {
4390
+ success: true,
4391
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
4392
+ access: {
4393
+ allowed: false,
4394
+ reason: "unknown_agent",
4395
+ failures: [
4396
+ {
4397
+ dimension: "identity.unknown_agent",
4398
+ message: "The presented agent identifier is not registered with AstraSync.",
4399
+ guidance: UNKNOWN_AGENT_GUIDANCE
4400
+ }
4401
+ ]
4402
+ }
4403
+ };
4404
+ }
4345
4405
  if (!response.ok) {
4346
4406
  if (response.status === 401) {
4347
4407
  return {
@@ -4356,9 +4416,11 @@ async function callVerifyAccessAPI(config, request) {
4356
4416
  }
4357
4417
  return {
4358
4418
  success: false,
4359
- error: data.message || data.error || `API returned ${response.status}`,
4419
+ error: typeof data?.message === "string" && data.message || typeof data?.error === "string" && data.error || `API returned ${response.status}`,
4360
4420
  correlationId: typeof data?.correlationId === "string" ? data.correlationId : void 0,
4361
- attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0
4421
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
4422
+ httpStatus: response.status,
4423
+ ...retryAfterMs !== void 0 && { retryAfterMs }
4362
4424
  };
4363
4425
  }
4364
4426
  return data;
@@ -4430,12 +4492,14 @@ async function verify(config, request, options) {
4430
4492
  correlationId: apiResponse.correlationId,
4431
4493
  attemptId: apiResponse.attemptId,
4432
4494
  remediation: apiResponse.remediation,
4495
+ httpStatus: apiResponse.httpStatus,
4496
+ retryAfterMs: apiResponse.retryAfterMs,
4433
4497
  urls
4434
4498
  });
4435
4499
  }
4436
4500
  if (!apiResponse.access?.allowed) {
4437
4501
  const aggregatedFailures = apiResponse.access?.failures;
4438
- const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true;
4502
+ const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true && !aggregatedFailures?.some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));
4439
4503
  const result2 = {
4440
4504
  identityVerified: idVerifiedFromBackend,
4441
4505
  policyAllowed: false,
@@ -4447,7 +4511,10 @@ async function verify(config, request, options) {
4447
4511
  requiresStepUp: apiResponse.access?.requiresStepUp,
4448
4512
  requiresApproval: apiResponse.access?.requiresApproval,
4449
4513
  guidance: {
4450
- message: apiResponse.access?.reason || "Access denied by PDLSS policy",
4514
+ // 5.12.0: a presented-but-rejected id (malformed / unknown) carries
4515
+ // actionable registration guidance on its failure — surface it
4516
+ // instead of the bare machine reason ('unknown_agent').
4517
+ message: rejectedIdentityGuidance(aggregatedFailures) ?? (apiResponse.access?.reason || "Access denied by PDLSS policy"),
4451
4518
  registrationUrl: urls?.registrationUrl ?? "",
4452
4519
  documentationUrl: urls?.documentationUrl ?? "",
4453
4520
  // 5.1.0: anonymous callers land on this branch — steer MCP-hosted
@@ -4547,7 +4614,7 @@ async function verify(config, request, options) {
4547
4614
  registrationUrl: urls?.registrationUrl ?? "",
4548
4615
  documentationUrl: urls?.documentationUrl ?? ""
4549
4616
  };
4550
- } else if (result.recommendation === "step_up_required") {
4617
+ } else if (result.recommendation === "step_up_required" && result.identityVerified) {
4551
4618
  result.requiresStepUp = true;
4552
4619
  result.denialReasons = serverDenialReasons ?? result.recommendationReasons ?? ["Step-up verification required"];
4553
4620
  }
@@ -4576,6 +4643,217 @@ var DEFAULT_EDGE_CONFIG = Object.freeze({
4576
4643
  var DEFAULT_TTL_MS = 60 * 1e3;
4577
4644
  var DEFAULT_MAX_STALE_MS = 24 * 60 * 60 * 1e3;
4578
4645
 
4646
+ // src/edge-core/events.ts
4647
+ async function withBudget(promise, ms) {
4648
+ let timer;
4649
+ try {
4650
+ return await Promise.race([
4651
+ promise,
4652
+ new Promise((resolve) => {
4653
+ timer = setTimeout(() => resolve(void 0), ms);
4654
+ })
4655
+ ]);
4656
+ } catch {
4657
+ return void 0;
4658
+ } finally {
4659
+ if (timer) clearTimeout(timer);
4660
+ }
4661
+ }
4662
+ var destKeyOf = (d) => `${d.apiBaseUrl}\0${d.apiKey ?? ""}\0${d.counterparty}\0${d.adapter ?? ""}`;
4663
+ var BeaconBuffer = class {
4664
+ constructor(options = {}) {
4665
+ this.queue = [];
4666
+ this.droppedSinceLast = 0;
4667
+ this.droppedTotal = 0;
4668
+ this.deliveredTotal = 0;
4669
+ this.backoffUntil = 0;
4670
+ this.collapse = /* @__PURE__ */ new Map();
4671
+ /** Keys the backend answered 401 for — later batches go unauthenticated. */
4672
+ this.rejectedKeys = /* @__PURE__ */ new Set();
4673
+ this.opts = {
4674
+ maxItems: options.maxItems ?? 1e3,
4675
+ maxBatch: options.maxBatch ?? 100,
4676
+ maxAttempts: options.maxAttempts ?? 3,
4677
+ collapseWindowMs: options.collapseWindowMs ?? 6e4,
4678
+ collapseMaxKeys: options.collapseMaxKeys ?? 1e3,
4679
+ requestTimeoutMs: options.requestTimeoutMs ?? 1e4,
4680
+ retryBackoffMs: options.retryBackoffMs ?? 1e3,
4681
+ now: options.now ?? Date.now
4682
+ };
4683
+ }
4684
+ /**
4685
+ * Queue one beacon. With a `collapseKey`, a repeat inside the window is
4686
+ * merged into a held aggregate (sent when the window closes) instead of
4687
+ * becoming its own item.
4688
+ */
4689
+ enqueue(dest, item, collapseKey) {
4690
+ const now = this.opts.now();
4691
+ if (collapseKey) {
4692
+ const entry = this.collapse.get(collapseKey);
4693
+ if (entry && now - entry.firstSeenAt < this.opts.collapseWindowMs) {
4694
+ for (const target of [entry.first, entry.held]) {
4695
+ if (target && !target.inFlight && this.queue.includes(target)) {
4696
+ target.item.repeatCount = (target.item.repeatCount ?? 1) + 1;
4697
+ return;
4698
+ }
4699
+ }
4700
+ const held = this.push(
4701
+ dest,
4702
+ { ...item, repeatCount: 1 },
4703
+ entry.firstSeenAt + this.opts.collapseWindowMs
4704
+ );
4705
+ entry.held = held;
4706
+ return;
4707
+ }
4708
+ this.collapse.delete(collapseKey);
4709
+ if (this.collapse.size >= this.opts.collapseMaxKeys) {
4710
+ const oldest = this.collapse.keys().next().value;
4711
+ if (oldest !== void 0) this.collapse.delete(oldest);
4712
+ }
4713
+ const fresh = { firstSeenAt: now };
4714
+ this.collapse.set(collapseKey, fresh);
4715
+ fresh.first = this.push(dest, item, now);
4716
+ return;
4717
+ }
4718
+ this.push(dest, item, now);
4719
+ }
4720
+ /**
4721
+ * Deliver every eligible queued item. Concurrent callers share ONE
4722
+ * in-flight drain (it survives the caller's budget and a Lambda freeze),
4723
+ * so nothing in flight is ever sent twice; items queued while it runs are
4724
+ * picked up by the same drain.
4725
+ */
4726
+ flush() {
4727
+ if (!this.inFlight) {
4728
+ this.inFlight = this.drain().finally(() => {
4729
+ this.inFlight = void 0;
4730
+ });
4731
+ }
4732
+ return this.inFlight;
4733
+ }
4734
+ /** Counters for tests and diagnostics. */
4735
+ stats() {
4736
+ return {
4737
+ queueDepth: this.queue.length,
4738
+ droppedSinceLast: this.droppedSinceLast,
4739
+ droppedTotal: this.droppedTotal,
4740
+ deliveredTotal: this.deliveredTotal,
4741
+ flushing: this.inFlight !== void 0
4742
+ };
4743
+ }
4744
+ push(dest, item, eligibleAt) {
4745
+ while (this.queue.length >= this.opts.maxItems) this.dropOldest();
4746
+ const entry = {
4747
+ dest,
4748
+ destKey: destKeyOf(dest),
4749
+ item,
4750
+ attempts: 0,
4751
+ eligibleAt,
4752
+ inFlight: false
4753
+ };
4754
+ this.queue.push(entry);
4755
+ return entry;
4756
+ }
4757
+ dropOldest() {
4758
+ if (this.queue.shift()) this.countDropped(1);
4759
+ }
4760
+ countDropped(n) {
4761
+ this.droppedSinceLast += n;
4762
+ this.droppedTotal += n;
4763
+ }
4764
+ async drain() {
4765
+ for (; ; ) {
4766
+ const now = this.opts.now();
4767
+ if (now < this.backoffUntil) return;
4768
+ const batch = this.takeBatch(now);
4769
+ if (batch.length === 0) return;
4770
+ const ok = await this.send(batch);
4771
+ if (!ok) return;
4772
+ }
4773
+ }
4774
+ /** Oldest eligible item + up to maxBatch-1 more for the same destination. */
4775
+ takeBatch(now) {
4776
+ const first = this.queue.find((q) => q.eligibleAt <= now);
4777
+ if (!first) return [];
4778
+ const batch = [];
4779
+ const rest = [];
4780
+ for (const q of this.queue) {
4781
+ if (batch.length < this.opts.maxBatch && q.destKey === first.destKey && q.eligibleAt <= now) {
4782
+ q.inFlight = true;
4783
+ batch.push(q);
4784
+ } else {
4785
+ rest.push(q);
4786
+ }
4787
+ }
4788
+ this.queue = rest;
4789
+ return batch;
4790
+ }
4791
+ /** POST one batch. Returns false when the drain should pause (backoff). */
4792
+ async send(batch) {
4793
+ const dest = batch[0].dest;
4794
+ const useKey = dest.apiKey && !this.rejectedKeys.has(dest.apiKey) ? dest.apiKey : void 0;
4795
+ const reportedDropped = this.droppedSinceLast;
4796
+ const meta = {
4797
+ droppedSinceLast: reportedDropped,
4798
+ queueDepth: this.queue.length,
4799
+ adapter: dest.adapter ?? "edge-core",
4800
+ version: SDK_VERSION
4801
+ };
4802
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
4803
+ const response = await withBudget(
4804
+ sdkFetch(`${dest.apiBaseUrl}/verification-activity/edge-events`, {
4805
+ method: "POST",
4806
+ headers: {
4807
+ "Content-Type": "application/json",
4808
+ ...useKey && { Authorization: `Bearer ${useKey}` }
4809
+ },
4810
+ body: JSON.stringify({ events: batch.map((q) => q.item), meta }),
4811
+ ...controller && { signal: controller.signal }
4812
+ }),
4813
+ this.opts.requestTimeoutMs
4814
+ );
4815
+ if (!response) controller?.abort();
4816
+ const status = response?.status;
4817
+ for (const q of batch) q.inFlight = false;
4818
+ if (status !== void 0 && status >= 200 && status < 300) {
4819
+ this.droppedSinceLast = Math.max(0, this.droppedSinceLast - reportedDropped);
4820
+ this.deliveredTotal += batch.length;
4821
+ return true;
4822
+ }
4823
+ if (status === 401 && useKey) {
4824
+ this.rejectedKeys.add(useKey);
4825
+ this.requeue(batch, false);
4826
+ return true;
4827
+ }
4828
+ if (status === 429) {
4829
+ const retryAfter = Number(response?.headers.get("retry-after"));
4830
+ const waitMs = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 120) * 1e3 : 3e4;
4831
+ this.backoffUntil = this.opts.now() + waitMs;
4832
+ this.requeue(batch, false);
4833
+ return false;
4834
+ }
4835
+ if (status !== void 0 && status >= 400 && status < 500) {
4836
+ this.countDropped(batch.length);
4837
+ return true;
4838
+ }
4839
+ this.backoffUntil = this.opts.now() + this.opts.retryBackoffMs;
4840
+ this.requeue(batch, true);
4841
+ return false;
4842
+ }
4843
+ /** Put a failed batch back at the head of the queue (order preserved). */
4844
+ requeue(batch, countAttempt) {
4845
+ const keep = [];
4846
+ for (const q of batch) {
4847
+ if (countAttempt) q.attempts += 1;
4848
+ if (q.attempts >= this.opts.maxAttempts) this.countDropped(1);
4849
+ else keep.push(q);
4850
+ }
4851
+ this.queue = [...keep, ...this.queue];
4852
+ while (this.queue.length > this.opts.maxItems) this.dropOldest();
4853
+ }
4854
+ };
4855
+ var beaconBuffer = new BeaconBuffer();
4856
+
4579
4857
  // src/adapters/express.ts
4580
4858
  var DEFAULT_ROUTES_REFRESH_MS = 5 * 60 * 1e3;
4581
4859
 
@@ -5173,22 +5451,118 @@ var AstraSyncGateway = class {
5173
5451
  };
5174
5452
 
5175
5453
  // src/claude-code/guard-config.ts
5176
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
5454
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
5455
+ import { homedir as homedir2 } from "os";
5456
+ import { join as join3 } from "path";
5457
+
5458
+ // src/fleet/enrolment-store.ts
5459
+ import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
5177
5460
  import { homedir } from "os";
5178
- import { join as join2 } from "path";
5179
- function resolveGuardConfig(env, payloadCwd, home = homedir()) {
5461
+ import { dirname as dirname2, join as join2 } from "path";
5462
+ function machineScopeDir(platform = process.platform, env = process.env) {
5463
+ if (platform === "darwin") return "/Library/Application Support/AstraSync";
5464
+ if (platform === "win32") return join2(env.ProgramData || "C:\\ProgramData", "AstraSync");
5465
+ return "/etc/astrasync";
5466
+ }
5467
+ function fleetPaths(options = {}) {
5468
+ const home = options.home ?? homedir();
5469
+ const machineDir = options.machineDir ?? options.env?.ASTRASYNC_FLEET_MACHINE_DIR ?? machineScopeDir(options.platform, options.env);
5470
+ const userDir = join2(home, ".astrasync", "fleet");
5471
+ return {
5472
+ machineDevice: join2(machineDir, "fleet.json"),
5473
+ machinePolicy: join2(machineDir, "policy.jws"),
5474
+ userDir,
5475
+ userDevice: join2(userDir, "device.json"),
5476
+ userPolicy: join2(userDir, "policy.jws"),
5477
+ userKeyChain: join2(userDir, "keychain.json"),
5478
+ state: join2(userDir, "state.json")
5479
+ };
5480
+ }
5481
+ function isEnrolment(value) {
5482
+ const v = value;
5483
+ return !!v && typeof v.deviceId === "string" && typeof v.credential === "string" && typeof v.apiBaseUrl === "string" && !!v.org && typeof v.org.ownerId === "string" && !!v.jwks && Array.isArray(v.jwks.keys);
5484
+ }
5485
+ function loadEnrolment(paths) {
5486
+ const candidates = [
5487
+ [paths.machineDevice, "machine"],
5488
+ [paths.userDevice, "user"]
5489
+ ];
5490
+ for (const [path, scope] of candidates) {
5491
+ if (!existsSync3(path)) continue;
5492
+ try {
5493
+ const parsed = JSON.parse(readFileSync3(path, "utf-8"));
5494
+ if (isEnrolment(parsed)) return { enrolment: parsed, scope };
5495
+ } catch {
5496
+ }
5497
+ return { corrupt: true, path };
5498
+ }
5499
+ return null;
5500
+ }
5501
+ function writeFileMode(path, content, mode) {
5502
+ mkdirSync3(dirname2(path), { recursive: true, mode: 448 });
5503
+ writeFileSync2(path, content, { encoding: "utf-8", mode });
5504
+ try {
5505
+ chmodSync(path, mode);
5506
+ } catch {
5507
+ }
5508
+ }
5509
+ function readCachedPolicies(paths) {
5510
+ const out = [];
5511
+ for (const p of [paths.userPolicy, paths.machinePolicy]) {
5512
+ try {
5513
+ if (existsSync3(p)) out.push(readFileSync3(p, "utf-8").trim());
5514
+ } catch {
5515
+ }
5516
+ }
5517
+ return out.filter(Boolean);
5518
+ }
5519
+ function writeCachedPolicy(paths, jws) {
5520
+ writeFileMode(paths.userPolicy, jws, 384);
5521
+ }
5522
+ function readKeyChain(paths) {
5523
+ try {
5524
+ const parsed = JSON.parse(readFileSync3(paths.userKeyChain, "utf-8"));
5525
+ return Array.isArray(parsed) ? parsed.filter((j) => typeof j === "string") : [];
5526
+ } catch {
5527
+ return [];
5528
+ }
5529
+ }
5530
+ function writeKeyChain(paths, chain) {
5531
+ writeFileMode(paths.userKeyChain, JSON.stringify(chain), 384);
5532
+ }
5533
+ function readState(paths) {
5534
+ try {
5535
+ const parsed = JSON.parse(readFileSync3(paths.state, "utf-8"));
5536
+ const c = parsed.counts;
5537
+ return {
5538
+ ...parsed,
5539
+ counts: { allow: c?.allow ?? 0, deny: c?.deny ?? 0, ask: c?.ask ?? 0 }
5540
+ };
5541
+ } catch {
5542
+ return { counts: { allow: 0, deny: 0, ask: 0 } };
5543
+ }
5544
+ }
5545
+ function writeState(paths, state) {
5546
+ try {
5547
+ writeFileMode(paths.state, JSON.stringify(state, null, 2), 384);
5548
+ } catch {
5549
+ }
5550
+ }
5551
+
5552
+ // src/claude-code/guard-config.ts
5553
+ function resolveGuardConfig(env, payloadCwd, home = homedir2()) {
5180
5554
  const candidateRoots = [env.CLAUDE_PROJECT_DIR, payloadCwd, home].filter(
5181
5555
  (root) => typeof root === "string" && root.length > 0
5182
5556
  );
5183
5557
  for (const root of candidateRoots) {
5184
- const guardDir = join2(root, ".astrasync");
5185
- const policyFile = join2(guardDir, "policy.yaml");
5186
- if (!existsSync3(policyFile)) continue;
5558
+ const guardDir = join3(root, ".astrasync");
5559
+ const policyFile = join3(guardDir, "policy.yaml");
5560
+ if (!existsSync4(policyFile)) continue;
5187
5561
  let settings = {};
5188
- const settingsFile = join2(guardDir, "guard.json");
5189
- if (existsSync3(settingsFile)) {
5562
+ const settingsFile = join3(guardDir, "guard.json");
5563
+ if (existsSync4(settingsFile)) {
5190
5564
  try {
5191
- settings = JSON.parse(readFileSync3(settingsFile, "utf-8"));
5565
+ settings = JSON.parse(readFileSync4(settingsFile, "utf-8"));
5192
5566
  } catch {
5193
5567
  settings = {};
5194
5568
  }
@@ -5197,6 +5571,408 @@ function resolveGuardConfig(env, payloadCwd, home = homedir()) {
5197
5571
  }
5198
5572
  return null;
5199
5573
  }
5574
+ var FLEET_ENROL_INSTRUCTION = "This machine must be enrolled: run `astrasync guard enroll <token>` (token from your organisation admin)";
5575
+ function resolveFleet(env, home = homedir2(), paths = fleetPaths({ home, env })) {
5576
+ const loaded = loadEnrolment(paths);
5577
+ if (loaded && "corrupt" in loaded) {
5578
+ return {
5579
+ kind: "fleet-missing",
5580
+ reason: `fleet enrolment at ${loaded.path} is unreadable \u2014 ${FLEET_ENROL_INSTRUCTION}`,
5581
+ paths
5582
+ };
5583
+ }
5584
+ if (loaded) return { kind: "fleet", enrolment: loaded.enrolment, scope: loaded.scope, paths };
5585
+ if (env.ASTRASYNC_FLEET_REQUIRED === "1") {
5586
+ return { kind: "fleet-missing", reason: FLEET_ENROL_INSTRUCTION, paths };
5587
+ }
5588
+ return null;
5589
+ }
5590
+
5591
+ // src/fleet/hook-runner.ts
5592
+ import { join as join4 } from "path";
5593
+
5594
+ // src/fleet/client.ts
5595
+ var FleetApiError = class extends Error {
5596
+ constructor(message, status, code) {
5597
+ super(message);
5598
+ this.status = status;
5599
+ this.code = code;
5600
+ this.name = "FleetApiError";
5601
+ }
5602
+ };
5603
+ function base(url) {
5604
+ return url.replace(/\/+$/, "");
5605
+ }
5606
+ async function call(url, init, timeoutMs) {
5607
+ const controller = new AbortController();
5608
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
5609
+ try {
5610
+ const res = await sdkFetch(url, { ...init, signal: controller.signal });
5611
+ const text = await res.text();
5612
+ let body = text;
5613
+ try {
5614
+ body = text ? JSON.parse(text) : null;
5615
+ } catch {
5616
+ }
5617
+ return { status: res.status, body, headers: res.headers };
5618
+ } finally {
5619
+ clearTimeout(timer);
5620
+ }
5621
+ }
5622
+ function apiError(status, body, what) {
5623
+ const b = body ?? {};
5624
+ const code = b.code ?? (typeof b.error === "string" ? b.error : void 0);
5625
+ return new FleetApiError(`${what} failed (${status}${code ? ` ${code}` : ""})`, status, code);
5626
+ }
5627
+ function deviceHeaders(enrolment) {
5628
+ return { Authorization: `Device ${enrolment.credential}` };
5629
+ }
5630
+ function policyEtag(sha256, kid) {
5631
+ return `${sha256}.${kid ?? ""}`;
5632
+ }
5633
+ async function fetchFleetPolicy(enrolment, ifNoneMatch, timeoutMs = 1500) {
5634
+ const headers = deviceHeaders(enrolment);
5635
+ if (ifNoneMatch) headers["If-None-Match"] = `"${ifNoneMatch}"`;
5636
+ const r = await call(`${base(enrolment.apiBaseUrl)}/fleet/policy`, { headers }, timeoutMs);
5637
+ if (r.status === 304) return { status: "unchanged" };
5638
+ if (r.status !== 200) throw apiError(r.status, r.body, "Policy fetch");
5639
+ const data = r.body;
5640
+ if (!data?.policyJws) throw new FleetApiError("Policy response has no policyJws", r.status);
5641
+ return {
5642
+ status: "ok",
5643
+ policyJws: data.policyJws,
5644
+ sha256: data.sha256 ?? "",
5645
+ version: data.version ?? 0,
5646
+ keyChain: Array.isArray(data.keyChain) ? data.keyChain.filter((j) => typeof j === "string") : []
5647
+ };
5648
+ }
5649
+ async function sendHeartbeat(enrolment, request, timeoutMs = 1500) {
5650
+ const r = await call(
5651
+ `${base(enrolment.apiBaseUrl)}/fleet/heartbeat`,
5652
+ {
5653
+ method: "POST",
5654
+ headers: { ...deviceHeaders(enrolment), "Content-Type": "application/json" },
5655
+ body: JSON.stringify(request)
5656
+ },
5657
+ timeoutMs
5658
+ );
5659
+ if (r.status !== 200) throw apiError(r.status, r.body, "Heartbeat");
5660
+ return r.body;
5661
+ }
5662
+
5663
+ // src/fleet/policy-verify.ts
5664
+ import { createHash as createHash4 } from "crypto";
5665
+ import { compactVerify, createLocalJWKSet } from "jose";
5666
+
5667
+ // src/fleet/types.ts
5668
+ var FLEET_POLICY_TYP = "fleet-policy+jwt";
5669
+ var FLEET_POLICY_AUD = "astrasync:fleet-policy";
5670
+ var FLEET_POLICY_ISS = "astrasync.ai";
5671
+ var FLEET_KEYS_TYP = "fleet-keys+jwt";
5672
+ var FLEET_KEYS_AUD = "astrasync:fleet-keys";
5673
+ var DEFAULT_HEARTBEAT_INTERVAL_SEC = 900;
5674
+
5675
+ // src/fleet/policy-verify.ts
5676
+ var FleetPolicyError = class extends Error {
5677
+ constructor(message) {
5678
+ super(message);
5679
+ this.name = "FleetPolicyError";
5680
+ }
5681
+ };
5682
+ function sha256Hex(text) {
5683
+ return createHash4("sha256").update(text, "utf8").digest("hex");
5684
+ }
5685
+ function parseSettings(raw) {
5686
+ if (!raw || typeof raw !== "object") throw new FleetPolicyError("settings missing");
5687
+ const s = raw;
5688
+ if (s.posture !== "active" && s.posture !== "passive") {
5689
+ throw new FleetPolicyError("settings.posture must be active or passive");
5690
+ }
5691
+ if (s.failOpen !== void 0 && typeof s.failOpen !== "boolean") {
5692
+ throw new FleetPolicyError("settings.failOpen must be a boolean");
5693
+ }
5694
+ if (s.governMcp !== void 0 && typeof s.governMcp !== "boolean") {
5695
+ throw new FleetPolicyError("settings.governMcp must be a boolean");
5696
+ }
5697
+ if (s.skipTools !== void 0 && !(Array.isArray(s.skipTools) && s.skipTools.every((t) => typeof t === "string"))) {
5698
+ throw new FleetPolicyError("settings.skipTools must be a string array");
5699
+ }
5700
+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
5701
+ return {
5702
+ posture: s.posture,
5703
+ failOpen: s.failOpen === true,
5704
+ ...typeof s.governMcp === "boolean" && { governMcp: s.governMcp },
5705
+ ...Array.isArray(s.skipTools) && { skipTools: s.skipTools },
5706
+ ...num(s.heartbeatIntervalSec) && { heartbeatIntervalSec: num(s.heartbeatIntervalSec) },
5707
+ ...num(s.staleAfterSec) && { staleAfterSec: num(s.staleAfterSec) }
5708
+ };
5709
+ }
5710
+ async function verifyFleetPolicy(jws, jwks, options) {
5711
+ let payloadBytes;
5712
+ let header;
5713
+ try {
5714
+ const keySet = createLocalJWKSet(jwks);
5715
+ const result = await compactVerify(jws, keySet, { algorithms: ["ES256"] });
5716
+ payloadBytes = result.payload;
5717
+ header = result.protectedHeader;
5718
+ } catch (err) {
5719
+ throw new FleetPolicyError(
5720
+ `signature verification failed (${err instanceof Error ? err.message : String(err)})`
5721
+ );
5722
+ }
5723
+ if (header.typ !== FLEET_POLICY_TYP) throw new FleetPolicyError(`unexpected typ ${header.typ}`);
5724
+ let claims;
5725
+ try {
5726
+ claims = JSON.parse(new TextDecoder().decode(payloadBytes));
5727
+ } catch {
5728
+ throw new FleetPolicyError("payload is not JSON");
5729
+ }
5730
+ if (claims.aud !== FLEET_POLICY_AUD) throw new FleetPolicyError(`unexpected aud ${claims.aud}`);
5731
+ if (claims.iss !== FLEET_POLICY_ISS) throw new FleetPolicyError(`unexpected iss ${claims.iss}`);
5732
+ if (!options.expectedSubs.includes(claims.sub)) {
5733
+ throw new FleetPolicyError("policy was issued for a different organisation or device");
5734
+ }
5735
+ if (!Number.isInteger(claims.ver) || claims.ver < 1) {
5736
+ throw new FleetPolicyError("ver must be a positive integer");
5737
+ }
5738
+ if (options.minVer !== void 0 && claims.ver < options.minVer) {
5739
+ throw new FleetPolicyError(
5740
+ `policy version ${claims.ver} is older than the accepted version ${options.minVer} (rollback)`
5741
+ );
5742
+ }
5743
+ if (typeof claims.yaml !== "string" || sha256Hex(claims.yaml) !== claims.sha256) {
5744
+ throw new FleetPolicyError("policy hash mismatch");
5745
+ }
5746
+ const settings = parseSettings(claims.settings);
5747
+ const parsed = parseYaml(claims.yaml);
5748
+ if (!parsed.policy) {
5749
+ const first = parsed.validation.errors[0];
5750
+ throw new FleetPolicyError(
5751
+ `signed policy is invalid${first ? ` (${first.path}: ${first.message})` : ""}`
5752
+ );
5753
+ }
5754
+ return { kid: header.kid, claims: { ...claims, settings }, policy: parsed.policy, settings, jws };
5755
+ }
5756
+ async function resolveFleetJwks(pinned, chain, ownerId) {
5757
+ let trusted = pinned;
5758
+ let lastSeq = 0;
5759
+ for (const link of chain) {
5760
+ try {
5761
+ const { payload, protectedHeader } = await compactVerify(
5762
+ link,
5763
+ createLocalJWKSet(trusted),
5764
+ { algorithms: ["ES256"] }
5765
+ );
5766
+ if (protectedHeader.typ !== FLEET_KEYS_TYP) continue;
5767
+ const c = JSON.parse(new TextDecoder().decode(payload));
5768
+ if (c.aud !== FLEET_KEYS_AUD || c.iss !== FLEET_POLICY_ISS || c.sub !== ownerId) continue;
5769
+ if (!Number.isInteger(c.seq) || c.seq <= lastSeq) continue;
5770
+ const keys = Array.isArray(c.keys) ? c.keys.filter((k) => k && k.kty === "EC" && k.crv === "P-256" && !("d" in k)) : [];
5771
+ if (keys.length === 0) continue;
5772
+ trusted = { keys };
5773
+ lastSeq = c.seq;
5774
+ } catch {
5775
+ }
5776
+ }
5777
+ return trusted;
5778
+ }
5779
+ async function pickNewestValid(candidates, jwks, options) {
5780
+ let best = null;
5781
+ let lastError = new FleetPolicyError("no cached fleet policy");
5782
+ for (const jws of candidates) {
5783
+ try {
5784
+ const v = await verifyFleetPolicy(jws, jwks, options);
5785
+ if (!best || v.claims.ver > best.claims.ver) best = v;
5786
+ } catch (err) {
5787
+ lastError = err instanceof Error ? err : new FleetPolicyError(String(err));
5788
+ }
5789
+ }
5790
+ if (!best) throw lastError;
5791
+ return best;
5792
+ }
5793
+
5794
+ // src/fleet/runtime.ts
5795
+ var FLEET_SYNC_BUDGET_MS = 1500;
5796
+ function expectedSubs(enrolment) {
5797
+ return [enrolment.org.ownerId, enrolment.deviceId];
5798
+ }
5799
+ function fleetJwks(ctx, chain = readKeyChain(ctx.paths)) {
5800
+ return resolveFleetJwks(ctx.enrolment.jwks, chain, ctx.enrolment.org.ownerId);
5801
+ }
5802
+ async function acceptFetched(ctx, fetched, verifyOpts) {
5803
+ const jwks = await fleetJwks(ctx, fetched.keyChain);
5804
+ const verified = await verifyFleetPolicy(fetched.policyJws, jwks, verifyOpts);
5805
+ if (fetched.keyChain.length > 0) writeKeyChain(ctx.paths, fetched.keyChain);
5806
+ writeCachedPolicy(ctx.paths, fetched.policyJws);
5807
+ return verified;
5808
+ }
5809
+ function remember(paths, state, verified) {
5810
+ state.appliedSha256 = verified.claims.sha256;
5811
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5812
+ writeState(paths, state);
5813
+ }
5814
+ async function loadFleetPolicy(ctx, options = {}) {
5815
+ const state = readState(ctx.paths);
5816
+ const verifyOpts = { expectedSubs: expectedSubs(ctx.enrolment), minVer: state.maxVer };
5817
+ const cached = readCachedPolicies(ctx.paths);
5818
+ let cacheError = null;
5819
+ if (cached.length > 0) {
5820
+ try {
5821
+ const verified = await pickNewestValid(cached, await fleetJwks(ctx), verifyOpts);
5822
+ if (verified.claims.sha256 !== state.appliedSha256 || verified.claims.ver !== state.maxVer) {
5823
+ remember(ctx.paths, state, verified);
5824
+ }
5825
+ return verified;
5826
+ } catch (err) {
5827
+ cacheError = err instanceof Error ? err : new FleetPolicyError(String(err));
5828
+ }
5829
+ }
5830
+ try {
5831
+ const fetched = await fetchFleetPolicy(
5832
+ ctx.enrolment,
5833
+ null,
5834
+ options.fetchTimeoutMs ?? FLEET_SYNC_BUDGET_MS
5835
+ );
5836
+ if (fetched.status === "ok") {
5837
+ const verified = await acceptFetched(ctx, fetched, verifyOpts);
5838
+ remember(ctx.paths, state, verified);
5839
+ return verified;
5840
+ }
5841
+ } catch (err) {
5842
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5843
+ state.revoked = true;
5844
+ writeState(ctx.paths, state);
5845
+ }
5846
+ const detail = err instanceof Error ? err.message : String(err);
5847
+ throw new FleetPolicyError(
5848
+ cacheError ? `${cacheError.message}; refresh failed (${detail})` : `no fleet policy (${detail})`
5849
+ );
5850
+ }
5851
+ throw cacheError ?? new FleetPolicyError("no fleet policy available");
5852
+ }
5853
+ async function recordDecisionAndHeartbeat(ctx, applied, decision, options) {
5854
+ const now = options.now ?? Date.now;
5855
+ const state = readState(ctx.paths);
5856
+ if (decision) state.counts[decision] += 1;
5857
+ const intervalSec = applied.settings.heartbeatIntervalSec ?? ctx.enrolment.heartbeatIntervalSec ?? DEFAULT_HEARTBEAT_INTERVAL_SEC;
5858
+ const last = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : 0;
5859
+ if (now() - last < intervalSec * 1e3) {
5860
+ writeState(ctx.paths, state);
5861
+ return "throttled";
5862
+ }
5863
+ const deadline = now() + (options.budgetMs ?? FLEET_SYNC_BUDGET_MS);
5864
+ const remaining = () => Math.max(1, deadline - now());
5865
+ state.lastHeartbeatAt = new Date(now()).toISOString();
5866
+ let outcome = "sent";
5867
+ try {
5868
+ const hb = await sendHeartbeat(
5869
+ ctx.enrolment,
5870
+ {
5871
+ appliedSha256: applied.claims.sha256,
5872
+ guardVersion: options.guardVersion,
5873
+ adapters: [{ kind: options.adapterKind, managed: true }],
5874
+ posture: applied.settings.posture,
5875
+ decisionCounts: { ...state.counts }
5876
+ },
5877
+ remaining()
5878
+ );
5879
+ state.counts = { allow: 0, deny: 0, ask: 0 };
5880
+ state.revoked = false;
5881
+ delete state.lastError;
5882
+ const policyChanged = !!hb.activeSha256 && hb.activeSha256 !== applied.claims.sha256;
5883
+ const keyChanged = !!hb.activeKid && !!applied.kid && hb.activeKid !== applied.kid;
5884
+ if (policyChanged || keyChanged) {
5885
+ const fetched = await fetchFleetPolicy(
5886
+ ctx.enrolment,
5887
+ policyEtag(applied.claims.sha256, applied.kid),
5888
+ remaining()
5889
+ );
5890
+ if (fetched.status === "ok") {
5891
+ const verified = await acceptFetched(ctx, fetched, {
5892
+ expectedSubs: expectedSubs(ctx.enrolment),
5893
+ minVer: Math.max(state.maxVer ?? 0, applied.claims.ver)
5894
+ });
5895
+ state.appliedSha256 = verified.claims.sha256;
5896
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5897
+ outcome = "refreshed";
5898
+ }
5899
+ }
5900
+ } catch (err) {
5901
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5902
+ state.revoked = true;
5903
+ outcome = "revoked";
5904
+ } else {
5905
+ state.lastError = err instanceof Error ? err.message : String(err);
5906
+ outcome = "failed";
5907
+ }
5908
+ }
5909
+ writeState(ctx.paths, state);
5910
+ return outcome;
5911
+ }
5912
+
5913
+ // src/fleet/hook-runner.ts
5914
+ var PREFIX = "AstraSync Local Guard (organisation fleet policy)";
5915
+ async function runFleetHook(args) {
5916
+ if (args.resolution.kind === "fleet-missing") {
5917
+ return { output: args.denyOutput(`${PREFIX}: ${args.resolution.reason}`), exitCode: 0 };
5918
+ }
5919
+ const ctx = { enrolment: args.resolution.enrolment, paths: args.resolution.paths };
5920
+ let verified;
5921
+ try {
5922
+ verified = await loadFleetPolicy(ctx);
5923
+ } catch (err) {
5924
+ const detail = err instanceof Error ? err.message : String(err);
5925
+ return {
5926
+ output: args.denyOutput(`${PREFIX}: no valid signed policy \u2014 ${detail}`),
5927
+ exitCode: 0
5928
+ };
5929
+ }
5930
+ const { settings } = verified;
5931
+ const decide = async (output) => {
5932
+ try {
5933
+ const outcome = await recordDecisionAndHeartbeat(ctx, verified, args.classify(output), {
5934
+ guardVersion: SDK_VERSION,
5935
+ adapterKind: args.adapterKind,
5936
+ now: args.now
5937
+ });
5938
+ args.onHeartbeat?.(outcome);
5939
+ } catch {
5940
+ }
5941
+ return { output, exitCode: 0 };
5942
+ };
5943
+ let payload;
5944
+ try {
5945
+ payload = JSON.parse(args.payloadJson);
5946
+ } catch {
5947
+ if (settings.failOpen) return decide(null);
5948
+ return decide(args.denyOutput(`${PREFIX}: could not parse hook payload`));
5949
+ }
5950
+ try {
5951
+ const gatewayConfig = {
5952
+ mode: "local",
5953
+ policy: verified.policy,
5954
+ posture: settings.posture,
5955
+ traceEnabled: true,
5956
+ tracePath: join4(args.resolution.paths.userDir, "traces"),
5957
+ debug: false
5958
+ };
5959
+ const gateway = args.gatewayFactory ? args.gatewayFactory(gatewayConfig) : new AstraSyncGateway(gatewayConfig);
5960
+ await gateway.initialize();
5961
+ const adapter = args.createAdapter({
5962
+ ...settings.skipTools && { skipTools: settings.skipTools },
5963
+ ...typeof settings.governMcp === "boolean" && { governMcp: settings.governMcp }
5964
+ });
5965
+ await adapter.initialize({ gateway, adapterOptions: {} });
5966
+ const output = await adapter.evaluatePayload(payload);
5967
+ await adapter.shutdown();
5968
+ await gateway.shutdown();
5969
+ return decide(output);
5970
+ } catch (err) {
5971
+ if (settings.failOpen) return decide(null);
5972
+ const detail = err instanceof Error ? err.message : String(err);
5973
+ return decide(args.denyOutput(`${PREFIX}: policy evaluation failed (${detail})`));
5974
+ }
5975
+ }
5200
5976
 
5201
5977
  // src/codex/hook.ts
5202
5978
  var MAX_STDIN_BYTES = 1024 * 1024;
@@ -5214,6 +5990,19 @@ function denyOutput(reason) {
5214
5990
  }
5215
5991
  async function processCodexHookPayload(payloadJson, options = {}) {
5216
5992
  const env = options.env ?? process.env;
5993
+ const fleet = resolveFleet(env, options.home ?? homedir3(), options.fleetPaths);
5994
+ if (fleet) {
5995
+ return runFleetHook({
5996
+ resolution: fleet,
5997
+ payloadJson,
5998
+ adapterKind: "codex",
5999
+ createAdapter: (adapterOptions) => new CodexAdapter(adapterOptions),
6000
+ denyOutput,
6001
+ classify: (output) => output?.hookSpecificOutput?.permissionDecision === "deny" ? "deny" : output?.hookSpecificOutput?.permissionDecision === "ask" ? "ask" : "allow",
6002
+ gatewayFactory: options.gatewayFactory,
6003
+ now: options.now
6004
+ });
6005
+ }
5217
6006
  if (env.ASTRASYNC_GUARD_DISABLE === "1") {
5218
6007
  return { output: null, exitCode: 0 };
5219
6008
  }
@@ -5246,7 +6035,7 @@ async function processCodexHookPayload(payloadJson, options = {}) {
5246
6035
  policyFile: resolved.policyFile,
5247
6036
  posture: resolved.settings.posture ?? "active",
5248
6037
  traceEnabled: true,
5249
- tracePath: join3(resolved.guardDir, "traces"),
6038
+ tracePath: join5(resolved.guardDir, "traces"),
5250
6039
  debug: false,
5251
6040
  ...mode === "hybrid" && {
5252
6041
  apiBaseUrl: resolved.settings.apiBaseUrl,
@@ -5321,8 +6110,8 @@ if (typeof __require !== "undefined" && __require.main === module) {
5321
6110
  }
5322
6111
 
5323
6112
  // src/claude-code/settings-installer.ts
5324
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "fs";
5325
- import { dirname as dirname2 } from "path";
6113
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
6114
+ import { dirname as dirname3 } from "path";
5326
6115
  var ASTRASYNC_HOOK_MARKER = "astrasync-claude-hook";
5327
6116
  var HOOK_MATCHER = "Bash|PowerShell|Write|Edit|MultiEdit|NotebookEdit|Read|Glob|Grep|WebFetch|WebSearch|Task|Agent|mcp__.*";
5328
6117
  var HOOK_TIMEOUT_SECONDS = 10;
@@ -5332,14 +6121,14 @@ function isGuardEntry(entry, marker2) {
5332
6121
  );
5333
6122
  }
5334
6123
  function readSettings(settingsPath) {
5335
- if (!existsSync4(settingsPath)) return {};
5336
- const content = readFileSync4(settingsPath, "utf-8").trim();
6124
+ if (!existsSync5(settingsPath)) return {};
6125
+ const content = readFileSync5(settingsPath, "utf-8").trim();
5337
6126
  if (!content) return {};
5338
6127
  return JSON.parse(content);
5339
6128
  }
5340
6129
  function writeSettings(settingsPath, settings) {
5341
- mkdirSync3(dirname2(settingsPath), { recursive: true });
5342
- writeFileSync2(settingsPath, `${JSON.stringify(settings, null, 2)}
6130
+ mkdirSync4(dirname3(settingsPath), { recursive: true });
6131
+ writeFileSync3(settingsPath, `${JSON.stringify(settings, null, 2)}
5343
6132
  `, "utf-8");
5344
6133
  }
5345
6134
  function buildHookEntry(hookCommand, matcher = HOOK_MATCHER, extraHookFields = {}) {
@@ -5374,7 +6163,7 @@ function installClaudeHooks(settingsPath, hookCommand, marker2 = ASTRASYNC_HOOK_
5374
6163
  return { installed: true, alreadyPresent: false, updated: false };
5375
6164
  }
5376
6165
  function uninstallClaudeHooks(settingsPath, marker2 = ASTRASYNC_HOOK_MARKER) {
5377
- if (!existsSync4(settingsPath)) return false;
6166
+ if (!existsSync5(settingsPath)) return false;
5378
6167
  let settings;
5379
6168
  try {
5380
6169
  settings = readSettings(settingsPath);
@@ -5400,7 +6189,15 @@ var PERMISSION_DENY_PATHS = [
5400
6189
  "~/.claude/settings.json",
5401
6190
  "~/.claude/settings.local.json",
5402
6191
  "**/.astrasync/**",
5403
- "~/.astrasync/**"
6192
+ "~/.astrasync/**",
6193
+ // 5.11.0 fleet mode: enrolment + signed-policy cache (user scope is inside
6194
+ // ~/.astrasync already; listed explicitly so the intent survives edits) and
6195
+ // the machine-scope enrolment dirs. `//` = absolute from filesystem root;
6196
+ // Windows paths are matched in POSIX form (C:\ → /c/).
6197
+ "~/.astrasync/fleet/**",
6198
+ "//etc/astrasync/**",
6199
+ "//Library/Application Support/AstraSync/**",
6200
+ "//c/ProgramData/AstraSync/**"
5404
6201
  ];
5405
6202
  var GUARD_PERMISSION_DENY_RULES = PERMISSION_DENY_PATHS.map(
5406
6203
  (p) => `Edit(${p})`