@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,3 +1,7 @@
1
+ // src/cursor/extension.ts
2
+ import { homedir as homedir3 } from "os";
3
+ import { join as join3 } from "path";
4
+
1
5
  // src/adapter-interface/interface.ts
2
6
  var ADAPTER_INTERFACE_VERSION = 1;
3
7
 
@@ -3965,7 +3969,7 @@ function getTrustLevel(score) {
3965
3969
  }
3966
3970
 
3967
3971
  // src/version.ts
3968
- var SDK_VERSION = "5.9.0";
3972
+ var SDK_VERSION = "5.11.0";
3969
3973
 
3970
3974
  // src/http.ts
3971
3975
  var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
@@ -4284,6 +4288,24 @@ async function callVerifyAccessAPI(config, request) {
4284
4288
  }
4285
4289
  };
4286
4290
  }
4291
+ if (response.status === 400 && data?.error === "INVALID_AGENT_ID") {
4292
+ const message = typeof data?.message === "string" ? data.message : "Agent identifier must be a canonical ASTRA-* id.";
4293
+ return {
4294
+ success: true,
4295
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
4296
+ access: {
4297
+ allowed: false,
4298
+ reason: "invalid_agent_id",
4299
+ failures: [
4300
+ {
4301
+ dimension: "identity.invalid_agent_id",
4302
+ message,
4303
+ guidance: typeof data?.guidance === "string" ? data.guidance : "Present your canonical ASTRA-* id (discover it via GET /api/agents/request-registration/{requestId} after owner approval)."
4304
+ }
4305
+ ]
4306
+ }
4307
+ };
4308
+ }
4287
4309
  if (!response.ok) {
4288
4310
  if (response.status === 401) {
4289
4311
  return {
@@ -5114,11 +5136,445 @@ var AstraSyncGateway = class {
5114
5136
  }
5115
5137
  };
5116
5138
 
5139
+ // src/claude-code/guard-config.ts
5140
+ import { homedir as homedir2 } from "os";
5141
+
5142
+ // src/fleet/enrolment-store.ts
5143
+ import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
5144
+ import { homedir } from "os";
5145
+ import { dirname as dirname2, join as join2 } from "path";
5146
+ function machineScopeDir(platform = process.platform, env = process.env) {
5147
+ if (platform === "darwin") return "/Library/Application Support/AstraSync";
5148
+ if (platform === "win32") return join2(env.ProgramData || "C:\\ProgramData", "AstraSync");
5149
+ return "/etc/astrasync";
5150
+ }
5151
+ function fleetPaths(options = {}) {
5152
+ const home = options.home ?? homedir();
5153
+ const machineDir = options.machineDir ?? options.env?.ASTRASYNC_FLEET_MACHINE_DIR ?? machineScopeDir(options.platform, options.env);
5154
+ const userDir = join2(home, ".astrasync", "fleet");
5155
+ return {
5156
+ machineDevice: join2(machineDir, "fleet.json"),
5157
+ machinePolicy: join2(machineDir, "policy.jws"),
5158
+ userDir,
5159
+ userDevice: join2(userDir, "device.json"),
5160
+ userPolicy: join2(userDir, "policy.jws"),
5161
+ userKeyChain: join2(userDir, "keychain.json"),
5162
+ state: join2(userDir, "state.json")
5163
+ };
5164
+ }
5165
+ function isEnrolment(value) {
5166
+ const v = value;
5167
+ 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);
5168
+ }
5169
+ function loadEnrolment(paths) {
5170
+ const candidates = [
5171
+ [paths.machineDevice, "machine"],
5172
+ [paths.userDevice, "user"]
5173
+ ];
5174
+ for (const [path, scope] of candidates) {
5175
+ if (!existsSync3(path)) continue;
5176
+ try {
5177
+ const parsed = JSON.parse(readFileSync3(path, "utf-8"));
5178
+ if (isEnrolment(parsed)) return { enrolment: parsed, scope };
5179
+ } catch {
5180
+ }
5181
+ return { corrupt: true, path };
5182
+ }
5183
+ return null;
5184
+ }
5185
+ function writeFileMode(path, content, mode) {
5186
+ mkdirSync3(dirname2(path), { recursive: true, mode: 448 });
5187
+ writeFileSync2(path, content, { encoding: "utf-8", mode });
5188
+ try {
5189
+ chmodSync(path, mode);
5190
+ } catch {
5191
+ }
5192
+ }
5193
+ function readCachedPolicies(paths) {
5194
+ const out = [];
5195
+ for (const p of [paths.userPolicy, paths.machinePolicy]) {
5196
+ try {
5197
+ if (existsSync3(p)) out.push(readFileSync3(p, "utf-8").trim());
5198
+ } catch {
5199
+ }
5200
+ }
5201
+ return out.filter(Boolean);
5202
+ }
5203
+ function writeCachedPolicy(paths, jws) {
5204
+ writeFileMode(paths.userPolicy, jws, 384);
5205
+ }
5206
+ function readKeyChain(paths) {
5207
+ try {
5208
+ const parsed = JSON.parse(readFileSync3(paths.userKeyChain, "utf-8"));
5209
+ return Array.isArray(parsed) ? parsed.filter((j) => typeof j === "string") : [];
5210
+ } catch {
5211
+ return [];
5212
+ }
5213
+ }
5214
+ function writeKeyChain(paths, chain) {
5215
+ writeFileMode(paths.userKeyChain, JSON.stringify(chain), 384);
5216
+ }
5217
+ function readState(paths) {
5218
+ try {
5219
+ const parsed = JSON.parse(readFileSync3(paths.state, "utf-8"));
5220
+ const c = parsed.counts;
5221
+ return {
5222
+ ...parsed,
5223
+ counts: { allow: c?.allow ?? 0, deny: c?.deny ?? 0, ask: c?.ask ?? 0 }
5224
+ };
5225
+ } catch {
5226
+ return { counts: { allow: 0, deny: 0, ask: 0 } };
5227
+ }
5228
+ }
5229
+ function writeState(paths, state) {
5230
+ try {
5231
+ writeFileMode(paths.state, JSON.stringify(state, null, 2), 384);
5232
+ } catch {
5233
+ }
5234
+ }
5235
+
5236
+ // src/claude-code/guard-config.ts
5237
+ var FLEET_ENROL_INSTRUCTION = "This machine must be enrolled: run `astrasync guard enroll <token>` (token from your organisation admin)";
5238
+ function resolveFleet(env, home = homedir2(), paths = fleetPaths({ home, env })) {
5239
+ const loaded = loadEnrolment(paths);
5240
+ if (loaded && "corrupt" in loaded) {
5241
+ return {
5242
+ kind: "fleet-missing",
5243
+ reason: `fleet enrolment at ${loaded.path} is unreadable \u2014 ${FLEET_ENROL_INSTRUCTION}`,
5244
+ paths
5245
+ };
5246
+ }
5247
+ if (loaded) return { kind: "fleet", enrolment: loaded.enrolment, scope: loaded.scope, paths };
5248
+ if (env.ASTRASYNC_FLEET_REQUIRED === "1") {
5249
+ return { kind: "fleet-missing", reason: FLEET_ENROL_INSTRUCTION, paths };
5250
+ }
5251
+ return null;
5252
+ }
5253
+
5254
+ // src/fleet/client.ts
5255
+ var FleetApiError = class extends Error {
5256
+ constructor(message, status, code) {
5257
+ super(message);
5258
+ this.status = status;
5259
+ this.code = code;
5260
+ this.name = "FleetApiError";
5261
+ }
5262
+ };
5263
+ function base(url) {
5264
+ return url.replace(/\/+$/, "");
5265
+ }
5266
+ async function call(url, init, timeoutMs) {
5267
+ const controller = new AbortController();
5268
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
5269
+ try {
5270
+ const res = await sdkFetch(url, { ...init, signal: controller.signal });
5271
+ const text = await res.text();
5272
+ let body = text;
5273
+ try {
5274
+ body = text ? JSON.parse(text) : null;
5275
+ } catch {
5276
+ }
5277
+ return { status: res.status, body, headers: res.headers };
5278
+ } finally {
5279
+ clearTimeout(timer);
5280
+ }
5281
+ }
5282
+ function apiError(status, body, what) {
5283
+ const b = body ?? {};
5284
+ const code = b.code ?? (typeof b.error === "string" ? b.error : void 0);
5285
+ return new FleetApiError(`${what} failed (${status}${code ? ` ${code}` : ""})`, status, code);
5286
+ }
5287
+ function deviceHeaders(enrolment) {
5288
+ return { Authorization: `Device ${enrolment.credential}` };
5289
+ }
5290
+ function policyEtag(sha256, kid) {
5291
+ return `${sha256}.${kid ?? ""}`;
5292
+ }
5293
+ async function fetchFleetPolicy(enrolment, ifNoneMatch, timeoutMs = 1500) {
5294
+ const headers = deviceHeaders(enrolment);
5295
+ if (ifNoneMatch) headers["If-None-Match"] = `"${ifNoneMatch}"`;
5296
+ const r = await call(`${base(enrolment.apiBaseUrl)}/fleet/policy`, { headers }, timeoutMs);
5297
+ if (r.status === 304) return { status: "unchanged" };
5298
+ if (r.status !== 200) throw apiError(r.status, r.body, "Policy fetch");
5299
+ const data = r.body;
5300
+ if (!data?.policyJws) throw new FleetApiError("Policy response has no policyJws", r.status);
5301
+ return {
5302
+ status: "ok",
5303
+ policyJws: data.policyJws,
5304
+ sha256: data.sha256 ?? "",
5305
+ version: data.version ?? 0,
5306
+ keyChain: Array.isArray(data.keyChain) ? data.keyChain.filter((j) => typeof j === "string") : []
5307
+ };
5308
+ }
5309
+ async function sendHeartbeat(enrolment, request, timeoutMs = 1500) {
5310
+ const r = await call(
5311
+ `${base(enrolment.apiBaseUrl)}/fleet/heartbeat`,
5312
+ {
5313
+ method: "POST",
5314
+ headers: { ...deviceHeaders(enrolment), "Content-Type": "application/json" },
5315
+ body: JSON.stringify(request)
5316
+ },
5317
+ timeoutMs
5318
+ );
5319
+ if (r.status !== 200) throw apiError(r.status, r.body, "Heartbeat");
5320
+ return r.body;
5321
+ }
5322
+
5323
+ // src/fleet/policy-verify.ts
5324
+ import { createHash as createHash4 } from "crypto";
5325
+ import { compactVerify, createLocalJWKSet } from "jose";
5326
+
5327
+ // src/fleet/types.ts
5328
+ var FLEET_POLICY_TYP = "fleet-policy+jwt";
5329
+ var FLEET_POLICY_AUD = "astrasync:fleet-policy";
5330
+ var FLEET_POLICY_ISS = "astrasync.ai";
5331
+ var FLEET_KEYS_TYP = "fleet-keys+jwt";
5332
+ var FLEET_KEYS_AUD = "astrasync:fleet-keys";
5333
+ var DEFAULT_HEARTBEAT_INTERVAL_SEC = 900;
5334
+
5335
+ // src/fleet/policy-verify.ts
5336
+ var FleetPolicyError = class extends Error {
5337
+ constructor(message) {
5338
+ super(message);
5339
+ this.name = "FleetPolicyError";
5340
+ }
5341
+ };
5342
+ function sha256Hex(text) {
5343
+ return createHash4("sha256").update(text, "utf8").digest("hex");
5344
+ }
5345
+ function parseSettings(raw) {
5346
+ if (!raw || typeof raw !== "object") throw new FleetPolicyError("settings missing");
5347
+ const s = raw;
5348
+ if (s.posture !== "active" && s.posture !== "passive") {
5349
+ throw new FleetPolicyError("settings.posture must be active or passive");
5350
+ }
5351
+ if (s.failOpen !== void 0 && typeof s.failOpen !== "boolean") {
5352
+ throw new FleetPolicyError("settings.failOpen must be a boolean");
5353
+ }
5354
+ if (s.governMcp !== void 0 && typeof s.governMcp !== "boolean") {
5355
+ throw new FleetPolicyError("settings.governMcp must be a boolean");
5356
+ }
5357
+ if (s.skipTools !== void 0 && !(Array.isArray(s.skipTools) && s.skipTools.every((t) => typeof t === "string"))) {
5358
+ throw new FleetPolicyError("settings.skipTools must be a string array");
5359
+ }
5360
+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
5361
+ return {
5362
+ posture: s.posture,
5363
+ failOpen: s.failOpen === true,
5364
+ ...typeof s.governMcp === "boolean" && { governMcp: s.governMcp },
5365
+ ...Array.isArray(s.skipTools) && { skipTools: s.skipTools },
5366
+ ...num(s.heartbeatIntervalSec) && { heartbeatIntervalSec: num(s.heartbeatIntervalSec) },
5367
+ ...num(s.staleAfterSec) && { staleAfterSec: num(s.staleAfterSec) }
5368
+ };
5369
+ }
5370
+ async function verifyFleetPolicy(jws, jwks, options) {
5371
+ let payloadBytes;
5372
+ let header;
5373
+ try {
5374
+ const keySet = createLocalJWKSet(jwks);
5375
+ const result = await compactVerify(jws, keySet, { algorithms: ["ES256"] });
5376
+ payloadBytes = result.payload;
5377
+ header = result.protectedHeader;
5378
+ } catch (err) {
5379
+ throw new FleetPolicyError(
5380
+ `signature verification failed (${err instanceof Error ? err.message : String(err)})`
5381
+ );
5382
+ }
5383
+ if (header.typ !== FLEET_POLICY_TYP) throw new FleetPolicyError(`unexpected typ ${header.typ}`);
5384
+ let claims;
5385
+ try {
5386
+ claims = JSON.parse(new TextDecoder().decode(payloadBytes));
5387
+ } catch {
5388
+ throw new FleetPolicyError("payload is not JSON");
5389
+ }
5390
+ if (claims.aud !== FLEET_POLICY_AUD) throw new FleetPolicyError(`unexpected aud ${claims.aud}`);
5391
+ if (claims.iss !== FLEET_POLICY_ISS) throw new FleetPolicyError(`unexpected iss ${claims.iss}`);
5392
+ if (!options.expectedSubs.includes(claims.sub)) {
5393
+ throw new FleetPolicyError("policy was issued for a different organisation or device");
5394
+ }
5395
+ if (!Number.isInteger(claims.ver) || claims.ver < 1) {
5396
+ throw new FleetPolicyError("ver must be a positive integer");
5397
+ }
5398
+ if (options.minVer !== void 0 && claims.ver < options.minVer) {
5399
+ throw new FleetPolicyError(
5400
+ `policy version ${claims.ver} is older than the accepted version ${options.minVer} (rollback)`
5401
+ );
5402
+ }
5403
+ if (typeof claims.yaml !== "string" || sha256Hex(claims.yaml) !== claims.sha256) {
5404
+ throw new FleetPolicyError("policy hash mismatch");
5405
+ }
5406
+ const settings = parseSettings(claims.settings);
5407
+ const parsed = parseYaml(claims.yaml);
5408
+ if (!parsed.policy) {
5409
+ const first = parsed.validation.errors[0];
5410
+ throw new FleetPolicyError(
5411
+ `signed policy is invalid${first ? ` (${first.path}: ${first.message})` : ""}`
5412
+ );
5413
+ }
5414
+ return { kid: header.kid, claims: { ...claims, settings }, policy: parsed.policy, settings, jws };
5415
+ }
5416
+ async function resolveFleetJwks(pinned, chain, ownerId) {
5417
+ let trusted = pinned;
5418
+ let lastSeq = 0;
5419
+ for (const link of chain) {
5420
+ try {
5421
+ const { payload, protectedHeader } = await compactVerify(
5422
+ link,
5423
+ createLocalJWKSet(trusted),
5424
+ { algorithms: ["ES256"] }
5425
+ );
5426
+ if (protectedHeader.typ !== FLEET_KEYS_TYP) continue;
5427
+ const c = JSON.parse(new TextDecoder().decode(payload));
5428
+ if (c.aud !== FLEET_KEYS_AUD || c.iss !== FLEET_POLICY_ISS || c.sub !== ownerId) continue;
5429
+ if (!Number.isInteger(c.seq) || c.seq <= lastSeq) continue;
5430
+ const keys = Array.isArray(c.keys) ? c.keys.filter((k) => k && k.kty === "EC" && k.crv === "P-256" && !("d" in k)) : [];
5431
+ if (keys.length === 0) continue;
5432
+ trusted = { keys };
5433
+ lastSeq = c.seq;
5434
+ } catch {
5435
+ }
5436
+ }
5437
+ return trusted;
5438
+ }
5439
+ async function pickNewestValid(candidates, jwks, options) {
5440
+ let best = null;
5441
+ let lastError = new FleetPolicyError("no cached fleet policy");
5442
+ for (const jws of candidates) {
5443
+ try {
5444
+ const v = await verifyFleetPolicy(jws, jwks, options);
5445
+ if (!best || v.claims.ver > best.claims.ver) best = v;
5446
+ } catch (err) {
5447
+ lastError = err instanceof Error ? err : new FleetPolicyError(String(err));
5448
+ }
5449
+ }
5450
+ if (!best) throw lastError;
5451
+ return best;
5452
+ }
5453
+
5454
+ // src/fleet/runtime.ts
5455
+ var FLEET_SYNC_BUDGET_MS = 1500;
5456
+ function expectedSubs(enrolment) {
5457
+ return [enrolment.org.ownerId, enrolment.deviceId];
5458
+ }
5459
+ function fleetJwks(ctx, chain = readKeyChain(ctx.paths)) {
5460
+ return resolveFleetJwks(ctx.enrolment.jwks, chain, ctx.enrolment.org.ownerId);
5461
+ }
5462
+ async function acceptFetched(ctx, fetched, verifyOpts) {
5463
+ const jwks = await fleetJwks(ctx, fetched.keyChain);
5464
+ const verified = await verifyFleetPolicy(fetched.policyJws, jwks, verifyOpts);
5465
+ if (fetched.keyChain.length > 0) writeKeyChain(ctx.paths, fetched.keyChain);
5466
+ writeCachedPolicy(ctx.paths, fetched.policyJws);
5467
+ return verified;
5468
+ }
5469
+ function remember(paths, state, verified) {
5470
+ state.appliedSha256 = verified.claims.sha256;
5471
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5472
+ writeState(paths, state);
5473
+ }
5474
+ async function loadFleetPolicy(ctx, options = {}) {
5475
+ const state = readState(ctx.paths);
5476
+ const verifyOpts = { expectedSubs: expectedSubs(ctx.enrolment), minVer: state.maxVer };
5477
+ const cached = readCachedPolicies(ctx.paths);
5478
+ let cacheError = null;
5479
+ if (cached.length > 0) {
5480
+ try {
5481
+ const verified = await pickNewestValid(cached, await fleetJwks(ctx), verifyOpts);
5482
+ if (verified.claims.sha256 !== state.appliedSha256 || verified.claims.ver !== state.maxVer) {
5483
+ remember(ctx.paths, state, verified);
5484
+ }
5485
+ return verified;
5486
+ } catch (err) {
5487
+ cacheError = err instanceof Error ? err : new FleetPolicyError(String(err));
5488
+ }
5489
+ }
5490
+ try {
5491
+ const fetched = await fetchFleetPolicy(
5492
+ ctx.enrolment,
5493
+ null,
5494
+ options.fetchTimeoutMs ?? FLEET_SYNC_BUDGET_MS
5495
+ );
5496
+ if (fetched.status === "ok") {
5497
+ const verified = await acceptFetched(ctx, fetched, verifyOpts);
5498
+ remember(ctx.paths, state, verified);
5499
+ return verified;
5500
+ }
5501
+ } catch (err) {
5502
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5503
+ state.revoked = true;
5504
+ writeState(ctx.paths, state);
5505
+ }
5506
+ const detail = err instanceof Error ? err.message : String(err);
5507
+ throw new FleetPolicyError(
5508
+ cacheError ? `${cacheError.message}; refresh failed (${detail})` : `no fleet policy (${detail})`
5509
+ );
5510
+ }
5511
+ throw cacheError ?? new FleetPolicyError("no fleet policy available");
5512
+ }
5513
+ async function recordDecisionAndHeartbeat(ctx, applied, decision, options) {
5514
+ const now = options.now ?? Date.now;
5515
+ const state = readState(ctx.paths);
5516
+ if (decision) state.counts[decision] += 1;
5517
+ const intervalSec = applied.settings.heartbeatIntervalSec ?? ctx.enrolment.heartbeatIntervalSec ?? DEFAULT_HEARTBEAT_INTERVAL_SEC;
5518
+ const last = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : 0;
5519
+ if (now() - last < intervalSec * 1e3) {
5520
+ writeState(ctx.paths, state);
5521
+ return "throttled";
5522
+ }
5523
+ const deadline = now() + (options.budgetMs ?? FLEET_SYNC_BUDGET_MS);
5524
+ const remaining = () => Math.max(1, deadline - now());
5525
+ state.lastHeartbeatAt = new Date(now()).toISOString();
5526
+ let outcome = "sent";
5527
+ try {
5528
+ const hb = await sendHeartbeat(
5529
+ ctx.enrolment,
5530
+ {
5531
+ appliedSha256: applied.claims.sha256,
5532
+ guardVersion: options.guardVersion,
5533
+ adapters: [{ kind: options.adapterKind, managed: true }],
5534
+ posture: applied.settings.posture,
5535
+ decisionCounts: { ...state.counts }
5536
+ },
5537
+ remaining()
5538
+ );
5539
+ state.counts = { allow: 0, deny: 0, ask: 0 };
5540
+ state.revoked = false;
5541
+ delete state.lastError;
5542
+ const policyChanged = !!hb.activeSha256 && hb.activeSha256 !== applied.claims.sha256;
5543
+ const keyChanged = !!hb.activeKid && !!applied.kid && hb.activeKid !== applied.kid;
5544
+ if (policyChanged || keyChanged) {
5545
+ const fetched = await fetchFleetPolicy(
5546
+ ctx.enrolment,
5547
+ policyEtag(applied.claims.sha256, applied.kid),
5548
+ remaining()
5549
+ );
5550
+ if (fetched.status === "ok") {
5551
+ const verified = await acceptFetched(ctx, fetched, {
5552
+ expectedSubs: expectedSubs(ctx.enrolment),
5553
+ minVer: Math.max(state.maxVer ?? 0, applied.claims.ver)
5554
+ });
5555
+ state.appliedSha256 = verified.claims.sha256;
5556
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5557
+ outcome = "refreshed";
5558
+ }
5559
+ }
5560
+ } catch (err) {
5561
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5562
+ state.revoked = true;
5563
+ outcome = "revoked";
5564
+ } else {
5565
+ state.lastError = err instanceof Error ? err.message : String(err);
5566
+ outcome = "failed";
5567
+ }
5568
+ }
5569
+ writeState(ctx.paths, state);
5570
+ return outcome;
5571
+ }
5572
+
5117
5573
  // src/cursor/extension.ts
5118
5574
  var adapter = null;
5119
5575
  var gateway = null;
5120
- async function activate(vscodeApi) {
5121
- const config = loadConfiguration();
5576
+ async function activate(vscodeApi, options = {}) {
5577
+ const config = await loadConfiguration(options);
5122
5578
  gateway = new AstraSyncGateway(config.gatewayConfig);
5123
5579
  adapter = new CursorAdapter({
5124
5580
  vscode: vscodeApi,
@@ -5141,10 +5597,18 @@ Action: ${context.action} \u2192 ${context.target}`,
5141
5597
  const channel = vscodeApi.window.createOutputChannel("AstraSync Policy");
5142
5598
  channel.appendLine(`Mode: ${gateway.mode}`);
5143
5599
  channel.appendLine(`Posture: ${gateway.posture}`);
5144
- channel.appendLine(`Policy file: ${config.gatewayConfig.policyFile || "(inline/none)"}`);
5600
+ channel.appendLine(
5601
+ config.fleetManaged ? `Policy: organisation fleet policy (${config.fleetManaged})` : `Policy file: ${config.gatewayConfig.policyFile || "(inline/none)"}`
5602
+ );
5145
5603
  channel.show();
5146
5604
  });
5147
5605
  vscodeApi.commands.registerCommand("astrasync.switchMode", async () => {
5606
+ if (config.fleetManaged) {
5607
+ vscodeApi.window.showInformationMessage(
5608
+ "AstraSync: this machine is governed by your organisation\u2019s fleet policy \u2014 mode is managed centrally."
5609
+ );
5610
+ return;
5611
+ }
5148
5612
  if (!config.gatewayConfig.apiKey) {
5149
5613
  vscodeApi.window.showInformationMessage(
5150
5614
  "AstraSync: Set astrasync.apiKey in settings to enable online/hybrid mode."
@@ -5174,7 +5638,62 @@ async function deactivate() {
5174
5638
  gateway = null;
5175
5639
  }
5176
5640
  }
5177
- function loadConfiguration() {
5641
+ function fleetLockdownPolicy() {
5642
+ return {
5643
+ version: "1.0",
5644
+ name: "fleet-enrolment-required",
5645
+ purposes: [
5646
+ "file.read",
5647
+ "file.write",
5648
+ "file.delete",
5649
+ "shell.exec",
5650
+ "network.fetch",
5651
+ "payment.execute",
5652
+ "email.send"
5653
+ ].map((id) => ({ id, allowed: false }))
5654
+ };
5655
+ }
5656
+ async function loadConfiguration(options) {
5657
+ const env = options.env ?? process.env;
5658
+ const fleet = resolveFleet(env, options.home ?? homedir3(), options.fleetPaths);
5659
+ if (fleet?.kind === "fleet") {
5660
+ const ctx = { enrolment: fleet.enrolment, paths: fleet.paths };
5661
+ try {
5662
+ const verified = await loadFleetPolicy(ctx);
5663
+ void recordDecisionAndHeartbeat(ctx, verified, null, {
5664
+ guardVersion: SDK_VERSION,
5665
+ adapterKind: "cursor"
5666
+ }).catch(() => void 0);
5667
+ return {
5668
+ fleetManaged: `${fleet.enrolment.org.name ?? fleet.enrolment.org.ownerId} v${verified.claims.ver}`,
5669
+ gatewayConfig: {
5670
+ mode: "local",
5671
+ policy: verified.policy,
5672
+ posture: verified.settings.posture,
5673
+ traceEnabled: true,
5674
+ tracePath: join3(fleet.paths.userDir, "traces"),
5675
+ debug: false
5676
+ }
5677
+ };
5678
+ } catch {
5679
+ }
5680
+ }
5681
+ if (fleet) {
5682
+ return {
5683
+ fleetManaged: "unavailable \u2014 enrol this machine with `astrasync guard enroll <token>`",
5684
+ gatewayConfig: {
5685
+ mode: "local",
5686
+ policy: fleetLockdownPolicy(),
5687
+ posture: "active",
5688
+ traceEnabled: true,
5689
+ tracePath: join3(fleet.paths.userDir, "traces"),
5690
+ debug: false
5691
+ }
5692
+ };
5693
+ }
5694
+ return loadLocalConfiguration();
5695
+ }
5696
+ function loadLocalConfiguration() {
5178
5697
  return {
5179
5698
  gatewayConfig: {
5180
5699
  mode: "local",