@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
@@ -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.9.0";
4009
+ var SDK_VERSION = "5.11.0";
4009
4010
 
4010
4011
  // src/http.ts
4011
4012
  var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
@@ -4324,6 +4325,24 @@ async function callVerifyAccessAPI(config, request) {
4324
4325
  }
4325
4326
  };
4326
4327
  }
4328
+ if (response.status === 400 && data?.error === "INVALID_AGENT_ID") {
4329
+ const message = typeof data?.message === "string" ? data.message : "Agent identifier must be a canonical ASTRA-* id.";
4330
+ return {
4331
+ success: true,
4332
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
4333
+ access: {
4334
+ allowed: false,
4335
+ reason: "invalid_agent_id",
4336
+ failures: [
4337
+ {
4338
+ dimension: "identity.invalid_agent_id",
4339
+ message,
4340
+ guidance: typeof data?.guidance === "string" ? data.guidance : "Present your canonical ASTRA-* id (discover it via GET /api/agents/request-registration/{requestId} after owner approval)."
4341
+ }
4342
+ ]
4343
+ }
4344
+ };
4345
+ }
4327
4346
  if (!response.ok) {
4328
4347
  if (response.status === 401) {
4329
4348
  return {
@@ -5155,22 +5174,118 @@ var AstraSyncGateway = class {
5155
5174
  };
5156
5175
 
5157
5176
  // src/claude-code/guard-config.ts
5158
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
5177
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
5178
+ import { homedir as homedir2 } from "os";
5179
+ import { join as join3 } from "path";
5180
+
5181
+ // src/fleet/enrolment-store.ts
5182
+ import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
5159
5183
  import { homedir } from "os";
5160
- import { join as join2 } from "path";
5161
- function resolveGuardConfig(env, payloadCwd, home = homedir()) {
5184
+ import { dirname as dirname2, join as join2 } from "path";
5185
+ function machineScopeDir(platform = process.platform, env = process.env) {
5186
+ if (platform === "darwin") return "/Library/Application Support/AstraSync";
5187
+ if (platform === "win32") return join2(env.ProgramData || "C:\\ProgramData", "AstraSync");
5188
+ return "/etc/astrasync";
5189
+ }
5190
+ function fleetPaths(options = {}) {
5191
+ const home = options.home ?? homedir();
5192
+ const machineDir = options.machineDir ?? options.env?.ASTRASYNC_FLEET_MACHINE_DIR ?? machineScopeDir(options.platform, options.env);
5193
+ const userDir = join2(home, ".astrasync", "fleet");
5194
+ return {
5195
+ machineDevice: join2(machineDir, "fleet.json"),
5196
+ machinePolicy: join2(machineDir, "policy.jws"),
5197
+ userDir,
5198
+ userDevice: join2(userDir, "device.json"),
5199
+ userPolicy: join2(userDir, "policy.jws"),
5200
+ userKeyChain: join2(userDir, "keychain.json"),
5201
+ state: join2(userDir, "state.json")
5202
+ };
5203
+ }
5204
+ function isEnrolment(value) {
5205
+ const v = value;
5206
+ 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);
5207
+ }
5208
+ function loadEnrolment(paths) {
5209
+ const candidates = [
5210
+ [paths.machineDevice, "machine"],
5211
+ [paths.userDevice, "user"]
5212
+ ];
5213
+ for (const [path, scope] of candidates) {
5214
+ if (!existsSync3(path)) continue;
5215
+ try {
5216
+ const parsed = JSON.parse(readFileSync3(path, "utf-8"));
5217
+ if (isEnrolment(parsed)) return { enrolment: parsed, scope };
5218
+ } catch {
5219
+ }
5220
+ return { corrupt: true, path };
5221
+ }
5222
+ return null;
5223
+ }
5224
+ function writeFileMode(path, content, mode) {
5225
+ mkdirSync3(dirname2(path), { recursive: true, mode: 448 });
5226
+ writeFileSync2(path, content, { encoding: "utf-8", mode });
5227
+ try {
5228
+ chmodSync(path, mode);
5229
+ } catch {
5230
+ }
5231
+ }
5232
+ function readCachedPolicies(paths) {
5233
+ const out = [];
5234
+ for (const p of [paths.userPolicy, paths.machinePolicy]) {
5235
+ try {
5236
+ if (existsSync3(p)) out.push(readFileSync3(p, "utf-8").trim());
5237
+ } catch {
5238
+ }
5239
+ }
5240
+ return out.filter(Boolean);
5241
+ }
5242
+ function writeCachedPolicy(paths, jws) {
5243
+ writeFileMode(paths.userPolicy, jws, 384);
5244
+ }
5245
+ function readKeyChain(paths) {
5246
+ try {
5247
+ const parsed = JSON.parse(readFileSync3(paths.userKeyChain, "utf-8"));
5248
+ return Array.isArray(parsed) ? parsed.filter((j) => typeof j === "string") : [];
5249
+ } catch {
5250
+ return [];
5251
+ }
5252
+ }
5253
+ function writeKeyChain(paths, chain) {
5254
+ writeFileMode(paths.userKeyChain, JSON.stringify(chain), 384);
5255
+ }
5256
+ function readState(paths) {
5257
+ try {
5258
+ const parsed = JSON.parse(readFileSync3(paths.state, "utf-8"));
5259
+ const c = parsed.counts;
5260
+ return {
5261
+ ...parsed,
5262
+ counts: { allow: c?.allow ?? 0, deny: c?.deny ?? 0, ask: c?.ask ?? 0 }
5263
+ };
5264
+ } catch {
5265
+ return { counts: { allow: 0, deny: 0, ask: 0 } };
5266
+ }
5267
+ }
5268
+ function writeState(paths, state) {
5269
+ try {
5270
+ writeFileMode(paths.state, JSON.stringify(state, null, 2), 384);
5271
+ } catch {
5272
+ }
5273
+ }
5274
+
5275
+ // src/claude-code/guard-config.ts
5276
+ function resolveGuardConfig(env, payloadCwd, home = homedir2()) {
5162
5277
  const candidateRoots = [env.CLAUDE_PROJECT_DIR, payloadCwd, home].filter(
5163
5278
  (root) => typeof root === "string" && root.length > 0
5164
5279
  );
5165
5280
  for (const root of candidateRoots) {
5166
- const guardDir = join2(root, ".astrasync");
5167
- const policyFile = join2(guardDir, "policy.yaml");
5168
- if (!existsSync3(policyFile)) continue;
5281
+ const guardDir = join3(root, ".astrasync");
5282
+ const policyFile = join3(guardDir, "policy.yaml");
5283
+ if (!existsSync4(policyFile)) continue;
5169
5284
  let settings = {};
5170
- const settingsFile = join2(guardDir, "guard.json");
5171
- if (existsSync3(settingsFile)) {
5285
+ const settingsFile = join3(guardDir, "guard.json");
5286
+ if (existsSync4(settingsFile)) {
5172
5287
  try {
5173
- settings = JSON.parse(readFileSync3(settingsFile, "utf-8"));
5288
+ settings = JSON.parse(readFileSync4(settingsFile, "utf-8"));
5174
5289
  } catch {
5175
5290
  settings = {};
5176
5291
  }
@@ -5179,6 +5294,408 @@ function resolveGuardConfig(env, payloadCwd, home = homedir()) {
5179
5294
  }
5180
5295
  return null;
5181
5296
  }
5297
+ var FLEET_ENROL_INSTRUCTION = "This machine must be enrolled: run `astrasync guard enroll <token>` (token from your organisation admin)";
5298
+ function resolveFleet(env, home = homedir2(), paths = fleetPaths({ home, env })) {
5299
+ const loaded = loadEnrolment(paths);
5300
+ if (loaded && "corrupt" in loaded) {
5301
+ return {
5302
+ kind: "fleet-missing",
5303
+ reason: `fleet enrolment at ${loaded.path} is unreadable \u2014 ${FLEET_ENROL_INSTRUCTION}`,
5304
+ paths
5305
+ };
5306
+ }
5307
+ if (loaded) return { kind: "fleet", enrolment: loaded.enrolment, scope: loaded.scope, paths };
5308
+ if (env.ASTRASYNC_FLEET_REQUIRED === "1") {
5309
+ return { kind: "fleet-missing", reason: FLEET_ENROL_INSTRUCTION, paths };
5310
+ }
5311
+ return null;
5312
+ }
5313
+
5314
+ // src/fleet/hook-runner.ts
5315
+ import { join as join4 } from "path";
5316
+
5317
+ // src/fleet/client.ts
5318
+ var FleetApiError = class extends Error {
5319
+ constructor(message, status, code) {
5320
+ super(message);
5321
+ this.status = status;
5322
+ this.code = code;
5323
+ this.name = "FleetApiError";
5324
+ }
5325
+ };
5326
+ function base(url) {
5327
+ return url.replace(/\/+$/, "");
5328
+ }
5329
+ async function call(url, init, timeoutMs) {
5330
+ const controller = new AbortController();
5331
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
5332
+ try {
5333
+ const res = await sdkFetch(url, { ...init, signal: controller.signal });
5334
+ const text = await res.text();
5335
+ let body = text;
5336
+ try {
5337
+ body = text ? JSON.parse(text) : null;
5338
+ } catch {
5339
+ }
5340
+ return { status: res.status, body, headers: res.headers };
5341
+ } finally {
5342
+ clearTimeout(timer);
5343
+ }
5344
+ }
5345
+ function apiError(status, body, what) {
5346
+ const b = body ?? {};
5347
+ const code = b.code ?? (typeof b.error === "string" ? b.error : void 0);
5348
+ return new FleetApiError(`${what} failed (${status}${code ? ` ${code}` : ""})`, status, code);
5349
+ }
5350
+ function deviceHeaders(enrolment) {
5351
+ return { Authorization: `Device ${enrolment.credential}` };
5352
+ }
5353
+ function policyEtag(sha256, kid) {
5354
+ return `${sha256}.${kid ?? ""}`;
5355
+ }
5356
+ async function fetchFleetPolicy(enrolment, ifNoneMatch, timeoutMs = 1500) {
5357
+ const headers = deviceHeaders(enrolment);
5358
+ if (ifNoneMatch) headers["If-None-Match"] = `"${ifNoneMatch}"`;
5359
+ const r = await call(`${base(enrolment.apiBaseUrl)}/fleet/policy`, { headers }, timeoutMs);
5360
+ if (r.status === 304) return { status: "unchanged" };
5361
+ if (r.status !== 200) throw apiError(r.status, r.body, "Policy fetch");
5362
+ const data = r.body;
5363
+ if (!data?.policyJws) throw new FleetApiError("Policy response has no policyJws", r.status);
5364
+ return {
5365
+ status: "ok",
5366
+ policyJws: data.policyJws,
5367
+ sha256: data.sha256 ?? "",
5368
+ version: data.version ?? 0,
5369
+ keyChain: Array.isArray(data.keyChain) ? data.keyChain.filter((j) => typeof j === "string") : []
5370
+ };
5371
+ }
5372
+ async function sendHeartbeat(enrolment, request, timeoutMs = 1500) {
5373
+ const r = await call(
5374
+ `${base(enrolment.apiBaseUrl)}/fleet/heartbeat`,
5375
+ {
5376
+ method: "POST",
5377
+ headers: { ...deviceHeaders(enrolment), "Content-Type": "application/json" },
5378
+ body: JSON.stringify(request)
5379
+ },
5380
+ timeoutMs
5381
+ );
5382
+ if (r.status !== 200) throw apiError(r.status, r.body, "Heartbeat");
5383
+ return r.body;
5384
+ }
5385
+
5386
+ // src/fleet/policy-verify.ts
5387
+ import { createHash as createHash4 } from "crypto";
5388
+ import { compactVerify, createLocalJWKSet } from "jose";
5389
+
5390
+ // src/fleet/types.ts
5391
+ var FLEET_POLICY_TYP = "fleet-policy+jwt";
5392
+ var FLEET_POLICY_AUD = "astrasync:fleet-policy";
5393
+ var FLEET_POLICY_ISS = "astrasync.ai";
5394
+ var FLEET_KEYS_TYP = "fleet-keys+jwt";
5395
+ var FLEET_KEYS_AUD = "astrasync:fleet-keys";
5396
+ var DEFAULT_HEARTBEAT_INTERVAL_SEC = 900;
5397
+
5398
+ // src/fleet/policy-verify.ts
5399
+ var FleetPolicyError = class extends Error {
5400
+ constructor(message) {
5401
+ super(message);
5402
+ this.name = "FleetPolicyError";
5403
+ }
5404
+ };
5405
+ function sha256Hex(text) {
5406
+ return createHash4("sha256").update(text, "utf8").digest("hex");
5407
+ }
5408
+ function parseSettings(raw) {
5409
+ if (!raw || typeof raw !== "object") throw new FleetPolicyError("settings missing");
5410
+ const s = raw;
5411
+ if (s.posture !== "active" && s.posture !== "passive") {
5412
+ throw new FleetPolicyError("settings.posture must be active or passive");
5413
+ }
5414
+ if (s.failOpen !== void 0 && typeof s.failOpen !== "boolean") {
5415
+ throw new FleetPolicyError("settings.failOpen must be a boolean");
5416
+ }
5417
+ if (s.governMcp !== void 0 && typeof s.governMcp !== "boolean") {
5418
+ throw new FleetPolicyError("settings.governMcp must be a boolean");
5419
+ }
5420
+ if (s.skipTools !== void 0 && !(Array.isArray(s.skipTools) && s.skipTools.every((t) => typeof t === "string"))) {
5421
+ throw new FleetPolicyError("settings.skipTools must be a string array");
5422
+ }
5423
+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
5424
+ return {
5425
+ posture: s.posture,
5426
+ failOpen: s.failOpen === true,
5427
+ ...typeof s.governMcp === "boolean" && { governMcp: s.governMcp },
5428
+ ...Array.isArray(s.skipTools) && { skipTools: s.skipTools },
5429
+ ...num(s.heartbeatIntervalSec) && { heartbeatIntervalSec: num(s.heartbeatIntervalSec) },
5430
+ ...num(s.staleAfterSec) && { staleAfterSec: num(s.staleAfterSec) }
5431
+ };
5432
+ }
5433
+ async function verifyFleetPolicy(jws, jwks, options) {
5434
+ let payloadBytes;
5435
+ let header;
5436
+ try {
5437
+ const keySet = createLocalJWKSet(jwks);
5438
+ const result = await compactVerify(jws, keySet, { algorithms: ["ES256"] });
5439
+ payloadBytes = result.payload;
5440
+ header = result.protectedHeader;
5441
+ } catch (err) {
5442
+ throw new FleetPolicyError(
5443
+ `signature verification failed (${err instanceof Error ? err.message : String(err)})`
5444
+ );
5445
+ }
5446
+ if (header.typ !== FLEET_POLICY_TYP) throw new FleetPolicyError(`unexpected typ ${header.typ}`);
5447
+ let claims;
5448
+ try {
5449
+ claims = JSON.parse(new TextDecoder().decode(payloadBytes));
5450
+ } catch {
5451
+ throw new FleetPolicyError("payload is not JSON");
5452
+ }
5453
+ if (claims.aud !== FLEET_POLICY_AUD) throw new FleetPolicyError(`unexpected aud ${claims.aud}`);
5454
+ if (claims.iss !== FLEET_POLICY_ISS) throw new FleetPolicyError(`unexpected iss ${claims.iss}`);
5455
+ if (!options.expectedSubs.includes(claims.sub)) {
5456
+ throw new FleetPolicyError("policy was issued for a different organisation or device");
5457
+ }
5458
+ if (!Number.isInteger(claims.ver) || claims.ver < 1) {
5459
+ throw new FleetPolicyError("ver must be a positive integer");
5460
+ }
5461
+ if (options.minVer !== void 0 && claims.ver < options.minVer) {
5462
+ throw new FleetPolicyError(
5463
+ `policy version ${claims.ver} is older than the accepted version ${options.minVer} (rollback)`
5464
+ );
5465
+ }
5466
+ if (typeof claims.yaml !== "string" || sha256Hex(claims.yaml) !== claims.sha256) {
5467
+ throw new FleetPolicyError("policy hash mismatch");
5468
+ }
5469
+ const settings = parseSettings(claims.settings);
5470
+ const parsed = parseYaml(claims.yaml);
5471
+ if (!parsed.policy) {
5472
+ const first = parsed.validation.errors[0];
5473
+ throw new FleetPolicyError(
5474
+ `signed policy is invalid${first ? ` (${first.path}: ${first.message})` : ""}`
5475
+ );
5476
+ }
5477
+ return { kid: header.kid, claims: { ...claims, settings }, policy: parsed.policy, settings, jws };
5478
+ }
5479
+ async function resolveFleetJwks(pinned, chain, ownerId) {
5480
+ let trusted = pinned;
5481
+ let lastSeq = 0;
5482
+ for (const link of chain) {
5483
+ try {
5484
+ const { payload, protectedHeader } = await compactVerify(
5485
+ link,
5486
+ createLocalJWKSet(trusted),
5487
+ { algorithms: ["ES256"] }
5488
+ );
5489
+ if (protectedHeader.typ !== FLEET_KEYS_TYP) continue;
5490
+ const c = JSON.parse(new TextDecoder().decode(payload));
5491
+ if (c.aud !== FLEET_KEYS_AUD || c.iss !== FLEET_POLICY_ISS || c.sub !== ownerId) continue;
5492
+ if (!Number.isInteger(c.seq) || c.seq <= lastSeq) continue;
5493
+ const keys = Array.isArray(c.keys) ? c.keys.filter((k) => k && k.kty === "EC" && k.crv === "P-256" && !("d" in k)) : [];
5494
+ if (keys.length === 0) continue;
5495
+ trusted = { keys };
5496
+ lastSeq = c.seq;
5497
+ } catch {
5498
+ }
5499
+ }
5500
+ return trusted;
5501
+ }
5502
+ async function pickNewestValid(candidates, jwks, options) {
5503
+ let best = null;
5504
+ let lastError = new FleetPolicyError("no cached fleet policy");
5505
+ for (const jws of candidates) {
5506
+ try {
5507
+ const v = await verifyFleetPolicy(jws, jwks, options);
5508
+ if (!best || v.claims.ver > best.claims.ver) best = v;
5509
+ } catch (err) {
5510
+ lastError = err instanceof Error ? err : new FleetPolicyError(String(err));
5511
+ }
5512
+ }
5513
+ if (!best) throw lastError;
5514
+ return best;
5515
+ }
5516
+
5517
+ // src/fleet/runtime.ts
5518
+ var FLEET_SYNC_BUDGET_MS = 1500;
5519
+ function expectedSubs(enrolment) {
5520
+ return [enrolment.org.ownerId, enrolment.deviceId];
5521
+ }
5522
+ function fleetJwks(ctx, chain = readKeyChain(ctx.paths)) {
5523
+ return resolveFleetJwks(ctx.enrolment.jwks, chain, ctx.enrolment.org.ownerId);
5524
+ }
5525
+ async function acceptFetched(ctx, fetched, verifyOpts) {
5526
+ const jwks = await fleetJwks(ctx, fetched.keyChain);
5527
+ const verified = await verifyFleetPolicy(fetched.policyJws, jwks, verifyOpts);
5528
+ if (fetched.keyChain.length > 0) writeKeyChain(ctx.paths, fetched.keyChain);
5529
+ writeCachedPolicy(ctx.paths, fetched.policyJws);
5530
+ return verified;
5531
+ }
5532
+ function remember(paths, state, verified) {
5533
+ state.appliedSha256 = verified.claims.sha256;
5534
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5535
+ writeState(paths, state);
5536
+ }
5537
+ async function loadFleetPolicy(ctx, options = {}) {
5538
+ const state = readState(ctx.paths);
5539
+ const verifyOpts = { expectedSubs: expectedSubs(ctx.enrolment), minVer: state.maxVer };
5540
+ const cached = readCachedPolicies(ctx.paths);
5541
+ let cacheError = null;
5542
+ if (cached.length > 0) {
5543
+ try {
5544
+ const verified = await pickNewestValid(cached, await fleetJwks(ctx), verifyOpts);
5545
+ if (verified.claims.sha256 !== state.appliedSha256 || verified.claims.ver !== state.maxVer) {
5546
+ remember(ctx.paths, state, verified);
5547
+ }
5548
+ return verified;
5549
+ } catch (err) {
5550
+ cacheError = err instanceof Error ? err : new FleetPolicyError(String(err));
5551
+ }
5552
+ }
5553
+ try {
5554
+ const fetched = await fetchFleetPolicy(
5555
+ ctx.enrolment,
5556
+ null,
5557
+ options.fetchTimeoutMs ?? FLEET_SYNC_BUDGET_MS
5558
+ );
5559
+ if (fetched.status === "ok") {
5560
+ const verified = await acceptFetched(ctx, fetched, verifyOpts);
5561
+ remember(ctx.paths, state, verified);
5562
+ return verified;
5563
+ }
5564
+ } catch (err) {
5565
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5566
+ state.revoked = true;
5567
+ writeState(ctx.paths, state);
5568
+ }
5569
+ const detail = err instanceof Error ? err.message : String(err);
5570
+ throw new FleetPolicyError(
5571
+ cacheError ? `${cacheError.message}; refresh failed (${detail})` : `no fleet policy (${detail})`
5572
+ );
5573
+ }
5574
+ throw cacheError ?? new FleetPolicyError("no fleet policy available");
5575
+ }
5576
+ async function recordDecisionAndHeartbeat(ctx, applied, decision, options) {
5577
+ const now = options.now ?? Date.now;
5578
+ const state = readState(ctx.paths);
5579
+ if (decision) state.counts[decision] += 1;
5580
+ const intervalSec = applied.settings.heartbeatIntervalSec ?? ctx.enrolment.heartbeatIntervalSec ?? DEFAULT_HEARTBEAT_INTERVAL_SEC;
5581
+ const last = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : 0;
5582
+ if (now() - last < intervalSec * 1e3) {
5583
+ writeState(ctx.paths, state);
5584
+ return "throttled";
5585
+ }
5586
+ const deadline = now() + (options.budgetMs ?? FLEET_SYNC_BUDGET_MS);
5587
+ const remaining = () => Math.max(1, deadline - now());
5588
+ state.lastHeartbeatAt = new Date(now()).toISOString();
5589
+ let outcome = "sent";
5590
+ try {
5591
+ const hb = await sendHeartbeat(
5592
+ ctx.enrolment,
5593
+ {
5594
+ appliedSha256: applied.claims.sha256,
5595
+ guardVersion: options.guardVersion,
5596
+ adapters: [{ kind: options.adapterKind, managed: true }],
5597
+ posture: applied.settings.posture,
5598
+ decisionCounts: { ...state.counts }
5599
+ },
5600
+ remaining()
5601
+ );
5602
+ state.counts = { allow: 0, deny: 0, ask: 0 };
5603
+ state.revoked = false;
5604
+ delete state.lastError;
5605
+ const policyChanged = !!hb.activeSha256 && hb.activeSha256 !== applied.claims.sha256;
5606
+ const keyChanged = !!hb.activeKid && !!applied.kid && hb.activeKid !== applied.kid;
5607
+ if (policyChanged || keyChanged) {
5608
+ const fetched = await fetchFleetPolicy(
5609
+ ctx.enrolment,
5610
+ policyEtag(applied.claims.sha256, applied.kid),
5611
+ remaining()
5612
+ );
5613
+ if (fetched.status === "ok") {
5614
+ const verified = await acceptFetched(ctx, fetched, {
5615
+ expectedSubs: expectedSubs(ctx.enrolment),
5616
+ minVer: Math.max(state.maxVer ?? 0, applied.claims.ver)
5617
+ });
5618
+ state.appliedSha256 = verified.claims.sha256;
5619
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5620
+ outcome = "refreshed";
5621
+ }
5622
+ }
5623
+ } catch (err) {
5624
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5625
+ state.revoked = true;
5626
+ outcome = "revoked";
5627
+ } else {
5628
+ state.lastError = err instanceof Error ? err.message : String(err);
5629
+ outcome = "failed";
5630
+ }
5631
+ }
5632
+ writeState(ctx.paths, state);
5633
+ return outcome;
5634
+ }
5635
+
5636
+ // src/fleet/hook-runner.ts
5637
+ var PREFIX = "AstraSync Local Guard (organisation fleet policy)";
5638
+ async function runFleetHook(args) {
5639
+ if (args.resolution.kind === "fleet-missing") {
5640
+ return { output: args.denyOutput(`${PREFIX}: ${args.resolution.reason}`), exitCode: 0 };
5641
+ }
5642
+ const ctx = { enrolment: args.resolution.enrolment, paths: args.resolution.paths };
5643
+ let verified;
5644
+ try {
5645
+ verified = await loadFleetPolicy(ctx);
5646
+ } catch (err) {
5647
+ const detail = err instanceof Error ? err.message : String(err);
5648
+ return {
5649
+ output: args.denyOutput(`${PREFIX}: no valid signed policy \u2014 ${detail}`),
5650
+ exitCode: 0
5651
+ };
5652
+ }
5653
+ const { settings } = verified;
5654
+ const decide = async (output) => {
5655
+ try {
5656
+ const outcome = await recordDecisionAndHeartbeat(ctx, verified, args.classify(output), {
5657
+ guardVersion: SDK_VERSION,
5658
+ adapterKind: args.adapterKind,
5659
+ now: args.now
5660
+ });
5661
+ args.onHeartbeat?.(outcome);
5662
+ } catch {
5663
+ }
5664
+ return { output, exitCode: 0 };
5665
+ };
5666
+ let payload;
5667
+ try {
5668
+ payload = JSON.parse(args.payloadJson);
5669
+ } catch {
5670
+ if (settings.failOpen) return decide(null);
5671
+ return decide(args.denyOutput(`${PREFIX}: could not parse hook payload`));
5672
+ }
5673
+ try {
5674
+ const gatewayConfig = {
5675
+ mode: "local",
5676
+ policy: verified.policy,
5677
+ posture: settings.posture,
5678
+ traceEnabled: true,
5679
+ tracePath: join4(args.resolution.paths.userDir, "traces"),
5680
+ debug: false
5681
+ };
5682
+ const gateway = args.gatewayFactory ? args.gatewayFactory(gatewayConfig) : new AstraSyncGateway(gatewayConfig);
5683
+ await gateway.initialize();
5684
+ const adapter = args.createAdapter({
5685
+ ...settings.skipTools && { skipTools: settings.skipTools },
5686
+ ...typeof settings.governMcp === "boolean" && { governMcp: settings.governMcp }
5687
+ });
5688
+ await adapter.initialize({ gateway, adapterOptions: {} });
5689
+ const output = await adapter.evaluatePayload(payload);
5690
+ await adapter.shutdown();
5691
+ await gateway.shutdown();
5692
+ return decide(output);
5693
+ } catch (err) {
5694
+ if (settings.failOpen) return decide(null);
5695
+ const detail = err instanceof Error ? err.message : String(err);
5696
+ return decide(args.denyOutput(`${PREFIX}: policy evaluation failed (${detail})`));
5697
+ }
5698
+ }
5182
5699
 
5183
5700
  // src/codex/hook.ts
5184
5701
  var MAX_STDIN_BYTES = 1024 * 1024;
@@ -5196,6 +5713,19 @@ function denyOutput(reason) {
5196
5713
  }
5197
5714
  async function processCodexHookPayload(payloadJson, options = {}) {
5198
5715
  const env = options.env ?? process.env;
5716
+ const fleet = resolveFleet(env, options.home ?? homedir3(), options.fleetPaths);
5717
+ if (fleet) {
5718
+ return runFleetHook({
5719
+ resolution: fleet,
5720
+ payloadJson,
5721
+ adapterKind: "codex",
5722
+ createAdapter: (adapterOptions) => new CodexAdapter(adapterOptions),
5723
+ denyOutput,
5724
+ classify: (output) => output?.hookSpecificOutput?.permissionDecision === "deny" ? "deny" : output?.hookSpecificOutput?.permissionDecision === "ask" ? "ask" : "allow",
5725
+ gatewayFactory: options.gatewayFactory,
5726
+ now: options.now
5727
+ });
5728
+ }
5199
5729
  if (env.ASTRASYNC_GUARD_DISABLE === "1") {
5200
5730
  return { output: null, exitCode: 0 };
5201
5731
  }
@@ -5228,7 +5758,7 @@ async function processCodexHookPayload(payloadJson, options = {}) {
5228
5758
  policyFile: resolved.policyFile,
5229
5759
  posture: resolved.settings.posture ?? "active",
5230
5760
  traceEnabled: true,
5231
- tracePath: join3(resolved.guardDir, "traces"),
5761
+ tracePath: join5(resolved.guardDir, "traces"),
5232
5762
  debug: false,
5233
5763
  ...mode === "hybrid" && {
5234
5764
  apiBaseUrl: resolved.settings.apiBaseUrl,
@@ -5303,8 +5833,8 @@ if (typeof __require !== "undefined" && __require.main === module) {
5303
5833
  }
5304
5834
 
5305
5835
  // src/claude-code/settings-installer.ts
5306
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "fs";
5307
- import { dirname as dirname2 } from "path";
5836
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
5837
+ import { dirname as dirname3 } from "path";
5308
5838
  var ASTRASYNC_HOOK_MARKER = "astrasync-claude-hook";
5309
5839
  var HOOK_MATCHER = "Bash|PowerShell|Write|Edit|MultiEdit|NotebookEdit|Read|Glob|Grep|WebFetch|WebSearch|Task|Agent|mcp__.*";
5310
5840
  var HOOK_TIMEOUT_SECONDS = 10;
@@ -5314,14 +5844,14 @@ function isGuardEntry(entry, marker2) {
5314
5844
  );
5315
5845
  }
5316
5846
  function readSettings(settingsPath) {
5317
- if (!existsSync4(settingsPath)) return {};
5318
- const content = readFileSync4(settingsPath, "utf-8").trim();
5847
+ if (!existsSync5(settingsPath)) return {};
5848
+ const content = readFileSync5(settingsPath, "utf-8").trim();
5319
5849
  if (!content) return {};
5320
5850
  return JSON.parse(content);
5321
5851
  }
5322
5852
  function writeSettings(settingsPath, settings) {
5323
- mkdirSync3(dirname2(settingsPath), { recursive: true });
5324
- writeFileSync2(settingsPath, `${JSON.stringify(settings, null, 2)}
5853
+ mkdirSync4(dirname3(settingsPath), { recursive: true });
5854
+ writeFileSync3(settingsPath, `${JSON.stringify(settings, null, 2)}
5325
5855
  `, "utf-8");
5326
5856
  }
5327
5857
  function buildHookEntry(hookCommand, matcher = HOOK_MATCHER, extraHookFields = {}) {
@@ -5356,7 +5886,7 @@ function installClaudeHooks(settingsPath, hookCommand, marker2 = ASTRASYNC_HOOK_
5356
5886
  return { installed: true, alreadyPresent: false, updated: false };
5357
5887
  }
5358
5888
  function uninstallClaudeHooks(settingsPath, marker2 = ASTRASYNC_HOOK_MARKER) {
5359
- if (!existsSync4(settingsPath)) return false;
5889
+ if (!existsSync5(settingsPath)) return false;
5360
5890
  let settings;
5361
5891
  try {
5362
5892
  settings = readSettings(settingsPath);
@@ -5382,7 +5912,15 @@ var PERMISSION_DENY_PATHS = [
5382
5912
  "~/.claude/settings.json",
5383
5913
  "~/.claude/settings.local.json",
5384
5914
  "**/.astrasync/**",
5385
- "~/.astrasync/**"
5915
+ "~/.astrasync/**",
5916
+ // 5.11.0 fleet mode: enrolment + signed-policy cache (user scope is inside
5917
+ // ~/.astrasync already; listed explicitly so the intent survives edits) and
5918
+ // the machine-scope enrolment dirs. `//` = absolute from filesystem root;
5919
+ // Windows paths are matched in POSIX form (C:\ → /c/).
5920
+ "~/.astrasync/fleet/**",
5921
+ "//etc/astrasync/**",
5922
+ "//Library/Application Support/AstraSync/**",
5923
+ "//c/ProgramData/AstraSync/**"
5386
5924
  ];
5387
5925
  var GUARD_PERMISSION_DENY_RULES = PERMISSION_DENY_PATHS.map(
5388
5926
  (p) => `Edit(${p})`