@astrasyncai/verification-gateway 5.9.0 → 5.11.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 (79) hide show
  1. package/dist/adapters/express.js +19 -1
  2. package/dist/adapters/express.js.map +1 -1
  3. package/dist/adapters/express.mjs +19 -1
  4. package/dist/adapters/express.mjs.map +1 -1
  5. package/dist/adapters/mcp.js +19 -1
  6. package/dist/adapters/mcp.js.map +1 -1
  7. package/dist/adapters/mcp.mjs +19 -1
  8. package/dist/adapters/mcp.mjs.map +1 -1
  9. package/dist/adapters/nextjs.js +19 -1
  10. package/dist/adapters/nextjs.js.map +1 -1
  11. package/dist/adapters/nextjs.mjs +19 -1
  12. package/dist/adapters/nextjs.mjs.map +1 -1
  13. package/dist/adapters/sdk.js +19 -1
  14. package/dist/adapters/sdk.js.map +1 -1
  15. package/dist/adapters/sdk.mjs +19 -1
  16. package/dist/adapters/sdk.mjs.map +1 -1
  17. package/dist/agent/index.js +1 -1
  18. package/dist/agent/index.js.map +1 -1
  19. package/dist/agent/index.mjs +1 -1
  20. package/dist/agent/index.mjs.map +1 -1
  21. package/dist/bin/astrasync-claude-hook.js +540 -10
  22. package/dist/bin/astrasync-codex-hook.js +540 -10
  23. package/dist/bin/astrasync-guard.js +629 -65
  24. package/dist/bin/astrasync.js +673 -66
  25. package/dist/browser/background.js +19 -1
  26. package/dist/browser/background.js.map +1 -1
  27. package/dist/browser/background.mjs +19 -1
  28. package/dist/browser/background.mjs.map +1 -1
  29. package/dist/cli/index.d.mts +8 -8
  30. package/dist/cli/index.d.ts +8 -8
  31. package/dist/cli/index.js +22 -64
  32. package/dist/cli/index.js.map +1 -1
  33. package/dist/cli/index.mjs +22 -64
  34. package/dist/cli/index.mjs.map +1 -1
  35. package/dist/codex/index.d.mts +5 -0
  36. package/dist/codex/index.d.ts +5 -0
  37. package/dist/codex/index.js +556 -18
  38. package/dist/codex/index.js.map +1 -1
  39. package/dist/codex/index.mjs +558 -20
  40. package/dist/codex/index.mjs.map +1 -1
  41. package/dist/cursor/extension.d.mts +9 -2
  42. package/dist/cursor/extension.d.ts +9 -2
  43. package/dist/cursor/extension.js +522 -5
  44. package/dist/cursor/extension.js.map +1 -1
  45. package/dist/cursor/extension.mjs +524 -5
  46. package/dist/cursor/extension.mjs.map +1 -1
  47. package/dist/edge-config.js +1 -1
  48. package/dist/edge-config.js.map +1 -1
  49. package/dist/edge-config.mjs +1 -1
  50. package/dist/edge-config.mjs.map +1 -1
  51. package/dist/edge-core/index.js +20 -2
  52. package/dist/edge-core/index.js.map +1 -1
  53. package/dist/edge-core/index.mjs +20 -2
  54. package/dist/edge-core/index.mjs.map +1 -1
  55. package/dist/enrolment-store-8DyaIOLe.d.mts +26 -0
  56. package/dist/enrolment-store-8DyaIOLe.d.ts +26 -0
  57. package/dist/gateway/gateway.js +19 -1
  58. package/dist/gateway/gateway.js.map +1 -1
  59. package/dist/gateway/gateway.mjs +19 -1
  60. package/dist/gateway/gateway.mjs.map +1 -1
  61. package/dist/index.d.mts +100 -3
  62. package/dist/index.d.ts +100 -3
  63. package/dist/index.js +3289 -18
  64. package/dist/index.js.map +1 -1
  65. package/dist/index.mjs +3287 -18
  66. package/dist/index.mjs.map +1 -1
  67. package/dist/registration/index.js +1 -1
  68. package/dist/registration/index.js.map +1 -1
  69. package/dist/registration/index.mjs +1 -1
  70. package/dist/registration/index.mjs.map +1 -1
  71. package/dist/transport/index.js +1 -1
  72. package/dist/transport/index.js.map +1 -1
  73. package/dist/transport/index.mjs +1 -1
  74. package/dist/transport/index.mjs.map +1 -1
  75. package/dist/verify.js +19 -1
  76. package/dist/verify.js.map +1 -1
  77. package/dist/verify.mjs +19 -1
  78. package/dist/verify.mjs.map +1 -1
  79. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { f as PlatformAdapter, A as AdapterConfig, a as AgentAction, I as InterceptResult, P as PDLSSContext, V as VerificationDecision, b as AstraSyncGateway } from '../interface-q1WrMsB1.mjs';
2
+ import { F as FleetPaths } from '../enrolment-store-8DyaIOLe.mjs';
2
3
 
3
4
  /**
4
5
  * @astrasyncai/adapter-codex
@@ -173,6 +174,10 @@ interface ProcessCodexHookOptions {
173
174
  home?: string;
174
175
  /** Injectable for tests */
175
176
  gatewayFactory?: (config: ConstructorParameters<typeof AstraSyncGateway>[0]) => AstraSyncGateway;
177
+ /** Injectable for tests: fleet enrolment/cache locations. */
178
+ fleetPaths?: FleetPaths;
179
+ /** Injectable for tests: clock for the fleet heartbeat throttle. */
180
+ now?: () => number;
176
181
  }
177
182
  interface ProcessCodexHookResult {
178
183
  output: CodexHookOutput | null;
@@ -1,4 +1,5 @@
1
1
  import { f as PlatformAdapter, A as AdapterConfig, a as AgentAction, I as InterceptResult, P as PDLSSContext, V as VerificationDecision, b as AstraSyncGateway } from '../interface-q1WrMsB1.js';
2
+ import { F as FleetPaths } from '../enrolment-store-8DyaIOLe.js';
2
3
 
3
4
  /**
4
5
  * @astrasyncai/adapter-codex
@@ -173,6 +174,10 @@ interface ProcessCodexHookOptions {
173
174
  home?: string;
174
175
  /** Injectable for tests */
175
176
  gatewayFactory?: (config: ConstructorParameters<typeof AstraSyncGateway>[0]) => AstraSyncGateway;
177
+ /** Injectable for tests: fleet enrolment/cache locations. */
178
+ fleetPaths?: FleetPaths;
179
+ /** Injectable for tests: clock for the fleet heartbeat throttle. */
180
+ now?: () => number;
176
181
  }
177
182
  interface ProcessCodexHookResult {
178
183
  output: CodexHookOutput | null;
@@ -309,7 +309,8 @@ var CodexAdapter = class {
309
309
  };
310
310
 
311
311
  // src/codex/hook.ts
312
- var import_path4 = require("path");
312
+ var import_os3 = require("os");
313
+ var import_path6 = require("path");
313
314
 
314
315
  // src/gateway/types.ts
315
316
  var HIGH_RISK_COMMANDS = [
@@ -4035,7 +4036,7 @@ function getTrustLevel(score) {
4035
4036
  }
4036
4037
 
4037
4038
  // src/version.ts
4038
- var SDK_VERSION = "5.9.0";
4039
+ var SDK_VERSION = "5.11.0";
4039
4040
 
4040
4041
  // src/http.ts
4041
4042
  var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
@@ -4354,6 +4355,24 @@ async function callVerifyAccessAPI(config, request) {
4354
4355
  }
4355
4356
  };
4356
4357
  }
4358
+ if (response.status === 400 && data?.error === "INVALID_AGENT_ID") {
4359
+ const message = typeof data?.message === "string" ? data.message : "Agent identifier must be a canonical ASTRA-* id.";
4360
+ return {
4361
+ success: true,
4362
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
4363
+ access: {
4364
+ allowed: false,
4365
+ reason: "invalid_agent_id",
4366
+ failures: [
4367
+ {
4368
+ dimension: "identity.invalid_agent_id",
4369
+ message,
4370
+ guidance: typeof data?.guidance === "string" ? data.guidance : "Present your canonical ASTRA-* id (discover it via GET /api/agents/request-registration/{requestId} after owner approval)."
4371
+ }
4372
+ ]
4373
+ }
4374
+ };
4375
+ }
4357
4376
  if (!response.ok) {
4358
4377
  if (response.status === 401) {
4359
4378
  return {
@@ -5182,22 +5201,118 @@ var AstraSyncGateway = class {
5182
5201
  };
5183
5202
 
5184
5203
  // src/claude-code/guard-config.ts
5204
+ var import_fs5 = require("fs");
5205
+ var import_os2 = require("os");
5206
+ var import_path4 = require("path");
5207
+
5208
+ // src/fleet/enrolment-store.ts
5185
5209
  var import_fs4 = require("fs");
5186
5210
  var import_os = require("os");
5187
5211
  var import_path3 = require("path");
5188
- function resolveGuardConfig(env, payloadCwd, home = (0, import_os.homedir)()) {
5212
+ function machineScopeDir(platform = process.platform, env = process.env) {
5213
+ if (platform === "darwin") return "/Library/Application Support/AstraSync";
5214
+ if (platform === "win32") return (0, import_path3.join)(env.ProgramData || "C:\\ProgramData", "AstraSync");
5215
+ return "/etc/astrasync";
5216
+ }
5217
+ function fleetPaths(options = {}) {
5218
+ const home = options.home ?? (0, import_os.homedir)();
5219
+ const machineDir = options.machineDir ?? options.env?.ASTRASYNC_FLEET_MACHINE_DIR ?? machineScopeDir(options.platform, options.env);
5220
+ const userDir = (0, import_path3.join)(home, ".astrasync", "fleet");
5221
+ return {
5222
+ machineDevice: (0, import_path3.join)(machineDir, "fleet.json"),
5223
+ machinePolicy: (0, import_path3.join)(machineDir, "policy.jws"),
5224
+ userDir,
5225
+ userDevice: (0, import_path3.join)(userDir, "device.json"),
5226
+ userPolicy: (0, import_path3.join)(userDir, "policy.jws"),
5227
+ userKeyChain: (0, import_path3.join)(userDir, "keychain.json"),
5228
+ state: (0, import_path3.join)(userDir, "state.json")
5229
+ };
5230
+ }
5231
+ function isEnrolment(value) {
5232
+ const v = value;
5233
+ 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);
5234
+ }
5235
+ function loadEnrolment(paths) {
5236
+ const candidates = [
5237
+ [paths.machineDevice, "machine"],
5238
+ [paths.userDevice, "user"]
5239
+ ];
5240
+ for (const [path, scope] of candidates) {
5241
+ if (!(0, import_fs4.existsSync)(path)) continue;
5242
+ try {
5243
+ const parsed = JSON.parse((0, import_fs4.readFileSync)(path, "utf-8"));
5244
+ if (isEnrolment(parsed)) return { enrolment: parsed, scope };
5245
+ } catch {
5246
+ }
5247
+ return { corrupt: true, path };
5248
+ }
5249
+ return null;
5250
+ }
5251
+ function writeFileMode(path, content, mode) {
5252
+ (0, import_fs4.mkdirSync)((0, import_path3.dirname)(path), { recursive: true, mode: 448 });
5253
+ (0, import_fs4.writeFileSync)(path, content, { encoding: "utf-8", mode });
5254
+ try {
5255
+ (0, import_fs4.chmodSync)(path, mode);
5256
+ } catch {
5257
+ }
5258
+ }
5259
+ function readCachedPolicies(paths) {
5260
+ const out = [];
5261
+ for (const p of [paths.userPolicy, paths.machinePolicy]) {
5262
+ try {
5263
+ if ((0, import_fs4.existsSync)(p)) out.push((0, import_fs4.readFileSync)(p, "utf-8").trim());
5264
+ } catch {
5265
+ }
5266
+ }
5267
+ return out.filter(Boolean);
5268
+ }
5269
+ function writeCachedPolicy(paths, jws) {
5270
+ writeFileMode(paths.userPolicy, jws, 384);
5271
+ }
5272
+ function readKeyChain(paths) {
5273
+ try {
5274
+ const parsed = JSON.parse((0, import_fs4.readFileSync)(paths.userKeyChain, "utf-8"));
5275
+ return Array.isArray(parsed) ? parsed.filter((j) => typeof j === "string") : [];
5276
+ } catch {
5277
+ return [];
5278
+ }
5279
+ }
5280
+ function writeKeyChain(paths, chain) {
5281
+ writeFileMode(paths.userKeyChain, JSON.stringify(chain), 384);
5282
+ }
5283
+ function readState(paths) {
5284
+ try {
5285
+ const parsed = JSON.parse((0, import_fs4.readFileSync)(paths.state, "utf-8"));
5286
+ const c = parsed.counts;
5287
+ return {
5288
+ ...parsed,
5289
+ counts: { allow: c?.allow ?? 0, deny: c?.deny ?? 0, ask: c?.ask ?? 0 }
5290
+ };
5291
+ } catch {
5292
+ return { counts: { allow: 0, deny: 0, ask: 0 } };
5293
+ }
5294
+ }
5295
+ function writeState(paths, state) {
5296
+ try {
5297
+ writeFileMode(paths.state, JSON.stringify(state, null, 2), 384);
5298
+ } catch {
5299
+ }
5300
+ }
5301
+
5302
+ // src/claude-code/guard-config.ts
5303
+ function resolveGuardConfig(env, payloadCwd, home = (0, import_os2.homedir)()) {
5189
5304
  const candidateRoots = [env.CLAUDE_PROJECT_DIR, payloadCwd, home].filter(
5190
5305
  (root) => typeof root === "string" && root.length > 0
5191
5306
  );
5192
5307
  for (const root of candidateRoots) {
5193
- const guardDir = (0, import_path3.join)(root, ".astrasync");
5194
- const policyFile = (0, import_path3.join)(guardDir, "policy.yaml");
5195
- if (!(0, import_fs4.existsSync)(policyFile)) continue;
5308
+ const guardDir = (0, import_path4.join)(root, ".astrasync");
5309
+ const policyFile = (0, import_path4.join)(guardDir, "policy.yaml");
5310
+ if (!(0, import_fs5.existsSync)(policyFile)) continue;
5196
5311
  let settings = {};
5197
- const settingsFile = (0, import_path3.join)(guardDir, "guard.json");
5198
- if ((0, import_fs4.existsSync)(settingsFile)) {
5312
+ const settingsFile = (0, import_path4.join)(guardDir, "guard.json");
5313
+ if ((0, import_fs5.existsSync)(settingsFile)) {
5199
5314
  try {
5200
- settings = JSON.parse((0, import_fs4.readFileSync)(settingsFile, "utf-8"));
5315
+ settings = JSON.parse((0, import_fs5.readFileSync)(settingsFile, "utf-8"));
5201
5316
  } catch {
5202
5317
  settings = {};
5203
5318
  }
@@ -5206,6 +5321,408 @@ function resolveGuardConfig(env, payloadCwd, home = (0, import_os.homedir)()) {
5206
5321
  }
5207
5322
  return null;
5208
5323
  }
5324
+ var FLEET_ENROL_INSTRUCTION = "This machine must be enrolled: run `astrasync guard enroll <token>` (token from your organisation admin)";
5325
+ function resolveFleet(env, home = (0, import_os2.homedir)(), paths = fleetPaths({ home, env })) {
5326
+ const loaded = loadEnrolment(paths);
5327
+ if (loaded && "corrupt" in loaded) {
5328
+ return {
5329
+ kind: "fleet-missing",
5330
+ reason: `fleet enrolment at ${loaded.path} is unreadable \u2014 ${FLEET_ENROL_INSTRUCTION}`,
5331
+ paths
5332
+ };
5333
+ }
5334
+ if (loaded) return { kind: "fleet", enrolment: loaded.enrolment, scope: loaded.scope, paths };
5335
+ if (env.ASTRASYNC_FLEET_REQUIRED === "1") {
5336
+ return { kind: "fleet-missing", reason: FLEET_ENROL_INSTRUCTION, paths };
5337
+ }
5338
+ return null;
5339
+ }
5340
+
5341
+ // src/fleet/hook-runner.ts
5342
+ var import_path5 = require("path");
5343
+
5344
+ // src/fleet/client.ts
5345
+ var FleetApiError = class extends Error {
5346
+ constructor(message, status, code) {
5347
+ super(message);
5348
+ this.status = status;
5349
+ this.code = code;
5350
+ this.name = "FleetApiError";
5351
+ }
5352
+ };
5353
+ function base(url) {
5354
+ return url.replace(/\/+$/, "");
5355
+ }
5356
+ async function call(url, init, timeoutMs) {
5357
+ const controller = new AbortController();
5358
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
5359
+ try {
5360
+ const res = await sdkFetch(url, { ...init, signal: controller.signal });
5361
+ const text = await res.text();
5362
+ let body = text;
5363
+ try {
5364
+ body = text ? JSON.parse(text) : null;
5365
+ } catch {
5366
+ }
5367
+ return { status: res.status, body, headers: res.headers };
5368
+ } finally {
5369
+ clearTimeout(timer);
5370
+ }
5371
+ }
5372
+ function apiError(status, body, what) {
5373
+ const b = body ?? {};
5374
+ const code = b.code ?? (typeof b.error === "string" ? b.error : void 0);
5375
+ return new FleetApiError(`${what} failed (${status}${code ? ` ${code}` : ""})`, status, code);
5376
+ }
5377
+ function deviceHeaders(enrolment) {
5378
+ return { Authorization: `Device ${enrolment.credential}` };
5379
+ }
5380
+ function policyEtag(sha256, kid) {
5381
+ return `${sha256}.${kid ?? ""}`;
5382
+ }
5383
+ async function fetchFleetPolicy(enrolment, ifNoneMatch, timeoutMs = 1500) {
5384
+ const headers = deviceHeaders(enrolment);
5385
+ if (ifNoneMatch) headers["If-None-Match"] = `"${ifNoneMatch}"`;
5386
+ const r = await call(`${base(enrolment.apiBaseUrl)}/fleet/policy`, { headers }, timeoutMs);
5387
+ if (r.status === 304) return { status: "unchanged" };
5388
+ if (r.status !== 200) throw apiError(r.status, r.body, "Policy fetch");
5389
+ const data = r.body;
5390
+ if (!data?.policyJws) throw new FleetApiError("Policy response has no policyJws", r.status);
5391
+ return {
5392
+ status: "ok",
5393
+ policyJws: data.policyJws,
5394
+ sha256: data.sha256 ?? "",
5395
+ version: data.version ?? 0,
5396
+ keyChain: Array.isArray(data.keyChain) ? data.keyChain.filter((j) => typeof j === "string") : []
5397
+ };
5398
+ }
5399
+ async function sendHeartbeat(enrolment, request, timeoutMs = 1500) {
5400
+ const r = await call(
5401
+ `${base(enrolment.apiBaseUrl)}/fleet/heartbeat`,
5402
+ {
5403
+ method: "POST",
5404
+ headers: { ...deviceHeaders(enrolment), "Content-Type": "application/json" },
5405
+ body: JSON.stringify(request)
5406
+ },
5407
+ timeoutMs
5408
+ );
5409
+ if (r.status !== 200) throw apiError(r.status, r.body, "Heartbeat");
5410
+ return r.body;
5411
+ }
5412
+
5413
+ // src/fleet/policy-verify.ts
5414
+ var import_crypto = require("crypto");
5415
+ var import_jose2 = require("jose");
5416
+
5417
+ // src/fleet/types.ts
5418
+ var FLEET_POLICY_TYP = "fleet-policy+jwt";
5419
+ var FLEET_POLICY_AUD = "astrasync:fleet-policy";
5420
+ var FLEET_POLICY_ISS = "astrasync.ai";
5421
+ var FLEET_KEYS_TYP = "fleet-keys+jwt";
5422
+ var FLEET_KEYS_AUD = "astrasync:fleet-keys";
5423
+ var DEFAULT_HEARTBEAT_INTERVAL_SEC = 900;
5424
+
5425
+ // src/fleet/policy-verify.ts
5426
+ var FleetPolicyError = class extends Error {
5427
+ constructor(message) {
5428
+ super(message);
5429
+ this.name = "FleetPolicyError";
5430
+ }
5431
+ };
5432
+ function sha256Hex(text) {
5433
+ return (0, import_crypto.createHash)("sha256").update(text, "utf8").digest("hex");
5434
+ }
5435
+ function parseSettings(raw) {
5436
+ if (!raw || typeof raw !== "object") throw new FleetPolicyError("settings missing");
5437
+ const s = raw;
5438
+ if (s.posture !== "active" && s.posture !== "passive") {
5439
+ throw new FleetPolicyError("settings.posture must be active or passive");
5440
+ }
5441
+ if (s.failOpen !== void 0 && typeof s.failOpen !== "boolean") {
5442
+ throw new FleetPolicyError("settings.failOpen must be a boolean");
5443
+ }
5444
+ if (s.governMcp !== void 0 && typeof s.governMcp !== "boolean") {
5445
+ throw new FleetPolicyError("settings.governMcp must be a boolean");
5446
+ }
5447
+ if (s.skipTools !== void 0 && !(Array.isArray(s.skipTools) && s.skipTools.every((t) => typeof t === "string"))) {
5448
+ throw new FleetPolicyError("settings.skipTools must be a string array");
5449
+ }
5450
+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
5451
+ return {
5452
+ posture: s.posture,
5453
+ failOpen: s.failOpen === true,
5454
+ ...typeof s.governMcp === "boolean" && { governMcp: s.governMcp },
5455
+ ...Array.isArray(s.skipTools) && { skipTools: s.skipTools },
5456
+ ...num(s.heartbeatIntervalSec) && { heartbeatIntervalSec: num(s.heartbeatIntervalSec) },
5457
+ ...num(s.staleAfterSec) && { staleAfterSec: num(s.staleAfterSec) }
5458
+ };
5459
+ }
5460
+ async function verifyFleetPolicy(jws, jwks, options) {
5461
+ let payloadBytes;
5462
+ let header;
5463
+ try {
5464
+ const keySet = (0, import_jose2.createLocalJWKSet)(jwks);
5465
+ const result = await (0, import_jose2.compactVerify)(jws, keySet, { algorithms: ["ES256"] });
5466
+ payloadBytes = result.payload;
5467
+ header = result.protectedHeader;
5468
+ } catch (err) {
5469
+ throw new FleetPolicyError(
5470
+ `signature verification failed (${err instanceof Error ? err.message : String(err)})`
5471
+ );
5472
+ }
5473
+ if (header.typ !== FLEET_POLICY_TYP) throw new FleetPolicyError(`unexpected typ ${header.typ}`);
5474
+ let claims;
5475
+ try {
5476
+ claims = JSON.parse(new TextDecoder().decode(payloadBytes));
5477
+ } catch {
5478
+ throw new FleetPolicyError("payload is not JSON");
5479
+ }
5480
+ if (claims.aud !== FLEET_POLICY_AUD) throw new FleetPolicyError(`unexpected aud ${claims.aud}`);
5481
+ if (claims.iss !== FLEET_POLICY_ISS) throw new FleetPolicyError(`unexpected iss ${claims.iss}`);
5482
+ if (!options.expectedSubs.includes(claims.sub)) {
5483
+ throw new FleetPolicyError("policy was issued for a different organisation or device");
5484
+ }
5485
+ if (!Number.isInteger(claims.ver) || claims.ver < 1) {
5486
+ throw new FleetPolicyError("ver must be a positive integer");
5487
+ }
5488
+ if (options.minVer !== void 0 && claims.ver < options.minVer) {
5489
+ throw new FleetPolicyError(
5490
+ `policy version ${claims.ver} is older than the accepted version ${options.minVer} (rollback)`
5491
+ );
5492
+ }
5493
+ if (typeof claims.yaml !== "string" || sha256Hex(claims.yaml) !== claims.sha256) {
5494
+ throw new FleetPolicyError("policy hash mismatch");
5495
+ }
5496
+ const settings = parseSettings(claims.settings);
5497
+ const parsed = parseYaml(claims.yaml);
5498
+ if (!parsed.policy) {
5499
+ const first = parsed.validation.errors[0];
5500
+ throw new FleetPolicyError(
5501
+ `signed policy is invalid${first ? ` (${first.path}: ${first.message})` : ""}`
5502
+ );
5503
+ }
5504
+ return { kid: header.kid, claims: { ...claims, settings }, policy: parsed.policy, settings, jws };
5505
+ }
5506
+ async function resolveFleetJwks(pinned, chain, ownerId) {
5507
+ let trusted = pinned;
5508
+ let lastSeq = 0;
5509
+ for (const link of chain) {
5510
+ try {
5511
+ const { payload, protectedHeader } = await (0, import_jose2.compactVerify)(
5512
+ link,
5513
+ (0, import_jose2.createLocalJWKSet)(trusted),
5514
+ { algorithms: ["ES256"] }
5515
+ );
5516
+ if (protectedHeader.typ !== FLEET_KEYS_TYP) continue;
5517
+ const c = JSON.parse(new TextDecoder().decode(payload));
5518
+ if (c.aud !== FLEET_KEYS_AUD || c.iss !== FLEET_POLICY_ISS || c.sub !== ownerId) continue;
5519
+ if (!Number.isInteger(c.seq) || c.seq <= lastSeq) continue;
5520
+ const keys = Array.isArray(c.keys) ? c.keys.filter((k) => k && k.kty === "EC" && k.crv === "P-256" && !("d" in k)) : [];
5521
+ if (keys.length === 0) continue;
5522
+ trusted = { keys };
5523
+ lastSeq = c.seq;
5524
+ } catch {
5525
+ }
5526
+ }
5527
+ return trusted;
5528
+ }
5529
+ async function pickNewestValid(candidates, jwks, options) {
5530
+ let best = null;
5531
+ let lastError = new FleetPolicyError("no cached fleet policy");
5532
+ for (const jws of candidates) {
5533
+ try {
5534
+ const v = await verifyFleetPolicy(jws, jwks, options);
5535
+ if (!best || v.claims.ver > best.claims.ver) best = v;
5536
+ } catch (err) {
5537
+ lastError = err instanceof Error ? err : new FleetPolicyError(String(err));
5538
+ }
5539
+ }
5540
+ if (!best) throw lastError;
5541
+ return best;
5542
+ }
5543
+
5544
+ // src/fleet/runtime.ts
5545
+ var FLEET_SYNC_BUDGET_MS = 1500;
5546
+ function expectedSubs(enrolment) {
5547
+ return [enrolment.org.ownerId, enrolment.deviceId];
5548
+ }
5549
+ function fleetJwks(ctx, chain = readKeyChain(ctx.paths)) {
5550
+ return resolveFleetJwks(ctx.enrolment.jwks, chain, ctx.enrolment.org.ownerId);
5551
+ }
5552
+ async function acceptFetched(ctx, fetched, verifyOpts) {
5553
+ const jwks = await fleetJwks(ctx, fetched.keyChain);
5554
+ const verified = await verifyFleetPolicy(fetched.policyJws, jwks, verifyOpts);
5555
+ if (fetched.keyChain.length > 0) writeKeyChain(ctx.paths, fetched.keyChain);
5556
+ writeCachedPolicy(ctx.paths, fetched.policyJws);
5557
+ return verified;
5558
+ }
5559
+ function remember(paths, state, verified) {
5560
+ state.appliedSha256 = verified.claims.sha256;
5561
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5562
+ writeState(paths, state);
5563
+ }
5564
+ async function loadFleetPolicy(ctx, options = {}) {
5565
+ const state = readState(ctx.paths);
5566
+ const verifyOpts = { expectedSubs: expectedSubs(ctx.enrolment), minVer: state.maxVer };
5567
+ const cached = readCachedPolicies(ctx.paths);
5568
+ let cacheError = null;
5569
+ if (cached.length > 0) {
5570
+ try {
5571
+ const verified = await pickNewestValid(cached, await fleetJwks(ctx), verifyOpts);
5572
+ if (verified.claims.sha256 !== state.appliedSha256 || verified.claims.ver !== state.maxVer) {
5573
+ remember(ctx.paths, state, verified);
5574
+ }
5575
+ return verified;
5576
+ } catch (err) {
5577
+ cacheError = err instanceof Error ? err : new FleetPolicyError(String(err));
5578
+ }
5579
+ }
5580
+ try {
5581
+ const fetched = await fetchFleetPolicy(
5582
+ ctx.enrolment,
5583
+ null,
5584
+ options.fetchTimeoutMs ?? FLEET_SYNC_BUDGET_MS
5585
+ );
5586
+ if (fetched.status === "ok") {
5587
+ const verified = await acceptFetched(ctx, fetched, verifyOpts);
5588
+ remember(ctx.paths, state, verified);
5589
+ return verified;
5590
+ }
5591
+ } catch (err) {
5592
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5593
+ state.revoked = true;
5594
+ writeState(ctx.paths, state);
5595
+ }
5596
+ const detail = err instanceof Error ? err.message : String(err);
5597
+ throw new FleetPolicyError(
5598
+ cacheError ? `${cacheError.message}; refresh failed (${detail})` : `no fleet policy (${detail})`
5599
+ );
5600
+ }
5601
+ throw cacheError ?? new FleetPolicyError("no fleet policy available");
5602
+ }
5603
+ async function recordDecisionAndHeartbeat(ctx, applied, decision, options) {
5604
+ const now = options.now ?? Date.now;
5605
+ const state = readState(ctx.paths);
5606
+ if (decision) state.counts[decision] += 1;
5607
+ const intervalSec = applied.settings.heartbeatIntervalSec ?? ctx.enrolment.heartbeatIntervalSec ?? DEFAULT_HEARTBEAT_INTERVAL_SEC;
5608
+ const last = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : 0;
5609
+ if (now() - last < intervalSec * 1e3) {
5610
+ writeState(ctx.paths, state);
5611
+ return "throttled";
5612
+ }
5613
+ const deadline = now() + (options.budgetMs ?? FLEET_SYNC_BUDGET_MS);
5614
+ const remaining = () => Math.max(1, deadline - now());
5615
+ state.lastHeartbeatAt = new Date(now()).toISOString();
5616
+ let outcome = "sent";
5617
+ try {
5618
+ const hb = await sendHeartbeat(
5619
+ ctx.enrolment,
5620
+ {
5621
+ appliedSha256: applied.claims.sha256,
5622
+ guardVersion: options.guardVersion,
5623
+ adapters: [{ kind: options.adapterKind, managed: true }],
5624
+ posture: applied.settings.posture,
5625
+ decisionCounts: { ...state.counts }
5626
+ },
5627
+ remaining()
5628
+ );
5629
+ state.counts = { allow: 0, deny: 0, ask: 0 };
5630
+ state.revoked = false;
5631
+ delete state.lastError;
5632
+ const policyChanged = !!hb.activeSha256 && hb.activeSha256 !== applied.claims.sha256;
5633
+ const keyChanged = !!hb.activeKid && !!applied.kid && hb.activeKid !== applied.kid;
5634
+ if (policyChanged || keyChanged) {
5635
+ const fetched = await fetchFleetPolicy(
5636
+ ctx.enrolment,
5637
+ policyEtag(applied.claims.sha256, applied.kid),
5638
+ remaining()
5639
+ );
5640
+ if (fetched.status === "ok") {
5641
+ const verified = await acceptFetched(ctx, fetched, {
5642
+ expectedSubs: expectedSubs(ctx.enrolment),
5643
+ minVer: Math.max(state.maxVer ?? 0, applied.claims.ver)
5644
+ });
5645
+ state.appliedSha256 = verified.claims.sha256;
5646
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5647
+ outcome = "refreshed";
5648
+ }
5649
+ }
5650
+ } catch (err) {
5651
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5652
+ state.revoked = true;
5653
+ outcome = "revoked";
5654
+ } else {
5655
+ state.lastError = err instanceof Error ? err.message : String(err);
5656
+ outcome = "failed";
5657
+ }
5658
+ }
5659
+ writeState(ctx.paths, state);
5660
+ return outcome;
5661
+ }
5662
+
5663
+ // src/fleet/hook-runner.ts
5664
+ var PREFIX = "AstraSync Local Guard (organisation fleet policy)";
5665
+ async function runFleetHook(args) {
5666
+ if (args.resolution.kind === "fleet-missing") {
5667
+ return { output: args.denyOutput(`${PREFIX}: ${args.resolution.reason}`), exitCode: 0 };
5668
+ }
5669
+ const ctx = { enrolment: args.resolution.enrolment, paths: args.resolution.paths };
5670
+ let verified;
5671
+ try {
5672
+ verified = await loadFleetPolicy(ctx);
5673
+ } catch (err) {
5674
+ const detail = err instanceof Error ? err.message : String(err);
5675
+ return {
5676
+ output: args.denyOutput(`${PREFIX}: no valid signed policy \u2014 ${detail}`),
5677
+ exitCode: 0
5678
+ };
5679
+ }
5680
+ const { settings } = verified;
5681
+ const decide = async (output) => {
5682
+ try {
5683
+ const outcome = await recordDecisionAndHeartbeat(ctx, verified, args.classify(output), {
5684
+ guardVersion: SDK_VERSION,
5685
+ adapterKind: args.adapterKind,
5686
+ now: args.now
5687
+ });
5688
+ args.onHeartbeat?.(outcome);
5689
+ } catch {
5690
+ }
5691
+ return { output, exitCode: 0 };
5692
+ };
5693
+ let payload;
5694
+ try {
5695
+ payload = JSON.parse(args.payloadJson);
5696
+ } catch {
5697
+ if (settings.failOpen) return decide(null);
5698
+ return decide(args.denyOutput(`${PREFIX}: could not parse hook payload`));
5699
+ }
5700
+ try {
5701
+ const gatewayConfig = {
5702
+ mode: "local",
5703
+ policy: verified.policy,
5704
+ posture: settings.posture,
5705
+ traceEnabled: true,
5706
+ tracePath: (0, import_path5.join)(args.resolution.paths.userDir, "traces"),
5707
+ debug: false
5708
+ };
5709
+ const gateway = args.gatewayFactory ? args.gatewayFactory(gatewayConfig) : new AstraSyncGateway(gatewayConfig);
5710
+ await gateway.initialize();
5711
+ const adapter = args.createAdapter({
5712
+ ...settings.skipTools && { skipTools: settings.skipTools },
5713
+ ...typeof settings.governMcp === "boolean" && { governMcp: settings.governMcp }
5714
+ });
5715
+ await adapter.initialize({ gateway, adapterOptions: {} });
5716
+ const output = await adapter.evaluatePayload(payload);
5717
+ await adapter.shutdown();
5718
+ await gateway.shutdown();
5719
+ return decide(output);
5720
+ } catch (err) {
5721
+ if (settings.failOpen) return decide(null);
5722
+ const detail = err instanceof Error ? err.message : String(err);
5723
+ return decide(args.denyOutput(`${PREFIX}: policy evaluation failed (${detail})`));
5724
+ }
5725
+ }
5209
5726
 
5210
5727
  // src/codex/hook.ts
5211
5728
  var MAX_STDIN_BYTES = 1024 * 1024;
@@ -5223,6 +5740,19 @@ function denyOutput(reason) {
5223
5740
  }
5224
5741
  async function processCodexHookPayload(payloadJson, options = {}) {
5225
5742
  const env = options.env ?? process.env;
5743
+ const fleet = resolveFleet(env, options.home ?? (0, import_os3.homedir)(), options.fleetPaths);
5744
+ if (fleet) {
5745
+ return runFleetHook({
5746
+ resolution: fleet,
5747
+ payloadJson,
5748
+ adapterKind: "codex",
5749
+ createAdapter: (adapterOptions) => new CodexAdapter(adapterOptions),
5750
+ denyOutput,
5751
+ classify: (output) => output?.hookSpecificOutput?.permissionDecision === "deny" ? "deny" : output?.hookSpecificOutput?.permissionDecision === "ask" ? "ask" : "allow",
5752
+ gatewayFactory: options.gatewayFactory,
5753
+ now: options.now
5754
+ });
5755
+ }
5226
5756
  if (env.ASTRASYNC_GUARD_DISABLE === "1") {
5227
5757
  return { output: null, exitCode: 0 };
5228
5758
  }
@@ -5255,7 +5785,7 @@ async function processCodexHookPayload(payloadJson, options = {}) {
5255
5785
  policyFile: resolved.policyFile,
5256
5786
  posture: resolved.settings.posture ?? "active",
5257
5787
  traceEnabled: true,
5258
- tracePath: (0, import_path4.join)(resolved.guardDir, "traces"),
5788
+ tracePath: (0, import_path6.join)(resolved.guardDir, "traces"),
5259
5789
  debug: false,
5260
5790
  ...mode === "hybrid" && {
5261
5791
  apiBaseUrl: resolved.settings.apiBaseUrl,
@@ -5330,8 +5860,8 @@ if (typeof require !== "undefined" && require.main === module) {
5330
5860
  }
5331
5861
 
5332
5862
  // src/claude-code/settings-installer.ts
5333
- var import_fs5 = require("fs");
5334
- var import_path5 = require("path");
5863
+ var import_fs6 = require("fs");
5864
+ var import_path7 = require("path");
5335
5865
  var ASTRASYNC_HOOK_MARKER = "astrasync-claude-hook";
5336
5866
  var HOOK_MATCHER = "Bash|PowerShell|Write|Edit|MultiEdit|NotebookEdit|Read|Glob|Grep|WebFetch|WebSearch|Task|Agent|mcp__.*";
5337
5867
  var HOOK_TIMEOUT_SECONDS = 10;
@@ -5341,14 +5871,14 @@ function isGuardEntry(entry, marker2) {
5341
5871
  );
5342
5872
  }
5343
5873
  function readSettings(settingsPath) {
5344
- if (!(0, import_fs5.existsSync)(settingsPath)) return {};
5345
- const content = (0, import_fs5.readFileSync)(settingsPath, "utf-8").trim();
5874
+ if (!(0, import_fs6.existsSync)(settingsPath)) return {};
5875
+ const content = (0, import_fs6.readFileSync)(settingsPath, "utf-8").trim();
5346
5876
  if (!content) return {};
5347
5877
  return JSON.parse(content);
5348
5878
  }
5349
5879
  function writeSettings(settingsPath, settings) {
5350
- (0, import_fs5.mkdirSync)((0, import_path5.dirname)(settingsPath), { recursive: true });
5351
- (0, import_fs5.writeFileSync)(settingsPath, `${JSON.stringify(settings, null, 2)}
5880
+ (0, import_fs6.mkdirSync)((0, import_path7.dirname)(settingsPath), { recursive: true });
5881
+ (0, import_fs6.writeFileSync)(settingsPath, `${JSON.stringify(settings, null, 2)}
5352
5882
  `, "utf-8");
5353
5883
  }
5354
5884
  function buildHookEntry(hookCommand, matcher = HOOK_MATCHER, extraHookFields = {}) {
@@ -5383,7 +5913,7 @@ function installClaudeHooks(settingsPath, hookCommand, marker2 = ASTRASYNC_HOOK_
5383
5913
  return { installed: true, alreadyPresent: false, updated: false };
5384
5914
  }
5385
5915
  function uninstallClaudeHooks(settingsPath, marker2 = ASTRASYNC_HOOK_MARKER) {
5386
- if (!(0, import_fs5.existsSync)(settingsPath)) return false;
5916
+ if (!(0, import_fs6.existsSync)(settingsPath)) return false;
5387
5917
  let settings;
5388
5918
  try {
5389
5919
  settings = readSettings(settingsPath);
@@ -5409,7 +5939,15 @@ var PERMISSION_DENY_PATHS = [
5409
5939
  "~/.claude/settings.json",
5410
5940
  "~/.claude/settings.local.json",
5411
5941
  "**/.astrasync/**",
5412
- "~/.astrasync/**"
5942
+ "~/.astrasync/**",
5943
+ // 5.11.0 fleet mode: enrolment + signed-policy cache (user scope is inside
5944
+ // ~/.astrasync already; listed explicitly so the intent survives edits) and
5945
+ // the machine-scope enrolment dirs. `//` = absolute from filesystem root;
5946
+ // Windows paths are matched in POSIX form (C:\ → /c/).
5947
+ "~/.astrasync/fleet/**",
5948
+ "//etc/astrasync/**",
5949
+ "//Library/Application Support/AstraSync/**",
5950
+ "//c/ProgramData/AstraSync/**"
5413
5951
  ];
5414
5952
  var GUARD_PERMISSION_DENY_RULES = PERMISSION_DENY_PATHS.map(
5415
5953
  (p) => `Edit(${p})`