@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
|
@@ -25,7 +25,8 @@ __export(hook_exports, {
|
|
|
25
25
|
resolveGuardConfig: () => resolveGuardConfig
|
|
26
26
|
});
|
|
27
27
|
module.exports = __toCommonJS(hook_exports);
|
|
28
|
-
var
|
|
28
|
+
var import_os3 = require("os");
|
|
29
|
+
var import_path6 = require("path");
|
|
29
30
|
|
|
30
31
|
// src/gateway/types.ts
|
|
31
32
|
var HIGH_RISK_COMMANDS = [
|
|
@@ -3751,7 +3752,7 @@ function getTrustLevel(score) {
|
|
|
3751
3752
|
}
|
|
3752
3753
|
|
|
3753
3754
|
// src/version.ts
|
|
3754
|
-
var SDK_VERSION = "5.
|
|
3755
|
+
var SDK_VERSION = "5.12.0";
|
|
3755
3756
|
|
|
3756
3757
|
// src/http.ts
|
|
3757
3758
|
var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
|
|
@@ -3778,6 +3779,14 @@ function getCachedWellKnownUrls(apiBaseUrl) {
|
|
|
3778
3779
|
return cache.get(apiBaseUrl)?.data;
|
|
3779
3780
|
}
|
|
3780
3781
|
|
|
3782
|
+
// src/failure-posture.ts
|
|
3783
|
+
var REJECTED_IDENTITY_DIMENSIONS = /* @__PURE__ */ new Set([
|
|
3784
|
+
"identity.invalid_agent_id",
|
|
3785
|
+
"identity.unknown_agent",
|
|
3786
|
+
"agent.lookup"
|
|
3787
|
+
]);
|
|
3788
|
+
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.";
|
|
3789
|
+
|
|
3781
3790
|
// src/verify.ts
|
|
3782
3791
|
var DEFAULT_CONFIG = {
|
|
3783
3792
|
apiBaseUrl: "https://astrasync.ai/api",
|
|
@@ -3989,11 +3998,44 @@ function createGuidanceResponse(_config, reason, options = {}) {
|
|
|
3989
3998
|
// coercing the absent recommendation to a policy 'deny'. Misconfig is
|
|
3990
3999
|
// deterministic and intentionally NOT marked retryable.
|
|
3991
4000
|
...isApiError && { retryable: true },
|
|
4001
|
+
...options.httpStatus !== void 0 && { httpStatus: options.httpStatus },
|
|
4002
|
+
...options.retryAfterMs !== void 0 && { retryAfterMs: options.retryAfterMs },
|
|
3992
4003
|
correlationId: options.correlationId,
|
|
3993
4004
|
attemptId: options.attemptId,
|
|
3994
4005
|
verifiedAt: /* @__PURE__ */ new Date()
|
|
3995
4006
|
};
|
|
3996
4007
|
}
|
|
4008
|
+
async function readJsonSafe(response) {
|
|
4009
|
+
try {
|
|
4010
|
+
const parsed = await response.json();
|
|
4011
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
4012
|
+
} catch {
|
|
4013
|
+
return {};
|
|
4014
|
+
}
|
|
4015
|
+
}
|
|
4016
|
+
function rejectedIdentityGuidance(failures) {
|
|
4017
|
+
const f = failures?.find((x) => REJECTED_IDENTITY_DIMENSIONS.has(x.dimension));
|
|
4018
|
+
if (!f) return void 0;
|
|
4019
|
+
if (f.dimension === "agent.lookup") {
|
|
4020
|
+
return `The presented agent identifier is not registered with AstraSync. ${UNKNOWN_AGENT_GUIDANCE}`;
|
|
4021
|
+
}
|
|
4022
|
+
return f.guidance ? `${f.message} ${f.guidance}` : f.message;
|
|
4023
|
+
}
|
|
4024
|
+
var MAX_RETRY_AFTER_MS = 15 * 60 * 1e3;
|
|
4025
|
+
function parseRetryAfterMs(response) {
|
|
4026
|
+
const raw = response.headers?.get?.("retry-after");
|
|
4027
|
+
if (!raw) return void 0;
|
|
4028
|
+
const trimmed = raw.trim();
|
|
4029
|
+
let ms;
|
|
4030
|
+
if (/^\d+(\.\d+)?$/.test(trimmed)) {
|
|
4031
|
+
ms = Number(trimmed) * 1e3;
|
|
4032
|
+
} else {
|
|
4033
|
+
const at = Date.parse(trimmed);
|
|
4034
|
+
if (Number.isNaN(at)) return void 0;
|
|
4035
|
+
ms = at - Date.now();
|
|
4036
|
+
}
|
|
4037
|
+
return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, Math.round(ms)));
|
|
4038
|
+
}
|
|
3997
4039
|
async function callVerifyAccessAPI(config, request) {
|
|
3998
4040
|
const { credentials, ...requestData } = request;
|
|
3999
4041
|
const body = {
|
|
@@ -4050,7 +4092,8 @@ async function callVerifyAccessAPI(config, request) {
|
|
|
4050
4092
|
body: JSON.stringify(body),
|
|
4051
4093
|
signal: AbortSignal.timeout(config.verifyTimeoutMs ?? 1e4)
|
|
4052
4094
|
});
|
|
4053
|
-
const data = await response
|
|
4095
|
+
const data = await readJsonSafe(response);
|
|
4096
|
+
const retryAfterMs = parseRetryAfterMs(response);
|
|
4054
4097
|
if (response.status === 410) {
|
|
4055
4098
|
return {
|
|
4056
4099
|
success: true,
|
|
@@ -4088,6 +4131,23 @@ async function callVerifyAccessAPI(config, request) {
|
|
|
4088
4131
|
}
|
|
4089
4132
|
};
|
|
4090
4133
|
}
|
|
4134
|
+
if (response.status === 404 && credentials.astraId && (data?.error === "AGENT_NOT_FOUND" || typeof data?.message === "string" && /agent/i.test(data.message))) {
|
|
4135
|
+
return {
|
|
4136
|
+
success: true,
|
|
4137
|
+
attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
|
|
4138
|
+
access: {
|
|
4139
|
+
allowed: false,
|
|
4140
|
+
reason: "unknown_agent",
|
|
4141
|
+
failures: [
|
|
4142
|
+
{
|
|
4143
|
+
dimension: "identity.unknown_agent",
|
|
4144
|
+
message: "The presented agent identifier is not registered with AstraSync.",
|
|
4145
|
+
guidance: UNKNOWN_AGENT_GUIDANCE
|
|
4146
|
+
}
|
|
4147
|
+
]
|
|
4148
|
+
}
|
|
4149
|
+
};
|
|
4150
|
+
}
|
|
4091
4151
|
if (!response.ok) {
|
|
4092
4152
|
if (response.status === 401) {
|
|
4093
4153
|
return {
|
|
@@ -4102,9 +4162,11 @@ async function callVerifyAccessAPI(config, request) {
|
|
|
4102
4162
|
}
|
|
4103
4163
|
return {
|
|
4104
4164
|
success: false,
|
|
4105
|
-
error: data.message || data.error || `API returned ${response.status}`,
|
|
4165
|
+
error: typeof data?.message === "string" && data.message || typeof data?.error === "string" && data.error || `API returned ${response.status}`,
|
|
4106
4166
|
correlationId: typeof data?.correlationId === "string" ? data.correlationId : void 0,
|
|
4107
|
-
attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0
|
|
4167
|
+
attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
|
|
4168
|
+
httpStatus: response.status,
|
|
4169
|
+
...retryAfterMs !== void 0 && { retryAfterMs }
|
|
4108
4170
|
};
|
|
4109
4171
|
}
|
|
4110
4172
|
return data;
|
|
@@ -4176,12 +4238,14 @@ async function verify(config, request, options) {
|
|
|
4176
4238
|
correlationId: apiResponse.correlationId,
|
|
4177
4239
|
attemptId: apiResponse.attemptId,
|
|
4178
4240
|
remediation: apiResponse.remediation,
|
|
4241
|
+
httpStatus: apiResponse.httpStatus,
|
|
4242
|
+
retryAfterMs: apiResponse.retryAfterMs,
|
|
4179
4243
|
urls
|
|
4180
4244
|
});
|
|
4181
4245
|
}
|
|
4182
4246
|
if (!apiResponse.access?.allowed) {
|
|
4183
4247
|
const aggregatedFailures = apiResponse.access?.failures;
|
|
4184
|
-
const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true;
|
|
4248
|
+
const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true && !aggregatedFailures?.some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));
|
|
4185
4249
|
const result2 = {
|
|
4186
4250
|
identityVerified: idVerifiedFromBackend,
|
|
4187
4251
|
policyAllowed: false,
|
|
@@ -4193,7 +4257,10 @@ async function verify(config, request, options) {
|
|
|
4193
4257
|
requiresStepUp: apiResponse.access?.requiresStepUp,
|
|
4194
4258
|
requiresApproval: apiResponse.access?.requiresApproval,
|
|
4195
4259
|
guidance: {
|
|
4196
|
-
|
|
4260
|
+
// 5.12.0: a presented-but-rejected id (malformed / unknown) carries
|
|
4261
|
+
// actionable registration guidance on its failure — surface it
|
|
4262
|
+
// instead of the bare machine reason ('unknown_agent').
|
|
4263
|
+
message: rejectedIdentityGuidance(aggregatedFailures) ?? (apiResponse.access?.reason || "Access denied by PDLSS policy"),
|
|
4197
4264
|
registrationUrl: urls?.registrationUrl ?? "",
|
|
4198
4265
|
documentationUrl: urls?.documentationUrl ?? "",
|
|
4199
4266
|
// 5.1.0: anonymous callers land on this branch — steer MCP-hosted
|
|
@@ -4293,7 +4360,7 @@ async function verify(config, request, options) {
|
|
|
4293
4360
|
registrationUrl: urls?.registrationUrl ?? "",
|
|
4294
4361
|
documentationUrl: urls?.documentationUrl ?? ""
|
|
4295
4362
|
};
|
|
4296
|
-
} else if (result.recommendation === "step_up_required") {
|
|
4363
|
+
} else if (result.recommendation === "step_up_required" && result.identityVerified) {
|
|
4297
4364
|
result.requiresStepUp = true;
|
|
4298
4365
|
result.denialReasons = serverDenialReasons ?? result.recommendationReasons ?? ["Step-up verification required"];
|
|
4299
4366
|
}
|
|
@@ -4322,6 +4389,217 @@ var DEFAULT_EDGE_CONFIG = Object.freeze({
|
|
|
4322
4389
|
var DEFAULT_TTL_MS = 60 * 1e3;
|
|
4323
4390
|
var DEFAULT_MAX_STALE_MS = 24 * 60 * 60 * 1e3;
|
|
4324
4391
|
|
|
4392
|
+
// src/edge-core/events.ts
|
|
4393
|
+
async function withBudget(promise, ms) {
|
|
4394
|
+
let timer;
|
|
4395
|
+
try {
|
|
4396
|
+
return await Promise.race([
|
|
4397
|
+
promise,
|
|
4398
|
+
new Promise((resolve) => {
|
|
4399
|
+
timer = setTimeout(() => resolve(void 0), ms);
|
|
4400
|
+
})
|
|
4401
|
+
]);
|
|
4402
|
+
} catch {
|
|
4403
|
+
return void 0;
|
|
4404
|
+
} finally {
|
|
4405
|
+
if (timer) clearTimeout(timer);
|
|
4406
|
+
}
|
|
4407
|
+
}
|
|
4408
|
+
var destKeyOf = (d) => `${d.apiBaseUrl}\0${d.apiKey ?? ""}\0${d.counterparty}\0${d.adapter ?? ""}`;
|
|
4409
|
+
var BeaconBuffer = class {
|
|
4410
|
+
constructor(options = {}) {
|
|
4411
|
+
this.queue = [];
|
|
4412
|
+
this.droppedSinceLast = 0;
|
|
4413
|
+
this.droppedTotal = 0;
|
|
4414
|
+
this.deliveredTotal = 0;
|
|
4415
|
+
this.backoffUntil = 0;
|
|
4416
|
+
this.collapse = /* @__PURE__ */ new Map();
|
|
4417
|
+
/** Keys the backend answered 401 for — later batches go unauthenticated. */
|
|
4418
|
+
this.rejectedKeys = /* @__PURE__ */ new Set();
|
|
4419
|
+
this.opts = {
|
|
4420
|
+
maxItems: options.maxItems ?? 1e3,
|
|
4421
|
+
maxBatch: options.maxBatch ?? 100,
|
|
4422
|
+
maxAttempts: options.maxAttempts ?? 3,
|
|
4423
|
+
collapseWindowMs: options.collapseWindowMs ?? 6e4,
|
|
4424
|
+
collapseMaxKeys: options.collapseMaxKeys ?? 1e3,
|
|
4425
|
+
requestTimeoutMs: options.requestTimeoutMs ?? 1e4,
|
|
4426
|
+
retryBackoffMs: options.retryBackoffMs ?? 1e3,
|
|
4427
|
+
now: options.now ?? Date.now
|
|
4428
|
+
};
|
|
4429
|
+
}
|
|
4430
|
+
/**
|
|
4431
|
+
* Queue one beacon. With a `collapseKey`, a repeat inside the window is
|
|
4432
|
+
* merged into a held aggregate (sent when the window closes) instead of
|
|
4433
|
+
* becoming its own item.
|
|
4434
|
+
*/
|
|
4435
|
+
enqueue(dest, item, collapseKey) {
|
|
4436
|
+
const now = this.opts.now();
|
|
4437
|
+
if (collapseKey) {
|
|
4438
|
+
const entry = this.collapse.get(collapseKey);
|
|
4439
|
+
if (entry && now - entry.firstSeenAt < this.opts.collapseWindowMs) {
|
|
4440
|
+
for (const target of [entry.first, entry.held]) {
|
|
4441
|
+
if (target && !target.inFlight && this.queue.includes(target)) {
|
|
4442
|
+
target.item.repeatCount = (target.item.repeatCount ?? 1) + 1;
|
|
4443
|
+
return;
|
|
4444
|
+
}
|
|
4445
|
+
}
|
|
4446
|
+
const held = this.push(
|
|
4447
|
+
dest,
|
|
4448
|
+
{ ...item, repeatCount: 1 },
|
|
4449
|
+
entry.firstSeenAt + this.opts.collapseWindowMs
|
|
4450
|
+
);
|
|
4451
|
+
entry.held = held;
|
|
4452
|
+
return;
|
|
4453
|
+
}
|
|
4454
|
+
this.collapse.delete(collapseKey);
|
|
4455
|
+
if (this.collapse.size >= this.opts.collapseMaxKeys) {
|
|
4456
|
+
const oldest = this.collapse.keys().next().value;
|
|
4457
|
+
if (oldest !== void 0) this.collapse.delete(oldest);
|
|
4458
|
+
}
|
|
4459
|
+
const fresh = { firstSeenAt: now };
|
|
4460
|
+
this.collapse.set(collapseKey, fresh);
|
|
4461
|
+
fresh.first = this.push(dest, item, now);
|
|
4462
|
+
return;
|
|
4463
|
+
}
|
|
4464
|
+
this.push(dest, item, now);
|
|
4465
|
+
}
|
|
4466
|
+
/**
|
|
4467
|
+
* Deliver every eligible queued item. Concurrent callers share ONE
|
|
4468
|
+
* in-flight drain (it survives the caller's budget and a Lambda freeze),
|
|
4469
|
+
* so nothing in flight is ever sent twice; items queued while it runs are
|
|
4470
|
+
* picked up by the same drain.
|
|
4471
|
+
*/
|
|
4472
|
+
flush() {
|
|
4473
|
+
if (!this.inFlight) {
|
|
4474
|
+
this.inFlight = this.drain().finally(() => {
|
|
4475
|
+
this.inFlight = void 0;
|
|
4476
|
+
});
|
|
4477
|
+
}
|
|
4478
|
+
return this.inFlight;
|
|
4479
|
+
}
|
|
4480
|
+
/** Counters for tests and diagnostics. */
|
|
4481
|
+
stats() {
|
|
4482
|
+
return {
|
|
4483
|
+
queueDepth: this.queue.length,
|
|
4484
|
+
droppedSinceLast: this.droppedSinceLast,
|
|
4485
|
+
droppedTotal: this.droppedTotal,
|
|
4486
|
+
deliveredTotal: this.deliveredTotal,
|
|
4487
|
+
flushing: this.inFlight !== void 0
|
|
4488
|
+
};
|
|
4489
|
+
}
|
|
4490
|
+
push(dest, item, eligibleAt) {
|
|
4491
|
+
while (this.queue.length >= this.opts.maxItems) this.dropOldest();
|
|
4492
|
+
const entry = {
|
|
4493
|
+
dest,
|
|
4494
|
+
destKey: destKeyOf(dest),
|
|
4495
|
+
item,
|
|
4496
|
+
attempts: 0,
|
|
4497
|
+
eligibleAt,
|
|
4498
|
+
inFlight: false
|
|
4499
|
+
};
|
|
4500
|
+
this.queue.push(entry);
|
|
4501
|
+
return entry;
|
|
4502
|
+
}
|
|
4503
|
+
dropOldest() {
|
|
4504
|
+
if (this.queue.shift()) this.countDropped(1);
|
|
4505
|
+
}
|
|
4506
|
+
countDropped(n) {
|
|
4507
|
+
this.droppedSinceLast += n;
|
|
4508
|
+
this.droppedTotal += n;
|
|
4509
|
+
}
|
|
4510
|
+
async drain() {
|
|
4511
|
+
for (; ; ) {
|
|
4512
|
+
const now = this.opts.now();
|
|
4513
|
+
if (now < this.backoffUntil) return;
|
|
4514
|
+
const batch = this.takeBatch(now);
|
|
4515
|
+
if (batch.length === 0) return;
|
|
4516
|
+
const ok = await this.send(batch);
|
|
4517
|
+
if (!ok) return;
|
|
4518
|
+
}
|
|
4519
|
+
}
|
|
4520
|
+
/** Oldest eligible item + up to maxBatch-1 more for the same destination. */
|
|
4521
|
+
takeBatch(now) {
|
|
4522
|
+
const first = this.queue.find((q) => q.eligibleAt <= now);
|
|
4523
|
+
if (!first) return [];
|
|
4524
|
+
const batch = [];
|
|
4525
|
+
const rest = [];
|
|
4526
|
+
for (const q of this.queue) {
|
|
4527
|
+
if (batch.length < this.opts.maxBatch && q.destKey === first.destKey && q.eligibleAt <= now) {
|
|
4528
|
+
q.inFlight = true;
|
|
4529
|
+
batch.push(q);
|
|
4530
|
+
} else {
|
|
4531
|
+
rest.push(q);
|
|
4532
|
+
}
|
|
4533
|
+
}
|
|
4534
|
+
this.queue = rest;
|
|
4535
|
+
return batch;
|
|
4536
|
+
}
|
|
4537
|
+
/** POST one batch. Returns false when the drain should pause (backoff). */
|
|
4538
|
+
async send(batch) {
|
|
4539
|
+
const dest = batch[0].dest;
|
|
4540
|
+
const useKey = dest.apiKey && !this.rejectedKeys.has(dest.apiKey) ? dest.apiKey : void 0;
|
|
4541
|
+
const reportedDropped = this.droppedSinceLast;
|
|
4542
|
+
const meta = {
|
|
4543
|
+
droppedSinceLast: reportedDropped,
|
|
4544
|
+
queueDepth: this.queue.length,
|
|
4545
|
+
adapter: dest.adapter ?? "edge-core",
|
|
4546
|
+
version: SDK_VERSION
|
|
4547
|
+
};
|
|
4548
|
+
const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
|
|
4549
|
+
const response = await withBudget(
|
|
4550
|
+
sdkFetch(`${dest.apiBaseUrl}/verification-activity/edge-events`, {
|
|
4551
|
+
method: "POST",
|
|
4552
|
+
headers: {
|
|
4553
|
+
"Content-Type": "application/json",
|
|
4554
|
+
...useKey && { Authorization: `Bearer ${useKey}` }
|
|
4555
|
+
},
|
|
4556
|
+
body: JSON.stringify({ events: batch.map((q) => q.item), meta }),
|
|
4557
|
+
...controller && { signal: controller.signal }
|
|
4558
|
+
}),
|
|
4559
|
+
this.opts.requestTimeoutMs
|
|
4560
|
+
);
|
|
4561
|
+
if (!response) controller?.abort();
|
|
4562
|
+
const status = response?.status;
|
|
4563
|
+
for (const q of batch) q.inFlight = false;
|
|
4564
|
+
if (status !== void 0 && status >= 200 && status < 300) {
|
|
4565
|
+
this.droppedSinceLast = Math.max(0, this.droppedSinceLast - reportedDropped);
|
|
4566
|
+
this.deliveredTotal += batch.length;
|
|
4567
|
+
return true;
|
|
4568
|
+
}
|
|
4569
|
+
if (status === 401 && useKey) {
|
|
4570
|
+
this.rejectedKeys.add(useKey);
|
|
4571
|
+
this.requeue(batch, false);
|
|
4572
|
+
return true;
|
|
4573
|
+
}
|
|
4574
|
+
if (status === 429) {
|
|
4575
|
+
const retryAfter = Number(response?.headers.get("retry-after"));
|
|
4576
|
+
const waitMs = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 120) * 1e3 : 3e4;
|
|
4577
|
+
this.backoffUntil = this.opts.now() + waitMs;
|
|
4578
|
+
this.requeue(batch, false);
|
|
4579
|
+
return false;
|
|
4580
|
+
}
|
|
4581
|
+
if (status !== void 0 && status >= 400 && status < 500) {
|
|
4582
|
+
this.countDropped(batch.length);
|
|
4583
|
+
return true;
|
|
4584
|
+
}
|
|
4585
|
+
this.backoffUntil = this.opts.now() + this.opts.retryBackoffMs;
|
|
4586
|
+
this.requeue(batch, true);
|
|
4587
|
+
return false;
|
|
4588
|
+
}
|
|
4589
|
+
/** Put a failed batch back at the head of the queue (order preserved). */
|
|
4590
|
+
requeue(batch, countAttempt) {
|
|
4591
|
+
const keep = [];
|
|
4592
|
+
for (const q of batch) {
|
|
4593
|
+
if (countAttempt) q.attempts += 1;
|
|
4594
|
+
if (q.attempts >= this.opts.maxAttempts) this.countDropped(1);
|
|
4595
|
+
else keep.push(q);
|
|
4596
|
+
}
|
|
4597
|
+
this.queue = [...keep, ...this.queue];
|
|
4598
|
+
while (this.queue.length > this.opts.maxItems) this.dropOldest();
|
|
4599
|
+
}
|
|
4600
|
+
};
|
|
4601
|
+
var beaconBuffer = new BeaconBuffer();
|
|
4602
|
+
|
|
4325
4603
|
// src/adapters/express.ts
|
|
4326
4604
|
var DEFAULT_ROUTES_REFRESH_MS = 5 * 60 * 1e3;
|
|
4327
4605
|
|
|
@@ -5169,22 +5447,118 @@ var ClaudeCodeAdapter = class {
|
|
|
5169
5447
|
};
|
|
5170
5448
|
|
|
5171
5449
|
// src/claude-code/guard-config.ts
|
|
5450
|
+
var import_fs5 = require("fs");
|
|
5451
|
+
var import_os2 = require("os");
|
|
5452
|
+
var import_path4 = require("path");
|
|
5453
|
+
|
|
5454
|
+
// src/fleet/enrolment-store.ts
|
|
5172
5455
|
var import_fs4 = require("fs");
|
|
5173
5456
|
var import_os = require("os");
|
|
5174
5457
|
var import_path3 = require("path");
|
|
5175
|
-
function
|
|
5458
|
+
function machineScopeDir(platform = process.platform, env = process.env) {
|
|
5459
|
+
if (platform === "darwin") return "/Library/Application Support/AstraSync";
|
|
5460
|
+
if (platform === "win32") return (0, import_path3.join)(env.ProgramData || "C:\\ProgramData", "AstraSync");
|
|
5461
|
+
return "/etc/astrasync";
|
|
5462
|
+
}
|
|
5463
|
+
function fleetPaths(options = {}) {
|
|
5464
|
+
const home = options.home ?? (0, import_os.homedir)();
|
|
5465
|
+
const machineDir = options.machineDir ?? options.env?.ASTRASYNC_FLEET_MACHINE_DIR ?? machineScopeDir(options.platform, options.env);
|
|
5466
|
+
const userDir = (0, import_path3.join)(home, ".astrasync", "fleet");
|
|
5467
|
+
return {
|
|
5468
|
+
machineDevice: (0, import_path3.join)(machineDir, "fleet.json"),
|
|
5469
|
+
machinePolicy: (0, import_path3.join)(machineDir, "policy.jws"),
|
|
5470
|
+
userDir,
|
|
5471
|
+
userDevice: (0, import_path3.join)(userDir, "device.json"),
|
|
5472
|
+
userPolicy: (0, import_path3.join)(userDir, "policy.jws"),
|
|
5473
|
+
userKeyChain: (0, import_path3.join)(userDir, "keychain.json"),
|
|
5474
|
+
state: (0, import_path3.join)(userDir, "state.json")
|
|
5475
|
+
};
|
|
5476
|
+
}
|
|
5477
|
+
function isEnrolment(value) {
|
|
5478
|
+
const v = value;
|
|
5479
|
+
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);
|
|
5480
|
+
}
|
|
5481
|
+
function loadEnrolment(paths) {
|
|
5482
|
+
const candidates = [
|
|
5483
|
+
[paths.machineDevice, "machine"],
|
|
5484
|
+
[paths.userDevice, "user"]
|
|
5485
|
+
];
|
|
5486
|
+
for (const [path, scope] of candidates) {
|
|
5487
|
+
if (!(0, import_fs4.existsSync)(path)) continue;
|
|
5488
|
+
try {
|
|
5489
|
+
const parsed = JSON.parse((0, import_fs4.readFileSync)(path, "utf-8"));
|
|
5490
|
+
if (isEnrolment(parsed)) return { enrolment: parsed, scope };
|
|
5491
|
+
} catch {
|
|
5492
|
+
}
|
|
5493
|
+
return { corrupt: true, path };
|
|
5494
|
+
}
|
|
5495
|
+
return null;
|
|
5496
|
+
}
|
|
5497
|
+
function writeFileMode(path, content, mode) {
|
|
5498
|
+
(0, import_fs4.mkdirSync)((0, import_path3.dirname)(path), { recursive: true, mode: 448 });
|
|
5499
|
+
(0, import_fs4.writeFileSync)(path, content, { encoding: "utf-8", mode });
|
|
5500
|
+
try {
|
|
5501
|
+
(0, import_fs4.chmodSync)(path, mode);
|
|
5502
|
+
} catch {
|
|
5503
|
+
}
|
|
5504
|
+
}
|
|
5505
|
+
function readCachedPolicies(paths) {
|
|
5506
|
+
const out = [];
|
|
5507
|
+
for (const p of [paths.userPolicy, paths.machinePolicy]) {
|
|
5508
|
+
try {
|
|
5509
|
+
if ((0, import_fs4.existsSync)(p)) out.push((0, import_fs4.readFileSync)(p, "utf-8").trim());
|
|
5510
|
+
} catch {
|
|
5511
|
+
}
|
|
5512
|
+
}
|
|
5513
|
+
return out.filter(Boolean);
|
|
5514
|
+
}
|
|
5515
|
+
function writeCachedPolicy(paths, jws) {
|
|
5516
|
+
writeFileMode(paths.userPolicy, jws, 384);
|
|
5517
|
+
}
|
|
5518
|
+
function readKeyChain(paths) {
|
|
5519
|
+
try {
|
|
5520
|
+
const parsed = JSON.parse((0, import_fs4.readFileSync)(paths.userKeyChain, "utf-8"));
|
|
5521
|
+
return Array.isArray(parsed) ? parsed.filter((j) => typeof j === "string") : [];
|
|
5522
|
+
} catch {
|
|
5523
|
+
return [];
|
|
5524
|
+
}
|
|
5525
|
+
}
|
|
5526
|
+
function writeKeyChain(paths, chain) {
|
|
5527
|
+
writeFileMode(paths.userKeyChain, JSON.stringify(chain), 384);
|
|
5528
|
+
}
|
|
5529
|
+
function readState(paths) {
|
|
5530
|
+
try {
|
|
5531
|
+
const parsed = JSON.parse((0, import_fs4.readFileSync)(paths.state, "utf-8"));
|
|
5532
|
+
const c = parsed.counts;
|
|
5533
|
+
return {
|
|
5534
|
+
...parsed,
|
|
5535
|
+
counts: { allow: c?.allow ?? 0, deny: c?.deny ?? 0, ask: c?.ask ?? 0 }
|
|
5536
|
+
};
|
|
5537
|
+
} catch {
|
|
5538
|
+
return { counts: { allow: 0, deny: 0, ask: 0 } };
|
|
5539
|
+
}
|
|
5540
|
+
}
|
|
5541
|
+
function writeState(paths, state) {
|
|
5542
|
+
try {
|
|
5543
|
+
writeFileMode(paths.state, JSON.stringify(state, null, 2), 384);
|
|
5544
|
+
} catch {
|
|
5545
|
+
}
|
|
5546
|
+
}
|
|
5547
|
+
|
|
5548
|
+
// src/claude-code/guard-config.ts
|
|
5549
|
+
function resolveGuardConfig(env, payloadCwd, home = (0, import_os2.homedir)()) {
|
|
5176
5550
|
const candidateRoots = [env.CLAUDE_PROJECT_DIR, payloadCwd, home].filter(
|
|
5177
5551
|
(root) => typeof root === "string" && root.length > 0
|
|
5178
5552
|
);
|
|
5179
5553
|
for (const root of candidateRoots) {
|
|
5180
|
-
const guardDir = (0,
|
|
5181
|
-
const policyFile = (0,
|
|
5182
|
-
if (!(0,
|
|
5554
|
+
const guardDir = (0, import_path4.join)(root, ".astrasync");
|
|
5555
|
+
const policyFile = (0, import_path4.join)(guardDir, "policy.yaml");
|
|
5556
|
+
if (!(0, import_fs5.existsSync)(policyFile)) continue;
|
|
5183
5557
|
let settings = {};
|
|
5184
|
-
const settingsFile = (0,
|
|
5185
|
-
if ((0,
|
|
5558
|
+
const settingsFile = (0, import_path4.join)(guardDir, "guard.json");
|
|
5559
|
+
if ((0, import_fs5.existsSync)(settingsFile)) {
|
|
5186
5560
|
try {
|
|
5187
|
-
settings = JSON.parse((0,
|
|
5561
|
+
settings = JSON.parse((0, import_fs5.readFileSync)(settingsFile, "utf-8"));
|
|
5188
5562
|
} catch {
|
|
5189
5563
|
settings = {};
|
|
5190
5564
|
}
|
|
@@ -5193,6 +5567,408 @@ function resolveGuardConfig(env, payloadCwd, home = (0, import_os.homedir)()) {
|
|
|
5193
5567
|
}
|
|
5194
5568
|
return null;
|
|
5195
5569
|
}
|
|
5570
|
+
var FLEET_ENROL_INSTRUCTION = "This machine must be enrolled: run `astrasync guard enroll <token>` (token from your organisation admin)";
|
|
5571
|
+
function resolveFleet(env, home = (0, import_os2.homedir)(), paths = fleetPaths({ home, env })) {
|
|
5572
|
+
const loaded = loadEnrolment(paths);
|
|
5573
|
+
if (loaded && "corrupt" in loaded) {
|
|
5574
|
+
return {
|
|
5575
|
+
kind: "fleet-missing",
|
|
5576
|
+
reason: `fleet enrolment at ${loaded.path} is unreadable \u2014 ${FLEET_ENROL_INSTRUCTION}`,
|
|
5577
|
+
paths
|
|
5578
|
+
};
|
|
5579
|
+
}
|
|
5580
|
+
if (loaded) return { kind: "fleet", enrolment: loaded.enrolment, scope: loaded.scope, paths };
|
|
5581
|
+
if (env.ASTRASYNC_FLEET_REQUIRED === "1") {
|
|
5582
|
+
return { kind: "fleet-missing", reason: FLEET_ENROL_INSTRUCTION, paths };
|
|
5583
|
+
}
|
|
5584
|
+
return null;
|
|
5585
|
+
}
|
|
5586
|
+
|
|
5587
|
+
// src/fleet/hook-runner.ts
|
|
5588
|
+
var import_path5 = require("path");
|
|
5589
|
+
|
|
5590
|
+
// src/fleet/client.ts
|
|
5591
|
+
var FleetApiError = class extends Error {
|
|
5592
|
+
constructor(message, status, code) {
|
|
5593
|
+
super(message);
|
|
5594
|
+
this.status = status;
|
|
5595
|
+
this.code = code;
|
|
5596
|
+
this.name = "FleetApiError";
|
|
5597
|
+
}
|
|
5598
|
+
};
|
|
5599
|
+
function base(url) {
|
|
5600
|
+
return url.replace(/\/+$/, "");
|
|
5601
|
+
}
|
|
5602
|
+
async function call(url, init, timeoutMs) {
|
|
5603
|
+
const controller = new AbortController();
|
|
5604
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
5605
|
+
try {
|
|
5606
|
+
const res = await sdkFetch(url, { ...init, signal: controller.signal });
|
|
5607
|
+
const text = await res.text();
|
|
5608
|
+
let body = text;
|
|
5609
|
+
try {
|
|
5610
|
+
body = text ? JSON.parse(text) : null;
|
|
5611
|
+
} catch {
|
|
5612
|
+
}
|
|
5613
|
+
return { status: res.status, body, headers: res.headers };
|
|
5614
|
+
} finally {
|
|
5615
|
+
clearTimeout(timer);
|
|
5616
|
+
}
|
|
5617
|
+
}
|
|
5618
|
+
function apiError(status, body, what) {
|
|
5619
|
+
const b = body ?? {};
|
|
5620
|
+
const code = b.code ?? (typeof b.error === "string" ? b.error : void 0);
|
|
5621
|
+
return new FleetApiError(`${what} failed (${status}${code ? ` ${code}` : ""})`, status, code);
|
|
5622
|
+
}
|
|
5623
|
+
function deviceHeaders(enrolment) {
|
|
5624
|
+
return { Authorization: `Device ${enrolment.credential}` };
|
|
5625
|
+
}
|
|
5626
|
+
function policyEtag(sha256, kid) {
|
|
5627
|
+
return `${sha256}.${kid ?? ""}`;
|
|
5628
|
+
}
|
|
5629
|
+
async function fetchFleetPolicy(enrolment, ifNoneMatch, timeoutMs = 1500) {
|
|
5630
|
+
const headers = deviceHeaders(enrolment);
|
|
5631
|
+
if (ifNoneMatch) headers["If-None-Match"] = `"${ifNoneMatch}"`;
|
|
5632
|
+
const r = await call(`${base(enrolment.apiBaseUrl)}/fleet/policy`, { headers }, timeoutMs);
|
|
5633
|
+
if (r.status === 304) return { status: "unchanged" };
|
|
5634
|
+
if (r.status !== 200) throw apiError(r.status, r.body, "Policy fetch");
|
|
5635
|
+
const data = r.body;
|
|
5636
|
+
if (!data?.policyJws) throw new FleetApiError("Policy response has no policyJws", r.status);
|
|
5637
|
+
return {
|
|
5638
|
+
status: "ok",
|
|
5639
|
+
policyJws: data.policyJws,
|
|
5640
|
+
sha256: data.sha256 ?? "",
|
|
5641
|
+
version: data.version ?? 0,
|
|
5642
|
+
keyChain: Array.isArray(data.keyChain) ? data.keyChain.filter((j) => typeof j === "string") : []
|
|
5643
|
+
};
|
|
5644
|
+
}
|
|
5645
|
+
async function sendHeartbeat(enrolment, request, timeoutMs = 1500) {
|
|
5646
|
+
const r = await call(
|
|
5647
|
+
`${base(enrolment.apiBaseUrl)}/fleet/heartbeat`,
|
|
5648
|
+
{
|
|
5649
|
+
method: "POST",
|
|
5650
|
+
headers: { ...deviceHeaders(enrolment), "Content-Type": "application/json" },
|
|
5651
|
+
body: JSON.stringify(request)
|
|
5652
|
+
},
|
|
5653
|
+
timeoutMs
|
|
5654
|
+
);
|
|
5655
|
+
if (r.status !== 200) throw apiError(r.status, r.body, "Heartbeat");
|
|
5656
|
+
return r.body;
|
|
5657
|
+
}
|
|
5658
|
+
|
|
5659
|
+
// src/fleet/policy-verify.ts
|
|
5660
|
+
var import_crypto = require("crypto");
|
|
5661
|
+
var import_jose2 = require("jose");
|
|
5662
|
+
|
|
5663
|
+
// src/fleet/types.ts
|
|
5664
|
+
var FLEET_POLICY_TYP = "fleet-policy+jwt";
|
|
5665
|
+
var FLEET_POLICY_AUD = "astrasync:fleet-policy";
|
|
5666
|
+
var FLEET_POLICY_ISS = "astrasync.ai";
|
|
5667
|
+
var FLEET_KEYS_TYP = "fleet-keys+jwt";
|
|
5668
|
+
var FLEET_KEYS_AUD = "astrasync:fleet-keys";
|
|
5669
|
+
var DEFAULT_HEARTBEAT_INTERVAL_SEC = 900;
|
|
5670
|
+
|
|
5671
|
+
// src/fleet/policy-verify.ts
|
|
5672
|
+
var FleetPolicyError = class extends Error {
|
|
5673
|
+
constructor(message) {
|
|
5674
|
+
super(message);
|
|
5675
|
+
this.name = "FleetPolicyError";
|
|
5676
|
+
}
|
|
5677
|
+
};
|
|
5678
|
+
function sha256Hex(text) {
|
|
5679
|
+
return (0, import_crypto.createHash)("sha256").update(text, "utf8").digest("hex");
|
|
5680
|
+
}
|
|
5681
|
+
function parseSettings(raw) {
|
|
5682
|
+
if (!raw || typeof raw !== "object") throw new FleetPolicyError("settings missing");
|
|
5683
|
+
const s = raw;
|
|
5684
|
+
if (s.posture !== "active" && s.posture !== "passive") {
|
|
5685
|
+
throw new FleetPolicyError("settings.posture must be active or passive");
|
|
5686
|
+
}
|
|
5687
|
+
if (s.failOpen !== void 0 && typeof s.failOpen !== "boolean") {
|
|
5688
|
+
throw new FleetPolicyError("settings.failOpen must be a boolean");
|
|
5689
|
+
}
|
|
5690
|
+
if (s.governMcp !== void 0 && typeof s.governMcp !== "boolean") {
|
|
5691
|
+
throw new FleetPolicyError("settings.governMcp must be a boolean");
|
|
5692
|
+
}
|
|
5693
|
+
if (s.skipTools !== void 0 && !(Array.isArray(s.skipTools) && s.skipTools.every((t) => typeof t === "string"))) {
|
|
5694
|
+
throw new FleetPolicyError("settings.skipTools must be a string array");
|
|
5695
|
+
}
|
|
5696
|
+
const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
|
|
5697
|
+
return {
|
|
5698
|
+
posture: s.posture,
|
|
5699
|
+
failOpen: s.failOpen === true,
|
|
5700
|
+
...typeof s.governMcp === "boolean" && { governMcp: s.governMcp },
|
|
5701
|
+
...Array.isArray(s.skipTools) && { skipTools: s.skipTools },
|
|
5702
|
+
...num(s.heartbeatIntervalSec) && { heartbeatIntervalSec: num(s.heartbeatIntervalSec) },
|
|
5703
|
+
...num(s.staleAfterSec) && { staleAfterSec: num(s.staleAfterSec) }
|
|
5704
|
+
};
|
|
5705
|
+
}
|
|
5706
|
+
async function verifyFleetPolicy(jws, jwks, options) {
|
|
5707
|
+
let payloadBytes;
|
|
5708
|
+
let header;
|
|
5709
|
+
try {
|
|
5710
|
+
const keySet = (0, import_jose2.createLocalJWKSet)(jwks);
|
|
5711
|
+
const result = await (0, import_jose2.compactVerify)(jws, keySet, { algorithms: ["ES256"] });
|
|
5712
|
+
payloadBytes = result.payload;
|
|
5713
|
+
header = result.protectedHeader;
|
|
5714
|
+
} catch (err) {
|
|
5715
|
+
throw new FleetPolicyError(
|
|
5716
|
+
`signature verification failed (${err instanceof Error ? err.message : String(err)})`
|
|
5717
|
+
);
|
|
5718
|
+
}
|
|
5719
|
+
if (header.typ !== FLEET_POLICY_TYP) throw new FleetPolicyError(`unexpected typ ${header.typ}`);
|
|
5720
|
+
let claims;
|
|
5721
|
+
try {
|
|
5722
|
+
claims = JSON.parse(new TextDecoder().decode(payloadBytes));
|
|
5723
|
+
} catch {
|
|
5724
|
+
throw new FleetPolicyError("payload is not JSON");
|
|
5725
|
+
}
|
|
5726
|
+
if (claims.aud !== FLEET_POLICY_AUD) throw new FleetPolicyError(`unexpected aud ${claims.aud}`);
|
|
5727
|
+
if (claims.iss !== FLEET_POLICY_ISS) throw new FleetPolicyError(`unexpected iss ${claims.iss}`);
|
|
5728
|
+
if (!options.expectedSubs.includes(claims.sub)) {
|
|
5729
|
+
throw new FleetPolicyError("policy was issued for a different organisation or device");
|
|
5730
|
+
}
|
|
5731
|
+
if (!Number.isInteger(claims.ver) || claims.ver < 1) {
|
|
5732
|
+
throw new FleetPolicyError("ver must be a positive integer");
|
|
5733
|
+
}
|
|
5734
|
+
if (options.minVer !== void 0 && claims.ver < options.minVer) {
|
|
5735
|
+
throw new FleetPolicyError(
|
|
5736
|
+
`policy version ${claims.ver} is older than the accepted version ${options.minVer} (rollback)`
|
|
5737
|
+
);
|
|
5738
|
+
}
|
|
5739
|
+
if (typeof claims.yaml !== "string" || sha256Hex(claims.yaml) !== claims.sha256) {
|
|
5740
|
+
throw new FleetPolicyError("policy hash mismatch");
|
|
5741
|
+
}
|
|
5742
|
+
const settings = parseSettings(claims.settings);
|
|
5743
|
+
const parsed = parseYaml(claims.yaml);
|
|
5744
|
+
if (!parsed.policy) {
|
|
5745
|
+
const first = parsed.validation.errors[0];
|
|
5746
|
+
throw new FleetPolicyError(
|
|
5747
|
+
`signed policy is invalid${first ? ` (${first.path}: ${first.message})` : ""}`
|
|
5748
|
+
);
|
|
5749
|
+
}
|
|
5750
|
+
return { kid: header.kid, claims: { ...claims, settings }, policy: parsed.policy, settings, jws };
|
|
5751
|
+
}
|
|
5752
|
+
async function resolveFleetJwks(pinned, chain, ownerId) {
|
|
5753
|
+
let trusted = pinned;
|
|
5754
|
+
let lastSeq = 0;
|
|
5755
|
+
for (const link of chain) {
|
|
5756
|
+
try {
|
|
5757
|
+
const { payload, protectedHeader } = await (0, import_jose2.compactVerify)(
|
|
5758
|
+
link,
|
|
5759
|
+
(0, import_jose2.createLocalJWKSet)(trusted),
|
|
5760
|
+
{ algorithms: ["ES256"] }
|
|
5761
|
+
);
|
|
5762
|
+
if (protectedHeader.typ !== FLEET_KEYS_TYP) continue;
|
|
5763
|
+
const c = JSON.parse(new TextDecoder().decode(payload));
|
|
5764
|
+
if (c.aud !== FLEET_KEYS_AUD || c.iss !== FLEET_POLICY_ISS || c.sub !== ownerId) continue;
|
|
5765
|
+
if (!Number.isInteger(c.seq) || c.seq <= lastSeq) continue;
|
|
5766
|
+
const keys = Array.isArray(c.keys) ? c.keys.filter((k) => k && k.kty === "EC" && k.crv === "P-256" && !("d" in k)) : [];
|
|
5767
|
+
if (keys.length === 0) continue;
|
|
5768
|
+
trusted = { keys };
|
|
5769
|
+
lastSeq = c.seq;
|
|
5770
|
+
} catch {
|
|
5771
|
+
}
|
|
5772
|
+
}
|
|
5773
|
+
return trusted;
|
|
5774
|
+
}
|
|
5775
|
+
async function pickNewestValid(candidates, jwks, options) {
|
|
5776
|
+
let best = null;
|
|
5777
|
+
let lastError = new FleetPolicyError("no cached fleet policy");
|
|
5778
|
+
for (const jws of candidates) {
|
|
5779
|
+
try {
|
|
5780
|
+
const v = await verifyFleetPolicy(jws, jwks, options);
|
|
5781
|
+
if (!best || v.claims.ver > best.claims.ver) best = v;
|
|
5782
|
+
} catch (err) {
|
|
5783
|
+
lastError = err instanceof Error ? err : new FleetPolicyError(String(err));
|
|
5784
|
+
}
|
|
5785
|
+
}
|
|
5786
|
+
if (!best) throw lastError;
|
|
5787
|
+
return best;
|
|
5788
|
+
}
|
|
5789
|
+
|
|
5790
|
+
// src/fleet/runtime.ts
|
|
5791
|
+
var FLEET_SYNC_BUDGET_MS = 1500;
|
|
5792
|
+
function expectedSubs(enrolment) {
|
|
5793
|
+
return [enrolment.org.ownerId, enrolment.deviceId];
|
|
5794
|
+
}
|
|
5795
|
+
function fleetJwks(ctx, chain = readKeyChain(ctx.paths)) {
|
|
5796
|
+
return resolveFleetJwks(ctx.enrolment.jwks, chain, ctx.enrolment.org.ownerId);
|
|
5797
|
+
}
|
|
5798
|
+
async function acceptFetched(ctx, fetched, verifyOpts) {
|
|
5799
|
+
const jwks = await fleetJwks(ctx, fetched.keyChain);
|
|
5800
|
+
const verified = await verifyFleetPolicy(fetched.policyJws, jwks, verifyOpts);
|
|
5801
|
+
if (fetched.keyChain.length > 0) writeKeyChain(ctx.paths, fetched.keyChain);
|
|
5802
|
+
writeCachedPolicy(ctx.paths, fetched.policyJws);
|
|
5803
|
+
return verified;
|
|
5804
|
+
}
|
|
5805
|
+
function remember(paths, state, verified) {
|
|
5806
|
+
state.appliedSha256 = verified.claims.sha256;
|
|
5807
|
+
state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
|
|
5808
|
+
writeState(paths, state);
|
|
5809
|
+
}
|
|
5810
|
+
async function loadFleetPolicy(ctx, options = {}) {
|
|
5811
|
+
const state = readState(ctx.paths);
|
|
5812
|
+
const verifyOpts = { expectedSubs: expectedSubs(ctx.enrolment), minVer: state.maxVer };
|
|
5813
|
+
const cached = readCachedPolicies(ctx.paths);
|
|
5814
|
+
let cacheError = null;
|
|
5815
|
+
if (cached.length > 0) {
|
|
5816
|
+
try {
|
|
5817
|
+
const verified = await pickNewestValid(cached, await fleetJwks(ctx), verifyOpts);
|
|
5818
|
+
if (verified.claims.sha256 !== state.appliedSha256 || verified.claims.ver !== state.maxVer) {
|
|
5819
|
+
remember(ctx.paths, state, verified);
|
|
5820
|
+
}
|
|
5821
|
+
return verified;
|
|
5822
|
+
} catch (err) {
|
|
5823
|
+
cacheError = err instanceof Error ? err : new FleetPolicyError(String(err));
|
|
5824
|
+
}
|
|
5825
|
+
}
|
|
5826
|
+
try {
|
|
5827
|
+
const fetched = await fetchFleetPolicy(
|
|
5828
|
+
ctx.enrolment,
|
|
5829
|
+
null,
|
|
5830
|
+
options.fetchTimeoutMs ?? FLEET_SYNC_BUDGET_MS
|
|
5831
|
+
);
|
|
5832
|
+
if (fetched.status === "ok") {
|
|
5833
|
+
const verified = await acceptFetched(ctx, fetched, verifyOpts);
|
|
5834
|
+
remember(ctx.paths, state, verified);
|
|
5835
|
+
return verified;
|
|
5836
|
+
}
|
|
5837
|
+
} catch (err) {
|
|
5838
|
+
if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
|
|
5839
|
+
state.revoked = true;
|
|
5840
|
+
writeState(ctx.paths, state);
|
|
5841
|
+
}
|
|
5842
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
5843
|
+
throw new FleetPolicyError(
|
|
5844
|
+
cacheError ? `${cacheError.message}; refresh failed (${detail})` : `no fleet policy (${detail})`
|
|
5845
|
+
);
|
|
5846
|
+
}
|
|
5847
|
+
throw cacheError ?? new FleetPolicyError("no fleet policy available");
|
|
5848
|
+
}
|
|
5849
|
+
async function recordDecisionAndHeartbeat(ctx, applied, decision, options) {
|
|
5850
|
+
const now = options.now ?? Date.now;
|
|
5851
|
+
const state = readState(ctx.paths);
|
|
5852
|
+
if (decision) state.counts[decision] += 1;
|
|
5853
|
+
const intervalSec = applied.settings.heartbeatIntervalSec ?? ctx.enrolment.heartbeatIntervalSec ?? DEFAULT_HEARTBEAT_INTERVAL_SEC;
|
|
5854
|
+
const last = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : 0;
|
|
5855
|
+
if (now() - last < intervalSec * 1e3) {
|
|
5856
|
+
writeState(ctx.paths, state);
|
|
5857
|
+
return "throttled";
|
|
5858
|
+
}
|
|
5859
|
+
const deadline = now() + (options.budgetMs ?? FLEET_SYNC_BUDGET_MS);
|
|
5860
|
+
const remaining = () => Math.max(1, deadline - now());
|
|
5861
|
+
state.lastHeartbeatAt = new Date(now()).toISOString();
|
|
5862
|
+
let outcome = "sent";
|
|
5863
|
+
try {
|
|
5864
|
+
const hb = await sendHeartbeat(
|
|
5865
|
+
ctx.enrolment,
|
|
5866
|
+
{
|
|
5867
|
+
appliedSha256: applied.claims.sha256,
|
|
5868
|
+
guardVersion: options.guardVersion,
|
|
5869
|
+
adapters: [{ kind: options.adapterKind, managed: true }],
|
|
5870
|
+
posture: applied.settings.posture,
|
|
5871
|
+
decisionCounts: { ...state.counts }
|
|
5872
|
+
},
|
|
5873
|
+
remaining()
|
|
5874
|
+
);
|
|
5875
|
+
state.counts = { allow: 0, deny: 0, ask: 0 };
|
|
5876
|
+
state.revoked = false;
|
|
5877
|
+
delete state.lastError;
|
|
5878
|
+
const policyChanged = !!hb.activeSha256 && hb.activeSha256 !== applied.claims.sha256;
|
|
5879
|
+
const keyChanged = !!hb.activeKid && !!applied.kid && hb.activeKid !== applied.kid;
|
|
5880
|
+
if (policyChanged || keyChanged) {
|
|
5881
|
+
const fetched = await fetchFleetPolicy(
|
|
5882
|
+
ctx.enrolment,
|
|
5883
|
+
policyEtag(applied.claims.sha256, applied.kid),
|
|
5884
|
+
remaining()
|
|
5885
|
+
);
|
|
5886
|
+
if (fetched.status === "ok") {
|
|
5887
|
+
const verified = await acceptFetched(ctx, fetched, {
|
|
5888
|
+
expectedSubs: expectedSubs(ctx.enrolment),
|
|
5889
|
+
minVer: Math.max(state.maxVer ?? 0, applied.claims.ver)
|
|
5890
|
+
});
|
|
5891
|
+
state.appliedSha256 = verified.claims.sha256;
|
|
5892
|
+
state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
|
|
5893
|
+
outcome = "refreshed";
|
|
5894
|
+
}
|
|
5895
|
+
}
|
|
5896
|
+
} catch (err) {
|
|
5897
|
+
if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
|
|
5898
|
+
state.revoked = true;
|
|
5899
|
+
outcome = "revoked";
|
|
5900
|
+
} else {
|
|
5901
|
+
state.lastError = err instanceof Error ? err.message : String(err);
|
|
5902
|
+
outcome = "failed";
|
|
5903
|
+
}
|
|
5904
|
+
}
|
|
5905
|
+
writeState(ctx.paths, state);
|
|
5906
|
+
return outcome;
|
|
5907
|
+
}
|
|
5908
|
+
|
|
5909
|
+
// src/fleet/hook-runner.ts
|
|
5910
|
+
var PREFIX = "AstraSync Local Guard (organisation fleet policy)";
|
|
5911
|
+
async function runFleetHook(args) {
|
|
5912
|
+
if (args.resolution.kind === "fleet-missing") {
|
|
5913
|
+
return { output: args.denyOutput(`${PREFIX}: ${args.resolution.reason}`), exitCode: 0 };
|
|
5914
|
+
}
|
|
5915
|
+
const ctx = { enrolment: args.resolution.enrolment, paths: args.resolution.paths };
|
|
5916
|
+
let verified;
|
|
5917
|
+
try {
|
|
5918
|
+
verified = await loadFleetPolicy(ctx);
|
|
5919
|
+
} catch (err) {
|
|
5920
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
5921
|
+
return {
|
|
5922
|
+
output: args.denyOutput(`${PREFIX}: no valid signed policy \u2014 ${detail}`),
|
|
5923
|
+
exitCode: 0
|
|
5924
|
+
};
|
|
5925
|
+
}
|
|
5926
|
+
const { settings } = verified;
|
|
5927
|
+
const decide = async (output) => {
|
|
5928
|
+
try {
|
|
5929
|
+
const outcome = await recordDecisionAndHeartbeat(ctx, verified, args.classify(output), {
|
|
5930
|
+
guardVersion: SDK_VERSION,
|
|
5931
|
+
adapterKind: args.adapterKind,
|
|
5932
|
+
now: args.now
|
|
5933
|
+
});
|
|
5934
|
+
args.onHeartbeat?.(outcome);
|
|
5935
|
+
} catch {
|
|
5936
|
+
}
|
|
5937
|
+
return { output, exitCode: 0 };
|
|
5938
|
+
};
|
|
5939
|
+
let payload;
|
|
5940
|
+
try {
|
|
5941
|
+
payload = JSON.parse(args.payloadJson);
|
|
5942
|
+
} catch {
|
|
5943
|
+
if (settings.failOpen) return decide(null);
|
|
5944
|
+
return decide(args.denyOutput(`${PREFIX}: could not parse hook payload`));
|
|
5945
|
+
}
|
|
5946
|
+
try {
|
|
5947
|
+
const gatewayConfig = {
|
|
5948
|
+
mode: "local",
|
|
5949
|
+
policy: verified.policy,
|
|
5950
|
+
posture: settings.posture,
|
|
5951
|
+
traceEnabled: true,
|
|
5952
|
+
tracePath: (0, import_path5.join)(args.resolution.paths.userDir, "traces"),
|
|
5953
|
+
debug: false
|
|
5954
|
+
};
|
|
5955
|
+
const gateway = args.gatewayFactory ? args.gatewayFactory(gatewayConfig) : new AstraSyncGateway(gatewayConfig);
|
|
5956
|
+
await gateway.initialize();
|
|
5957
|
+
const adapter = args.createAdapter({
|
|
5958
|
+
...settings.skipTools && { skipTools: settings.skipTools },
|
|
5959
|
+
...typeof settings.governMcp === "boolean" && { governMcp: settings.governMcp }
|
|
5960
|
+
});
|
|
5961
|
+
await adapter.initialize({ gateway, adapterOptions: {} });
|
|
5962
|
+
const output = await adapter.evaluatePayload(payload);
|
|
5963
|
+
await adapter.shutdown();
|
|
5964
|
+
await gateway.shutdown();
|
|
5965
|
+
return decide(output);
|
|
5966
|
+
} catch (err) {
|
|
5967
|
+
if (settings.failOpen) return decide(null);
|
|
5968
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
5969
|
+
return decide(args.denyOutput(`${PREFIX}: policy evaluation failed (${detail})`));
|
|
5970
|
+
}
|
|
5971
|
+
}
|
|
5196
5972
|
|
|
5197
5973
|
// src/claude-code/hook.ts
|
|
5198
5974
|
var MAX_STDIN_BYTES = 1024 * 1024;
|
|
@@ -5210,6 +5986,19 @@ function denyOutput(reason) {
|
|
|
5210
5986
|
}
|
|
5211
5987
|
async function processHookPayload(payloadJson, options = {}) {
|
|
5212
5988
|
const env = options.env ?? process.env;
|
|
5989
|
+
const fleet = resolveFleet(env, options.home ?? (0, import_os3.homedir)(), options.fleetPaths);
|
|
5990
|
+
if (fleet) {
|
|
5991
|
+
return runFleetHook({
|
|
5992
|
+
resolution: fleet,
|
|
5993
|
+
payloadJson,
|
|
5994
|
+
adapterKind: "claude-code",
|
|
5995
|
+
createAdapter: (adapterOptions) => new ClaudeCodeAdapter(adapterOptions),
|
|
5996
|
+
denyOutput,
|
|
5997
|
+
classify: (output) => output?.hookSpecificOutput?.permissionDecision === "deny" ? "deny" : output?.hookSpecificOutput?.permissionDecision === "ask" ? "ask" : "allow",
|
|
5998
|
+
gatewayFactory: options.gatewayFactory,
|
|
5999
|
+
now: options.now
|
|
6000
|
+
});
|
|
6001
|
+
}
|
|
5213
6002
|
if (env.ASTRASYNC_GUARD_DISABLE === "1") {
|
|
5214
6003
|
return { output: null, exitCode: 0 };
|
|
5215
6004
|
}
|
|
@@ -5242,7 +6031,7 @@ async function processHookPayload(payloadJson, options = {}) {
|
|
|
5242
6031
|
policyFile: resolved.policyFile,
|
|
5243
6032
|
posture: resolved.settings.posture ?? "active",
|
|
5244
6033
|
traceEnabled: true,
|
|
5245
|
-
tracePath: (0,
|
|
6034
|
+
tracePath: (0, import_path6.join)(resolved.guardDir, "traces"),
|
|
5246
6035
|
debug: false,
|
|
5247
6036
|
...mode === "hybrid" && {
|
|
5248
6037
|
apiBaseUrl: resolved.settings.apiBaseUrl,
|