@astrasyncai/verification-gateway 5.10.0 → 5.12.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.
- package/README.md +4 -0
- package/dist/adapters/express.d.mts +1 -1
- package/dist/adapters/express.d.ts +1 -1
- package/dist/adapters/express.js +359 -30
- package/dist/adapters/express.js.map +1 -1
- package/dist/adapters/express.mjs +359 -30
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/mcp.d.mts +5 -1
- package/dist/adapters/mcp.d.ts +5 -1
- package/dist/adapters/mcp.js +168 -41
- package/dist/adapters/mcp.js.map +1 -1
- package/dist/adapters/mcp.mjs +168 -41
- package/dist/adapters/mcp.mjs.map +1 -1
- package/dist/adapters/nextjs.d.mts +1 -1
- package/dist/adapters/nextjs.d.ts +1 -1
- package/dist/adapters/nextjs.js +352 -13
- package/dist/adapters/nextjs.js.map +1 -1
- package/dist/adapters/nextjs.mjs +352 -13
- package/dist/adapters/nextjs.mjs.map +1 -1
- package/dist/adapters/sdk.d.mts +9 -1
- package/dist/adapters/sdk.d.ts +9 -1
- package/dist/adapters/sdk.js +100 -8
- package/dist/adapters/sdk.js.map +1 -1
- package/dist/adapters/sdk.mjs +100 -8
- package/dist/adapters/sdk.mjs.map +1 -1
- package/dist/agent/index.js +1 -1
- package/dist/agent/index.js.map +1 -1
- package/dist/agent/index.mjs +1 -1
- package/dist/agent/index.mjs.map +1 -1
- package/dist/bin/astrasync-claude-hook.js +805 -16
- package/dist/bin/astrasync-codex-hook.js +805 -16
- package/dist/bin/astrasync-guard.js +894 -71
- package/dist/bin/astrasync.js +951 -74
- package/dist/browser/background.js +284 -7
- package/dist/browser/background.js.map +1 -1
- package/dist/browser/background.mjs +284 -7
- package/dist/browser/background.mjs.map +1 -1
- package/dist/cli/index.d.mts +8 -8
- package/dist/cli/index.d.ts +8 -8
- package/dist/cli/index.js +22 -64
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/index.mjs +22 -64
- package/dist/cli/index.mjs.map +1 -1
- package/dist/codex/index.d.mts +5 -0
- package/dist/codex/index.d.ts +5 -0
- package/dist/codex/index.js +821 -24
- package/dist/codex/index.js.map +1 -1
- package/dist/codex/index.mjs +823 -26
- package/dist/codex/index.mjs.map +1 -1
- package/dist/cursor/extension.d.mts +9 -2
- package/dist/cursor/extension.d.ts +9 -2
- package/dist/cursor/extension.js +787 -11
- package/dist/cursor/extension.js.map +1 -1
- package/dist/cursor/extension.mjs +789 -11
- package/dist/cursor/extension.mjs.map +1 -1
- package/dist/edge-config.d.mts +1 -1
- package/dist/edge-config.d.ts +1 -1
- package/dist/edge-config.js +1 -1
- package/dist/edge-config.js.map +1 -1
- package/dist/edge-config.mjs +1 -1
- package/dist/edge-config.mjs.map +1 -1
- package/dist/edge-core/index.d.mts +128 -13
- package/dist/edge-core/index.d.ts +128 -13
- package/dist/edge-core/index.js +337 -55
- package/dist/edge-core/index.js.map +1 -1
- package/dist/edge-core/index.mjs +334 -55
- package/dist/edge-core/index.mjs.map +1 -1
- package/dist/enrolment-store-8DyaIOLe.d.mts +26 -0
- package/dist/enrolment-store-8DyaIOLe.d.ts +26 -0
- package/dist/gateway/gateway.js +284 -7
- package/dist/gateway/gateway.js.map +1 -1
- package/dist/gateway/gateway.mjs +284 -7
- package/dist/gateway/gateway.mjs.map +1 -1
- package/dist/git-trigger/git-hooks.d.mts +1 -1
- package/dist/git-trigger/git-hooks.d.ts +1 -1
- package/dist/index.d.mts +215 -5
- package/dist/index.d.ts +215 -5
- package/dist/index.js +3756 -80
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3748 -80
- package/dist/index.mjs.map +1 -1
- package/dist/platform-signatures.js +4 -1
- package/dist/platform-signatures.js.map +1 -1
- package/dist/platform-signatures.mjs +4 -1
- package/dist/platform-signatures.mjs.map +1 -1
- package/dist/registration/index.js +1 -1
- package/dist/registration/index.js.map +1 -1
- package/dist/registration/index.mjs +1 -1
- package/dist/registration/index.mjs.map +1 -1
- package/dist/transport/index.js +1 -1
- package/dist/transport/index.js.map +1 -1
- package/dist/transport/index.mjs +1 -1
- package/dist/transport/index.mjs.map +1 -1
- package/dist/{types-CTmUpNpS.d.mts → types-BCkwBA84.d.mts} +12 -0
- package/dist/{types-CTmUpNpS.d.ts → types-BCkwBA84.d.ts} +12 -0
- package/dist/{types-CtFXmDzm.d.ts → types-C_b4QTyO.d.ts} +18 -0
- package/dist/{types-DQrn_kei.d.mts → types-DlshIIR-.d.mts} +18 -0
- package/dist/ui/index.d.mts +1 -1
- package/dist/ui/index.d.ts +1 -1
- package/dist/verify.d.mts +35 -4
- package/dist/verify.d.ts +35 -4
- package/dist/verify.js +130 -16
- package/dist/verify.js.map +1 -1
- package/dist/verify.mjs +129 -16
- package/dist/verify.mjs.map +1 -1
- 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
|
|
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.
|
|
3754
|
+
var SDK_VERSION = "5.12.0";
|
|
3754
3755
|
|
|
3755
3756
|
// src/http.ts
|
|
3756
3757
|
var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
|
|
@@ -3777,6 +3778,14 @@ function getCachedWellKnownUrls(apiBaseUrl) {
|
|
|
3777
3778
|
return cache.get(apiBaseUrl)?.data;
|
|
3778
3779
|
}
|
|
3779
3780
|
|
|
3781
|
+
// src/failure-posture.ts
|
|
3782
|
+
var REJECTED_IDENTITY_DIMENSIONS = /* @__PURE__ */ new Set([
|
|
3783
|
+
"identity.invalid_agent_id",
|
|
3784
|
+
"identity.unknown_agent",
|
|
3785
|
+
"agent.lookup"
|
|
3786
|
+
]);
|
|
3787
|
+
var UNKNOWN_AGENT_GUIDANCE = "Register your agent with AstraSync (or, inside an MCP host, add the AstraSync MCP connector for keyless, human-approved registration), then present the canonical ASTRA-* id issued after owner approval.";
|
|
3788
|
+
|
|
3780
3789
|
// src/verify.ts
|
|
3781
3790
|
var DEFAULT_CONFIG = {
|
|
3782
3791
|
apiBaseUrl: "https://astrasync.ai/api",
|
|
@@ -3988,11 +3997,44 @@ function createGuidanceResponse(_config, reason, options = {}) {
|
|
|
3988
3997
|
// coercing the absent recommendation to a policy 'deny'. Misconfig is
|
|
3989
3998
|
// deterministic and intentionally NOT marked retryable.
|
|
3990
3999
|
...isApiError && { retryable: true },
|
|
4000
|
+
...options.httpStatus !== void 0 && { httpStatus: options.httpStatus },
|
|
4001
|
+
...options.retryAfterMs !== void 0 && { retryAfterMs: options.retryAfterMs },
|
|
3991
4002
|
correlationId: options.correlationId,
|
|
3992
4003
|
attemptId: options.attemptId,
|
|
3993
4004
|
verifiedAt: /* @__PURE__ */ new Date()
|
|
3994
4005
|
};
|
|
3995
4006
|
}
|
|
4007
|
+
async function readJsonSafe(response) {
|
|
4008
|
+
try {
|
|
4009
|
+
const parsed = await response.json();
|
|
4010
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
4011
|
+
} catch {
|
|
4012
|
+
return {};
|
|
4013
|
+
}
|
|
4014
|
+
}
|
|
4015
|
+
function rejectedIdentityGuidance(failures) {
|
|
4016
|
+
const f = failures?.find((x) => REJECTED_IDENTITY_DIMENSIONS.has(x.dimension));
|
|
4017
|
+
if (!f) return void 0;
|
|
4018
|
+
if (f.dimension === "agent.lookup") {
|
|
4019
|
+
return `The presented agent identifier is not registered with AstraSync. ${UNKNOWN_AGENT_GUIDANCE}`;
|
|
4020
|
+
}
|
|
4021
|
+
return f.guidance ? `${f.message} ${f.guidance}` : f.message;
|
|
4022
|
+
}
|
|
4023
|
+
var MAX_RETRY_AFTER_MS = 15 * 60 * 1e3;
|
|
4024
|
+
function parseRetryAfterMs(response) {
|
|
4025
|
+
const raw = response.headers?.get?.("retry-after");
|
|
4026
|
+
if (!raw) return void 0;
|
|
4027
|
+
const trimmed = raw.trim();
|
|
4028
|
+
let ms;
|
|
4029
|
+
if (/^\d+(\.\d+)?$/.test(trimmed)) {
|
|
4030
|
+
ms = Number(trimmed) * 1e3;
|
|
4031
|
+
} else {
|
|
4032
|
+
const at = Date.parse(trimmed);
|
|
4033
|
+
if (Number.isNaN(at)) return void 0;
|
|
4034
|
+
ms = at - Date.now();
|
|
4035
|
+
}
|
|
4036
|
+
return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, Math.round(ms)));
|
|
4037
|
+
}
|
|
3996
4038
|
async function callVerifyAccessAPI(config, request) {
|
|
3997
4039
|
const { credentials, ...requestData } = request;
|
|
3998
4040
|
const body = {
|
|
@@ -4049,7 +4091,8 @@ async function callVerifyAccessAPI(config, request) {
|
|
|
4049
4091
|
body: JSON.stringify(body),
|
|
4050
4092
|
signal: AbortSignal.timeout(config.verifyTimeoutMs ?? 1e4)
|
|
4051
4093
|
});
|
|
4052
|
-
const data = await response
|
|
4094
|
+
const data = await readJsonSafe(response);
|
|
4095
|
+
const retryAfterMs = parseRetryAfterMs(response);
|
|
4053
4096
|
if (response.status === 410) {
|
|
4054
4097
|
return {
|
|
4055
4098
|
success: true,
|
|
@@ -4087,6 +4130,23 @@ async function callVerifyAccessAPI(config, request) {
|
|
|
4087
4130
|
}
|
|
4088
4131
|
};
|
|
4089
4132
|
}
|
|
4133
|
+
if (response.status === 404 && credentials.astraId && (data?.error === "AGENT_NOT_FOUND" || typeof data?.message === "string" && /agent/i.test(data.message))) {
|
|
4134
|
+
return {
|
|
4135
|
+
success: true,
|
|
4136
|
+
attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
|
|
4137
|
+
access: {
|
|
4138
|
+
allowed: false,
|
|
4139
|
+
reason: "unknown_agent",
|
|
4140
|
+
failures: [
|
|
4141
|
+
{
|
|
4142
|
+
dimension: "identity.unknown_agent",
|
|
4143
|
+
message: "The presented agent identifier is not registered with AstraSync.",
|
|
4144
|
+
guidance: UNKNOWN_AGENT_GUIDANCE
|
|
4145
|
+
}
|
|
4146
|
+
]
|
|
4147
|
+
}
|
|
4148
|
+
};
|
|
4149
|
+
}
|
|
4090
4150
|
if (!response.ok) {
|
|
4091
4151
|
if (response.status === 401) {
|
|
4092
4152
|
return {
|
|
@@ -4101,9 +4161,11 @@ async function callVerifyAccessAPI(config, request) {
|
|
|
4101
4161
|
}
|
|
4102
4162
|
return {
|
|
4103
4163
|
success: false,
|
|
4104
|
-
error: data.message || data.error || `API returned ${response.status}`,
|
|
4164
|
+
error: typeof data?.message === "string" && data.message || typeof data?.error === "string" && data.error || `API returned ${response.status}`,
|
|
4105
4165
|
correlationId: typeof data?.correlationId === "string" ? data.correlationId : void 0,
|
|
4106
|
-
attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0
|
|
4166
|
+
attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
|
|
4167
|
+
httpStatus: response.status,
|
|
4168
|
+
...retryAfterMs !== void 0 && { retryAfterMs }
|
|
4107
4169
|
};
|
|
4108
4170
|
}
|
|
4109
4171
|
return data;
|
|
@@ -4175,12 +4237,14 @@ async function verify(config, request, options) {
|
|
|
4175
4237
|
correlationId: apiResponse.correlationId,
|
|
4176
4238
|
attemptId: apiResponse.attemptId,
|
|
4177
4239
|
remediation: apiResponse.remediation,
|
|
4240
|
+
httpStatus: apiResponse.httpStatus,
|
|
4241
|
+
retryAfterMs: apiResponse.retryAfterMs,
|
|
4178
4242
|
urls
|
|
4179
4243
|
});
|
|
4180
4244
|
}
|
|
4181
4245
|
if (!apiResponse.access?.allowed) {
|
|
4182
4246
|
const aggregatedFailures = apiResponse.access?.failures;
|
|
4183
|
-
const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true;
|
|
4247
|
+
const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true && !aggregatedFailures?.some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));
|
|
4184
4248
|
const result2 = {
|
|
4185
4249
|
identityVerified: idVerifiedFromBackend,
|
|
4186
4250
|
policyAllowed: false,
|
|
@@ -4192,7 +4256,10 @@ async function verify(config, request, options) {
|
|
|
4192
4256
|
requiresStepUp: apiResponse.access?.requiresStepUp,
|
|
4193
4257
|
requiresApproval: apiResponse.access?.requiresApproval,
|
|
4194
4258
|
guidance: {
|
|
4195
|
-
|
|
4259
|
+
// 5.12.0: a presented-but-rejected id (malformed / unknown) carries
|
|
4260
|
+
// actionable registration guidance on its failure — surface it
|
|
4261
|
+
// instead of the bare machine reason ('unknown_agent').
|
|
4262
|
+
message: rejectedIdentityGuidance(aggregatedFailures) ?? (apiResponse.access?.reason || "Access denied by PDLSS policy"),
|
|
4196
4263
|
registrationUrl: urls?.registrationUrl ?? "",
|
|
4197
4264
|
documentationUrl: urls?.documentationUrl ?? "",
|
|
4198
4265
|
// 5.1.0: anonymous callers land on this branch — steer MCP-hosted
|
|
@@ -4292,7 +4359,7 @@ async function verify(config, request, options) {
|
|
|
4292
4359
|
registrationUrl: urls?.registrationUrl ?? "",
|
|
4293
4360
|
documentationUrl: urls?.documentationUrl ?? ""
|
|
4294
4361
|
};
|
|
4295
|
-
} else if (result.recommendation === "step_up_required") {
|
|
4362
|
+
} else if (result.recommendation === "step_up_required" && result.identityVerified) {
|
|
4296
4363
|
result.requiresStepUp = true;
|
|
4297
4364
|
result.denialReasons = serverDenialReasons ?? result.recommendationReasons ?? ["Step-up verification required"];
|
|
4298
4365
|
}
|
|
@@ -4321,6 +4388,217 @@ var DEFAULT_EDGE_CONFIG = Object.freeze({
|
|
|
4321
4388
|
var DEFAULT_TTL_MS = 60 * 1e3;
|
|
4322
4389
|
var DEFAULT_MAX_STALE_MS = 24 * 60 * 60 * 1e3;
|
|
4323
4390
|
|
|
4391
|
+
// src/edge-core/events.ts
|
|
4392
|
+
async function withBudget(promise, ms) {
|
|
4393
|
+
let timer;
|
|
4394
|
+
try {
|
|
4395
|
+
return await Promise.race([
|
|
4396
|
+
promise,
|
|
4397
|
+
new Promise((resolve) => {
|
|
4398
|
+
timer = setTimeout(() => resolve(void 0), ms);
|
|
4399
|
+
})
|
|
4400
|
+
]);
|
|
4401
|
+
} catch {
|
|
4402
|
+
return void 0;
|
|
4403
|
+
} finally {
|
|
4404
|
+
if (timer) clearTimeout(timer);
|
|
4405
|
+
}
|
|
4406
|
+
}
|
|
4407
|
+
var destKeyOf = (d) => `${d.apiBaseUrl}\0${d.apiKey ?? ""}\0${d.counterparty}\0${d.adapter ?? ""}`;
|
|
4408
|
+
var BeaconBuffer = class {
|
|
4409
|
+
constructor(options = {}) {
|
|
4410
|
+
this.queue = [];
|
|
4411
|
+
this.droppedSinceLast = 0;
|
|
4412
|
+
this.droppedTotal = 0;
|
|
4413
|
+
this.deliveredTotal = 0;
|
|
4414
|
+
this.backoffUntil = 0;
|
|
4415
|
+
this.collapse = /* @__PURE__ */ new Map();
|
|
4416
|
+
/** Keys the backend answered 401 for — later batches go unauthenticated. */
|
|
4417
|
+
this.rejectedKeys = /* @__PURE__ */ new Set();
|
|
4418
|
+
this.opts = {
|
|
4419
|
+
maxItems: options.maxItems ?? 1e3,
|
|
4420
|
+
maxBatch: options.maxBatch ?? 100,
|
|
4421
|
+
maxAttempts: options.maxAttempts ?? 3,
|
|
4422
|
+
collapseWindowMs: options.collapseWindowMs ?? 6e4,
|
|
4423
|
+
collapseMaxKeys: options.collapseMaxKeys ?? 1e3,
|
|
4424
|
+
requestTimeoutMs: options.requestTimeoutMs ?? 1e4,
|
|
4425
|
+
retryBackoffMs: options.retryBackoffMs ?? 1e3,
|
|
4426
|
+
now: options.now ?? Date.now
|
|
4427
|
+
};
|
|
4428
|
+
}
|
|
4429
|
+
/**
|
|
4430
|
+
* Queue one beacon. With a `collapseKey`, a repeat inside the window is
|
|
4431
|
+
* merged into a held aggregate (sent when the window closes) instead of
|
|
4432
|
+
* becoming its own item.
|
|
4433
|
+
*/
|
|
4434
|
+
enqueue(dest, item, collapseKey) {
|
|
4435
|
+
const now = this.opts.now();
|
|
4436
|
+
if (collapseKey) {
|
|
4437
|
+
const entry = this.collapse.get(collapseKey);
|
|
4438
|
+
if (entry && now - entry.firstSeenAt < this.opts.collapseWindowMs) {
|
|
4439
|
+
for (const target of [entry.first, entry.held]) {
|
|
4440
|
+
if (target && !target.inFlight && this.queue.includes(target)) {
|
|
4441
|
+
target.item.repeatCount = (target.item.repeatCount ?? 1) + 1;
|
|
4442
|
+
return;
|
|
4443
|
+
}
|
|
4444
|
+
}
|
|
4445
|
+
const held = this.push(
|
|
4446
|
+
dest,
|
|
4447
|
+
{ ...item, repeatCount: 1 },
|
|
4448
|
+
entry.firstSeenAt + this.opts.collapseWindowMs
|
|
4449
|
+
);
|
|
4450
|
+
entry.held = held;
|
|
4451
|
+
return;
|
|
4452
|
+
}
|
|
4453
|
+
this.collapse.delete(collapseKey);
|
|
4454
|
+
if (this.collapse.size >= this.opts.collapseMaxKeys) {
|
|
4455
|
+
const oldest = this.collapse.keys().next().value;
|
|
4456
|
+
if (oldest !== void 0) this.collapse.delete(oldest);
|
|
4457
|
+
}
|
|
4458
|
+
const fresh = { firstSeenAt: now };
|
|
4459
|
+
this.collapse.set(collapseKey, fresh);
|
|
4460
|
+
fresh.first = this.push(dest, item, now);
|
|
4461
|
+
return;
|
|
4462
|
+
}
|
|
4463
|
+
this.push(dest, item, now);
|
|
4464
|
+
}
|
|
4465
|
+
/**
|
|
4466
|
+
* Deliver every eligible queued item. Concurrent callers share ONE
|
|
4467
|
+
* in-flight drain (it survives the caller's budget and a Lambda freeze),
|
|
4468
|
+
* so nothing in flight is ever sent twice; items queued while it runs are
|
|
4469
|
+
* picked up by the same drain.
|
|
4470
|
+
*/
|
|
4471
|
+
flush() {
|
|
4472
|
+
if (!this.inFlight) {
|
|
4473
|
+
this.inFlight = this.drain().finally(() => {
|
|
4474
|
+
this.inFlight = void 0;
|
|
4475
|
+
});
|
|
4476
|
+
}
|
|
4477
|
+
return this.inFlight;
|
|
4478
|
+
}
|
|
4479
|
+
/** Counters for tests and diagnostics. */
|
|
4480
|
+
stats() {
|
|
4481
|
+
return {
|
|
4482
|
+
queueDepth: this.queue.length,
|
|
4483
|
+
droppedSinceLast: this.droppedSinceLast,
|
|
4484
|
+
droppedTotal: this.droppedTotal,
|
|
4485
|
+
deliveredTotal: this.deliveredTotal,
|
|
4486
|
+
flushing: this.inFlight !== void 0
|
|
4487
|
+
};
|
|
4488
|
+
}
|
|
4489
|
+
push(dest, item, eligibleAt) {
|
|
4490
|
+
while (this.queue.length >= this.opts.maxItems) this.dropOldest();
|
|
4491
|
+
const entry = {
|
|
4492
|
+
dest,
|
|
4493
|
+
destKey: destKeyOf(dest),
|
|
4494
|
+
item,
|
|
4495
|
+
attempts: 0,
|
|
4496
|
+
eligibleAt,
|
|
4497
|
+
inFlight: false
|
|
4498
|
+
};
|
|
4499
|
+
this.queue.push(entry);
|
|
4500
|
+
return entry;
|
|
4501
|
+
}
|
|
4502
|
+
dropOldest() {
|
|
4503
|
+
if (this.queue.shift()) this.countDropped(1);
|
|
4504
|
+
}
|
|
4505
|
+
countDropped(n) {
|
|
4506
|
+
this.droppedSinceLast += n;
|
|
4507
|
+
this.droppedTotal += n;
|
|
4508
|
+
}
|
|
4509
|
+
async drain() {
|
|
4510
|
+
for (; ; ) {
|
|
4511
|
+
const now = this.opts.now();
|
|
4512
|
+
if (now < this.backoffUntil) return;
|
|
4513
|
+
const batch = this.takeBatch(now);
|
|
4514
|
+
if (batch.length === 0) return;
|
|
4515
|
+
const ok = await this.send(batch);
|
|
4516
|
+
if (!ok) return;
|
|
4517
|
+
}
|
|
4518
|
+
}
|
|
4519
|
+
/** Oldest eligible item + up to maxBatch-1 more for the same destination. */
|
|
4520
|
+
takeBatch(now) {
|
|
4521
|
+
const first = this.queue.find((q) => q.eligibleAt <= now);
|
|
4522
|
+
if (!first) return [];
|
|
4523
|
+
const batch = [];
|
|
4524
|
+
const rest = [];
|
|
4525
|
+
for (const q of this.queue) {
|
|
4526
|
+
if (batch.length < this.opts.maxBatch && q.destKey === first.destKey && q.eligibleAt <= now) {
|
|
4527
|
+
q.inFlight = true;
|
|
4528
|
+
batch.push(q);
|
|
4529
|
+
} else {
|
|
4530
|
+
rest.push(q);
|
|
4531
|
+
}
|
|
4532
|
+
}
|
|
4533
|
+
this.queue = rest;
|
|
4534
|
+
return batch;
|
|
4535
|
+
}
|
|
4536
|
+
/** POST one batch. Returns false when the drain should pause (backoff). */
|
|
4537
|
+
async send(batch) {
|
|
4538
|
+
const dest = batch[0].dest;
|
|
4539
|
+
const useKey = dest.apiKey && !this.rejectedKeys.has(dest.apiKey) ? dest.apiKey : void 0;
|
|
4540
|
+
const reportedDropped = this.droppedSinceLast;
|
|
4541
|
+
const meta = {
|
|
4542
|
+
droppedSinceLast: reportedDropped,
|
|
4543
|
+
queueDepth: this.queue.length,
|
|
4544
|
+
adapter: dest.adapter ?? "edge-core",
|
|
4545
|
+
version: SDK_VERSION
|
|
4546
|
+
};
|
|
4547
|
+
const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
|
|
4548
|
+
const response = await withBudget(
|
|
4549
|
+
sdkFetch(`${dest.apiBaseUrl}/verification-activity/edge-events`, {
|
|
4550
|
+
method: "POST",
|
|
4551
|
+
headers: {
|
|
4552
|
+
"Content-Type": "application/json",
|
|
4553
|
+
...useKey && { Authorization: `Bearer ${useKey}` }
|
|
4554
|
+
},
|
|
4555
|
+
body: JSON.stringify({ events: batch.map((q) => q.item), meta }),
|
|
4556
|
+
...controller && { signal: controller.signal }
|
|
4557
|
+
}),
|
|
4558
|
+
this.opts.requestTimeoutMs
|
|
4559
|
+
);
|
|
4560
|
+
if (!response) controller?.abort();
|
|
4561
|
+
const status = response?.status;
|
|
4562
|
+
for (const q of batch) q.inFlight = false;
|
|
4563
|
+
if (status !== void 0 && status >= 200 && status < 300) {
|
|
4564
|
+
this.droppedSinceLast = Math.max(0, this.droppedSinceLast - reportedDropped);
|
|
4565
|
+
this.deliveredTotal += batch.length;
|
|
4566
|
+
return true;
|
|
4567
|
+
}
|
|
4568
|
+
if (status === 401 && useKey) {
|
|
4569
|
+
this.rejectedKeys.add(useKey);
|
|
4570
|
+
this.requeue(batch, false);
|
|
4571
|
+
return true;
|
|
4572
|
+
}
|
|
4573
|
+
if (status === 429) {
|
|
4574
|
+
const retryAfter = Number(response?.headers.get("retry-after"));
|
|
4575
|
+
const waitMs = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 120) * 1e3 : 3e4;
|
|
4576
|
+
this.backoffUntil = this.opts.now() + waitMs;
|
|
4577
|
+
this.requeue(batch, false);
|
|
4578
|
+
return false;
|
|
4579
|
+
}
|
|
4580
|
+
if (status !== void 0 && status >= 400 && status < 500) {
|
|
4581
|
+
this.countDropped(batch.length);
|
|
4582
|
+
return true;
|
|
4583
|
+
}
|
|
4584
|
+
this.backoffUntil = this.opts.now() + this.opts.retryBackoffMs;
|
|
4585
|
+
this.requeue(batch, true);
|
|
4586
|
+
return false;
|
|
4587
|
+
}
|
|
4588
|
+
/** Put a failed batch back at the head of the queue (order preserved). */
|
|
4589
|
+
requeue(batch, countAttempt) {
|
|
4590
|
+
const keep = [];
|
|
4591
|
+
for (const q of batch) {
|
|
4592
|
+
if (countAttempt) q.attempts += 1;
|
|
4593
|
+
if (q.attempts >= this.opts.maxAttempts) this.countDropped(1);
|
|
4594
|
+
else keep.push(q);
|
|
4595
|
+
}
|
|
4596
|
+
this.queue = [...keep, ...this.queue];
|
|
4597
|
+
while (this.queue.length > this.opts.maxItems) this.dropOldest();
|
|
4598
|
+
}
|
|
4599
|
+
};
|
|
4600
|
+
var beaconBuffer = new BeaconBuffer();
|
|
4601
|
+
|
|
4324
4602
|
// src/adapters/express.ts
|
|
4325
4603
|
var DEFAULT_ROUTES_REFRESH_MS = 5 * 60 * 1e3;
|
|
4326
4604
|
|
|
@@ -4915,22 +5193,118 @@ var AstraSyncGateway = class {
|
|
|
4915
5193
|
};
|
|
4916
5194
|
|
|
4917
5195
|
// src/claude-code/guard-config.ts
|
|
5196
|
+
var import_fs5 = require("fs");
|
|
5197
|
+
var import_os2 = require("os");
|
|
5198
|
+
var import_path4 = require("path");
|
|
5199
|
+
|
|
5200
|
+
// src/fleet/enrolment-store.ts
|
|
4918
5201
|
var import_fs4 = require("fs");
|
|
4919
5202
|
var import_os = require("os");
|
|
4920
5203
|
var import_path3 = require("path");
|
|
4921
|
-
function
|
|
5204
|
+
function machineScopeDir(platform = process.platform, env = process.env) {
|
|
5205
|
+
if (platform === "darwin") return "/Library/Application Support/AstraSync";
|
|
5206
|
+
if (platform === "win32") return (0, import_path3.join)(env.ProgramData || "C:\\ProgramData", "AstraSync");
|
|
5207
|
+
return "/etc/astrasync";
|
|
5208
|
+
}
|
|
5209
|
+
function fleetPaths(options = {}) {
|
|
5210
|
+
const home = options.home ?? (0, import_os.homedir)();
|
|
5211
|
+
const machineDir = options.machineDir ?? options.env?.ASTRASYNC_FLEET_MACHINE_DIR ?? machineScopeDir(options.platform, options.env);
|
|
5212
|
+
const userDir = (0, import_path3.join)(home, ".astrasync", "fleet");
|
|
5213
|
+
return {
|
|
5214
|
+
machineDevice: (0, import_path3.join)(machineDir, "fleet.json"),
|
|
5215
|
+
machinePolicy: (0, import_path3.join)(machineDir, "policy.jws"),
|
|
5216
|
+
userDir,
|
|
5217
|
+
userDevice: (0, import_path3.join)(userDir, "device.json"),
|
|
5218
|
+
userPolicy: (0, import_path3.join)(userDir, "policy.jws"),
|
|
5219
|
+
userKeyChain: (0, import_path3.join)(userDir, "keychain.json"),
|
|
5220
|
+
state: (0, import_path3.join)(userDir, "state.json")
|
|
5221
|
+
};
|
|
5222
|
+
}
|
|
5223
|
+
function isEnrolment(value) {
|
|
5224
|
+
const v = value;
|
|
5225
|
+
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);
|
|
5226
|
+
}
|
|
5227
|
+
function loadEnrolment(paths) {
|
|
5228
|
+
const candidates = [
|
|
5229
|
+
[paths.machineDevice, "machine"],
|
|
5230
|
+
[paths.userDevice, "user"]
|
|
5231
|
+
];
|
|
5232
|
+
for (const [path, scope] of candidates) {
|
|
5233
|
+
if (!(0, import_fs4.existsSync)(path)) continue;
|
|
5234
|
+
try {
|
|
5235
|
+
const parsed = JSON.parse((0, import_fs4.readFileSync)(path, "utf-8"));
|
|
5236
|
+
if (isEnrolment(parsed)) return { enrolment: parsed, scope };
|
|
5237
|
+
} catch {
|
|
5238
|
+
}
|
|
5239
|
+
return { corrupt: true, path };
|
|
5240
|
+
}
|
|
5241
|
+
return null;
|
|
5242
|
+
}
|
|
5243
|
+
function writeFileMode(path, content, mode) {
|
|
5244
|
+
(0, import_fs4.mkdirSync)((0, import_path3.dirname)(path), { recursive: true, mode: 448 });
|
|
5245
|
+
(0, import_fs4.writeFileSync)(path, content, { encoding: "utf-8", mode });
|
|
5246
|
+
try {
|
|
5247
|
+
(0, import_fs4.chmodSync)(path, mode);
|
|
5248
|
+
} catch {
|
|
5249
|
+
}
|
|
5250
|
+
}
|
|
5251
|
+
function readCachedPolicies(paths) {
|
|
5252
|
+
const out = [];
|
|
5253
|
+
for (const p of [paths.userPolicy, paths.machinePolicy]) {
|
|
5254
|
+
try {
|
|
5255
|
+
if ((0, import_fs4.existsSync)(p)) out.push((0, import_fs4.readFileSync)(p, "utf-8").trim());
|
|
5256
|
+
} catch {
|
|
5257
|
+
}
|
|
5258
|
+
}
|
|
5259
|
+
return out.filter(Boolean);
|
|
5260
|
+
}
|
|
5261
|
+
function writeCachedPolicy(paths, jws) {
|
|
5262
|
+
writeFileMode(paths.userPolicy, jws, 384);
|
|
5263
|
+
}
|
|
5264
|
+
function readKeyChain(paths) {
|
|
5265
|
+
try {
|
|
5266
|
+
const parsed = JSON.parse((0, import_fs4.readFileSync)(paths.userKeyChain, "utf-8"));
|
|
5267
|
+
return Array.isArray(parsed) ? parsed.filter((j) => typeof j === "string") : [];
|
|
5268
|
+
} catch {
|
|
5269
|
+
return [];
|
|
5270
|
+
}
|
|
5271
|
+
}
|
|
5272
|
+
function writeKeyChain(paths, chain) {
|
|
5273
|
+
writeFileMode(paths.userKeyChain, JSON.stringify(chain), 384);
|
|
5274
|
+
}
|
|
5275
|
+
function readState(paths) {
|
|
5276
|
+
try {
|
|
5277
|
+
const parsed = JSON.parse((0, import_fs4.readFileSync)(paths.state, "utf-8"));
|
|
5278
|
+
const c = parsed.counts;
|
|
5279
|
+
return {
|
|
5280
|
+
...parsed,
|
|
5281
|
+
counts: { allow: c?.allow ?? 0, deny: c?.deny ?? 0, ask: c?.ask ?? 0 }
|
|
5282
|
+
};
|
|
5283
|
+
} catch {
|
|
5284
|
+
return { counts: { allow: 0, deny: 0, ask: 0 } };
|
|
5285
|
+
}
|
|
5286
|
+
}
|
|
5287
|
+
function writeState(paths, state) {
|
|
5288
|
+
try {
|
|
5289
|
+
writeFileMode(paths.state, JSON.stringify(state, null, 2), 384);
|
|
5290
|
+
} catch {
|
|
5291
|
+
}
|
|
5292
|
+
}
|
|
5293
|
+
|
|
5294
|
+
// src/claude-code/guard-config.ts
|
|
5295
|
+
function resolveGuardConfig(env, payloadCwd, home = (0, import_os2.homedir)()) {
|
|
4922
5296
|
const candidateRoots = [env.CLAUDE_PROJECT_DIR, payloadCwd, home].filter(
|
|
4923
5297
|
(root) => typeof root === "string" && root.length > 0
|
|
4924
5298
|
);
|
|
4925
5299
|
for (const root of candidateRoots) {
|
|
4926
|
-
const guardDir = (0,
|
|
4927
|
-
const policyFile = (0,
|
|
4928
|
-
if (!(0,
|
|
5300
|
+
const guardDir = (0, import_path4.join)(root, ".astrasync");
|
|
5301
|
+
const policyFile = (0, import_path4.join)(guardDir, "policy.yaml");
|
|
5302
|
+
if (!(0, import_fs5.existsSync)(policyFile)) continue;
|
|
4929
5303
|
let settings = {};
|
|
4930
|
-
const settingsFile = (0,
|
|
4931
|
-
if ((0,
|
|
5304
|
+
const settingsFile = (0, import_path4.join)(guardDir, "guard.json");
|
|
5305
|
+
if ((0, import_fs5.existsSync)(settingsFile)) {
|
|
4932
5306
|
try {
|
|
4933
|
-
settings = JSON.parse((0,
|
|
5307
|
+
settings = JSON.parse((0, import_fs5.readFileSync)(settingsFile, "utf-8"));
|
|
4934
5308
|
} catch {
|
|
4935
5309
|
settings = {};
|
|
4936
5310
|
}
|
|
@@ -4939,6 +5313,408 @@ function resolveGuardConfig(env, payloadCwd, home = (0, import_os.homedir)()) {
|
|
|
4939
5313
|
}
|
|
4940
5314
|
return null;
|
|
4941
5315
|
}
|
|
5316
|
+
var FLEET_ENROL_INSTRUCTION = "This machine must be enrolled: run `astrasync guard enroll <token>` (token from your organisation admin)";
|
|
5317
|
+
function resolveFleet(env, home = (0, import_os2.homedir)(), paths = fleetPaths({ home, env })) {
|
|
5318
|
+
const loaded = loadEnrolment(paths);
|
|
5319
|
+
if (loaded && "corrupt" in loaded) {
|
|
5320
|
+
return {
|
|
5321
|
+
kind: "fleet-missing",
|
|
5322
|
+
reason: `fleet enrolment at ${loaded.path} is unreadable \u2014 ${FLEET_ENROL_INSTRUCTION}`,
|
|
5323
|
+
paths
|
|
5324
|
+
};
|
|
5325
|
+
}
|
|
5326
|
+
if (loaded) return { kind: "fleet", enrolment: loaded.enrolment, scope: loaded.scope, paths };
|
|
5327
|
+
if (env.ASTRASYNC_FLEET_REQUIRED === "1") {
|
|
5328
|
+
return { kind: "fleet-missing", reason: FLEET_ENROL_INSTRUCTION, paths };
|
|
5329
|
+
}
|
|
5330
|
+
return null;
|
|
5331
|
+
}
|
|
5332
|
+
|
|
5333
|
+
// src/fleet/hook-runner.ts
|
|
5334
|
+
var import_path5 = require("path");
|
|
5335
|
+
|
|
5336
|
+
// src/fleet/client.ts
|
|
5337
|
+
var FleetApiError = class extends Error {
|
|
5338
|
+
constructor(message, status, code) {
|
|
5339
|
+
super(message);
|
|
5340
|
+
this.status = status;
|
|
5341
|
+
this.code = code;
|
|
5342
|
+
this.name = "FleetApiError";
|
|
5343
|
+
}
|
|
5344
|
+
};
|
|
5345
|
+
function base(url) {
|
|
5346
|
+
return url.replace(/\/+$/, "");
|
|
5347
|
+
}
|
|
5348
|
+
async function call(url, init, timeoutMs) {
|
|
5349
|
+
const controller = new AbortController();
|
|
5350
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
5351
|
+
try {
|
|
5352
|
+
const res = await sdkFetch(url, { ...init, signal: controller.signal });
|
|
5353
|
+
const text = await res.text();
|
|
5354
|
+
let body = text;
|
|
5355
|
+
try {
|
|
5356
|
+
body = text ? JSON.parse(text) : null;
|
|
5357
|
+
} catch {
|
|
5358
|
+
}
|
|
5359
|
+
return { status: res.status, body, headers: res.headers };
|
|
5360
|
+
} finally {
|
|
5361
|
+
clearTimeout(timer);
|
|
5362
|
+
}
|
|
5363
|
+
}
|
|
5364
|
+
function apiError(status, body, what) {
|
|
5365
|
+
const b = body ?? {};
|
|
5366
|
+
const code = b.code ?? (typeof b.error === "string" ? b.error : void 0);
|
|
5367
|
+
return new FleetApiError(`${what} failed (${status}${code ? ` ${code}` : ""})`, status, code);
|
|
5368
|
+
}
|
|
5369
|
+
function deviceHeaders(enrolment) {
|
|
5370
|
+
return { Authorization: `Device ${enrolment.credential}` };
|
|
5371
|
+
}
|
|
5372
|
+
function policyEtag(sha256, kid) {
|
|
5373
|
+
return `${sha256}.${kid ?? ""}`;
|
|
5374
|
+
}
|
|
5375
|
+
async function fetchFleetPolicy(enrolment, ifNoneMatch, timeoutMs = 1500) {
|
|
5376
|
+
const headers = deviceHeaders(enrolment);
|
|
5377
|
+
if (ifNoneMatch) headers["If-None-Match"] = `"${ifNoneMatch}"`;
|
|
5378
|
+
const r = await call(`${base(enrolment.apiBaseUrl)}/fleet/policy`, { headers }, timeoutMs);
|
|
5379
|
+
if (r.status === 304) return { status: "unchanged" };
|
|
5380
|
+
if (r.status !== 200) throw apiError(r.status, r.body, "Policy fetch");
|
|
5381
|
+
const data = r.body;
|
|
5382
|
+
if (!data?.policyJws) throw new FleetApiError("Policy response has no policyJws", r.status);
|
|
5383
|
+
return {
|
|
5384
|
+
status: "ok",
|
|
5385
|
+
policyJws: data.policyJws,
|
|
5386
|
+
sha256: data.sha256 ?? "",
|
|
5387
|
+
version: data.version ?? 0,
|
|
5388
|
+
keyChain: Array.isArray(data.keyChain) ? data.keyChain.filter((j) => typeof j === "string") : []
|
|
5389
|
+
};
|
|
5390
|
+
}
|
|
5391
|
+
async function sendHeartbeat(enrolment, request, timeoutMs = 1500) {
|
|
5392
|
+
const r = await call(
|
|
5393
|
+
`${base(enrolment.apiBaseUrl)}/fleet/heartbeat`,
|
|
5394
|
+
{
|
|
5395
|
+
method: "POST",
|
|
5396
|
+
headers: { ...deviceHeaders(enrolment), "Content-Type": "application/json" },
|
|
5397
|
+
body: JSON.stringify(request)
|
|
5398
|
+
},
|
|
5399
|
+
timeoutMs
|
|
5400
|
+
);
|
|
5401
|
+
if (r.status !== 200) throw apiError(r.status, r.body, "Heartbeat");
|
|
5402
|
+
return r.body;
|
|
5403
|
+
}
|
|
5404
|
+
|
|
5405
|
+
// src/fleet/policy-verify.ts
|
|
5406
|
+
var import_crypto = require("crypto");
|
|
5407
|
+
var import_jose2 = require("jose");
|
|
5408
|
+
|
|
5409
|
+
// src/fleet/types.ts
|
|
5410
|
+
var FLEET_POLICY_TYP = "fleet-policy+jwt";
|
|
5411
|
+
var FLEET_POLICY_AUD = "astrasync:fleet-policy";
|
|
5412
|
+
var FLEET_POLICY_ISS = "astrasync.ai";
|
|
5413
|
+
var FLEET_KEYS_TYP = "fleet-keys+jwt";
|
|
5414
|
+
var FLEET_KEYS_AUD = "astrasync:fleet-keys";
|
|
5415
|
+
var DEFAULT_HEARTBEAT_INTERVAL_SEC = 900;
|
|
5416
|
+
|
|
5417
|
+
// src/fleet/policy-verify.ts
|
|
5418
|
+
var FleetPolicyError = class extends Error {
|
|
5419
|
+
constructor(message) {
|
|
5420
|
+
super(message);
|
|
5421
|
+
this.name = "FleetPolicyError";
|
|
5422
|
+
}
|
|
5423
|
+
};
|
|
5424
|
+
function sha256Hex(text) {
|
|
5425
|
+
return (0, import_crypto.createHash)("sha256").update(text, "utf8").digest("hex");
|
|
5426
|
+
}
|
|
5427
|
+
function parseSettings(raw) {
|
|
5428
|
+
if (!raw || typeof raw !== "object") throw new FleetPolicyError("settings missing");
|
|
5429
|
+
const s = raw;
|
|
5430
|
+
if (s.posture !== "active" && s.posture !== "passive") {
|
|
5431
|
+
throw new FleetPolicyError("settings.posture must be active or passive");
|
|
5432
|
+
}
|
|
5433
|
+
if (s.failOpen !== void 0 && typeof s.failOpen !== "boolean") {
|
|
5434
|
+
throw new FleetPolicyError("settings.failOpen must be a boolean");
|
|
5435
|
+
}
|
|
5436
|
+
if (s.governMcp !== void 0 && typeof s.governMcp !== "boolean") {
|
|
5437
|
+
throw new FleetPolicyError("settings.governMcp must be a boolean");
|
|
5438
|
+
}
|
|
5439
|
+
if (s.skipTools !== void 0 && !(Array.isArray(s.skipTools) && s.skipTools.every((t) => typeof t === "string"))) {
|
|
5440
|
+
throw new FleetPolicyError("settings.skipTools must be a string array");
|
|
5441
|
+
}
|
|
5442
|
+
const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
|
|
5443
|
+
return {
|
|
5444
|
+
posture: s.posture,
|
|
5445
|
+
failOpen: s.failOpen === true,
|
|
5446
|
+
...typeof s.governMcp === "boolean" && { governMcp: s.governMcp },
|
|
5447
|
+
...Array.isArray(s.skipTools) && { skipTools: s.skipTools },
|
|
5448
|
+
...num(s.heartbeatIntervalSec) && { heartbeatIntervalSec: num(s.heartbeatIntervalSec) },
|
|
5449
|
+
...num(s.staleAfterSec) && { staleAfterSec: num(s.staleAfterSec) }
|
|
5450
|
+
};
|
|
5451
|
+
}
|
|
5452
|
+
async function verifyFleetPolicy(jws, jwks, options) {
|
|
5453
|
+
let payloadBytes;
|
|
5454
|
+
let header;
|
|
5455
|
+
try {
|
|
5456
|
+
const keySet = (0, import_jose2.createLocalJWKSet)(jwks);
|
|
5457
|
+
const result = await (0, import_jose2.compactVerify)(jws, keySet, { algorithms: ["ES256"] });
|
|
5458
|
+
payloadBytes = result.payload;
|
|
5459
|
+
header = result.protectedHeader;
|
|
5460
|
+
} catch (err) {
|
|
5461
|
+
throw new FleetPolicyError(
|
|
5462
|
+
`signature verification failed (${err instanceof Error ? err.message : String(err)})`
|
|
5463
|
+
);
|
|
5464
|
+
}
|
|
5465
|
+
if (header.typ !== FLEET_POLICY_TYP) throw new FleetPolicyError(`unexpected typ ${header.typ}`);
|
|
5466
|
+
let claims;
|
|
5467
|
+
try {
|
|
5468
|
+
claims = JSON.parse(new TextDecoder().decode(payloadBytes));
|
|
5469
|
+
} catch {
|
|
5470
|
+
throw new FleetPolicyError("payload is not JSON");
|
|
5471
|
+
}
|
|
5472
|
+
if (claims.aud !== FLEET_POLICY_AUD) throw new FleetPolicyError(`unexpected aud ${claims.aud}`);
|
|
5473
|
+
if (claims.iss !== FLEET_POLICY_ISS) throw new FleetPolicyError(`unexpected iss ${claims.iss}`);
|
|
5474
|
+
if (!options.expectedSubs.includes(claims.sub)) {
|
|
5475
|
+
throw new FleetPolicyError("policy was issued for a different organisation or device");
|
|
5476
|
+
}
|
|
5477
|
+
if (!Number.isInteger(claims.ver) || claims.ver < 1) {
|
|
5478
|
+
throw new FleetPolicyError("ver must be a positive integer");
|
|
5479
|
+
}
|
|
5480
|
+
if (options.minVer !== void 0 && claims.ver < options.minVer) {
|
|
5481
|
+
throw new FleetPolicyError(
|
|
5482
|
+
`policy version ${claims.ver} is older than the accepted version ${options.minVer} (rollback)`
|
|
5483
|
+
);
|
|
5484
|
+
}
|
|
5485
|
+
if (typeof claims.yaml !== "string" || sha256Hex(claims.yaml) !== claims.sha256) {
|
|
5486
|
+
throw new FleetPolicyError("policy hash mismatch");
|
|
5487
|
+
}
|
|
5488
|
+
const settings = parseSettings(claims.settings);
|
|
5489
|
+
const parsed = parseYaml(claims.yaml);
|
|
5490
|
+
if (!parsed.policy) {
|
|
5491
|
+
const first = parsed.validation.errors[0];
|
|
5492
|
+
throw new FleetPolicyError(
|
|
5493
|
+
`signed policy is invalid${first ? ` (${first.path}: ${first.message})` : ""}`
|
|
5494
|
+
);
|
|
5495
|
+
}
|
|
5496
|
+
return { kid: header.kid, claims: { ...claims, settings }, policy: parsed.policy, settings, jws };
|
|
5497
|
+
}
|
|
5498
|
+
async function resolveFleetJwks(pinned, chain, ownerId) {
|
|
5499
|
+
let trusted = pinned;
|
|
5500
|
+
let lastSeq = 0;
|
|
5501
|
+
for (const link of chain) {
|
|
5502
|
+
try {
|
|
5503
|
+
const { payload, protectedHeader } = await (0, import_jose2.compactVerify)(
|
|
5504
|
+
link,
|
|
5505
|
+
(0, import_jose2.createLocalJWKSet)(trusted),
|
|
5506
|
+
{ algorithms: ["ES256"] }
|
|
5507
|
+
);
|
|
5508
|
+
if (protectedHeader.typ !== FLEET_KEYS_TYP) continue;
|
|
5509
|
+
const c = JSON.parse(new TextDecoder().decode(payload));
|
|
5510
|
+
if (c.aud !== FLEET_KEYS_AUD || c.iss !== FLEET_POLICY_ISS || c.sub !== ownerId) continue;
|
|
5511
|
+
if (!Number.isInteger(c.seq) || c.seq <= lastSeq) continue;
|
|
5512
|
+
const keys = Array.isArray(c.keys) ? c.keys.filter((k) => k && k.kty === "EC" && k.crv === "P-256" && !("d" in k)) : [];
|
|
5513
|
+
if (keys.length === 0) continue;
|
|
5514
|
+
trusted = { keys };
|
|
5515
|
+
lastSeq = c.seq;
|
|
5516
|
+
} catch {
|
|
5517
|
+
}
|
|
5518
|
+
}
|
|
5519
|
+
return trusted;
|
|
5520
|
+
}
|
|
5521
|
+
async function pickNewestValid(candidates, jwks, options) {
|
|
5522
|
+
let best = null;
|
|
5523
|
+
let lastError = new FleetPolicyError("no cached fleet policy");
|
|
5524
|
+
for (const jws of candidates) {
|
|
5525
|
+
try {
|
|
5526
|
+
const v = await verifyFleetPolicy(jws, jwks, options);
|
|
5527
|
+
if (!best || v.claims.ver > best.claims.ver) best = v;
|
|
5528
|
+
} catch (err) {
|
|
5529
|
+
lastError = err instanceof Error ? err : new FleetPolicyError(String(err));
|
|
5530
|
+
}
|
|
5531
|
+
}
|
|
5532
|
+
if (!best) throw lastError;
|
|
5533
|
+
return best;
|
|
5534
|
+
}
|
|
5535
|
+
|
|
5536
|
+
// src/fleet/runtime.ts
|
|
5537
|
+
var FLEET_SYNC_BUDGET_MS = 1500;
|
|
5538
|
+
function expectedSubs(enrolment) {
|
|
5539
|
+
return [enrolment.org.ownerId, enrolment.deviceId];
|
|
5540
|
+
}
|
|
5541
|
+
function fleetJwks(ctx, chain = readKeyChain(ctx.paths)) {
|
|
5542
|
+
return resolveFleetJwks(ctx.enrolment.jwks, chain, ctx.enrolment.org.ownerId);
|
|
5543
|
+
}
|
|
5544
|
+
async function acceptFetched(ctx, fetched, verifyOpts) {
|
|
5545
|
+
const jwks = await fleetJwks(ctx, fetched.keyChain);
|
|
5546
|
+
const verified = await verifyFleetPolicy(fetched.policyJws, jwks, verifyOpts);
|
|
5547
|
+
if (fetched.keyChain.length > 0) writeKeyChain(ctx.paths, fetched.keyChain);
|
|
5548
|
+
writeCachedPolicy(ctx.paths, fetched.policyJws);
|
|
5549
|
+
return verified;
|
|
5550
|
+
}
|
|
5551
|
+
function remember(paths, state, verified) {
|
|
5552
|
+
state.appliedSha256 = verified.claims.sha256;
|
|
5553
|
+
state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
|
|
5554
|
+
writeState(paths, state);
|
|
5555
|
+
}
|
|
5556
|
+
async function loadFleetPolicy(ctx, options = {}) {
|
|
5557
|
+
const state = readState(ctx.paths);
|
|
5558
|
+
const verifyOpts = { expectedSubs: expectedSubs(ctx.enrolment), minVer: state.maxVer };
|
|
5559
|
+
const cached = readCachedPolicies(ctx.paths);
|
|
5560
|
+
let cacheError = null;
|
|
5561
|
+
if (cached.length > 0) {
|
|
5562
|
+
try {
|
|
5563
|
+
const verified = await pickNewestValid(cached, await fleetJwks(ctx), verifyOpts);
|
|
5564
|
+
if (verified.claims.sha256 !== state.appliedSha256 || verified.claims.ver !== state.maxVer) {
|
|
5565
|
+
remember(ctx.paths, state, verified);
|
|
5566
|
+
}
|
|
5567
|
+
return verified;
|
|
5568
|
+
} catch (err) {
|
|
5569
|
+
cacheError = err instanceof Error ? err : new FleetPolicyError(String(err));
|
|
5570
|
+
}
|
|
5571
|
+
}
|
|
5572
|
+
try {
|
|
5573
|
+
const fetched = await fetchFleetPolicy(
|
|
5574
|
+
ctx.enrolment,
|
|
5575
|
+
null,
|
|
5576
|
+
options.fetchTimeoutMs ?? FLEET_SYNC_BUDGET_MS
|
|
5577
|
+
);
|
|
5578
|
+
if (fetched.status === "ok") {
|
|
5579
|
+
const verified = await acceptFetched(ctx, fetched, verifyOpts);
|
|
5580
|
+
remember(ctx.paths, state, verified);
|
|
5581
|
+
return verified;
|
|
5582
|
+
}
|
|
5583
|
+
} catch (err) {
|
|
5584
|
+
if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
|
|
5585
|
+
state.revoked = true;
|
|
5586
|
+
writeState(ctx.paths, state);
|
|
5587
|
+
}
|
|
5588
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
5589
|
+
throw new FleetPolicyError(
|
|
5590
|
+
cacheError ? `${cacheError.message}; refresh failed (${detail})` : `no fleet policy (${detail})`
|
|
5591
|
+
);
|
|
5592
|
+
}
|
|
5593
|
+
throw cacheError ?? new FleetPolicyError("no fleet policy available");
|
|
5594
|
+
}
|
|
5595
|
+
async function recordDecisionAndHeartbeat(ctx, applied, decision, options) {
|
|
5596
|
+
const now = options.now ?? Date.now;
|
|
5597
|
+
const state = readState(ctx.paths);
|
|
5598
|
+
if (decision) state.counts[decision] += 1;
|
|
5599
|
+
const intervalSec = applied.settings.heartbeatIntervalSec ?? ctx.enrolment.heartbeatIntervalSec ?? DEFAULT_HEARTBEAT_INTERVAL_SEC;
|
|
5600
|
+
const last = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : 0;
|
|
5601
|
+
if (now() - last < intervalSec * 1e3) {
|
|
5602
|
+
writeState(ctx.paths, state);
|
|
5603
|
+
return "throttled";
|
|
5604
|
+
}
|
|
5605
|
+
const deadline = now() + (options.budgetMs ?? FLEET_SYNC_BUDGET_MS);
|
|
5606
|
+
const remaining = () => Math.max(1, deadline - now());
|
|
5607
|
+
state.lastHeartbeatAt = new Date(now()).toISOString();
|
|
5608
|
+
let outcome = "sent";
|
|
5609
|
+
try {
|
|
5610
|
+
const hb = await sendHeartbeat(
|
|
5611
|
+
ctx.enrolment,
|
|
5612
|
+
{
|
|
5613
|
+
appliedSha256: applied.claims.sha256,
|
|
5614
|
+
guardVersion: options.guardVersion,
|
|
5615
|
+
adapters: [{ kind: options.adapterKind, managed: true }],
|
|
5616
|
+
posture: applied.settings.posture,
|
|
5617
|
+
decisionCounts: { ...state.counts }
|
|
5618
|
+
},
|
|
5619
|
+
remaining()
|
|
5620
|
+
);
|
|
5621
|
+
state.counts = { allow: 0, deny: 0, ask: 0 };
|
|
5622
|
+
state.revoked = false;
|
|
5623
|
+
delete state.lastError;
|
|
5624
|
+
const policyChanged = !!hb.activeSha256 && hb.activeSha256 !== applied.claims.sha256;
|
|
5625
|
+
const keyChanged = !!hb.activeKid && !!applied.kid && hb.activeKid !== applied.kid;
|
|
5626
|
+
if (policyChanged || keyChanged) {
|
|
5627
|
+
const fetched = await fetchFleetPolicy(
|
|
5628
|
+
ctx.enrolment,
|
|
5629
|
+
policyEtag(applied.claims.sha256, applied.kid),
|
|
5630
|
+
remaining()
|
|
5631
|
+
);
|
|
5632
|
+
if (fetched.status === "ok") {
|
|
5633
|
+
const verified = await acceptFetched(ctx, fetched, {
|
|
5634
|
+
expectedSubs: expectedSubs(ctx.enrolment),
|
|
5635
|
+
minVer: Math.max(state.maxVer ?? 0, applied.claims.ver)
|
|
5636
|
+
});
|
|
5637
|
+
state.appliedSha256 = verified.claims.sha256;
|
|
5638
|
+
state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
|
|
5639
|
+
outcome = "refreshed";
|
|
5640
|
+
}
|
|
5641
|
+
}
|
|
5642
|
+
} catch (err) {
|
|
5643
|
+
if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
|
|
5644
|
+
state.revoked = true;
|
|
5645
|
+
outcome = "revoked";
|
|
5646
|
+
} else {
|
|
5647
|
+
state.lastError = err instanceof Error ? err.message : String(err);
|
|
5648
|
+
outcome = "failed";
|
|
5649
|
+
}
|
|
5650
|
+
}
|
|
5651
|
+
writeState(ctx.paths, state);
|
|
5652
|
+
return outcome;
|
|
5653
|
+
}
|
|
5654
|
+
|
|
5655
|
+
// src/fleet/hook-runner.ts
|
|
5656
|
+
var PREFIX = "AstraSync Local Guard (organisation fleet policy)";
|
|
5657
|
+
async function runFleetHook(args) {
|
|
5658
|
+
if (args.resolution.kind === "fleet-missing") {
|
|
5659
|
+
return { output: args.denyOutput(`${PREFIX}: ${args.resolution.reason}`), exitCode: 0 };
|
|
5660
|
+
}
|
|
5661
|
+
const ctx = { enrolment: args.resolution.enrolment, paths: args.resolution.paths };
|
|
5662
|
+
let verified;
|
|
5663
|
+
try {
|
|
5664
|
+
verified = await loadFleetPolicy(ctx);
|
|
5665
|
+
} catch (err) {
|
|
5666
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
5667
|
+
return {
|
|
5668
|
+
output: args.denyOutput(`${PREFIX}: no valid signed policy \u2014 ${detail}`),
|
|
5669
|
+
exitCode: 0
|
|
5670
|
+
};
|
|
5671
|
+
}
|
|
5672
|
+
const { settings } = verified;
|
|
5673
|
+
const decide = async (output) => {
|
|
5674
|
+
try {
|
|
5675
|
+
const outcome = await recordDecisionAndHeartbeat(ctx, verified, args.classify(output), {
|
|
5676
|
+
guardVersion: SDK_VERSION,
|
|
5677
|
+
adapterKind: args.adapterKind,
|
|
5678
|
+
now: args.now
|
|
5679
|
+
});
|
|
5680
|
+
args.onHeartbeat?.(outcome);
|
|
5681
|
+
} catch {
|
|
5682
|
+
}
|
|
5683
|
+
return { output, exitCode: 0 };
|
|
5684
|
+
};
|
|
5685
|
+
let payload;
|
|
5686
|
+
try {
|
|
5687
|
+
payload = JSON.parse(args.payloadJson);
|
|
5688
|
+
} catch {
|
|
5689
|
+
if (settings.failOpen) return decide(null);
|
|
5690
|
+
return decide(args.denyOutput(`${PREFIX}: could not parse hook payload`));
|
|
5691
|
+
}
|
|
5692
|
+
try {
|
|
5693
|
+
const gatewayConfig = {
|
|
5694
|
+
mode: "local",
|
|
5695
|
+
policy: verified.policy,
|
|
5696
|
+
posture: settings.posture,
|
|
5697
|
+
traceEnabled: true,
|
|
5698
|
+
tracePath: (0, import_path5.join)(args.resolution.paths.userDir, "traces"),
|
|
5699
|
+
debug: false
|
|
5700
|
+
};
|
|
5701
|
+
const gateway = args.gatewayFactory ? args.gatewayFactory(gatewayConfig) : new AstraSyncGateway(gatewayConfig);
|
|
5702
|
+
await gateway.initialize();
|
|
5703
|
+
const adapter = args.createAdapter({
|
|
5704
|
+
...settings.skipTools && { skipTools: settings.skipTools },
|
|
5705
|
+
...typeof settings.governMcp === "boolean" && { governMcp: settings.governMcp }
|
|
5706
|
+
});
|
|
5707
|
+
await adapter.initialize({ gateway, adapterOptions: {} });
|
|
5708
|
+
const output = await adapter.evaluatePayload(payload);
|
|
5709
|
+
await adapter.shutdown();
|
|
5710
|
+
await gateway.shutdown();
|
|
5711
|
+
return decide(output);
|
|
5712
|
+
} catch (err) {
|
|
5713
|
+
if (settings.failOpen) return decide(null);
|
|
5714
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
5715
|
+
return decide(args.denyOutput(`${PREFIX}: policy evaluation failed (${detail})`));
|
|
5716
|
+
}
|
|
5717
|
+
}
|
|
4942
5718
|
|
|
4943
5719
|
// src/adapter-interface/interface.ts
|
|
4944
5720
|
var ADAPTER_INTERFACE_VERSION = 1;
|
|
@@ -5229,6 +6005,19 @@ function denyOutput(reason) {
|
|
|
5229
6005
|
}
|
|
5230
6006
|
async function processCodexHookPayload(payloadJson, options = {}) {
|
|
5231
6007
|
const env = options.env ?? process.env;
|
|
6008
|
+
const fleet = resolveFleet(env, options.home ?? (0, import_os3.homedir)(), options.fleetPaths);
|
|
6009
|
+
if (fleet) {
|
|
6010
|
+
return runFleetHook({
|
|
6011
|
+
resolution: fleet,
|
|
6012
|
+
payloadJson,
|
|
6013
|
+
adapterKind: "codex",
|
|
6014
|
+
createAdapter: (adapterOptions) => new CodexAdapter(adapterOptions),
|
|
6015
|
+
denyOutput,
|
|
6016
|
+
classify: (output) => output?.hookSpecificOutput?.permissionDecision === "deny" ? "deny" : output?.hookSpecificOutput?.permissionDecision === "ask" ? "ask" : "allow",
|
|
6017
|
+
gatewayFactory: options.gatewayFactory,
|
|
6018
|
+
now: options.now
|
|
6019
|
+
});
|
|
6020
|
+
}
|
|
5232
6021
|
if (env.ASTRASYNC_GUARD_DISABLE === "1") {
|
|
5233
6022
|
return { output: null, exitCode: 0 };
|
|
5234
6023
|
}
|
|
@@ -5261,7 +6050,7 @@ async function processCodexHookPayload(payloadJson, options = {}) {
|
|
|
5261
6050
|
policyFile: resolved.policyFile,
|
|
5262
6051
|
posture: resolved.settings.posture ?? "active",
|
|
5263
6052
|
traceEnabled: true,
|
|
5264
|
-
tracePath: (0,
|
|
6053
|
+
tracePath: (0, import_path6.join)(resolved.guardDir, "traces"),
|
|
5265
6054
|
debug: false,
|
|
5266
6055
|
...mode === "hybrid" && {
|
|
5267
6056
|
apiBaseUrl: resolved.settings.apiBaseUrl,
|