@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 { VSCodeAPI } from './cursor-adapter.mjs';
2
+ import { F as FleetPaths } from '../enrolment-store-8DyaIOLe.mjs';
2
3
  import '../interface-q1WrMsB1.mjs';
3
4
 
4
5
  /**
@@ -15,10 +16,16 @@ import '../interface-q1WrMsB1.mjs';
15
16
  * Called by VS Code when the extension activates.
16
17
  * The `vscode` module is passed in at runtime — never bundled.
17
18
  */
18
- declare function activate(vscodeApi: VSCodeAPI): Promise<void>;
19
+ interface ActivateOptions {
20
+ env?: NodeJS.ProcessEnv;
21
+ home?: string;
22
+ /** Test hook: fleet enrolment/cache locations. */
23
+ fleetPaths?: FleetPaths;
24
+ }
25
+ declare function activate(vscodeApi: VSCodeAPI, options?: ActivateOptions): Promise<void>;
19
26
  /**
20
27
  * Called by VS Code when the extension deactivates.
21
28
  */
22
29
  declare function deactivate(): Promise<void>;
23
30
 
24
- export { activate, deactivate };
31
+ export { type ActivateOptions, activate, deactivate };
@@ -1,4 +1,5 @@
1
1
  import { VSCodeAPI } from './cursor-adapter.js';
2
+ import { F as FleetPaths } from '../enrolment-store-8DyaIOLe.js';
2
3
  import '../interface-q1WrMsB1.js';
3
4
 
4
5
  /**
@@ -15,10 +16,16 @@ import '../interface-q1WrMsB1.js';
15
16
  * Called by VS Code when the extension activates.
16
17
  * The `vscode` module is passed in at runtime — never bundled.
17
18
  */
18
- declare function activate(vscodeApi: VSCodeAPI): Promise<void>;
19
+ interface ActivateOptions {
20
+ env?: NodeJS.ProcessEnv;
21
+ home?: string;
22
+ /** Test hook: fleet enrolment/cache locations. */
23
+ fleetPaths?: FleetPaths;
24
+ }
25
+ declare function activate(vscodeApi: VSCodeAPI, options?: ActivateOptions): Promise<void>;
19
26
  /**
20
27
  * Called by VS Code when the extension deactivates.
21
28
  */
22
29
  declare function deactivate(): Promise<void>;
23
30
 
24
- export { activate, deactivate };
31
+ export { type ActivateOptions, activate, deactivate };
@@ -24,6 +24,8 @@ __export(extension_exports, {
24
24
  deactivate: () => deactivate
25
25
  });
26
26
  module.exports = __toCommonJS(extension_exports);
27
+ var import_os3 = require("os");
28
+ var import_path4 = require("path");
27
29
 
28
30
  // src/adapter-interface/interface.ts
29
31
  var ADAPTER_INTERFACE_VERSION = 1;
@@ -3992,7 +3994,7 @@ function getTrustLevel(score) {
3992
3994
  }
3993
3995
 
3994
3996
  // src/version.ts
3995
- var SDK_VERSION = "5.9.0";
3997
+ var SDK_VERSION = "5.11.0";
3996
3998
 
3997
3999
  // src/http.ts
3998
4000
  var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
@@ -4311,6 +4313,24 @@ async function callVerifyAccessAPI(config, request) {
4311
4313
  }
4312
4314
  };
4313
4315
  }
4316
+ if (response.status === 400 && data?.error === "INVALID_AGENT_ID") {
4317
+ const message = typeof data?.message === "string" ? data.message : "Agent identifier must be a canonical ASTRA-* id.";
4318
+ return {
4319
+ success: true,
4320
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
4321
+ access: {
4322
+ allowed: false,
4323
+ reason: "invalid_agent_id",
4324
+ failures: [
4325
+ {
4326
+ dimension: "identity.invalid_agent_id",
4327
+ message,
4328
+ guidance: typeof data?.guidance === "string" ? data.guidance : "Present your canonical ASTRA-* id (discover it via GET /api/agents/request-registration/{requestId} after owner approval)."
4329
+ }
4330
+ ]
4331
+ }
4332
+ };
4333
+ }
4314
4334
  if (!response.ok) {
4315
4335
  if (response.status === 401) {
4316
4336
  return {
@@ -5138,11 +5158,445 @@ var AstraSyncGateway = class {
5138
5158
  }
5139
5159
  };
5140
5160
 
5161
+ // src/claude-code/guard-config.ts
5162
+ var import_os2 = require("os");
5163
+
5164
+ // src/fleet/enrolment-store.ts
5165
+ var import_fs4 = require("fs");
5166
+ var import_os = require("os");
5167
+ var import_path3 = require("path");
5168
+ function machineScopeDir(platform = process.platform, env = process.env) {
5169
+ if (platform === "darwin") return "/Library/Application Support/AstraSync";
5170
+ if (platform === "win32") return (0, import_path3.join)(env.ProgramData || "C:\\ProgramData", "AstraSync");
5171
+ return "/etc/astrasync";
5172
+ }
5173
+ function fleetPaths(options = {}) {
5174
+ const home = options.home ?? (0, import_os.homedir)();
5175
+ const machineDir = options.machineDir ?? options.env?.ASTRASYNC_FLEET_MACHINE_DIR ?? machineScopeDir(options.platform, options.env);
5176
+ const userDir = (0, import_path3.join)(home, ".astrasync", "fleet");
5177
+ return {
5178
+ machineDevice: (0, import_path3.join)(machineDir, "fleet.json"),
5179
+ machinePolicy: (0, import_path3.join)(machineDir, "policy.jws"),
5180
+ userDir,
5181
+ userDevice: (0, import_path3.join)(userDir, "device.json"),
5182
+ userPolicy: (0, import_path3.join)(userDir, "policy.jws"),
5183
+ userKeyChain: (0, import_path3.join)(userDir, "keychain.json"),
5184
+ state: (0, import_path3.join)(userDir, "state.json")
5185
+ };
5186
+ }
5187
+ function isEnrolment(value) {
5188
+ const v = value;
5189
+ 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);
5190
+ }
5191
+ function loadEnrolment(paths) {
5192
+ const candidates = [
5193
+ [paths.machineDevice, "machine"],
5194
+ [paths.userDevice, "user"]
5195
+ ];
5196
+ for (const [path, scope] of candidates) {
5197
+ if (!(0, import_fs4.existsSync)(path)) continue;
5198
+ try {
5199
+ const parsed = JSON.parse((0, import_fs4.readFileSync)(path, "utf-8"));
5200
+ if (isEnrolment(parsed)) return { enrolment: parsed, scope };
5201
+ } catch {
5202
+ }
5203
+ return { corrupt: true, path };
5204
+ }
5205
+ return null;
5206
+ }
5207
+ function writeFileMode(path, content, mode) {
5208
+ (0, import_fs4.mkdirSync)((0, import_path3.dirname)(path), { recursive: true, mode: 448 });
5209
+ (0, import_fs4.writeFileSync)(path, content, { encoding: "utf-8", mode });
5210
+ try {
5211
+ (0, import_fs4.chmodSync)(path, mode);
5212
+ } catch {
5213
+ }
5214
+ }
5215
+ function readCachedPolicies(paths) {
5216
+ const out = [];
5217
+ for (const p of [paths.userPolicy, paths.machinePolicy]) {
5218
+ try {
5219
+ if ((0, import_fs4.existsSync)(p)) out.push((0, import_fs4.readFileSync)(p, "utf-8").trim());
5220
+ } catch {
5221
+ }
5222
+ }
5223
+ return out.filter(Boolean);
5224
+ }
5225
+ function writeCachedPolicy(paths, jws) {
5226
+ writeFileMode(paths.userPolicy, jws, 384);
5227
+ }
5228
+ function readKeyChain(paths) {
5229
+ try {
5230
+ const parsed = JSON.parse((0, import_fs4.readFileSync)(paths.userKeyChain, "utf-8"));
5231
+ return Array.isArray(parsed) ? parsed.filter((j) => typeof j === "string") : [];
5232
+ } catch {
5233
+ return [];
5234
+ }
5235
+ }
5236
+ function writeKeyChain(paths, chain) {
5237
+ writeFileMode(paths.userKeyChain, JSON.stringify(chain), 384);
5238
+ }
5239
+ function readState(paths) {
5240
+ try {
5241
+ const parsed = JSON.parse((0, import_fs4.readFileSync)(paths.state, "utf-8"));
5242
+ const c = parsed.counts;
5243
+ return {
5244
+ ...parsed,
5245
+ counts: { allow: c?.allow ?? 0, deny: c?.deny ?? 0, ask: c?.ask ?? 0 }
5246
+ };
5247
+ } catch {
5248
+ return { counts: { allow: 0, deny: 0, ask: 0 } };
5249
+ }
5250
+ }
5251
+ function writeState(paths, state) {
5252
+ try {
5253
+ writeFileMode(paths.state, JSON.stringify(state, null, 2), 384);
5254
+ } catch {
5255
+ }
5256
+ }
5257
+
5258
+ // src/claude-code/guard-config.ts
5259
+ var FLEET_ENROL_INSTRUCTION = "This machine must be enrolled: run `astrasync guard enroll <token>` (token from your organisation admin)";
5260
+ function resolveFleet(env, home = (0, import_os2.homedir)(), paths = fleetPaths({ home, env })) {
5261
+ const loaded = loadEnrolment(paths);
5262
+ if (loaded && "corrupt" in loaded) {
5263
+ return {
5264
+ kind: "fleet-missing",
5265
+ reason: `fleet enrolment at ${loaded.path} is unreadable \u2014 ${FLEET_ENROL_INSTRUCTION}`,
5266
+ paths
5267
+ };
5268
+ }
5269
+ if (loaded) return { kind: "fleet", enrolment: loaded.enrolment, scope: loaded.scope, paths };
5270
+ if (env.ASTRASYNC_FLEET_REQUIRED === "1") {
5271
+ return { kind: "fleet-missing", reason: FLEET_ENROL_INSTRUCTION, paths };
5272
+ }
5273
+ return null;
5274
+ }
5275
+
5276
+ // src/fleet/client.ts
5277
+ var FleetApiError = class extends Error {
5278
+ constructor(message, status, code) {
5279
+ super(message);
5280
+ this.status = status;
5281
+ this.code = code;
5282
+ this.name = "FleetApiError";
5283
+ }
5284
+ };
5285
+ function base(url) {
5286
+ return url.replace(/\/+$/, "");
5287
+ }
5288
+ async function call(url, init, timeoutMs) {
5289
+ const controller = new AbortController();
5290
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
5291
+ try {
5292
+ const res = await sdkFetch(url, { ...init, signal: controller.signal });
5293
+ const text = await res.text();
5294
+ let body = text;
5295
+ try {
5296
+ body = text ? JSON.parse(text) : null;
5297
+ } catch {
5298
+ }
5299
+ return { status: res.status, body, headers: res.headers };
5300
+ } finally {
5301
+ clearTimeout(timer);
5302
+ }
5303
+ }
5304
+ function apiError(status, body, what) {
5305
+ const b = body ?? {};
5306
+ const code = b.code ?? (typeof b.error === "string" ? b.error : void 0);
5307
+ return new FleetApiError(`${what} failed (${status}${code ? ` ${code}` : ""})`, status, code);
5308
+ }
5309
+ function deviceHeaders(enrolment) {
5310
+ return { Authorization: `Device ${enrolment.credential}` };
5311
+ }
5312
+ function policyEtag(sha256, kid) {
5313
+ return `${sha256}.${kid ?? ""}`;
5314
+ }
5315
+ async function fetchFleetPolicy(enrolment, ifNoneMatch, timeoutMs = 1500) {
5316
+ const headers = deviceHeaders(enrolment);
5317
+ if (ifNoneMatch) headers["If-None-Match"] = `"${ifNoneMatch}"`;
5318
+ const r = await call(`${base(enrolment.apiBaseUrl)}/fleet/policy`, { headers }, timeoutMs);
5319
+ if (r.status === 304) return { status: "unchanged" };
5320
+ if (r.status !== 200) throw apiError(r.status, r.body, "Policy fetch");
5321
+ const data = r.body;
5322
+ if (!data?.policyJws) throw new FleetApiError("Policy response has no policyJws", r.status);
5323
+ return {
5324
+ status: "ok",
5325
+ policyJws: data.policyJws,
5326
+ sha256: data.sha256 ?? "",
5327
+ version: data.version ?? 0,
5328
+ keyChain: Array.isArray(data.keyChain) ? data.keyChain.filter((j) => typeof j === "string") : []
5329
+ };
5330
+ }
5331
+ async function sendHeartbeat(enrolment, request, timeoutMs = 1500) {
5332
+ const r = await call(
5333
+ `${base(enrolment.apiBaseUrl)}/fleet/heartbeat`,
5334
+ {
5335
+ method: "POST",
5336
+ headers: { ...deviceHeaders(enrolment), "Content-Type": "application/json" },
5337
+ body: JSON.stringify(request)
5338
+ },
5339
+ timeoutMs
5340
+ );
5341
+ if (r.status !== 200) throw apiError(r.status, r.body, "Heartbeat");
5342
+ return r.body;
5343
+ }
5344
+
5345
+ // src/fleet/policy-verify.ts
5346
+ var import_crypto = require("crypto");
5347
+ var import_jose2 = require("jose");
5348
+
5349
+ // src/fleet/types.ts
5350
+ var FLEET_POLICY_TYP = "fleet-policy+jwt";
5351
+ var FLEET_POLICY_AUD = "astrasync:fleet-policy";
5352
+ var FLEET_POLICY_ISS = "astrasync.ai";
5353
+ var FLEET_KEYS_TYP = "fleet-keys+jwt";
5354
+ var FLEET_KEYS_AUD = "astrasync:fleet-keys";
5355
+ var DEFAULT_HEARTBEAT_INTERVAL_SEC = 900;
5356
+
5357
+ // src/fleet/policy-verify.ts
5358
+ var FleetPolicyError = class extends Error {
5359
+ constructor(message) {
5360
+ super(message);
5361
+ this.name = "FleetPolicyError";
5362
+ }
5363
+ };
5364
+ function sha256Hex(text) {
5365
+ return (0, import_crypto.createHash)("sha256").update(text, "utf8").digest("hex");
5366
+ }
5367
+ function parseSettings(raw) {
5368
+ if (!raw || typeof raw !== "object") throw new FleetPolicyError("settings missing");
5369
+ const s = raw;
5370
+ if (s.posture !== "active" && s.posture !== "passive") {
5371
+ throw new FleetPolicyError("settings.posture must be active or passive");
5372
+ }
5373
+ if (s.failOpen !== void 0 && typeof s.failOpen !== "boolean") {
5374
+ throw new FleetPolicyError("settings.failOpen must be a boolean");
5375
+ }
5376
+ if (s.governMcp !== void 0 && typeof s.governMcp !== "boolean") {
5377
+ throw new FleetPolicyError("settings.governMcp must be a boolean");
5378
+ }
5379
+ if (s.skipTools !== void 0 && !(Array.isArray(s.skipTools) && s.skipTools.every((t) => typeof t === "string"))) {
5380
+ throw new FleetPolicyError("settings.skipTools must be a string array");
5381
+ }
5382
+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
5383
+ return {
5384
+ posture: s.posture,
5385
+ failOpen: s.failOpen === true,
5386
+ ...typeof s.governMcp === "boolean" && { governMcp: s.governMcp },
5387
+ ...Array.isArray(s.skipTools) && { skipTools: s.skipTools },
5388
+ ...num(s.heartbeatIntervalSec) && { heartbeatIntervalSec: num(s.heartbeatIntervalSec) },
5389
+ ...num(s.staleAfterSec) && { staleAfterSec: num(s.staleAfterSec) }
5390
+ };
5391
+ }
5392
+ async function verifyFleetPolicy(jws, jwks, options) {
5393
+ let payloadBytes;
5394
+ let header;
5395
+ try {
5396
+ const keySet = (0, import_jose2.createLocalJWKSet)(jwks);
5397
+ const result = await (0, import_jose2.compactVerify)(jws, keySet, { algorithms: ["ES256"] });
5398
+ payloadBytes = result.payload;
5399
+ header = result.protectedHeader;
5400
+ } catch (err) {
5401
+ throw new FleetPolicyError(
5402
+ `signature verification failed (${err instanceof Error ? err.message : String(err)})`
5403
+ );
5404
+ }
5405
+ if (header.typ !== FLEET_POLICY_TYP) throw new FleetPolicyError(`unexpected typ ${header.typ}`);
5406
+ let claims;
5407
+ try {
5408
+ claims = JSON.parse(new TextDecoder().decode(payloadBytes));
5409
+ } catch {
5410
+ throw new FleetPolicyError("payload is not JSON");
5411
+ }
5412
+ if (claims.aud !== FLEET_POLICY_AUD) throw new FleetPolicyError(`unexpected aud ${claims.aud}`);
5413
+ if (claims.iss !== FLEET_POLICY_ISS) throw new FleetPolicyError(`unexpected iss ${claims.iss}`);
5414
+ if (!options.expectedSubs.includes(claims.sub)) {
5415
+ throw new FleetPolicyError("policy was issued for a different organisation or device");
5416
+ }
5417
+ if (!Number.isInteger(claims.ver) || claims.ver < 1) {
5418
+ throw new FleetPolicyError("ver must be a positive integer");
5419
+ }
5420
+ if (options.minVer !== void 0 && claims.ver < options.minVer) {
5421
+ throw new FleetPolicyError(
5422
+ `policy version ${claims.ver} is older than the accepted version ${options.minVer} (rollback)`
5423
+ );
5424
+ }
5425
+ if (typeof claims.yaml !== "string" || sha256Hex(claims.yaml) !== claims.sha256) {
5426
+ throw new FleetPolicyError("policy hash mismatch");
5427
+ }
5428
+ const settings = parseSettings(claims.settings);
5429
+ const parsed = parseYaml(claims.yaml);
5430
+ if (!parsed.policy) {
5431
+ const first = parsed.validation.errors[0];
5432
+ throw new FleetPolicyError(
5433
+ `signed policy is invalid${first ? ` (${first.path}: ${first.message})` : ""}`
5434
+ );
5435
+ }
5436
+ return { kid: header.kid, claims: { ...claims, settings }, policy: parsed.policy, settings, jws };
5437
+ }
5438
+ async function resolveFleetJwks(pinned, chain, ownerId) {
5439
+ let trusted = pinned;
5440
+ let lastSeq = 0;
5441
+ for (const link of chain) {
5442
+ try {
5443
+ const { payload, protectedHeader } = await (0, import_jose2.compactVerify)(
5444
+ link,
5445
+ (0, import_jose2.createLocalJWKSet)(trusted),
5446
+ { algorithms: ["ES256"] }
5447
+ );
5448
+ if (protectedHeader.typ !== FLEET_KEYS_TYP) continue;
5449
+ const c = JSON.parse(new TextDecoder().decode(payload));
5450
+ if (c.aud !== FLEET_KEYS_AUD || c.iss !== FLEET_POLICY_ISS || c.sub !== ownerId) continue;
5451
+ if (!Number.isInteger(c.seq) || c.seq <= lastSeq) continue;
5452
+ const keys = Array.isArray(c.keys) ? c.keys.filter((k) => k && k.kty === "EC" && k.crv === "P-256" && !("d" in k)) : [];
5453
+ if (keys.length === 0) continue;
5454
+ trusted = { keys };
5455
+ lastSeq = c.seq;
5456
+ } catch {
5457
+ }
5458
+ }
5459
+ return trusted;
5460
+ }
5461
+ async function pickNewestValid(candidates, jwks, options) {
5462
+ let best = null;
5463
+ let lastError = new FleetPolicyError("no cached fleet policy");
5464
+ for (const jws of candidates) {
5465
+ try {
5466
+ const v = await verifyFleetPolicy(jws, jwks, options);
5467
+ if (!best || v.claims.ver > best.claims.ver) best = v;
5468
+ } catch (err) {
5469
+ lastError = err instanceof Error ? err : new FleetPolicyError(String(err));
5470
+ }
5471
+ }
5472
+ if (!best) throw lastError;
5473
+ return best;
5474
+ }
5475
+
5476
+ // src/fleet/runtime.ts
5477
+ var FLEET_SYNC_BUDGET_MS = 1500;
5478
+ function expectedSubs(enrolment) {
5479
+ return [enrolment.org.ownerId, enrolment.deviceId];
5480
+ }
5481
+ function fleetJwks(ctx, chain = readKeyChain(ctx.paths)) {
5482
+ return resolveFleetJwks(ctx.enrolment.jwks, chain, ctx.enrolment.org.ownerId);
5483
+ }
5484
+ async function acceptFetched(ctx, fetched, verifyOpts) {
5485
+ const jwks = await fleetJwks(ctx, fetched.keyChain);
5486
+ const verified = await verifyFleetPolicy(fetched.policyJws, jwks, verifyOpts);
5487
+ if (fetched.keyChain.length > 0) writeKeyChain(ctx.paths, fetched.keyChain);
5488
+ writeCachedPolicy(ctx.paths, fetched.policyJws);
5489
+ return verified;
5490
+ }
5491
+ function remember(paths, state, verified) {
5492
+ state.appliedSha256 = verified.claims.sha256;
5493
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5494
+ writeState(paths, state);
5495
+ }
5496
+ async function loadFleetPolicy(ctx, options = {}) {
5497
+ const state = readState(ctx.paths);
5498
+ const verifyOpts = { expectedSubs: expectedSubs(ctx.enrolment), minVer: state.maxVer };
5499
+ const cached = readCachedPolicies(ctx.paths);
5500
+ let cacheError = null;
5501
+ if (cached.length > 0) {
5502
+ try {
5503
+ const verified = await pickNewestValid(cached, await fleetJwks(ctx), verifyOpts);
5504
+ if (verified.claims.sha256 !== state.appliedSha256 || verified.claims.ver !== state.maxVer) {
5505
+ remember(ctx.paths, state, verified);
5506
+ }
5507
+ return verified;
5508
+ } catch (err) {
5509
+ cacheError = err instanceof Error ? err : new FleetPolicyError(String(err));
5510
+ }
5511
+ }
5512
+ try {
5513
+ const fetched = await fetchFleetPolicy(
5514
+ ctx.enrolment,
5515
+ null,
5516
+ options.fetchTimeoutMs ?? FLEET_SYNC_BUDGET_MS
5517
+ );
5518
+ if (fetched.status === "ok") {
5519
+ const verified = await acceptFetched(ctx, fetched, verifyOpts);
5520
+ remember(ctx.paths, state, verified);
5521
+ return verified;
5522
+ }
5523
+ } catch (err) {
5524
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5525
+ state.revoked = true;
5526
+ writeState(ctx.paths, state);
5527
+ }
5528
+ const detail = err instanceof Error ? err.message : String(err);
5529
+ throw new FleetPolicyError(
5530
+ cacheError ? `${cacheError.message}; refresh failed (${detail})` : `no fleet policy (${detail})`
5531
+ );
5532
+ }
5533
+ throw cacheError ?? new FleetPolicyError("no fleet policy available");
5534
+ }
5535
+ async function recordDecisionAndHeartbeat(ctx, applied, decision, options) {
5536
+ const now = options.now ?? Date.now;
5537
+ const state = readState(ctx.paths);
5538
+ if (decision) state.counts[decision] += 1;
5539
+ const intervalSec = applied.settings.heartbeatIntervalSec ?? ctx.enrolment.heartbeatIntervalSec ?? DEFAULT_HEARTBEAT_INTERVAL_SEC;
5540
+ const last = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : 0;
5541
+ if (now() - last < intervalSec * 1e3) {
5542
+ writeState(ctx.paths, state);
5543
+ return "throttled";
5544
+ }
5545
+ const deadline = now() + (options.budgetMs ?? FLEET_SYNC_BUDGET_MS);
5546
+ const remaining = () => Math.max(1, deadline - now());
5547
+ state.lastHeartbeatAt = new Date(now()).toISOString();
5548
+ let outcome = "sent";
5549
+ try {
5550
+ const hb = await sendHeartbeat(
5551
+ ctx.enrolment,
5552
+ {
5553
+ appliedSha256: applied.claims.sha256,
5554
+ guardVersion: options.guardVersion,
5555
+ adapters: [{ kind: options.adapterKind, managed: true }],
5556
+ posture: applied.settings.posture,
5557
+ decisionCounts: { ...state.counts }
5558
+ },
5559
+ remaining()
5560
+ );
5561
+ state.counts = { allow: 0, deny: 0, ask: 0 };
5562
+ state.revoked = false;
5563
+ delete state.lastError;
5564
+ const policyChanged = !!hb.activeSha256 && hb.activeSha256 !== applied.claims.sha256;
5565
+ const keyChanged = !!hb.activeKid && !!applied.kid && hb.activeKid !== applied.kid;
5566
+ if (policyChanged || keyChanged) {
5567
+ const fetched = await fetchFleetPolicy(
5568
+ ctx.enrolment,
5569
+ policyEtag(applied.claims.sha256, applied.kid),
5570
+ remaining()
5571
+ );
5572
+ if (fetched.status === "ok") {
5573
+ const verified = await acceptFetched(ctx, fetched, {
5574
+ expectedSubs: expectedSubs(ctx.enrolment),
5575
+ minVer: Math.max(state.maxVer ?? 0, applied.claims.ver)
5576
+ });
5577
+ state.appliedSha256 = verified.claims.sha256;
5578
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5579
+ outcome = "refreshed";
5580
+ }
5581
+ }
5582
+ } catch (err) {
5583
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5584
+ state.revoked = true;
5585
+ outcome = "revoked";
5586
+ } else {
5587
+ state.lastError = err instanceof Error ? err.message : String(err);
5588
+ outcome = "failed";
5589
+ }
5590
+ }
5591
+ writeState(ctx.paths, state);
5592
+ return outcome;
5593
+ }
5594
+
5141
5595
  // src/cursor/extension.ts
5142
5596
  var adapter = null;
5143
5597
  var gateway = null;
5144
- async function activate(vscodeApi) {
5145
- const config = loadConfiguration();
5598
+ async function activate(vscodeApi, options = {}) {
5599
+ const config = await loadConfiguration(options);
5146
5600
  gateway = new AstraSyncGateway(config.gatewayConfig);
5147
5601
  adapter = new CursorAdapter({
5148
5602
  vscode: vscodeApi,
@@ -5165,10 +5619,18 @@ Action: ${context.action} \u2192 ${context.target}`,
5165
5619
  const channel = vscodeApi.window.createOutputChannel("AstraSync Policy");
5166
5620
  channel.appendLine(`Mode: ${gateway.mode}`);
5167
5621
  channel.appendLine(`Posture: ${gateway.posture}`);
5168
- channel.appendLine(`Policy file: ${config.gatewayConfig.policyFile || "(inline/none)"}`);
5622
+ channel.appendLine(
5623
+ config.fleetManaged ? `Policy: organisation fleet policy (${config.fleetManaged})` : `Policy file: ${config.gatewayConfig.policyFile || "(inline/none)"}`
5624
+ );
5169
5625
  channel.show();
5170
5626
  });
5171
5627
  vscodeApi.commands.registerCommand("astrasync.switchMode", async () => {
5628
+ if (config.fleetManaged) {
5629
+ vscodeApi.window.showInformationMessage(
5630
+ "AstraSync: this machine is governed by your organisation\u2019s fleet policy \u2014 mode is managed centrally."
5631
+ );
5632
+ return;
5633
+ }
5172
5634
  if (!config.gatewayConfig.apiKey) {
5173
5635
  vscodeApi.window.showInformationMessage(
5174
5636
  "AstraSync: Set astrasync.apiKey in settings to enable online/hybrid mode."
@@ -5198,7 +5660,62 @@ async function deactivate() {
5198
5660
  gateway = null;
5199
5661
  }
5200
5662
  }
5201
- function loadConfiguration() {
5663
+ function fleetLockdownPolicy() {
5664
+ return {
5665
+ version: "1.0",
5666
+ name: "fleet-enrolment-required",
5667
+ purposes: [
5668
+ "file.read",
5669
+ "file.write",
5670
+ "file.delete",
5671
+ "shell.exec",
5672
+ "network.fetch",
5673
+ "payment.execute",
5674
+ "email.send"
5675
+ ].map((id) => ({ id, allowed: false }))
5676
+ };
5677
+ }
5678
+ async function loadConfiguration(options) {
5679
+ const env = options.env ?? process.env;
5680
+ const fleet = resolveFleet(env, options.home ?? (0, import_os3.homedir)(), options.fleetPaths);
5681
+ if (fleet?.kind === "fleet") {
5682
+ const ctx = { enrolment: fleet.enrolment, paths: fleet.paths };
5683
+ try {
5684
+ const verified = await loadFleetPolicy(ctx);
5685
+ void recordDecisionAndHeartbeat(ctx, verified, null, {
5686
+ guardVersion: SDK_VERSION,
5687
+ adapterKind: "cursor"
5688
+ }).catch(() => void 0);
5689
+ return {
5690
+ fleetManaged: `${fleet.enrolment.org.name ?? fleet.enrolment.org.ownerId} v${verified.claims.ver}`,
5691
+ gatewayConfig: {
5692
+ mode: "local",
5693
+ policy: verified.policy,
5694
+ posture: verified.settings.posture,
5695
+ traceEnabled: true,
5696
+ tracePath: (0, import_path4.join)(fleet.paths.userDir, "traces"),
5697
+ debug: false
5698
+ }
5699
+ };
5700
+ } catch {
5701
+ }
5702
+ }
5703
+ if (fleet) {
5704
+ return {
5705
+ fleetManaged: "unavailable \u2014 enrol this machine with `astrasync guard enroll <token>`",
5706
+ gatewayConfig: {
5707
+ mode: "local",
5708
+ policy: fleetLockdownPolicy(),
5709
+ posture: "active",
5710
+ traceEnabled: true,
5711
+ tracePath: (0, import_path4.join)(fleet.paths.userDir, "traces"),
5712
+ debug: false
5713
+ }
5714
+ };
5715
+ }
5716
+ return loadLocalConfiguration();
5717
+ }
5718
+ function loadLocalConfiguration() {
5202
5719
  return {
5203
5720
  gatewayConfig: {
5204
5721
  mode: "local",