@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
@@ -3713,7 +3713,7 @@ Policy saved to ${outputPath}`);
3713
3713
  };
3714
3714
 
3715
3715
  // src/version.ts
3716
- var SDK_VERSION = "5.10.0";
3716
+ var SDK_VERSION = "5.12.0";
3717
3717
 
3718
3718
  // src/http.ts
3719
3719
  var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
@@ -3793,27 +3793,23 @@ var UpgradeFlow = class {
3793
3793
  */
3794
3794
  async continueUpgrade(apiKey, kydId) {
3795
3795
  const { print, prompt } = this.callbacks;
3796
- print("\n[3/5] Migrate local policy to cloud");
3797
- print(` Policy: ${this.config.policyPath}`);
3798
- print(` Name: ${this.config.policy.name}`);
3799
- print(` Rules: ${this.config.policy.purposes.length} purpose rules`);
3800
- if (this.config.policy.scope) {
3801
- const scope = this.config.policy.scope;
3802
- const domains = [
3803
- ...(scope.allowedDomains || []).length ? [`${scope.allowedDomains.length} allowed`] : [],
3804
- ...(scope.blockedDomains || []).length ? [`${scope.blockedDomains.length} blocked`] : []
3805
- ];
3806
- if (domains.length) print(` Scope: ${domains.join(", ")} domains`);
3807
- }
3808
- print("");
3809
- print(" Uploading YAML -> Cloud PDLSS boundary...");
3810
- const uploadResult = await this.uploadPolicy(apiKey);
3811
- if (!uploadResult.success) {
3812
- print(` Upload failed: ${uploadResult.error}`);
3813
- return uploadResult;
3814
- }
3815
- print(" Policy uploaded. Same rules, now with trust scoring and audit.");
3816
- print(` Agent registered: ${uploadResult.agentId}`);
3796
+ print("\n[3/5] Link your agent");
3797
+ print(
3798
+ ` Local policy ${this.config.policyPath} stays on this machine (${this.config.policy.purposes.length} purpose rules).`
3799
+ );
3800
+ print(" Register the agent in the AstraSync dashboard (or with `astrasync register`) and");
3801
+ print(" paste its ASTRA- id so synced decisions are attributed to it.\n");
3802
+ const agentInput = (await prompt(" Agent ASTRA- id (Enter to skip): ")).trim();
3803
+ let agentId;
3804
+ if (agentInput) {
3805
+ if (!/^ASTRA-[A-Za-z0-9_-]+$/.test(agentInput)) {
3806
+ return { success: false, error: `Not an ASTRA- agent id: ${agentInput}` };
3807
+ }
3808
+ agentId = agentInput;
3809
+ print(` Agent: ${agentId}`);
3810
+ } else {
3811
+ print(" No agent linked \u2014 decisions sync under your API key only.");
3812
+ }
3817
3813
  if (kydId) {
3818
3814
  print(` Developer: ${kydId}`);
3819
3815
  }
@@ -3824,23 +3820,23 @@ var UpgradeFlow = class {
3824
3820
  const mode = modeInput.trim().toLowerCase() === "online" ? "online" : "hybrid";
3825
3821
  print(`
3826
3822
  [5/5] Activating ${mode} verification`);
3827
- await this.writeLocalConfig(apiKey, uploadResult.agentId, mode, kydId);
3823
+ await this.writeLocalConfig(apiKey, agentId, mode, kydId);
3828
3824
  print(` Config written to ${this.configDir}/config`);
3829
3825
  print(` Mode: ${mode}`);
3830
3826
  print(" Done!\n");
3831
- print(` Your agent (${uploadResult.agentId}) is verified on the AstraSync network.`);
3827
+ if (agentId) print(` Your agent (${agentId}) is verified on the AstraSync network.`);
3832
3828
  if (mode === "hybrid") {
3833
3829
  print(" Local evaluation active for speed. Cloud sync for audit and trust scoring.");
3834
3830
  } else {
3835
3831
  print(" Trust scoring, audit trails, and blockchain recording are active.");
3836
3832
  }
3837
3833
  print(`
3838
- Dashboard: ${this.platformUrl}/agents/${uploadResult.agentId}
3834
+ Dashboard: ${this.platformUrl}/agents${agentId ? `/${agentId}` : ""}
3839
3835
  `);
3840
3836
  return {
3841
3837
  success: true,
3842
3838
  apiKey,
3843
- agentId: uploadResult.agentId,
3839
+ agentId,
3844
3840
  kydId,
3845
3841
  mode
3846
3842
  };
@@ -3893,44 +3889,6 @@ var UpgradeFlow = class {
3893
3889
  return { valid: true, error: `Could not reach platform (proceeding anyway)` };
3894
3890
  }
3895
3891
  }
3896
- /**
3897
- * Upload local policy to the AstraSync cloud.
3898
- * YAML -> cloud PDLSS boundary, 1:1 mapping, no lossy transformation.
3899
- */
3900
- async uploadPolicy(apiKey) {
3901
- const policyYaml = toYaml(this.config.policy);
3902
- try {
3903
- const response = await sdkFetch(`${this.platformUrl}/api/v1/agents/policies/upload`, {
3904
- method: "POST",
3905
- headers: {
3906
- "Content-Type": "application/json",
3907
- Authorization: `Bearer ${apiKey}`
3908
- },
3909
- body: JSON.stringify({
3910
- policy: policyYaml,
3911
- policyObject: this.config.policy,
3912
- format: "yaml",
3913
- source: "local-guard-upgrade",
3914
- name: this.config.policy.name
3915
- })
3916
- });
3917
- if (!response.ok) {
3918
- const body = await response.text();
3919
- return { success: false, error: `Upload failed (${response.status}): ${body}` };
3920
- }
3921
- const data = await response.json();
3922
- return {
3923
- success: true,
3924
- agentId: data.agentId || "ASTRA-PENDING",
3925
- kydId: data.kydId
3926
- };
3927
- } catch (err) {
3928
- return {
3929
- success: false,
3930
- error: `Network error: ${err instanceof Error ? err.message : String(err)}`
3931
- };
3932
- }
3933
- }
3934
3892
  /**
3935
3893
  * Write the config file for the chosen mode.
3936
3894
  */
@@ -4686,6 +4644,14 @@ function getCachedWellKnownUrls(apiBaseUrl) {
4686
4644
  return cache.get(apiBaseUrl)?.data;
4687
4645
  }
4688
4646
 
4647
+ // src/failure-posture.ts
4648
+ var REJECTED_IDENTITY_DIMENSIONS = /* @__PURE__ */ new Set([
4649
+ "identity.invalid_agent_id",
4650
+ "identity.unknown_agent",
4651
+ "agent.lookup"
4652
+ ]);
4653
+ 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.";
4654
+
4689
4655
  // src/verify.ts
4690
4656
  var DEFAULT_CONFIG = {
4691
4657
  apiBaseUrl: "https://astrasync.ai/api",
@@ -4897,11 +4863,44 @@ function createGuidanceResponse(_config, reason, options = {}) {
4897
4863
  // coercing the absent recommendation to a policy 'deny'. Misconfig is
4898
4864
  // deterministic and intentionally NOT marked retryable.
4899
4865
  ...isApiError && { retryable: true },
4866
+ ...options.httpStatus !== void 0 && { httpStatus: options.httpStatus },
4867
+ ...options.retryAfterMs !== void 0 && { retryAfterMs: options.retryAfterMs },
4900
4868
  correlationId: options.correlationId,
4901
4869
  attemptId: options.attemptId,
4902
4870
  verifiedAt: /* @__PURE__ */ new Date()
4903
4871
  };
4904
4872
  }
4873
+ async function readJsonSafe(response) {
4874
+ try {
4875
+ const parsed = await response.json();
4876
+ return parsed && typeof parsed === "object" ? parsed : {};
4877
+ } catch {
4878
+ return {};
4879
+ }
4880
+ }
4881
+ function rejectedIdentityGuidance(failures) {
4882
+ const f = failures?.find((x) => REJECTED_IDENTITY_DIMENSIONS.has(x.dimension));
4883
+ if (!f) return void 0;
4884
+ if (f.dimension === "agent.lookup") {
4885
+ return `The presented agent identifier is not registered with AstraSync. ${UNKNOWN_AGENT_GUIDANCE}`;
4886
+ }
4887
+ return f.guidance ? `${f.message} ${f.guidance}` : f.message;
4888
+ }
4889
+ var MAX_RETRY_AFTER_MS = 15 * 60 * 1e3;
4890
+ function parseRetryAfterMs(response) {
4891
+ const raw = response.headers?.get?.("retry-after");
4892
+ if (!raw) return void 0;
4893
+ const trimmed = raw.trim();
4894
+ let ms;
4895
+ if (/^\d+(\.\d+)?$/.test(trimmed)) {
4896
+ ms = Number(trimmed) * 1e3;
4897
+ } else {
4898
+ const at = Date.parse(trimmed);
4899
+ if (Number.isNaN(at)) return void 0;
4900
+ ms = at - Date.now();
4901
+ }
4902
+ return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, Math.round(ms)));
4903
+ }
4905
4904
  async function callVerifyAccessAPI(config, request2) {
4906
4905
  const { credentials, ...requestData } = request2;
4907
4906
  const body = {
@@ -4958,7 +4957,8 @@ async function callVerifyAccessAPI(config, request2) {
4958
4957
  body: JSON.stringify(body),
4959
4958
  signal: AbortSignal.timeout(config.verifyTimeoutMs ?? 1e4)
4960
4959
  });
4961
- const data = await response.json();
4960
+ const data = await readJsonSafe(response);
4961
+ const retryAfterMs = parseRetryAfterMs(response);
4962
4962
  if (response.status === 410) {
4963
4963
  return {
4964
4964
  success: true,
@@ -4996,6 +4996,23 @@ async function callVerifyAccessAPI(config, request2) {
4996
4996
  }
4997
4997
  };
4998
4998
  }
4999
+ if (response.status === 404 && credentials.astraId && (data?.error === "AGENT_NOT_FOUND" || typeof data?.message === "string" && /agent/i.test(data.message))) {
5000
+ return {
5001
+ success: true,
5002
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
5003
+ access: {
5004
+ allowed: false,
5005
+ reason: "unknown_agent",
5006
+ failures: [
5007
+ {
5008
+ dimension: "identity.unknown_agent",
5009
+ message: "The presented agent identifier is not registered with AstraSync.",
5010
+ guidance: UNKNOWN_AGENT_GUIDANCE
5011
+ }
5012
+ ]
5013
+ }
5014
+ };
5015
+ }
4999
5016
  if (!response.ok) {
5000
5017
  if (response.status === 401) {
5001
5018
  return {
@@ -5010,9 +5027,11 @@ async function callVerifyAccessAPI(config, request2) {
5010
5027
  }
5011
5028
  return {
5012
5029
  success: false,
5013
- error: data.message || data.error || `API returned ${response.status}`,
5030
+ error: typeof data?.message === "string" && data.message || typeof data?.error === "string" && data.error || `API returned ${response.status}`,
5014
5031
  correlationId: typeof data?.correlationId === "string" ? data.correlationId : void 0,
5015
- attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0
5032
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
5033
+ httpStatus: response.status,
5034
+ ...retryAfterMs !== void 0 && { retryAfterMs }
5016
5035
  };
5017
5036
  }
5018
5037
  return data;
@@ -5084,12 +5103,14 @@ async function verify(config, request2, options) {
5084
5103
  correlationId: apiResponse.correlationId,
5085
5104
  attemptId: apiResponse.attemptId,
5086
5105
  remediation: apiResponse.remediation,
5106
+ httpStatus: apiResponse.httpStatus,
5107
+ retryAfterMs: apiResponse.retryAfterMs,
5087
5108
  urls
5088
5109
  });
5089
5110
  }
5090
5111
  if (!apiResponse.access?.allowed) {
5091
5112
  const aggregatedFailures = apiResponse.access?.failures;
5092
- const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true;
5113
+ const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true && !aggregatedFailures?.some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));
5093
5114
  const result2 = {
5094
5115
  identityVerified: idVerifiedFromBackend,
5095
5116
  policyAllowed: false,
@@ -5101,7 +5122,10 @@ async function verify(config, request2, options) {
5101
5122
  requiresStepUp: apiResponse.access?.requiresStepUp,
5102
5123
  requiresApproval: apiResponse.access?.requiresApproval,
5103
5124
  guidance: {
5104
- message: apiResponse.access?.reason || "Access denied by PDLSS policy",
5125
+ // 5.12.0: a presented-but-rejected id (malformed / unknown) carries
5126
+ // actionable registration guidance on its failure — surface it
5127
+ // instead of the bare machine reason ('unknown_agent').
5128
+ message: rejectedIdentityGuidance(aggregatedFailures) ?? (apiResponse.access?.reason || "Access denied by PDLSS policy"),
5105
5129
  registrationUrl: urls?.registrationUrl ?? "",
5106
5130
  documentationUrl: urls?.documentationUrl ?? "",
5107
5131
  // 5.1.0: anonymous callers land on this branch — steer MCP-hosted
@@ -5201,7 +5225,7 @@ async function verify(config, request2, options) {
5201
5225
  registrationUrl: urls?.registrationUrl ?? "",
5202
5226
  documentationUrl: urls?.documentationUrl ?? ""
5203
5227
  };
5204
- } else if (result.recommendation === "step_up_required") {
5228
+ } else if (result.recommendation === "step_up_required" && result.identityVerified) {
5205
5229
  result.requiresStepUp = true;
5206
5230
  result.denialReasons = serverDenialReasons ?? result.recommendationReasons ?? ["Step-up verification required"];
5207
5231
  }
@@ -5230,6 +5254,217 @@ var DEFAULT_EDGE_CONFIG = Object.freeze({
5230
5254
  var DEFAULT_TTL_MS = 60 * 1e3;
5231
5255
  var DEFAULT_MAX_STALE_MS = 24 * 60 * 60 * 1e3;
5232
5256
 
5257
+ // src/edge-core/events.ts
5258
+ async function withBudget(promise, ms) {
5259
+ let timer;
5260
+ try {
5261
+ return await Promise.race([
5262
+ promise,
5263
+ new Promise((resolve) => {
5264
+ timer = setTimeout(() => resolve(void 0), ms);
5265
+ })
5266
+ ]);
5267
+ } catch {
5268
+ return void 0;
5269
+ } finally {
5270
+ if (timer) clearTimeout(timer);
5271
+ }
5272
+ }
5273
+ var destKeyOf = (d) => `${d.apiBaseUrl}\0${d.apiKey ?? ""}\0${d.counterparty}\0${d.adapter ?? ""}`;
5274
+ var BeaconBuffer = class {
5275
+ constructor(options = {}) {
5276
+ this.queue = [];
5277
+ this.droppedSinceLast = 0;
5278
+ this.droppedTotal = 0;
5279
+ this.deliveredTotal = 0;
5280
+ this.backoffUntil = 0;
5281
+ this.collapse = /* @__PURE__ */ new Map();
5282
+ /** Keys the backend answered 401 for — later batches go unauthenticated. */
5283
+ this.rejectedKeys = /* @__PURE__ */ new Set();
5284
+ this.opts = {
5285
+ maxItems: options.maxItems ?? 1e3,
5286
+ maxBatch: options.maxBatch ?? 100,
5287
+ maxAttempts: options.maxAttempts ?? 3,
5288
+ collapseWindowMs: options.collapseWindowMs ?? 6e4,
5289
+ collapseMaxKeys: options.collapseMaxKeys ?? 1e3,
5290
+ requestTimeoutMs: options.requestTimeoutMs ?? 1e4,
5291
+ retryBackoffMs: options.retryBackoffMs ?? 1e3,
5292
+ now: options.now ?? Date.now
5293
+ };
5294
+ }
5295
+ /**
5296
+ * Queue one beacon. With a `collapseKey`, a repeat inside the window is
5297
+ * merged into a held aggregate (sent when the window closes) instead of
5298
+ * becoming its own item.
5299
+ */
5300
+ enqueue(dest, item, collapseKey) {
5301
+ const now = this.opts.now();
5302
+ if (collapseKey) {
5303
+ const entry = this.collapse.get(collapseKey);
5304
+ if (entry && now - entry.firstSeenAt < this.opts.collapseWindowMs) {
5305
+ for (const target of [entry.first, entry.held]) {
5306
+ if (target && !target.inFlight && this.queue.includes(target)) {
5307
+ target.item.repeatCount = (target.item.repeatCount ?? 1) + 1;
5308
+ return;
5309
+ }
5310
+ }
5311
+ const held = this.push(
5312
+ dest,
5313
+ { ...item, repeatCount: 1 },
5314
+ entry.firstSeenAt + this.opts.collapseWindowMs
5315
+ );
5316
+ entry.held = held;
5317
+ return;
5318
+ }
5319
+ this.collapse.delete(collapseKey);
5320
+ if (this.collapse.size >= this.opts.collapseMaxKeys) {
5321
+ const oldest = this.collapse.keys().next().value;
5322
+ if (oldest !== void 0) this.collapse.delete(oldest);
5323
+ }
5324
+ const fresh = { firstSeenAt: now };
5325
+ this.collapse.set(collapseKey, fresh);
5326
+ fresh.first = this.push(dest, item, now);
5327
+ return;
5328
+ }
5329
+ this.push(dest, item, now);
5330
+ }
5331
+ /**
5332
+ * Deliver every eligible queued item. Concurrent callers share ONE
5333
+ * in-flight drain (it survives the caller's budget and a Lambda freeze),
5334
+ * so nothing in flight is ever sent twice; items queued while it runs are
5335
+ * picked up by the same drain.
5336
+ */
5337
+ flush() {
5338
+ if (!this.inFlight) {
5339
+ this.inFlight = this.drain().finally(() => {
5340
+ this.inFlight = void 0;
5341
+ });
5342
+ }
5343
+ return this.inFlight;
5344
+ }
5345
+ /** Counters for tests and diagnostics. */
5346
+ stats() {
5347
+ return {
5348
+ queueDepth: this.queue.length,
5349
+ droppedSinceLast: this.droppedSinceLast,
5350
+ droppedTotal: this.droppedTotal,
5351
+ deliveredTotal: this.deliveredTotal,
5352
+ flushing: this.inFlight !== void 0
5353
+ };
5354
+ }
5355
+ push(dest, item, eligibleAt) {
5356
+ while (this.queue.length >= this.opts.maxItems) this.dropOldest();
5357
+ const entry = {
5358
+ dest,
5359
+ destKey: destKeyOf(dest),
5360
+ item,
5361
+ attempts: 0,
5362
+ eligibleAt,
5363
+ inFlight: false
5364
+ };
5365
+ this.queue.push(entry);
5366
+ return entry;
5367
+ }
5368
+ dropOldest() {
5369
+ if (this.queue.shift()) this.countDropped(1);
5370
+ }
5371
+ countDropped(n) {
5372
+ this.droppedSinceLast += n;
5373
+ this.droppedTotal += n;
5374
+ }
5375
+ async drain() {
5376
+ for (; ; ) {
5377
+ const now = this.opts.now();
5378
+ if (now < this.backoffUntil) return;
5379
+ const batch = this.takeBatch(now);
5380
+ if (batch.length === 0) return;
5381
+ const ok = await this.send(batch);
5382
+ if (!ok) return;
5383
+ }
5384
+ }
5385
+ /** Oldest eligible item + up to maxBatch-1 more for the same destination. */
5386
+ takeBatch(now) {
5387
+ const first = this.queue.find((q) => q.eligibleAt <= now);
5388
+ if (!first) return [];
5389
+ const batch = [];
5390
+ const rest = [];
5391
+ for (const q of this.queue) {
5392
+ if (batch.length < this.opts.maxBatch && q.destKey === first.destKey && q.eligibleAt <= now) {
5393
+ q.inFlight = true;
5394
+ batch.push(q);
5395
+ } else {
5396
+ rest.push(q);
5397
+ }
5398
+ }
5399
+ this.queue = rest;
5400
+ return batch;
5401
+ }
5402
+ /** POST one batch. Returns false when the drain should pause (backoff). */
5403
+ async send(batch) {
5404
+ const dest = batch[0].dest;
5405
+ const useKey = dest.apiKey && !this.rejectedKeys.has(dest.apiKey) ? dest.apiKey : void 0;
5406
+ const reportedDropped = this.droppedSinceLast;
5407
+ const meta = {
5408
+ droppedSinceLast: reportedDropped,
5409
+ queueDepth: this.queue.length,
5410
+ adapter: dest.adapter ?? "edge-core",
5411
+ version: SDK_VERSION
5412
+ };
5413
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
5414
+ const response = await withBudget(
5415
+ sdkFetch(`${dest.apiBaseUrl}/verification-activity/edge-events`, {
5416
+ method: "POST",
5417
+ headers: {
5418
+ "Content-Type": "application/json",
5419
+ ...useKey && { Authorization: `Bearer ${useKey}` }
5420
+ },
5421
+ body: JSON.stringify({ events: batch.map((q) => q.item), meta }),
5422
+ ...controller && { signal: controller.signal }
5423
+ }),
5424
+ this.opts.requestTimeoutMs
5425
+ );
5426
+ if (!response) controller?.abort();
5427
+ const status = response?.status;
5428
+ for (const q of batch) q.inFlight = false;
5429
+ if (status !== void 0 && status >= 200 && status < 300) {
5430
+ this.droppedSinceLast = Math.max(0, this.droppedSinceLast - reportedDropped);
5431
+ this.deliveredTotal += batch.length;
5432
+ return true;
5433
+ }
5434
+ if (status === 401 && useKey) {
5435
+ this.rejectedKeys.add(useKey);
5436
+ this.requeue(batch, false);
5437
+ return true;
5438
+ }
5439
+ if (status === 429) {
5440
+ const retryAfter = Number(response?.headers.get("retry-after"));
5441
+ const waitMs = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 120) * 1e3 : 3e4;
5442
+ this.backoffUntil = this.opts.now() + waitMs;
5443
+ this.requeue(batch, false);
5444
+ return false;
5445
+ }
5446
+ if (status !== void 0 && status >= 400 && status < 500) {
5447
+ this.countDropped(batch.length);
5448
+ return true;
5449
+ }
5450
+ this.backoffUntil = this.opts.now() + this.opts.retryBackoffMs;
5451
+ this.requeue(batch, true);
5452
+ return false;
5453
+ }
5454
+ /** Put a failed batch back at the head of the queue (order preserved). */
5455
+ requeue(batch, countAttempt) {
5456
+ const keep = [];
5457
+ for (const q of batch) {
5458
+ if (countAttempt) q.attempts += 1;
5459
+ if (q.attempts >= this.opts.maxAttempts) this.countDropped(1);
5460
+ else keep.push(q);
5461
+ }
5462
+ this.queue = [...keep, ...this.queue];
5463
+ while (this.queue.length > this.opts.maxItems) this.dropOldest();
5464
+ }
5465
+ };
5466
+ var beaconBuffer = new BeaconBuffer();
5467
+
5233
5468
  // src/adapters/express.ts
5234
5469
  var DEFAULT_ROUTES_REFRESH_MS = 5 * 60 * 1e3;
5235
5470
 
@@ -6025,7 +6260,15 @@ var PERMISSION_DENY_PATHS = [
6025
6260
  "~/.claude/settings.json",
6026
6261
  "~/.claude/settings.local.json",
6027
6262
  "**/.astrasync/**",
6028
- "~/.astrasync/**"
6263
+ "~/.astrasync/**",
6264
+ // 5.11.0 fleet mode: enrolment + signed-policy cache (user scope is inside
6265
+ // ~/.astrasync already; listed explicitly so the intent survives edits) and
6266
+ // the machine-scope enrolment dirs. `//` = absolute from filesystem root;
6267
+ // Windows paths are matched in POSIX form (C:\ → /c/).
6268
+ "~/.astrasync/fleet/**",
6269
+ "//etc/astrasync/**",
6270
+ "//Library/Application Support/AstraSync/**",
6271
+ "//c/ProgramData/AstraSync/**"
6029
6272
  ];
6030
6273
  var GUARD_PERMISSION_DENY_RULES = PERMISSION_DENY_PATHS.map(
6031
6274
  (p) => `Edit(${p})`
@@ -6156,6 +6399,509 @@ function uninstallCodexHooks(hooksPath) {
6156
6399
  return uninstallClaudeHooks(hooksPath, ASTRASYNC_CODEX_HOOK_MARKER);
6157
6400
  }
6158
6401
 
6402
+ // src/fleet/cli.ts
6403
+ var import_crypto2 = require("crypto");
6404
+ var import_fs7 = require("fs");
6405
+ var import_os2 = require("os");
6406
+ var import_path6 = require("path");
6407
+
6408
+ // src/fleet/client.ts
6409
+ var FleetApiError = class extends Error {
6410
+ constructor(message, status, code) {
6411
+ super(message);
6412
+ this.status = status;
6413
+ this.code = code;
6414
+ this.name = "FleetApiError";
6415
+ }
6416
+ };
6417
+ function base(url) {
6418
+ return url.replace(/\/+$/, "");
6419
+ }
6420
+ async function call(url, init, timeoutMs) {
6421
+ const controller = new AbortController();
6422
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
6423
+ try {
6424
+ const res = await sdkFetch(url, { ...init, signal: controller.signal });
6425
+ const text = await res.text();
6426
+ let body = text;
6427
+ try {
6428
+ body = text ? JSON.parse(text) : null;
6429
+ } catch {
6430
+ }
6431
+ return { status: res.status, body, headers: res.headers };
6432
+ } finally {
6433
+ clearTimeout(timer);
6434
+ }
6435
+ }
6436
+ function apiError(status, body, what) {
6437
+ const b = body ?? {};
6438
+ const code = b.code ?? (typeof b.error === "string" ? b.error : void 0);
6439
+ return new FleetApiError(`${what} failed (${status}${code ? ` ${code}` : ""})`, status, code);
6440
+ }
6441
+ async function enrolDevice(apiBaseUrl, request2, timeoutMs = 15e3) {
6442
+ const r = await call(
6443
+ `${base(apiBaseUrl)}/fleet/enrol`,
6444
+ {
6445
+ method: "POST",
6446
+ headers: { "Content-Type": "application/json" },
6447
+ body: JSON.stringify(request2)
6448
+ },
6449
+ timeoutMs
6450
+ );
6451
+ if (r.status !== 201 && r.status !== 200) throw apiError(r.status, r.body, "Enrolment");
6452
+ const data = r.body;
6453
+ if (!data?.deviceId || !data.credential || !data.jwks || !data.policyJws) {
6454
+ throw new FleetApiError("Enrolment response is missing required fields", r.status);
6455
+ }
6456
+ return data;
6457
+ }
6458
+
6459
+ // src/fleet/enrolment-store.ts
6460
+ var import_fs6 = require("fs");
6461
+ var import_os = require("os");
6462
+ var import_path5 = require("path");
6463
+ function machineScopeDir(platform2 = process.platform, env = process.env) {
6464
+ if (platform2 === "darwin") return "/Library/Application Support/AstraSync";
6465
+ if (platform2 === "win32") return (0, import_path5.join)(env.ProgramData || "C:\\ProgramData", "AstraSync");
6466
+ return "/etc/astrasync";
6467
+ }
6468
+ function fleetPaths(options = {}) {
6469
+ const home = options.home ?? (0, import_os.homedir)();
6470
+ const machineDir = options.machineDir ?? options.env?.ASTRASYNC_FLEET_MACHINE_DIR ?? machineScopeDir(options.platform, options.env);
6471
+ const userDir = (0, import_path5.join)(home, ".astrasync", "fleet");
6472
+ return {
6473
+ machineDevice: (0, import_path5.join)(machineDir, "fleet.json"),
6474
+ machinePolicy: (0, import_path5.join)(machineDir, "policy.jws"),
6475
+ userDir,
6476
+ userDevice: (0, import_path5.join)(userDir, "device.json"),
6477
+ userPolicy: (0, import_path5.join)(userDir, "policy.jws"),
6478
+ userKeyChain: (0, import_path5.join)(userDir, "keychain.json"),
6479
+ state: (0, import_path5.join)(userDir, "state.json")
6480
+ };
6481
+ }
6482
+ function isEnrolment(value) {
6483
+ const v = value;
6484
+ 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);
6485
+ }
6486
+ function loadEnrolment(paths) {
6487
+ const candidates = [
6488
+ [paths.machineDevice, "machine"],
6489
+ [paths.userDevice, "user"]
6490
+ ];
6491
+ for (const [path2, scope] of candidates) {
6492
+ if (!(0, import_fs6.existsSync)(path2)) continue;
6493
+ try {
6494
+ const parsed = JSON.parse((0, import_fs6.readFileSync)(path2, "utf-8"));
6495
+ if (isEnrolment(parsed)) return { enrolment: parsed, scope };
6496
+ } catch {
6497
+ }
6498
+ return { corrupt: true, path: path2 };
6499
+ }
6500
+ return null;
6501
+ }
6502
+ function writeFileMode(path2, content, mode) {
6503
+ (0, import_fs6.mkdirSync)((0, import_path5.dirname)(path2), { recursive: true, mode: 448 });
6504
+ (0, import_fs6.writeFileSync)(path2, content, { encoding: "utf-8", mode });
6505
+ try {
6506
+ (0, import_fs6.chmodSync)(path2, mode);
6507
+ } catch {
6508
+ }
6509
+ }
6510
+ function saveEnrolment(paths, enrolment, scope) {
6511
+ const path2 = scope === "machine" ? paths.machineDevice : paths.userDevice;
6512
+ writeFileMode(path2, JSON.stringify(enrolment, null, 2), scope === "machine" ? 420 : 384);
6513
+ return path2;
6514
+ }
6515
+ function readCachedPolicies(paths) {
6516
+ const out = [];
6517
+ for (const p of [paths.userPolicy, paths.machinePolicy]) {
6518
+ try {
6519
+ if ((0, import_fs6.existsSync)(p)) out.push((0, import_fs6.readFileSync)(p, "utf-8").trim());
6520
+ } catch {
6521
+ }
6522
+ }
6523
+ return out.filter(Boolean);
6524
+ }
6525
+ function writeCachedPolicy(paths, jws) {
6526
+ writeFileMode(paths.userPolicy, jws, 384);
6527
+ }
6528
+ function readKeyChain(paths) {
6529
+ try {
6530
+ const parsed = JSON.parse((0, import_fs6.readFileSync)(paths.userKeyChain, "utf-8"));
6531
+ return Array.isArray(parsed) ? parsed.filter((j) => typeof j === "string") : [];
6532
+ } catch {
6533
+ return [];
6534
+ }
6535
+ }
6536
+ function writeKeyChain(paths, chain) {
6537
+ writeFileMode(paths.userKeyChain, JSON.stringify(chain), 384);
6538
+ }
6539
+ function writeMachinePolicy(paths, jws) {
6540
+ writeFileMode(paths.machinePolicy, jws, 420);
6541
+ }
6542
+ function readState(paths) {
6543
+ try {
6544
+ const parsed = JSON.parse((0, import_fs6.readFileSync)(paths.state, "utf-8"));
6545
+ const c = parsed.counts;
6546
+ return {
6547
+ ...parsed,
6548
+ counts: { allow: c?.allow ?? 0, deny: c?.deny ?? 0, ask: c?.ask ?? 0 }
6549
+ };
6550
+ } catch {
6551
+ return { counts: { allow: 0, deny: 0, ask: 0 } };
6552
+ }
6553
+ }
6554
+ function writeState(paths, state) {
6555
+ try {
6556
+ writeFileMode(paths.state, JSON.stringify(state, null, 2), 384);
6557
+ } catch {
6558
+ }
6559
+ }
6560
+
6561
+ // src/fleet/policy-verify.ts
6562
+ var import_crypto = require("crypto");
6563
+ var import_jose2 = require("jose");
6564
+
6565
+ // src/fleet/types.ts
6566
+ var FLEET_POLICY_TYP = "fleet-policy+jwt";
6567
+ var FLEET_POLICY_AUD = "astrasync:fleet-policy";
6568
+ var FLEET_POLICY_ISS = "astrasync.ai";
6569
+ var FLEET_KEYS_TYP = "fleet-keys+jwt";
6570
+ var FLEET_KEYS_AUD = "astrasync:fleet-keys";
6571
+ var DEFAULT_HEARTBEAT_INTERVAL_SEC = 900;
6572
+
6573
+ // src/fleet/policy-verify.ts
6574
+ var FleetPolicyError = class extends Error {
6575
+ constructor(message) {
6576
+ super(message);
6577
+ this.name = "FleetPolicyError";
6578
+ }
6579
+ };
6580
+ function sha256Hex(text) {
6581
+ return (0, import_crypto.createHash)("sha256").update(text, "utf8").digest("hex");
6582
+ }
6583
+ function parseSettings(raw) {
6584
+ if (!raw || typeof raw !== "object") throw new FleetPolicyError("settings missing");
6585
+ const s = raw;
6586
+ if (s.posture !== "active" && s.posture !== "passive") {
6587
+ throw new FleetPolicyError("settings.posture must be active or passive");
6588
+ }
6589
+ if (s.failOpen !== void 0 && typeof s.failOpen !== "boolean") {
6590
+ throw new FleetPolicyError("settings.failOpen must be a boolean");
6591
+ }
6592
+ if (s.governMcp !== void 0 && typeof s.governMcp !== "boolean") {
6593
+ throw new FleetPolicyError("settings.governMcp must be a boolean");
6594
+ }
6595
+ if (s.skipTools !== void 0 && !(Array.isArray(s.skipTools) && s.skipTools.every((t) => typeof t === "string"))) {
6596
+ throw new FleetPolicyError("settings.skipTools must be a string array");
6597
+ }
6598
+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
6599
+ return {
6600
+ posture: s.posture,
6601
+ failOpen: s.failOpen === true,
6602
+ ...typeof s.governMcp === "boolean" && { governMcp: s.governMcp },
6603
+ ...Array.isArray(s.skipTools) && { skipTools: s.skipTools },
6604
+ ...num(s.heartbeatIntervalSec) && { heartbeatIntervalSec: num(s.heartbeatIntervalSec) },
6605
+ ...num(s.staleAfterSec) && { staleAfterSec: num(s.staleAfterSec) }
6606
+ };
6607
+ }
6608
+ async function verifyFleetPolicy(jws, jwks, options) {
6609
+ let payloadBytes;
6610
+ let header;
6611
+ try {
6612
+ const keySet = (0, import_jose2.createLocalJWKSet)(jwks);
6613
+ const result = await (0, import_jose2.compactVerify)(jws, keySet, { algorithms: ["ES256"] });
6614
+ payloadBytes = result.payload;
6615
+ header = result.protectedHeader;
6616
+ } catch (err) {
6617
+ throw new FleetPolicyError(
6618
+ `signature verification failed (${err instanceof Error ? err.message : String(err)})`
6619
+ );
6620
+ }
6621
+ if (header.typ !== FLEET_POLICY_TYP) throw new FleetPolicyError(`unexpected typ ${header.typ}`);
6622
+ let claims;
6623
+ try {
6624
+ claims = JSON.parse(new TextDecoder().decode(payloadBytes));
6625
+ } catch {
6626
+ throw new FleetPolicyError("payload is not JSON");
6627
+ }
6628
+ if (claims.aud !== FLEET_POLICY_AUD) throw new FleetPolicyError(`unexpected aud ${claims.aud}`);
6629
+ if (claims.iss !== FLEET_POLICY_ISS) throw new FleetPolicyError(`unexpected iss ${claims.iss}`);
6630
+ if (!options.expectedSubs.includes(claims.sub)) {
6631
+ throw new FleetPolicyError("policy was issued for a different organisation or device");
6632
+ }
6633
+ if (!Number.isInteger(claims.ver) || claims.ver < 1) {
6634
+ throw new FleetPolicyError("ver must be a positive integer");
6635
+ }
6636
+ if (options.minVer !== void 0 && claims.ver < options.minVer) {
6637
+ throw new FleetPolicyError(
6638
+ `policy version ${claims.ver} is older than the accepted version ${options.minVer} (rollback)`
6639
+ );
6640
+ }
6641
+ if (typeof claims.yaml !== "string" || sha256Hex(claims.yaml) !== claims.sha256) {
6642
+ throw new FleetPolicyError("policy hash mismatch");
6643
+ }
6644
+ const settings = parseSettings(claims.settings);
6645
+ const parsed = parseYaml(claims.yaml);
6646
+ if (!parsed.policy) {
6647
+ const first = parsed.validation.errors[0];
6648
+ throw new FleetPolicyError(
6649
+ `signed policy is invalid${first ? ` (${first.path}: ${first.message})` : ""}`
6650
+ );
6651
+ }
6652
+ return { kid: header.kid, claims: { ...claims, settings }, policy: parsed.policy, settings, jws };
6653
+ }
6654
+ async function resolveFleetJwks(pinned, chain, ownerId) {
6655
+ let trusted = pinned;
6656
+ let lastSeq = 0;
6657
+ for (const link of chain) {
6658
+ try {
6659
+ const { payload, protectedHeader } = await (0, import_jose2.compactVerify)(
6660
+ link,
6661
+ (0, import_jose2.createLocalJWKSet)(trusted),
6662
+ { algorithms: ["ES256"] }
6663
+ );
6664
+ if (protectedHeader.typ !== FLEET_KEYS_TYP) continue;
6665
+ const c = JSON.parse(new TextDecoder().decode(payload));
6666
+ if (c.aud !== FLEET_KEYS_AUD || c.iss !== FLEET_POLICY_ISS || c.sub !== ownerId) continue;
6667
+ if (!Number.isInteger(c.seq) || c.seq <= lastSeq) continue;
6668
+ const keys = Array.isArray(c.keys) ? c.keys.filter((k) => k && k.kty === "EC" && k.crv === "P-256" && !("d" in k)) : [];
6669
+ if (keys.length === 0) continue;
6670
+ trusted = { keys };
6671
+ lastSeq = c.seq;
6672
+ } catch {
6673
+ }
6674
+ }
6675
+ return trusted;
6676
+ }
6677
+ async function pickNewestValid(candidates, jwks, options) {
6678
+ let best = null;
6679
+ let lastError = new FleetPolicyError("no cached fleet policy");
6680
+ for (const jws of candidates) {
6681
+ try {
6682
+ const v = await verifyFleetPolicy(jws, jwks, options);
6683
+ if (!best || v.claims.ver > best.claims.ver) best = v;
6684
+ } catch (err) {
6685
+ lastError = err instanceof Error ? err : new FleetPolicyError(String(err));
6686
+ }
6687
+ }
6688
+ if (!best) throw lastError;
6689
+ return best;
6690
+ }
6691
+
6692
+ // src/fleet/cli.ts
6693
+ var DEFAULT_FLEET_API_BASE_URL = "https://astrasync.ai/api";
6694
+ function machineFingerprint() {
6695
+ const candidates = ["/etc/machine-id", "/var/lib/dbus/machine-id"];
6696
+ let raw = "";
6697
+ for (const c of candidates) {
6698
+ try {
6699
+ if ((0, import_fs7.existsSync)(c)) {
6700
+ raw = (0, import_fs7.readFileSync)(c, "utf-8").trim();
6701
+ if (raw) break;
6702
+ }
6703
+ } catch {
6704
+ }
6705
+ }
6706
+ if (!raw) raw = `${(0, import_os2.hostname)()}|${(0, import_os2.platform)()}|${(0, import_os2.arch)()}`;
6707
+ return (0, import_crypto2.createHash)("sha256").update(`astrasync-fleet:${raw}`).digest("hex");
6708
+ }
6709
+ async function runEnroll(options) {
6710
+ const print = options.print ?? ((l) => console.log(l));
6711
+ const token = options.token.trim();
6712
+ if (!token)
6713
+ throw new Error("Usage: astrasync guard enroll <token> [--api-base-url <url>] [--system]");
6714
+ const apiBaseUrl = (options.apiBaseUrl ?? DEFAULT_FLEET_API_BASE_URL).replace(/\/+$/, "");
6715
+ const paths = options.paths ?? fleetPaths();
6716
+ const response = await enrolDevice(apiBaseUrl, {
6717
+ token,
6718
+ fingerprint: options.fingerprint ?? machineFingerprint(),
6719
+ hostname: (0, import_os2.hostname)(),
6720
+ os: { platform: (0, import_os2.platform)(), release: (0, import_os2.release)(), arch: (0, import_os2.arch)() },
6721
+ guardVersion: SDK_VERSION,
6722
+ adapters: options.adapters ?? [
6723
+ { kind: "claude-code", managed: false },
6724
+ { kind: "codex", managed: false }
6725
+ ]
6726
+ });
6727
+ const enrolment = {
6728
+ version: 1,
6729
+ deviceId: response.deviceId,
6730
+ credential: response.credential,
6731
+ org: response.org,
6732
+ apiBaseUrl: response.apiBaseUrl || apiBaseUrl,
6733
+ jwks: response.jwks,
6734
+ heartbeatIntervalSec: response.heartbeatIntervalSec || DEFAULT_HEARTBEAT_INTERVAL_SEC,
6735
+ enrolledAt: (/* @__PURE__ */ new Date()).toISOString()
6736
+ };
6737
+ const verified = await verifyFleetPolicy(response.policyJws, enrolment.jwks, {
6738
+ expectedSubs: [enrolment.org.ownerId, enrolment.deviceId]
6739
+ });
6740
+ const scope = options.system ? "machine" : "user";
6741
+ const savedTo = saveEnrolment(paths, enrolment, scope);
6742
+ if (options.system) writeMachinePolicy(paths, response.policyJws);
6743
+ writeCachedPolicy(paths, response.policyJws);
6744
+ writeKeyChain(paths, []);
6745
+ const state = readState(paths);
6746
+ writeState(paths, {
6747
+ ...state,
6748
+ appliedSha256: verified.claims.sha256,
6749
+ maxVer: Math.max(state.maxVer ?? 0, verified.claims.ver),
6750
+ revoked: false
6751
+ });
6752
+ print(
6753
+ `Enrolled in ${enrolment.org.name ?? enrolment.org.ownerId} (device ${enrolment.deviceId}).`
6754
+ );
6755
+ print(` Enrolment: ${savedTo} (${scope} scope)`);
6756
+ print(` Policy: v${verified.claims.ver}, posture ${verified.settings.posture}`);
6757
+ print(
6758
+ " Local policy.yaml / guard.json files are now ignored \u2014 the organisation policy governs."
6759
+ );
6760
+ return enrolment;
6761
+ }
6762
+ async function getFleetStatus(paths = fleetPaths()) {
6763
+ const loaded = loadEnrolment(paths);
6764
+ if (!loaded) return { enrolled: false };
6765
+ if ("corrupt" in loaded) return { enrolled: true, corrupt: loaded.path };
6766
+ const { enrolment, scope } = loaded;
6767
+ const state = readState(paths);
6768
+ let policy;
6769
+ try {
6770
+ const jwks = await resolveFleetJwks(enrolment.jwks, readKeyChain(paths), enrolment.org.ownerId);
6771
+ const v = await pickNewestValid(readCachedPolicies(paths), jwks, {
6772
+ expectedSubs: [enrolment.org.ownerId, enrolment.deviceId],
6773
+ minVer: state.maxVer
6774
+ });
6775
+ policy = {
6776
+ ver: v.claims.ver,
6777
+ sha256: v.claims.sha256,
6778
+ posture: v.settings.posture,
6779
+ failOpen: v.settings.failOpen
6780
+ };
6781
+ } catch (err) {
6782
+ policy = { error: err instanceof Error ? err.message : String(err) };
6783
+ }
6784
+ return {
6785
+ enrolled: true,
6786
+ scope,
6787
+ org: enrolment.org,
6788
+ deviceId: enrolment.deviceId,
6789
+ apiBaseUrl: enrolment.apiBaseUrl,
6790
+ policy,
6791
+ lastHeartbeatAt: state.lastHeartbeatAt,
6792
+ revoked: state.revoked === true,
6793
+ lastError: state.lastError,
6794
+ pendingCounts: state.counts
6795
+ };
6796
+ }
6797
+ function formatFleetStatus(status) {
6798
+ if (!status.enrolled) return ["Fleet: not enrolled (local policy mode)."];
6799
+ if (status.corrupt) {
6800
+ return [`Fleet: enrolment file ${status.corrupt} is unreadable \u2014 the guard fails closed.`];
6801
+ }
6802
+ const lines = [
6803
+ `Fleet: enrolled in ${status.org?.name ?? status.org?.ownerId} (${status.scope} scope)`,
6804
+ ` Device: ${status.deviceId}`,
6805
+ ` Platform: ${status.apiBaseUrl}`
6806
+ ];
6807
+ if (status.policy && "error" in status.policy) {
6808
+ lines.push(` Policy: NO VALID SIGNED POLICY \u2014 ${status.policy.error} (guard denies)`);
6809
+ } else if (status.policy) {
6810
+ lines.push(
6811
+ ` Policy: v${status.policy.ver} (${status.policy.sha256.slice(0, 12)}\u2026), posture ${status.policy.posture}${status.policy.failOpen ? ", fail-open" : ""}`
6812
+ );
6813
+ }
6814
+ lines.push(` Heartbeat: ${status.lastHeartbeatAt ?? "never"}`);
6815
+ if (status.revoked) {
6816
+ lines.push(" Status: REVOKED by the organisation \u2014 enforcing the last good policy");
6817
+ }
6818
+ if (status.lastError) lines.push(` Last sync error: ${status.lastError}`);
6819
+ return lines;
6820
+ }
6821
+ var MANAGED_SETTINGS_LOCATIONS = {
6822
+ // code.claude.com/docs/en/managed-settings
6823
+ claude: {
6824
+ darwin: "/Library/Application Support/ClaudeCode/managed-settings.json",
6825
+ linux: "/etc/claude-code/managed-settings.json",
6826
+ win32: "C:\\Program Files\\ClaudeCode\\managed-settings.json"
6827
+ },
6828
+ // learn.chatgpt.com/docs/enterprise/managed-configuration
6829
+ codex: {
6830
+ darwin: "/etc/codex/requirements.toml",
6831
+ linux: "/etc/codex/requirements.toml",
6832
+ win32: "%ProgramData%\\OpenAI\\Codex\\requirements.toml"
6833
+ }
6834
+ };
6835
+ function managedHookCommand(target, os2) {
6836
+ const bin = target === "claude" ? "astrasync-claude-hook" : "astrasync-codex-hook";
6837
+ if (os2 === "win32") return `"C:\\Program Files\\nodejs\\${bin}.cmd"`;
6838
+ return `/usr/local/bin/${bin}`;
6839
+ }
6840
+ function buildClaudeManagedSettings(os2) {
6841
+ return {
6842
+ allowManagedHooksOnly: true,
6843
+ env: { ASTRASYNC_FLEET_REQUIRED: "1" },
6844
+ hooks: {
6845
+ PreToolUse: [
6846
+ {
6847
+ matcher: HOOK_MATCHER,
6848
+ hooks: [{ type: "command", command: managedHookCommand("claude", os2), timeout: 10 }]
6849
+ }
6850
+ ]
6851
+ },
6852
+ permissions: { deny: [...GUARD_PERMISSION_DENY_RULES] }
6853
+ };
6854
+ }
6855
+ function tomlString(value) {
6856
+ return JSON.stringify(value);
6857
+ }
6858
+ function buildCodexRequirementsToml(os2) {
6859
+ const command = os2 === "win32" ? `set ASTRASYNC_FLEET_REQUIRED=1&& ${managedHookCommand("codex", os2)}` : `ASTRASYNC_FLEET_REQUIRED=1 ${managedHookCommand("codex", os2)}`;
6860
+ return [
6861
+ "# AstraSync Local Guard \u2014 managed hook (generated by `astrasync guard managed-settings --codex`)",
6862
+ `# Install at: ${MANAGED_SETTINGS_LOCATIONS.codex[os2]}`,
6863
+ "allow_managed_hooks_only = true",
6864
+ "",
6865
+ "[features]",
6866
+ "hooks = true",
6867
+ "",
6868
+ "[[hooks.PreToolUse]]",
6869
+ `matcher = ${tomlString(CODEX_HOOK_MATCHER)}`,
6870
+ "",
6871
+ "[[hooks.PreToolUse.hooks]]",
6872
+ 'type = "command"',
6873
+ `command = ${tomlString(command)}`,
6874
+ "timeout = 10",
6875
+ 'statusMessage = "AstraSync Local Guard"',
6876
+ ""
6877
+ ].join("\n");
6878
+ }
6879
+ function buildManagedSettingsFiles(targets) {
6880
+ const out = [];
6881
+ for (const target of targets) {
6882
+ for (const os2 of ["darwin", "linux", "win32"]) {
6883
+ const content = target === "claude" ? `${JSON.stringify(buildClaudeManagedSettings(os2), null, 2)}
6884
+ ` : buildCodexRequirementsToml(os2);
6885
+ out.push({
6886
+ target,
6887
+ os: os2,
6888
+ installPath: MANAGED_SETTINGS_LOCATIONS[target][os2],
6889
+ fileName: `${target}-${os2}-${target === "claude" ? "managed-settings.json" : "requirements.toml"}`,
6890
+ content
6891
+ });
6892
+ }
6893
+ }
6894
+ return out;
6895
+ }
6896
+ function writeManagedSettings(files, outDir) {
6897
+ (0, import_fs7.mkdirSync)(outDir, { recursive: true });
6898
+ return files.map((f) => {
6899
+ const p = (0, import_path6.join)(outDir, f.fileName);
6900
+ (0, import_fs7.writeFileSync)(p, f.content, "utf-8");
6901
+ return p;
6902
+ });
6903
+ }
6904
+
6159
6905
  // src/cli/guard.ts
6160
6906
  var DEFAULT_POLICY_PATH = "./local-policy.yaml";
6161
6907
  var DEFAULT_CONFIG_DIR = ".astrasync";
@@ -6295,6 +7041,9 @@ async function cmdStatus() {
6295
7041
  }
6296
7042
  });
6297
7043
  console.log("\nAstraSync Local Guard Status\n");
7044
+ for (const line of formatFleetStatus(await getFleetStatus(fleetPaths()))) {
7045
+ console.log(` ${line}`);
7046
+ }
6298
7047
  if (upgraded) {
6299
7048
  const config = JSON.parse(fs.readFileSync(`${DEFAULT_CONFIG_DIR}/config`, "utf-8"));
6300
7049
  console.log(` Mode: ${config.mode}`);
@@ -6650,6 +7399,66 @@ function printClaudeCodeStatus() {
6650
7399
  }
6651
7400
  }
6652
7401
  }
7402
+ function flagValue(flag) {
7403
+ const i = process.argv.indexOf(flag);
7404
+ return i !== -1 ? process.argv[i + 1] : void 0;
7405
+ }
7406
+ function positionalAfter(command) {
7407
+ const argv = process.argv;
7408
+ const start = argv.indexOf(command) + 1;
7409
+ for (let i = start; i < argv.length; i++) {
7410
+ if (argv[i].startsWith("--")) {
7411
+ if (argv[i] === "--api-base-url" || argv[i] === "--out") i++;
7412
+ continue;
7413
+ }
7414
+ return argv[i];
7415
+ }
7416
+ return void 0;
7417
+ }
7418
+ async function cmdEnroll() {
7419
+ const token = positionalAfter("enroll") ?? "";
7420
+ try {
7421
+ await runEnroll({
7422
+ token,
7423
+ apiBaseUrl: flagValue("--api-base-url"),
7424
+ system: process.argv.includes("--system")
7425
+ });
7426
+ } catch (err) {
7427
+ console.error(`Enrolment failed: ${err instanceof Error ? err.message : String(err)}`);
7428
+ if (process.argv.includes("--system")) {
7429
+ console.error(
7430
+ " (--system writes the machine-scope enrolment and needs administrator rights)"
7431
+ );
7432
+ }
7433
+ process.exit(1);
7434
+ }
7435
+ }
7436
+ async function cmdFleetStatus() {
7437
+ const status = await getFleetStatus(fleetPaths());
7438
+ for (const line of formatFleetStatus(status)) console.log(line);
7439
+ }
7440
+ async function cmdManagedSettings() {
7441
+ const targets = [];
7442
+ if (process.argv.includes("--claude")) targets.push("claude");
7443
+ if (process.argv.includes("--codex")) targets.push("codex");
7444
+ if (targets.length === 0) targets.push("claude", "codex");
7445
+ const files = buildManagedSettingsFiles(targets);
7446
+ const outDir = flagValue("--out");
7447
+ if (outDir) {
7448
+ const written = writeManagedSettings(files, outDir);
7449
+ console.log("Managed-settings templates written:");
7450
+ files.forEach((f, i) => console.log(` ${written[i]} \u2192 deploy to ${f.installPath}`));
7451
+ } else {
7452
+ for (const f of files) {
7453
+ console.log(`===== ${f.target} \xB7 ${f.os} \u2192 ${f.installPath}`);
7454
+ console.log(f.content);
7455
+ }
7456
+ }
7457
+ console.log(
7458
+ "Hook commands assume npm\u2019s default global prefix; adjust if your MDM installs elsewhere."
7459
+ );
7460
+ console.log("Machines must also be enrolled: astrasync guard enroll <token> --system");
7461
+ }
6653
7462
  async function main() {
6654
7463
  const command = process.argv[2] === "guard" ? process.argv[3] : process.argv[2];
6655
7464
  switch (command) {
@@ -6686,6 +7495,16 @@ async function main() {
6686
7495
  case "uninstall-codex":
6687
7496
  await cmdUninstallCodex();
6688
7497
  break;
7498
+ case "enroll":
7499
+ case "enrol":
7500
+ await cmdEnroll();
7501
+ break;
7502
+ case "fleet-status":
7503
+ await cmdFleetStatus();
7504
+ break;
7505
+ case "managed-settings":
7506
+ await cmdManagedSettings();
7507
+ break;
6689
7508
  default:
6690
7509
  console.log("AstraSync Local Guard\n");
6691
7510
  console.log("Usage: astrasync guard <command>\n");
@@ -6706,6 +7525,10 @@ async function main() {
6706
7525
  console.log(" install-codex Install the Local Guard hook for OpenAI Codex CLI");
6707
7526
  console.log(" (same flags; policy shared with Claude Code)");
6708
7527
  console.log(" uninstall-codex Remove the Codex hook (--project for project scope)");
7528
+ console.log(" enroll <token> Enrol this machine in your organisation fleet");
7529
+ console.log(" (--api-base-url <url>, --system for machine scope)");
7530
+ console.log(" fleet-status Show fleet enrolment, signed policy and heartbeat");
7531
+ console.log(" managed-settings Print MDM templates (--claude, --codex, --out <dir>)");
6709
7532
  console.log("");
6710
7533
  process.exit(command ? 1 : 0);
6711
7534
  }