@astrasyncai/verification-gateway 5.10.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 +1 -1
  2. package/dist/adapters/express.js.map +1 -1
  3. package/dist/adapters/express.mjs +1 -1
  4. package/dist/adapters/express.mjs.map +1 -1
  5. package/dist/adapters/mcp.js +1 -1
  6. package/dist/adapters/mcp.js.map +1 -1
  7. package/dist/adapters/mcp.mjs +1 -1
  8. package/dist/adapters/mcp.mjs.map +1 -1
  9. package/dist/adapters/nextjs.js +1 -1
  10. package/dist/adapters/nextjs.js.map +1 -1
  11. package/dist/adapters/nextjs.mjs +1 -1
  12. package/dist/adapters/nextjs.mjs.map +1 -1
  13. package/dist/adapters/sdk.js +1 -1
  14. package/dist/adapters/sdk.js.map +1 -1
  15. package/dist/adapters/sdk.mjs +1 -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 +522 -10
  22. package/dist/bin/astrasync-codex-hook.js +522 -10
  23. package/dist/bin/astrasync-guard.js +611 -65
  24. package/dist/bin/astrasync.js +655 -66
  25. package/dist/browser/background.js +1 -1
  26. package/dist/browser/background.js.map +1 -1
  27. package/dist/browser/background.mjs +1 -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 +538 -18
  38. package/dist/codex/index.js.map +1 -1
  39. package/dist/codex/index.mjs +540 -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 +504 -5
  44. package/dist/cursor/extension.js.map +1 -1
  45. package/dist/cursor/extension.mjs +506 -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 +1 -1
  52. package/dist/edge-core/index.js.map +1 -1
  53. package/dist/edge-core/index.mjs +1 -1
  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 +1 -1
  58. package/dist/gateway/gateway.js.map +1 -1
  59. package/dist/gateway/gateway.mjs +1 -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 +3271 -18
  64. package/dist/index.js.map +1 -1
  65. package/dist/index.mjs +3269 -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 +1 -1
  76. package/dist/verify.js.map +1 -1
  77. package/dist/verify.mjs +1 -1
  78. package/dist/verify.mjs.map +1 -1
  79. package/package.json +1 -1
@@ -24,7 +24,8 @@ __export(hook_exports, {
24
24
  processCodexHookPayload: () => processCodexHookPayload
25
25
  });
26
26
  module.exports = __toCommonJS(hook_exports);
27
- var import_path4 = require("path");
27
+ var import_os3 = require("os");
28
+ var import_path6 = require("path");
28
29
 
29
30
  // src/gateway/types.ts
30
31
  var HIGH_RISK_COMMANDS = [
@@ -3750,7 +3751,7 @@ function getTrustLevel(score) {
3750
3751
  }
3751
3752
 
3752
3753
  // src/version.ts
3753
- var SDK_VERSION = "5.10.0";
3754
+ var SDK_VERSION = "5.11.0";
3754
3755
 
3755
3756
  // src/http.ts
3756
3757
  var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
@@ -4915,22 +4916,118 @@ var AstraSyncGateway = class {
4915
4916
  };
4916
4917
 
4917
4918
  // src/claude-code/guard-config.ts
4919
+ var import_fs5 = require("fs");
4920
+ var import_os2 = require("os");
4921
+ var import_path4 = require("path");
4922
+
4923
+ // src/fleet/enrolment-store.ts
4918
4924
  var import_fs4 = require("fs");
4919
4925
  var import_os = require("os");
4920
4926
  var import_path3 = require("path");
4921
- function resolveGuardConfig(env, payloadCwd, home = (0, import_os.homedir)()) {
4927
+ function machineScopeDir(platform = process.platform, env = process.env) {
4928
+ if (platform === "darwin") return "/Library/Application Support/AstraSync";
4929
+ if (platform === "win32") return (0, import_path3.join)(env.ProgramData || "C:\\ProgramData", "AstraSync");
4930
+ return "/etc/astrasync";
4931
+ }
4932
+ function fleetPaths(options = {}) {
4933
+ const home = options.home ?? (0, import_os.homedir)();
4934
+ const machineDir = options.machineDir ?? options.env?.ASTRASYNC_FLEET_MACHINE_DIR ?? machineScopeDir(options.platform, options.env);
4935
+ const userDir = (0, import_path3.join)(home, ".astrasync", "fleet");
4936
+ return {
4937
+ machineDevice: (0, import_path3.join)(machineDir, "fleet.json"),
4938
+ machinePolicy: (0, import_path3.join)(machineDir, "policy.jws"),
4939
+ userDir,
4940
+ userDevice: (0, import_path3.join)(userDir, "device.json"),
4941
+ userPolicy: (0, import_path3.join)(userDir, "policy.jws"),
4942
+ userKeyChain: (0, import_path3.join)(userDir, "keychain.json"),
4943
+ state: (0, import_path3.join)(userDir, "state.json")
4944
+ };
4945
+ }
4946
+ function isEnrolment(value) {
4947
+ const v = value;
4948
+ 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);
4949
+ }
4950
+ function loadEnrolment(paths) {
4951
+ const candidates = [
4952
+ [paths.machineDevice, "machine"],
4953
+ [paths.userDevice, "user"]
4954
+ ];
4955
+ for (const [path, scope] of candidates) {
4956
+ if (!(0, import_fs4.existsSync)(path)) continue;
4957
+ try {
4958
+ const parsed = JSON.parse((0, import_fs4.readFileSync)(path, "utf-8"));
4959
+ if (isEnrolment(parsed)) return { enrolment: parsed, scope };
4960
+ } catch {
4961
+ }
4962
+ return { corrupt: true, path };
4963
+ }
4964
+ return null;
4965
+ }
4966
+ function writeFileMode(path, content, mode) {
4967
+ (0, import_fs4.mkdirSync)((0, import_path3.dirname)(path), { recursive: true, mode: 448 });
4968
+ (0, import_fs4.writeFileSync)(path, content, { encoding: "utf-8", mode });
4969
+ try {
4970
+ (0, import_fs4.chmodSync)(path, mode);
4971
+ } catch {
4972
+ }
4973
+ }
4974
+ function readCachedPolicies(paths) {
4975
+ const out = [];
4976
+ for (const p of [paths.userPolicy, paths.machinePolicy]) {
4977
+ try {
4978
+ if ((0, import_fs4.existsSync)(p)) out.push((0, import_fs4.readFileSync)(p, "utf-8").trim());
4979
+ } catch {
4980
+ }
4981
+ }
4982
+ return out.filter(Boolean);
4983
+ }
4984
+ function writeCachedPolicy(paths, jws) {
4985
+ writeFileMode(paths.userPolicy, jws, 384);
4986
+ }
4987
+ function readKeyChain(paths) {
4988
+ try {
4989
+ const parsed = JSON.parse((0, import_fs4.readFileSync)(paths.userKeyChain, "utf-8"));
4990
+ return Array.isArray(parsed) ? parsed.filter((j) => typeof j === "string") : [];
4991
+ } catch {
4992
+ return [];
4993
+ }
4994
+ }
4995
+ function writeKeyChain(paths, chain) {
4996
+ writeFileMode(paths.userKeyChain, JSON.stringify(chain), 384);
4997
+ }
4998
+ function readState(paths) {
4999
+ try {
5000
+ const parsed = JSON.parse((0, import_fs4.readFileSync)(paths.state, "utf-8"));
5001
+ const c = parsed.counts;
5002
+ return {
5003
+ ...parsed,
5004
+ counts: { allow: c?.allow ?? 0, deny: c?.deny ?? 0, ask: c?.ask ?? 0 }
5005
+ };
5006
+ } catch {
5007
+ return { counts: { allow: 0, deny: 0, ask: 0 } };
5008
+ }
5009
+ }
5010
+ function writeState(paths, state) {
5011
+ try {
5012
+ writeFileMode(paths.state, JSON.stringify(state, null, 2), 384);
5013
+ } catch {
5014
+ }
5015
+ }
5016
+
5017
+ // src/claude-code/guard-config.ts
5018
+ function resolveGuardConfig(env, payloadCwd, home = (0, import_os2.homedir)()) {
4922
5019
  const candidateRoots = [env.CLAUDE_PROJECT_DIR, payloadCwd, home].filter(
4923
5020
  (root) => typeof root === "string" && root.length > 0
4924
5021
  );
4925
5022
  for (const root of candidateRoots) {
4926
- const guardDir = (0, import_path3.join)(root, ".astrasync");
4927
- const policyFile = (0, import_path3.join)(guardDir, "policy.yaml");
4928
- if (!(0, import_fs4.existsSync)(policyFile)) continue;
5023
+ const guardDir = (0, import_path4.join)(root, ".astrasync");
5024
+ const policyFile = (0, import_path4.join)(guardDir, "policy.yaml");
5025
+ if (!(0, import_fs5.existsSync)(policyFile)) continue;
4929
5026
  let settings = {};
4930
- const settingsFile = (0, import_path3.join)(guardDir, "guard.json");
4931
- if ((0, import_fs4.existsSync)(settingsFile)) {
5027
+ const settingsFile = (0, import_path4.join)(guardDir, "guard.json");
5028
+ if ((0, import_fs5.existsSync)(settingsFile)) {
4932
5029
  try {
4933
- settings = JSON.parse((0, import_fs4.readFileSync)(settingsFile, "utf-8"));
5030
+ settings = JSON.parse((0, import_fs5.readFileSync)(settingsFile, "utf-8"));
4934
5031
  } catch {
4935
5032
  settings = {};
4936
5033
  }
@@ -4939,6 +5036,408 @@ function resolveGuardConfig(env, payloadCwd, home = (0, import_os.homedir)()) {
4939
5036
  }
4940
5037
  return null;
4941
5038
  }
5039
+ var FLEET_ENROL_INSTRUCTION = "This machine must be enrolled: run `astrasync guard enroll <token>` (token from your organisation admin)";
5040
+ function resolveFleet(env, home = (0, import_os2.homedir)(), paths = fleetPaths({ home, env })) {
5041
+ const loaded = loadEnrolment(paths);
5042
+ if (loaded && "corrupt" in loaded) {
5043
+ return {
5044
+ kind: "fleet-missing",
5045
+ reason: `fleet enrolment at ${loaded.path} is unreadable \u2014 ${FLEET_ENROL_INSTRUCTION}`,
5046
+ paths
5047
+ };
5048
+ }
5049
+ if (loaded) return { kind: "fleet", enrolment: loaded.enrolment, scope: loaded.scope, paths };
5050
+ if (env.ASTRASYNC_FLEET_REQUIRED === "1") {
5051
+ return { kind: "fleet-missing", reason: FLEET_ENROL_INSTRUCTION, paths };
5052
+ }
5053
+ return null;
5054
+ }
5055
+
5056
+ // src/fleet/hook-runner.ts
5057
+ var import_path5 = require("path");
5058
+
5059
+ // src/fleet/client.ts
5060
+ var FleetApiError = class extends Error {
5061
+ constructor(message, status, code) {
5062
+ super(message);
5063
+ this.status = status;
5064
+ this.code = code;
5065
+ this.name = "FleetApiError";
5066
+ }
5067
+ };
5068
+ function base(url) {
5069
+ return url.replace(/\/+$/, "");
5070
+ }
5071
+ async function call(url, init, timeoutMs) {
5072
+ const controller = new AbortController();
5073
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
5074
+ try {
5075
+ const res = await sdkFetch(url, { ...init, signal: controller.signal });
5076
+ const text = await res.text();
5077
+ let body = text;
5078
+ try {
5079
+ body = text ? JSON.parse(text) : null;
5080
+ } catch {
5081
+ }
5082
+ return { status: res.status, body, headers: res.headers };
5083
+ } finally {
5084
+ clearTimeout(timer);
5085
+ }
5086
+ }
5087
+ function apiError(status, body, what) {
5088
+ const b = body ?? {};
5089
+ const code = b.code ?? (typeof b.error === "string" ? b.error : void 0);
5090
+ return new FleetApiError(`${what} failed (${status}${code ? ` ${code}` : ""})`, status, code);
5091
+ }
5092
+ function deviceHeaders(enrolment) {
5093
+ return { Authorization: `Device ${enrolment.credential}` };
5094
+ }
5095
+ function policyEtag(sha256, kid) {
5096
+ return `${sha256}.${kid ?? ""}`;
5097
+ }
5098
+ async function fetchFleetPolicy(enrolment, ifNoneMatch, timeoutMs = 1500) {
5099
+ const headers = deviceHeaders(enrolment);
5100
+ if (ifNoneMatch) headers["If-None-Match"] = `"${ifNoneMatch}"`;
5101
+ const r = await call(`${base(enrolment.apiBaseUrl)}/fleet/policy`, { headers }, timeoutMs);
5102
+ if (r.status === 304) return { status: "unchanged" };
5103
+ if (r.status !== 200) throw apiError(r.status, r.body, "Policy fetch");
5104
+ const data = r.body;
5105
+ if (!data?.policyJws) throw new FleetApiError("Policy response has no policyJws", r.status);
5106
+ return {
5107
+ status: "ok",
5108
+ policyJws: data.policyJws,
5109
+ sha256: data.sha256 ?? "",
5110
+ version: data.version ?? 0,
5111
+ keyChain: Array.isArray(data.keyChain) ? data.keyChain.filter((j) => typeof j === "string") : []
5112
+ };
5113
+ }
5114
+ async function sendHeartbeat(enrolment, request, timeoutMs = 1500) {
5115
+ const r = await call(
5116
+ `${base(enrolment.apiBaseUrl)}/fleet/heartbeat`,
5117
+ {
5118
+ method: "POST",
5119
+ headers: { ...deviceHeaders(enrolment), "Content-Type": "application/json" },
5120
+ body: JSON.stringify(request)
5121
+ },
5122
+ timeoutMs
5123
+ );
5124
+ if (r.status !== 200) throw apiError(r.status, r.body, "Heartbeat");
5125
+ return r.body;
5126
+ }
5127
+
5128
+ // src/fleet/policy-verify.ts
5129
+ var import_crypto = require("crypto");
5130
+ var import_jose2 = require("jose");
5131
+
5132
+ // src/fleet/types.ts
5133
+ var FLEET_POLICY_TYP = "fleet-policy+jwt";
5134
+ var FLEET_POLICY_AUD = "astrasync:fleet-policy";
5135
+ var FLEET_POLICY_ISS = "astrasync.ai";
5136
+ var FLEET_KEYS_TYP = "fleet-keys+jwt";
5137
+ var FLEET_KEYS_AUD = "astrasync:fleet-keys";
5138
+ var DEFAULT_HEARTBEAT_INTERVAL_SEC = 900;
5139
+
5140
+ // src/fleet/policy-verify.ts
5141
+ var FleetPolicyError = class extends Error {
5142
+ constructor(message) {
5143
+ super(message);
5144
+ this.name = "FleetPolicyError";
5145
+ }
5146
+ };
5147
+ function sha256Hex(text) {
5148
+ return (0, import_crypto.createHash)("sha256").update(text, "utf8").digest("hex");
5149
+ }
5150
+ function parseSettings(raw) {
5151
+ if (!raw || typeof raw !== "object") throw new FleetPolicyError("settings missing");
5152
+ const s = raw;
5153
+ if (s.posture !== "active" && s.posture !== "passive") {
5154
+ throw new FleetPolicyError("settings.posture must be active or passive");
5155
+ }
5156
+ if (s.failOpen !== void 0 && typeof s.failOpen !== "boolean") {
5157
+ throw new FleetPolicyError("settings.failOpen must be a boolean");
5158
+ }
5159
+ if (s.governMcp !== void 0 && typeof s.governMcp !== "boolean") {
5160
+ throw new FleetPolicyError("settings.governMcp must be a boolean");
5161
+ }
5162
+ if (s.skipTools !== void 0 && !(Array.isArray(s.skipTools) && s.skipTools.every((t) => typeof t === "string"))) {
5163
+ throw new FleetPolicyError("settings.skipTools must be a string array");
5164
+ }
5165
+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
5166
+ return {
5167
+ posture: s.posture,
5168
+ failOpen: s.failOpen === true,
5169
+ ...typeof s.governMcp === "boolean" && { governMcp: s.governMcp },
5170
+ ...Array.isArray(s.skipTools) && { skipTools: s.skipTools },
5171
+ ...num(s.heartbeatIntervalSec) && { heartbeatIntervalSec: num(s.heartbeatIntervalSec) },
5172
+ ...num(s.staleAfterSec) && { staleAfterSec: num(s.staleAfterSec) }
5173
+ };
5174
+ }
5175
+ async function verifyFleetPolicy(jws, jwks, options) {
5176
+ let payloadBytes;
5177
+ let header;
5178
+ try {
5179
+ const keySet = (0, import_jose2.createLocalJWKSet)(jwks);
5180
+ const result = await (0, import_jose2.compactVerify)(jws, keySet, { algorithms: ["ES256"] });
5181
+ payloadBytes = result.payload;
5182
+ header = result.protectedHeader;
5183
+ } catch (err) {
5184
+ throw new FleetPolicyError(
5185
+ `signature verification failed (${err instanceof Error ? err.message : String(err)})`
5186
+ );
5187
+ }
5188
+ if (header.typ !== FLEET_POLICY_TYP) throw new FleetPolicyError(`unexpected typ ${header.typ}`);
5189
+ let claims;
5190
+ try {
5191
+ claims = JSON.parse(new TextDecoder().decode(payloadBytes));
5192
+ } catch {
5193
+ throw new FleetPolicyError("payload is not JSON");
5194
+ }
5195
+ if (claims.aud !== FLEET_POLICY_AUD) throw new FleetPolicyError(`unexpected aud ${claims.aud}`);
5196
+ if (claims.iss !== FLEET_POLICY_ISS) throw new FleetPolicyError(`unexpected iss ${claims.iss}`);
5197
+ if (!options.expectedSubs.includes(claims.sub)) {
5198
+ throw new FleetPolicyError("policy was issued for a different organisation or device");
5199
+ }
5200
+ if (!Number.isInteger(claims.ver) || claims.ver < 1) {
5201
+ throw new FleetPolicyError("ver must be a positive integer");
5202
+ }
5203
+ if (options.minVer !== void 0 && claims.ver < options.minVer) {
5204
+ throw new FleetPolicyError(
5205
+ `policy version ${claims.ver} is older than the accepted version ${options.minVer} (rollback)`
5206
+ );
5207
+ }
5208
+ if (typeof claims.yaml !== "string" || sha256Hex(claims.yaml) !== claims.sha256) {
5209
+ throw new FleetPolicyError("policy hash mismatch");
5210
+ }
5211
+ const settings = parseSettings(claims.settings);
5212
+ const parsed = parseYaml(claims.yaml);
5213
+ if (!parsed.policy) {
5214
+ const first = parsed.validation.errors[0];
5215
+ throw new FleetPolicyError(
5216
+ `signed policy is invalid${first ? ` (${first.path}: ${first.message})` : ""}`
5217
+ );
5218
+ }
5219
+ return { kid: header.kid, claims: { ...claims, settings }, policy: parsed.policy, settings, jws };
5220
+ }
5221
+ async function resolveFleetJwks(pinned, chain, ownerId) {
5222
+ let trusted = pinned;
5223
+ let lastSeq = 0;
5224
+ for (const link of chain) {
5225
+ try {
5226
+ const { payload, protectedHeader } = await (0, import_jose2.compactVerify)(
5227
+ link,
5228
+ (0, import_jose2.createLocalJWKSet)(trusted),
5229
+ { algorithms: ["ES256"] }
5230
+ );
5231
+ if (protectedHeader.typ !== FLEET_KEYS_TYP) continue;
5232
+ const c = JSON.parse(new TextDecoder().decode(payload));
5233
+ if (c.aud !== FLEET_KEYS_AUD || c.iss !== FLEET_POLICY_ISS || c.sub !== ownerId) continue;
5234
+ if (!Number.isInteger(c.seq) || c.seq <= lastSeq) continue;
5235
+ const keys = Array.isArray(c.keys) ? c.keys.filter((k) => k && k.kty === "EC" && k.crv === "P-256" && !("d" in k)) : [];
5236
+ if (keys.length === 0) continue;
5237
+ trusted = { keys };
5238
+ lastSeq = c.seq;
5239
+ } catch {
5240
+ }
5241
+ }
5242
+ return trusted;
5243
+ }
5244
+ async function pickNewestValid(candidates, jwks, options) {
5245
+ let best = null;
5246
+ let lastError = new FleetPolicyError("no cached fleet policy");
5247
+ for (const jws of candidates) {
5248
+ try {
5249
+ const v = await verifyFleetPolicy(jws, jwks, options);
5250
+ if (!best || v.claims.ver > best.claims.ver) best = v;
5251
+ } catch (err) {
5252
+ lastError = err instanceof Error ? err : new FleetPolicyError(String(err));
5253
+ }
5254
+ }
5255
+ if (!best) throw lastError;
5256
+ return best;
5257
+ }
5258
+
5259
+ // src/fleet/runtime.ts
5260
+ var FLEET_SYNC_BUDGET_MS = 1500;
5261
+ function expectedSubs(enrolment) {
5262
+ return [enrolment.org.ownerId, enrolment.deviceId];
5263
+ }
5264
+ function fleetJwks(ctx, chain = readKeyChain(ctx.paths)) {
5265
+ return resolveFleetJwks(ctx.enrolment.jwks, chain, ctx.enrolment.org.ownerId);
5266
+ }
5267
+ async function acceptFetched(ctx, fetched, verifyOpts) {
5268
+ const jwks = await fleetJwks(ctx, fetched.keyChain);
5269
+ const verified = await verifyFleetPolicy(fetched.policyJws, jwks, verifyOpts);
5270
+ if (fetched.keyChain.length > 0) writeKeyChain(ctx.paths, fetched.keyChain);
5271
+ writeCachedPolicy(ctx.paths, fetched.policyJws);
5272
+ return verified;
5273
+ }
5274
+ function remember(paths, state, verified) {
5275
+ state.appliedSha256 = verified.claims.sha256;
5276
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5277
+ writeState(paths, state);
5278
+ }
5279
+ async function loadFleetPolicy(ctx, options = {}) {
5280
+ const state = readState(ctx.paths);
5281
+ const verifyOpts = { expectedSubs: expectedSubs(ctx.enrolment), minVer: state.maxVer };
5282
+ const cached = readCachedPolicies(ctx.paths);
5283
+ let cacheError = null;
5284
+ if (cached.length > 0) {
5285
+ try {
5286
+ const verified = await pickNewestValid(cached, await fleetJwks(ctx), verifyOpts);
5287
+ if (verified.claims.sha256 !== state.appliedSha256 || verified.claims.ver !== state.maxVer) {
5288
+ remember(ctx.paths, state, verified);
5289
+ }
5290
+ return verified;
5291
+ } catch (err) {
5292
+ cacheError = err instanceof Error ? err : new FleetPolicyError(String(err));
5293
+ }
5294
+ }
5295
+ try {
5296
+ const fetched = await fetchFleetPolicy(
5297
+ ctx.enrolment,
5298
+ null,
5299
+ options.fetchTimeoutMs ?? FLEET_SYNC_BUDGET_MS
5300
+ );
5301
+ if (fetched.status === "ok") {
5302
+ const verified = await acceptFetched(ctx, fetched, verifyOpts);
5303
+ remember(ctx.paths, state, verified);
5304
+ return verified;
5305
+ }
5306
+ } catch (err) {
5307
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5308
+ state.revoked = true;
5309
+ writeState(ctx.paths, state);
5310
+ }
5311
+ const detail = err instanceof Error ? err.message : String(err);
5312
+ throw new FleetPolicyError(
5313
+ cacheError ? `${cacheError.message}; refresh failed (${detail})` : `no fleet policy (${detail})`
5314
+ );
5315
+ }
5316
+ throw cacheError ?? new FleetPolicyError("no fleet policy available");
5317
+ }
5318
+ async function recordDecisionAndHeartbeat(ctx, applied, decision, options) {
5319
+ const now = options.now ?? Date.now;
5320
+ const state = readState(ctx.paths);
5321
+ if (decision) state.counts[decision] += 1;
5322
+ const intervalSec = applied.settings.heartbeatIntervalSec ?? ctx.enrolment.heartbeatIntervalSec ?? DEFAULT_HEARTBEAT_INTERVAL_SEC;
5323
+ const last = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : 0;
5324
+ if (now() - last < intervalSec * 1e3) {
5325
+ writeState(ctx.paths, state);
5326
+ return "throttled";
5327
+ }
5328
+ const deadline = now() + (options.budgetMs ?? FLEET_SYNC_BUDGET_MS);
5329
+ const remaining = () => Math.max(1, deadline - now());
5330
+ state.lastHeartbeatAt = new Date(now()).toISOString();
5331
+ let outcome = "sent";
5332
+ try {
5333
+ const hb = await sendHeartbeat(
5334
+ ctx.enrolment,
5335
+ {
5336
+ appliedSha256: applied.claims.sha256,
5337
+ guardVersion: options.guardVersion,
5338
+ adapters: [{ kind: options.adapterKind, managed: true }],
5339
+ posture: applied.settings.posture,
5340
+ decisionCounts: { ...state.counts }
5341
+ },
5342
+ remaining()
5343
+ );
5344
+ state.counts = { allow: 0, deny: 0, ask: 0 };
5345
+ state.revoked = false;
5346
+ delete state.lastError;
5347
+ const policyChanged = !!hb.activeSha256 && hb.activeSha256 !== applied.claims.sha256;
5348
+ const keyChanged = !!hb.activeKid && !!applied.kid && hb.activeKid !== applied.kid;
5349
+ if (policyChanged || keyChanged) {
5350
+ const fetched = await fetchFleetPolicy(
5351
+ ctx.enrolment,
5352
+ policyEtag(applied.claims.sha256, applied.kid),
5353
+ remaining()
5354
+ );
5355
+ if (fetched.status === "ok") {
5356
+ const verified = await acceptFetched(ctx, fetched, {
5357
+ expectedSubs: expectedSubs(ctx.enrolment),
5358
+ minVer: Math.max(state.maxVer ?? 0, applied.claims.ver)
5359
+ });
5360
+ state.appliedSha256 = verified.claims.sha256;
5361
+ state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
5362
+ outcome = "refreshed";
5363
+ }
5364
+ }
5365
+ } catch (err) {
5366
+ if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
5367
+ state.revoked = true;
5368
+ outcome = "revoked";
5369
+ } else {
5370
+ state.lastError = err instanceof Error ? err.message : String(err);
5371
+ outcome = "failed";
5372
+ }
5373
+ }
5374
+ writeState(ctx.paths, state);
5375
+ return outcome;
5376
+ }
5377
+
5378
+ // src/fleet/hook-runner.ts
5379
+ var PREFIX = "AstraSync Local Guard (organisation fleet policy)";
5380
+ async function runFleetHook(args) {
5381
+ if (args.resolution.kind === "fleet-missing") {
5382
+ return { output: args.denyOutput(`${PREFIX}: ${args.resolution.reason}`), exitCode: 0 };
5383
+ }
5384
+ const ctx = { enrolment: args.resolution.enrolment, paths: args.resolution.paths };
5385
+ let verified;
5386
+ try {
5387
+ verified = await loadFleetPolicy(ctx);
5388
+ } catch (err) {
5389
+ const detail = err instanceof Error ? err.message : String(err);
5390
+ return {
5391
+ output: args.denyOutput(`${PREFIX}: no valid signed policy \u2014 ${detail}`),
5392
+ exitCode: 0
5393
+ };
5394
+ }
5395
+ const { settings } = verified;
5396
+ const decide = async (output) => {
5397
+ try {
5398
+ const outcome = await recordDecisionAndHeartbeat(ctx, verified, args.classify(output), {
5399
+ guardVersion: SDK_VERSION,
5400
+ adapterKind: args.adapterKind,
5401
+ now: args.now
5402
+ });
5403
+ args.onHeartbeat?.(outcome);
5404
+ } catch {
5405
+ }
5406
+ return { output, exitCode: 0 };
5407
+ };
5408
+ let payload;
5409
+ try {
5410
+ payload = JSON.parse(args.payloadJson);
5411
+ } catch {
5412
+ if (settings.failOpen) return decide(null);
5413
+ return decide(args.denyOutput(`${PREFIX}: could not parse hook payload`));
5414
+ }
5415
+ try {
5416
+ const gatewayConfig = {
5417
+ mode: "local",
5418
+ policy: verified.policy,
5419
+ posture: settings.posture,
5420
+ traceEnabled: true,
5421
+ tracePath: (0, import_path5.join)(args.resolution.paths.userDir, "traces"),
5422
+ debug: false
5423
+ };
5424
+ const gateway = args.gatewayFactory ? args.gatewayFactory(gatewayConfig) : new AstraSyncGateway(gatewayConfig);
5425
+ await gateway.initialize();
5426
+ const adapter = args.createAdapter({
5427
+ ...settings.skipTools && { skipTools: settings.skipTools },
5428
+ ...typeof settings.governMcp === "boolean" && { governMcp: settings.governMcp }
5429
+ });
5430
+ await adapter.initialize({ gateway, adapterOptions: {} });
5431
+ const output = await adapter.evaluatePayload(payload);
5432
+ await adapter.shutdown();
5433
+ await gateway.shutdown();
5434
+ return decide(output);
5435
+ } catch (err) {
5436
+ if (settings.failOpen) return decide(null);
5437
+ const detail = err instanceof Error ? err.message : String(err);
5438
+ return decide(args.denyOutput(`${PREFIX}: policy evaluation failed (${detail})`));
5439
+ }
5440
+ }
4942
5441
 
4943
5442
  // src/adapter-interface/interface.ts
4944
5443
  var ADAPTER_INTERFACE_VERSION = 1;
@@ -5229,6 +5728,19 @@ function denyOutput(reason) {
5229
5728
  }
5230
5729
  async function processCodexHookPayload(payloadJson, options = {}) {
5231
5730
  const env = options.env ?? process.env;
5731
+ const fleet = resolveFleet(env, options.home ?? (0, import_os3.homedir)(), options.fleetPaths);
5732
+ if (fleet) {
5733
+ return runFleetHook({
5734
+ resolution: fleet,
5735
+ payloadJson,
5736
+ adapterKind: "codex",
5737
+ createAdapter: (adapterOptions) => new CodexAdapter(adapterOptions),
5738
+ denyOutput,
5739
+ classify: (output) => output?.hookSpecificOutput?.permissionDecision === "deny" ? "deny" : output?.hookSpecificOutput?.permissionDecision === "ask" ? "ask" : "allow",
5740
+ gatewayFactory: options.gatewayFactory,
5741
+ now: options.now
5742
+ });
5743
+ }
5232
5744
  if (env.ASTRASYNC_GUARD_DISABLE === "1") {
5233
5745
  return { output: null, exitCode: 0 };
5234
5746
  }
@@ -5261,7 +5773,7 @@ async function processCodexHookPayload(payloadJson, options = {}) {
5261
5773
  policyFile: resolved.policyFile,
5262
5774
  posture: resolved.settings.posture ?? "active",
5263
5775
  traceEnabled: true,
5264
- tracePath: (0, import_path4.join)(resolved.guardDir, "traces"),
5776
+ tracePath: (0, import_path6.join)(resolved.guardDir, "traces"),
5265
5777
  debug: false,
5266
5778
  ...mode === "hybrid" && {
5267
5779
  apiBaseUrl: resolved.settings.apiBaseUrl,