@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
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
// src/cursor/extension.ts
|
|
2
|
+
import { homedir as homedir3 } from "os";
|
|
3
|
+
import { join as join3 } from "path";
|
|
4
|
+
|
|
1
5
|
// src/adapter-interface/interface.ts
|
|
2
6
|
var ADAPTER_INTERFACE_VERSION = 1;
|
|
3
7
|
|
|
@@ -3965,7 +3969,7 @@ function getTrustLevel(score) {
|
|
|
3965
3969
|
}
|
|
3966
3970
|
|
|
3967
3971
|
// src/version.ts
|
|
3968
|
-
var SDK_VERSION = "5.
|
|
3972
|
+
var SDK_VERSION = "5.12.0";
|
|
3969
3973
|
|
|
3970
3974
|
// src/http.ts
|
|
3971
3975
|
var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
|
|
@@ -3992,6 +3996,14 @@ function getCachedWellKnownUrls(apiBaseUrl) {
|
|
|
3992
3996
|
return cache.get(apiBaseUrl)?.data;
|
|
3993
3997
|
}
|
|
3994
3998
|
|
|
3999
|
+
// src/failure-posture.ts
|
|
4000
|
+
var REJECTED_IDENTITY_DIMENSIONS = /* @__PURE__ */ new Set([
|
|
4001
|
+
"identity.invalid_agent_id",
|
|
4002
|
+
"identity.unknown_agent",
|
|
4003
|
+
"agent.lookup"
|
|
4004
|
+
]);
|
|
4005
|
+
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.";
|
|
4006
|
+
|
|
3995
4007
|
// src/verify.ts
|
|
3996
4008
|
var DEFAULT_CONFIG = {
|
|
3997
4009
|
apiBaseUrl: "https://astrasync.ai/api",
|
|
@@ -4203,11 +4215,44 @@ function createGuidanceResponse(_config, reason, options = {}) {
|
|
|
4203
4215
|
// coercing the absent recommendation to a policy 'deny'. Misconfig is
|
|
4204
4216
|
// deterministic and intentionally NOT marked retryable.
|
|
4205
4217
|
...isApiError && { retryable: true },
|
|
4218
|
+
...options.httpStatus !== void 0 && { httpStatus: options.httpStatus },
|
|
4219
|
+
...options.retryAfterMs !== void 0 && { retryAfterMs: options.retryAfterMs },
|
|
4206
4220
|
correlationId: options.correlationId,
|
|
4207
4221
|
attemptId: options.attemptId,
|
|
4208
4222
|
verifiedAt: /* @__PURE__ */ new Date()
|
|
4209
4223
|
};
|
|
4210
4224
|
}
|
|
4225
|
+
async function readJsonSafe(response) {
|
|
4226
|
+
try {
|
|
4227
|
+
const parsed = await response.json();
|
|
4228
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
4229
|
+
} catch {
|
|
4230
|
+
return {};
|
|
4231
|
+
}
|
|
4232
|
+
}
|
|
4233
|
+
function rejectedIdentityGuidance(failures) {
|
|
4234
|
+
const f = failures?.find((x) => REJECTED_IDENTITY_DIMENSIONS.has(x.dimension));
|
|
4235
|
+
if (!f) return void 0;
|
|
4236
|
+
if (f.dimension === "agent.lookup") {
|
|
4237
|
+
return `The presented agent identifier is not registered with AstraSync. ${UNKNOWN_AGENT_GUIDANCE}`;
|
|
4238
|
+
}
|
|
4239
|
+
return f.guidance ? `${f.message} ${f.guidance}` : f.message;
|
|
4240
|
+
}
|
|
4241
|
+
var MAX_RETRY_AFTER_MS = 15 * 60 * 1e3;
|
|
4242
|
+
function parseRetryAfterMs(response) {
|
|
4243
|
+
const raw = response.headers?.get?.("retry-after");
|
|
4244
|
+
if (!raw) return void 0;
|
|
4245
|
+
const trimmed = raw.trim();
|
|
4246
|
+
let ms;
|
|
4247
|
+
if (/^\d+(\.\d+)?$/.test(trimmed)) {
|
|
4248
|
+
ms = Number(trimmed) * 1e3;
|
|
4249
|
+
} else {
|
|
4250
|
+
const at = Date.parse(trimmed);
|
|
4251
|
+
if (Number.isNaN(at)) return void 0;
|
|
4252
|
+
ms = at - Date.now();
|
|
4253
|
+
}
|
|
4254
|
+
return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, Math.round(ms)));
|
|
4255
|
+
}
|
|
4211
4256
|
async function callVerifyAccessAPI(config, request) {
|
|
4212
4257
|
const { credentials, ...requestData } = request;
|
|
4213
4258
|
const body = {
|
|
@@ -4264,7 +4309,8 @@ async function callVerifyAccessAPI(config, request) {
|
|
|
4264
4309
|
body: JSON.stringify(body),
|
|
4265
4310
|
signal: AbortSignal.timeout(config.verifyTimeoutMs ?? 1e4)
|
|
4266
4311
|
});
|
|
4267
|
-
const data = await response
|
|
4312
|
+
const data = await readJsonSafe(response);
|
|
4313
|
+
const retryAfterMs = parseRetryAfterMs(response);
|
|
4268
4314
|
if (response.status === 410) {
|
|
4269
4315
|
return {
|
|
4270
4316
|
success: true,
|
|
@@ -4302,6 +4348,23 @@ async function callVerifyAccessAPI(config, request) {
|
|
|
4302
4348
|
}
|
|
4303
4349
|
};
|
|
4304
4350
|
}
|
|
4351
|
+
if (response.status === 404 && credentials.astraId && (data?.error === "AGENT_NOT_FOUND" || typeof data?.message === "string" && /agent/i.test(data.message))) {
|
|
4352
|
+
return {
|
|
4353
|
+
success: true,
|
|
4354
|
+
attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
|
|
4355
|
+
access: {
|
|
4356
|
+
allowed: false,
|
|
4357
|
+
reason: "unknown_agent",
|
|
4358
|
+
failures: [
|
|
4359
|
+
{
|
|
4360
|
+
dimension: "identity.unknown_agent",
|
|
4361
|
+
message: "The presented agent identifier is not registered with AstraSync.",
|
|
4362
|
+
guidance: UNKNOWN_AGENT_GUIDANCE
|
|
4363
|
+
}
|
|
4364
|
+
]
|
|
4365
|
+
}
|
|
4366
|
+
};
|
|
4367
|
+
}
|
|
4305
4368
|
if (!response.ok) {
|
|
4306
4369
|
if (response.status === 401) {
|
|
4307
4370
|
return {
|
|
@@ -4316,9 +4379,11 @@ async function callVerifyAccessAPI(config, request) {
|
|
|
4316
4379
|
}
|
|
4317
4380
|
return {
|
|
4318
4381
|
success: false,
|
|
4319
|
-
error: data.message || data.error || `API returned ${response.status}`,
|
|
4382
|
+
error: typeof data?.message === "string" && data.message || typeof data?.error === "string" && data.error || `API returned ${response.status}`,
|
|
4320
4383
|
correlationId: typeof data?.correlationId === "string" ? data.correlationId : void 0,
|
|
4321
|
-
attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0
|
|
4384
|
+
attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
|
|
4385
|
+
httpStatus: response.status,
|
|
4386
|
+
...retryAfterMs !== void 0 && { retryAfterMs }
|
|
4322
4387
|
};
|
|
4323
4388
|
}
|
|
4324
4389
|
return data;
|
|
@@ -4390,12 +4455,14 @@ async function verify(config, request, options) {
|
|
|
4390
4455
|
correlationId: apiResponse.correlationId,
|
|
4391
4456
|
attemptId: apiResponse.attemptId,
|
|
4392
4457
|
remediation: apiResponse.remediation,
|
|
4458
|
+
httpStatus: apiResponse.httpStatus,
|
|
4459
|
+
retryAfterMs: apiResponse.retryAfterMs,
|
|
4393
4460
|
urls
|
|
4394
4461
|
});
|
|
4395
4462
|
}
|
|
4396
4463
|
if (!apiResponse.access?.allowed) {
|
|
4397
4464
|
const aggregatedFailures = apiResponse.access?.failures;
|
|
4398
|
-
const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true;
|
|
4465
|
+
const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true && !aggregatedFailures?.some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));
|
|
4399
4466
|
const result2 = {
|
|
4400
4467
|
identityVerified: idVerifiedFromBackend,
|
|
4401
4468
|
policyAllowed: false,
|
|
@@ -4407,7 +4474,10 @@ async function verify(config, request, options) {
|
|
|
4407
4474
|
requiresStepUp: apiResponse.access?.requiresStepUp,
|
|
4408
4475
|
requiresApproval: apiResponse.access?.requiresApproval,
|
|
4409
4476
|
guidance: {
|
|
4410
|
-
|
|
4477
|
+
// 5.12.0: a presented-but-rejected id (malformed / unknown) carries
|
|
4478
|
+
// actionable registration guidance on its failure — surface it
|
|
4479
|
+
// instead of the bare machine reason ('unknown_agent').
|
|
4480
|
+
message: rejectedIdentityGuidance(aggregatedFailures) ?? (apiResponse.access?.reason || "Access denied by PDLSS policy"),
|
|
4411
4481
|
registrationUrl: urls?.registrationUrl ?? "",
|
|
4412
4482
|
documentationUrl: urls?.documentationUrl ?? "",
|
|
4413
4483
|
// 5.1.0: anonymous callers land on this branch — steer MCP-hosted
|
|
@@ -4507,7 +4577,7 @@ async function verify(config, request, options) {
|
|
|
4507
4577
|
registrationUrl: urls?.registrationUrl ?? "",
|
|
4508
4578
|
documentationUrl: urls?.documentationUrl ?? ""
|
|
4509
4579
|
};
|
|
4510
|
-
} else if (result.recommendation === "step_up_required") {
|
|
4580
|
+
} else if (result.recommendation === "step_up_required" && result.identityVerified) {
|
|
4511
4581
|
result.requiresStepUp = true;
|
|
4512
4582
|
result.denialReasons = serverDenialReasons ?? result.recommendationReasons ?? ["Step-up verification required"];
|
|
4513
4583
|
}
|
|
@@ -4536,6 +4606,217 @@ var DEFAULT_EDGE_CONFIG = Object.freeze({
|
|
|
4536
4606
|
var DEFAULT_TTL_MS = 60 * 1e3;
|
|
4537
4607
|
var DEFAULT_MAX_STALE_MS = 24 * 60 * 60 * 1e3;
|
|
4538
4608
|
|
|
4609
|
+
// src/edge-core/events.ts
|
|
4610
|
+
async function withBudget(promise, ms) {
|
|
4611
|
+
let timer;
|
|
4612
|
+
try {
|
|
4613
|
+
return await Promise.race([
|
|
4614
|
+
promise,
|
|
4615
|
+
new Promise((resolve) => {
|
|
4616
|
+
timer = setTimeout(() => resolve(void 0), ms);
|
|
4617
|
+
})
|
|
4618
|
+
]);
|
|
4619
|
+
} catch {
|
|
4620
|
+
return void 0;
|
|
4621
|
+
} finally {
|
|
4622
|
+
if (timer) clearTimeout(timer);
|
|
4623
|
+
}
|
|
4624
|
+
}
|
|
4625
|
+
var destKeyOf = (d) => `${d.apiBaseUrl}\0${d.apiKey ?? ""}\0${d.counterparty}\0${d.adapter ?? ""}`;
|
|
4626
|
+
var BeaconBuffer = class {
|
|
4627
|
+
constructor(options = {}) {
|
|
4628
|
+
this.queue = [];
|
|
4629
|
+
this.droppedSinceLast = 0;
|
|
4630
|
+
this.droppedTotal = 0;
|
|
4631
|
+
this.deliveredTotal = 0;
|
|
4632
|
+
this.backoffUntil = 0;
|
|
4633
|
+
this.collapse = /* @__PURE__ */ new Map();
|
|
4634
|
+
/** Keys the backend answered 401 for — later batches go unauthenticated. */
|
|
4635
|
+
this.rejectedKeys = /* @__PURE__ */ new Set();
|
|
4636
|
+
this.opts = {
|
|
4637
|
+
maxItems: options.maxItems ?? 1e3,
|
|
4638
|
+
maxBatch: options.maxBatch ?? 100,
|
|
4639
|
+
maxAttempts: options.maxAttempts ?? 3,
|
|
4640
|
+
collapseWindowMs: options.collapseWindowMs ?? 6e4,
|
|
4641
|
+
collapseMaxKeys: options.collapseMaxKeys ?? 1e3,
|
|
4642
|
+
requestTimeoutMs: options.requestTimeoutMs ?? 1e4,
|
|
4643
|
+
retryBackoffMs: options.retryBackoffMs ?? 1e3,
|
|
4644
|
+
now: options.now ?? Date.now
|
|
4645
|
+
};
|
|
4646
|
+
}
|
|
4647
|
+
/**
|
|
4648
|
+
* Queue one beacon. With a `collapseKey`, a repeat inside the window is
|
|
4649
|
+
* merged into a held aggregate (sent when the window closes) instead of
|
|
4650
|
+
* becoming its own item.
|
|
4651
|
+
*/
|
|
4652
|
+
enqueue(dest, item, collapseKey) {
|
|
4653
|
+
const now = this.opts.now();
|
|
4654
|
+
if (collapseKey) {
|
|
4655
|
+
const entry = this.collapse.get(collapseKey);
|
|
4656
|
+
if (entry && now - entry.firstSeenAt < this.opts.collapseWindowMs) {
|
|
4657
|
+
for (const target of [entry.first, entry.held]) {
|
|
4658
|
+
if (target && !target.inFlight && this.queue.includes(target)) {
|
|
4659
|
+
target.item.repeatCount = (target.item.repeatCount ?? 1) + 1;
|
|
4660
|
+
return;
|
|
4661
|
+
}
|
|
4662
|
+
}
|
|
4663
|
+
const held = this.push(
|
|
4664
|
+
dest,
|
|
4665
|
+
{ ...item, repeatCount: 1 },
|
|
4666
|
+
entry.firstSeenAt + this.opts.collapseWindowMs
|
|
4667
|
+
);
|
|
4668
|
+
entry.held = held;
|
|
4669
|
+
return;
|
|
4670
|
+
}
|
|
4671
|
+
this.collapse.delete(collapseKey);
|
|
4672
|
+
if (this.collapse.size >= this.opts.collapseMaxKeys) {
|
|
4673
|
+
const oldest = this.collapse.keys().next().value;
|
|
4674
|
+
if (oldest !== void 0) this.collapse.delete(oldest);
|
|
4675
|
+
}
|
|
4676
|
+
const fresh = { firstSeenAt: now };
|
|
4677
|
+
this.collapse.set(collapseKey, fresh);
|
|
4678
|
+
fresh.first = this.push(dest, item, now);
|
|
4679
|
+
return;
|
|
4680
|
+
}
|
|
4681
|
+
this.push(dest, item, now);
|
|
4682
|
+
}
|
|
4683
|
+
/**
|
|
4684
|
+
* Deliver every eligible queued item. Concurrent callers share ONE
|
|
4685
|
+
* in-flight drain (it survives the caller's budget and a Lambda freeze),
|
|
4686
|
+
* so nothing in flight is ever sent twice; items queued while it runs are
|
|
4687
|
+
* picked up by the same drain.
|
|
4688
|
+
*/
|
|
4689
|
+
flush() {
|
|
4690
|
+
if (!this.inFlight) {
|
|
4691
|
+
this.inFlight = this.drain().finally(() => {
|
|
4692
|
+
this.inFlight = void 0;
|
|
4693
|
+
});
|
|
4694
|
+
}
|
|
4695
|
+
return this.inFlight;
|
|
4696
|
+
}
|
|
4697
|
+
/** Counters for tests and diagnostics. */
|
|
4698
|
+
stats() {
|
|
4699
|
+
return {
|
|
4700
|
+
queueDepth: this.queue.length,
|
|
4701
|
+
droppedSinceLast: this.droppedSinceLast,
|
|
4702
|
+
droppedTotal: this.droppedTotal,
|
|
4703
|
+
deliveredTotal: this.deliveredTotal,
|
|
4704
|
+
flushing: this.inFlight !== void 0
|
|
4705
|
+
};
|
|
4706
|
+
}
|
|
4707
|
+
push(dest, item, eligibleAt) {
|
|
4708
|
+
while (this.queue.length >= this.opts.maxItems) this.dropOldest();
|
|
4709
|
+
const entry = {
|
|
4710
|
+
dest,
|
|
4711
|
+
destKey: destKeyOf(dest),
|
|
4712
|
+
item,
|
|
4713
|
+
attempts: 0,
|
|
4714
|
+
eligibleAt,
|
|
4715
|
+
inFlight: false
|
|
4716
|
+
};
|
|
4717
|
+
this.queue.push(entry);
|
|
4718
|
+
return entry;
|
|
4719
|
+
}
|
|
4720
|
+
dropOldest() {
|
|
4721
|
+
if (this.queue.shift()) this.countDropped(1);
|
|
4722
|
+
}
|
|
4723
|
+
countDropped(n) {
|
|
4724
|
+
this.droppedSinceLast += n;
|
|
4725
|
+
this.droppedTotal += n;
|
|
4726
|
+
}
|
|
4727
|
+
async drain() {
|
|
4728
|
+
for (; ; ) {
|
|
4729
|
+
const now = this.opts.now();
|
|
4730
|
+
if (now < this.backoffUntil) return;
|
|
4731
|
+
const batch = this.takeBatch(now);
|
|
4732
|
+
if (batch.length === 0) return;
|
|
4733
|
+
const ok = await this.send(batch);
|
|
4734
|
+
if (!ok) return;
|
|
4735
|
+
}
|
|
4736
|
+
}
|
|
4737
|
+
/** Oldest eligible item + up to maxBatch-1 more for the same destination. */
|
|
4738
|
+
takeBatch(now) {
|
|
4739
|
+
const first = this.queue.find((q) => q.eligibleAt <= now);
|
|
4740
|
+
if (!first) return [];
|
|
4741
|
+
const batch = [];
|
|
4742
|
+
const rest = [];
|
|
4743
|
+
for (const q of this.queue) {
|
|
4744
|
+
if (batch.length < this.opts.maxBatch && q.destKey === first.destKey && q.eligibleAt <= now) {
|
|
4745
|
+
q.inFlight = true;
|
|
4746
|
+
batch.push(q);
|
|
4747
|
+
} else {
|
|
4748
|
+
rest.push(q);
|
|
4749
|
+
}
|
|
4750
|
+
}
|
|
4751
|
+
this.queue = rest;
|
|
4752
|
+
return batch;
|
|
4753
|
+
}
|
|
4754
|
+
/** POST one batch. Returns false when the drain should pause (backoff). */
|
|
4755
|
+
async send(batch) {
|
|
4756
|
+
const dest = batch[0].dest;
|
|
4757
|
+
const useKey = dest.apiKey && !this.rejectedKeys.has(dest.apiKey) ? dest.apiKey : void 0;
|
|
4758
|
+
const reportedDropped = this.droppedSinceLast;
|
|
4759
|
+
const meta = {
|
|
4760
|
+
droppedSinceLast: reportedDropped,
|
|
4761
|
+
queueDepth: this.queue.length,
|
|
4762
|
+
adapter: dest.adapter ?? "edge-core",
|
|
4763
|
+
version: SDK_VERSION
|
|
4764
|
+
};
|
|
4765
|
+
const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
|
|
4766
|
+
const response = await withBudget(
|
|
4767
|
+
sdkFetch(`${dest.apiBaseUrl}/verification-activity/edge-events`, {
|
|
4768
|
+
method: "POST",
|
|
4769
|
+
headers: {
|
|
4770
|
+
"Content-Type": "application/json",
|
|
4771
|
+
...useKey && { Authorization: `Bearer ${useKey}` }
|
|
4772
|
+
},
|
|
4773
|
+
body: JSON.stringify({ events: batch.map((q) => q.item), meta }),
|
|
4774
|
+
...controller && { signal: controller.signal }
|
|
4775
|
+
}),
|
|
4776
|
+
this.opts.requestTimeoutMs
|
|
4777
|
+
);
|
|
4778
|
+
if (!response) controller?.abort();
|
|
4779
|
+
const status = response?.status;
|
|
4780
|
+
for (const q of batch) q.inFlight = false;
|
|
4781
|
+
if (status !== void 0 && status >= 200 && status < 300) {
|
|
4782
|
+
this.droppedSinceLast = Math.max(0, this.droppedSinceLast - reportedDropped);
|
|
4783
|
+
this.deliveredTotal += batch.length;
|
|
4784
|
+
return true;
|
|
4785
|
+
}
|
|
4786
|
+
if (status === 401 && useKey) {
|
|
4787
|
+
this.rejectedKeys.add(useKey);
|
|
4788
|
+
this.requeue(batch, false);
|
|
4789
|
+
return true;
|
|
4790
|
+
}
|
|
4791
|
+
if (status === 429) {
|
|
4792
|
+
const retryAfter = Number(response?.headers.get("retry-after"));
|
|
4793
|
+
const waitMs = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 120) * 1e3 : 3e4;
|
|
4794
|
+
this.backoffUntil = this.opts.now() + waitMs;
|
|
4795
|
+
this.requeue(batch, false);
|
|
4796
|
+
return false;
|
|
4797
|
+
}
|
|
4798
|
+
if (status !== void 0 && status >= 400 && status < 500) {
|
|
4799
|
+
this.countDropped(batch.length);
|
|
4800
|
+
return true;
|
|
4801
|
+
}
|
|
4802
|
+
this.backoffUntil = this.opts.now() + this.opts.retryBackoffMs;
|
|
4803
|
+
this.requeue(batch, true);
|
|
4804
|
+
return false;
|
|
4805
|
+
}
|
|
4806
|
+
/** Put a failed batch back at the head of the queue (order preserved). */
|
|
4807
|
+
requeue(batch, countAttempt) {
|
|
4808
|
+
const keep = [];
|
|
4809
|
+
for (const q of batch) {
|
|
4810
|
+
if (countAttempt) q.attempts += 1;
|
|
4811
|
+
if (q.attempts >= this.opts.maxAttempts) this.countDropped(1);
|
|
4812
|
+
else keep.push(q);
|
|
4813
|
+
}
|
|
4814
|
+
this.queue = [...keep, ...this.queue];
|
|
4815
|
+
while (this.queue.length > this.opts.maxItems) this.dropOldest();
|
|
4816
|
+
}
|
|
4817
|
+
};
|
|
4818
|
+
var beaconBuffer = new BeaconBuffer();
|
|
4819
|
+
|
|
4539
4820
|
// src/adapters/express.ts
|
|
4540
4821
|
var DEFAULT_ROUTES_REFRESH_MS = 5 * 60 * 1e3;
|
|
4541
4822
|
|
|
@@ -5132,11 +5413,445 @@ var AstraSyncGateway = class {
|
|
|
5132
5413
|
}
|
|
5133
5414
|
};
|
|
5134
5415
|
|
|
5416
|
+
// src/claude-code/guard-config.ts
|
|
5417
|
+
import { homedir as homedir2 } from "os";
|
|
5418
|
+
|
|
5419
|
+
// src/fleet/enrolment-store.ts
|
|
5420
|
+
import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
5421
|
+
import { homedir } from "os";
|
|
5422
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
5423
|
+
function machineScopeDir(platform = process.platform, env = process.env) {
|
|
5424
|
+
if (platform === "darwin") return "/Library/Application Support/AstraSync";
|
|
5425
|
+
if (platform === "win32") return join2(env.ProgramData || "C:\\ProgramData", "AstraSync");
|
|
5426
|
+
return "/etc/astrasync";
|
|
5427
|
+
}
|
|
5428
|
+
function fleetPaths(options = {}) {
|
|
5429
|
+
const home = options.home ?? homedir();
|
|
5430
|
+
const machineDir = options.machineDir ?? options.env?.ASTRASYNC_FLEET_MACHINE_DIR ?? machineScopeDir(options.platform, options.env);
|
|
5431
|
+
const userDir = join2(home, ".astrasync", "fleet");
|
|
5432
|
+
return {
|
|
5433
|
+
machineDevice: join2(machineDir, "fleet.json"),
|
|
5434
|
+
machinePolicy: join2(machineDir, "policy.jws"),
|
|
5435
|
+
userDir,
|
|
5436
|
+
userDevice: join2(userDir, "device.json"),
|
|
5437
|
+
userPolicy: join2(userDir, "policy.jws"),
|
|
5438
|
+
userKeyChain: join2(userDir, "keychain.json"),
|
|
5439
|
+
state: join2(userDir, "state.json")
|
|
5440
|
+
};
|
|
5441
|
+
}
|
|
5442
|
+
function isEnrolment(value) {
|
|
5443
|
+
const v = value;
|
|
5444
|
+
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);
|
|
5445
|
+
}
|
|
5446
|
+
function loadEnrolment(paths) {
|
|
5447
|
+
const candidates = [
|
|
5448
|
+
[paths.machineDevice, "machine"],
|
|
5449
|
+
[paths.userDevice, "user"]
|
|
5450
|
+
];
|
|
5451
|
+
for (const [path, scope] of candidates) {
|
|
5452
|
+
if (!existsSync3(path)) continue;
|
|
5453
|
+
try {
|
|
5454
|
+
const parsed = JSON.parse(readFileSync3(path, "utf-8"));
|
|
5455
|
+
if (isEnrolment(parsed)) return { enrolment: parsed, scope };
|
|
5456
|
+
} catch {
|
|
5457
|
+
}
|
|
5458
|
+
return { corrupt: true, path };
|
|
5459
|
+
}
|
|
5460
|
+
return null;
|
|
5461
|
+
}
|
|
5462
|
+
function writeFileMode(path, content, mode) {
|
|
5463
|
+
mkdirSync3(dirname2(path), { recursive: true, mode: 448 });
|
|
5464
|
+
writeFileSync2(path, content, { encoding: "utf-8", mode });
|
|
5465
|
+
try {
|
|
5466
|
+
chmodSync(path, mode);
|
|
5467
|
+
} catch {
|
|
5468
|
+
}
|
|
5469
|
+
}
|
|
5470
|
+
function readCachedPolicies(paths) {
|
|
5471
|
+
const out = [];
|
|
5472
|
+
for (const p of [paths.userPolicy, paths.machinePolicy]) {
|
|
5473
|
+
try {
|
|
5474
|
+
if (existsSync3(p)) out.push(readFileSync3(p, "utf-8").trim());
|
|
5475
|
+
} catch {
|
|
5476
|
+
}
|
|
5477
|
+
}
|
|
5478
|
+
return out.filter(Boolean);
|
|
5479
|
+
}
|
|
5480
|
+
function writeCachedPolicy(paths, jws) {
|
|
5481
|
+
writeFileMode(paths.userPolicy, jws, 384);
|
|
5482
|
+
}
|
|
5483
|
+
function readKeyChain(paths) {
|
|
5484
|
+
try {
|
|
5485
|
+
const parsed = JSON.parse(readFileSync3(paths.userKeyChain, "utf-8"));
|
|
5486
|
+
return Array.isArray(parsed) ? parsed.filter((j) => typeof j === "string") : [];
|
|
5487
|
+
} catch {
|
|
5488
|
+
return [];
|
|
5489
|
+
}
|
|
5490
|
+
}
|
|
5491
|
+
function writeKeyChain(paths, chain) {
|
|
5492
|
+
writeFileMode(paths.userKeyChain, JSON.stringify(chain), 384);
|
|
5493
|
+
}
|
|
5494
|
+
function readState(paths) {
|
|
5495
|
+
try {
|
|
5496
|
+
const parsed = JSON.parse(readFileSync3(paths.state, "utf-8"));
|
|
5497
|
+
const c = parsed.counts;
|
|
5498
|
+
return {
|
|
5499
|
+
...parsed,
|
|
5500
|
+
counts: { allow: c?.allow ?? 0, deny: c?.deny ?? 0, ask: c?.ask ?? 0 }
|
|
5501
|
+
};
|
|
5502
|
+
} catch {
|
|
5503
|
+
return { counts: { allow: 0, deny: 0, ask: 0 } };
|
|
5504
|
+
}
|
|
5505
|
+
}
|
|
5506
|
+
function writeState(paths, state) {
|
|
5507
|
+
try {
|
|
5508
|
+
writeFileMode(paths.state, JSON.stringify(state, null, 2), 384);
|
|
5509
|
+
} catch {
|
|
5510
|
+
}
|
|
5511
|
+
}
|
|
5512
|
+
|
|
5513
|
+
// src/claude-code/guard-config.ts
|
|
5514
|
+
var FLEET_ENROL_INSTRUCTION = "This machine must be enrolled: run `astrasync guard enroll <token>` (token from your organisation admin)";
|
|
5515
|
+
function resolveFleet(env, home = homedir2(), paths = fleetPaths({ home, env })) {
|
|
5516
|
+
const loaded = loadEnrolment(paths);
|
|
5517
|
+
if (loaded && "corrupt" in loaded) {
|
|
5518
|
+
return {
|
|
5519
|
+
kind: "fleet-missing",
|
|
5520
|
+
reason: `fleet enrolment at ${loaded.path} is unreadable \u2014 ${FLEET_ENROL_INSTRUCTION}`,
|
|
5521
|
+
paths
|
|
5522
|
+
};
|
|
5523
|
+
}
|
|
5524
|
+
if (loaded) return { kind: "fleet", enrolment: loaded.enrolment, scope: loaded.scope, paths };
|
|
5525
|
+
if (env.ASTRASYNC_FLEET_REQUIRED === "1") {
|
|
5526
|
+
return { kind: "fleet-missing", reason: FLEET_ENROL_INSTRUCTION, paths };
|
|
5527
|
+
}
|
|
5528
|
+
return null;
|
|
5529
|
+
}
|
|
5530
|
+
|
|
5531
|
+
// src/fleet/client.ts
|
|
5532
|
+
var FleetApiError = class extends Error {
|
|
5533
|
+
constructor(message, status, code) {
|
|
5534
|
+
super(message);
|
|
5535
|
+
this.status = status;
|
|
5536
|
+
this.code = code;
|
|
5537
|
+
this.name = "FleetApiError";
|
|
5538
|
+
}
|
|
5539
|
+
};
|
|
5540
|
+
function base(url) {
|
|
5541
|
+
return url.replace(/\/+$/, "");
|
|
5542
|
+
}
|
|
5543
|
+
async function call(url, init, timeoutMs) {
|
|
5544
|
+
const controller = new AbortController();
|
|
5545
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
5546
|
+
try {
|
|
5547
|
+
const res = await sdkFetch(url, { ...init, signal: controller.signal });
|
|
5548
|
+
const text = await res.text();
|
|
5549
|
+
let body = text;
|
|
5550
|
+
try {
|
|
5551
|
+
body = text ? JSON.parse(text) : null;
|
|
5552
|
+
} catch {
|
|
5553
|
+
}
|
|
5554
|
+
return { status: res.status, body, headers: res.headers };
|
|
5555
|
+
} finally {
|
|
5556
|
+
clearTimeout(timer);
|
|
5557
|
+
}
|
|
5558
|
+
}
|
|
5559
|
+
function apiError(status, body, what) {
|
|
5560
|
+
const b = body ?? {};
|
|
5561
|
+
const code = b.code ?? (typeof b.error === "string" ? b.error : void 0);
|
|
5562
|
+
return new FleetApiError(`${what} failed (${status}${code ? ` ${code}` : ""})`, status, code);
|
|
5563
|
+
}
|
|
5564
|
+
function deviceHeaders(enrolment) {
|
|
5565
|
+
return { Authorization: `Device ${enrolment.credential}` };
|
|
5566
|
+
}
|
|
5567
|
+
function policyEtag(sha256, kid) {
|
|
5568
|
+
return `${sha256}.${kid ?? ""}`;
|
|
5569
|
+
}
|
|
5570
|
+
async function fetchFleetPolicy(enrolment, ifNoneMatch, timeoutMs = 1500) {
|
|
5571
|
+
const headers = deviceHeaders(enrolment);
|
|
5572
|
+
if (ifNoneMatch) headers["If-None-Match"] = `"${ifNoneMatch}"`;
|
|
5573
|
+
const r = await call(`${base(enrolment.apiBaseUrl)}/fleet/policy`, { headers }, timeoutMs);
|
|
5574
|
+
if (r.status === 304) return { status: "unchanged" };
|
|
5575
|
+
if (r.status !== 200) throw apiError(r.status, r.body, "Policy fetch");
|
|
5576
|
+
const data = r.body;
|
|
5577
|
+
if (!data?.policyJws) throw new FleetApiError("Policy response has no policyJws", r.status);
|
|
5578
|
+
return {
|
|
5579
|
+
status: "ok",
|
|
5580
|
+
policyJws: data.policyJws,
|
|
5581
|
+
sha256: data.sha256 ?? "",
|
|
5582
|
+
version: data.version ?? 0,
|
|
5583
|
+
keyChain: Array.isArray(data.keyChain) ? data.keyChain.filter((j) => typeof j === "string") : []
|
|
5584
|
+
};
|
|
5585
|
+
}
|
|
5586
|
+
async function sendHeartbeat(enrolment, request, timeoutMs = 1500) {
|
|
5587
|
+
const r = await call(
|
|
5588
|
+
`${base(enrolment.apiBaseUrl)}/fleet/heartbeat`,
|
|
5589
|
+
{
|
|
5590
|
+
method: "POST",
|
|
5591
|
+
headers: { ...deviceHeaders(enrolment), "Content-Type": "application/json" },
|
|
5592
|
+
body: JSON.stringify(request)
|
|
5593
|
+
},
|
|
5594
|
+
timeoutMs
|
|
5595
|
+
);
|
|
5596
|
+
if (r.status !== 200) throw apiError(r.status, r.body, "Heartbeat");
|
|
5597
|
+
return r.body;
|
|
5598
|
+
}
|
|
5599
|
+
|
|
5600
|
+
// src/fleet/policy-verify.ts
|
|
5601
|
+
import { createHash as createHash4 } from "crypto";
|
|
5602
|
+
import { compactVerify, createLocalJWKSet } from "jose";
|
|
5603
|
+
|
|
5604
|
+
// src/fleet/types.ts
|
|
5605
|
+
var FLEET_POLICY_TYP = "fleet-policy+jwt";
|
|
5606
|
+
var FLEET_POLICY_AUD = "astrasync:fleet-policy";
|
|
5607
|
+
var FLEET_POLICY_ISS = "astrasync.ai";
|
|
5608
|
+
var FLEET_KEYS_TYP = "fleet-keys+jwt";
|
|
5609
|
+
var FLEET_KEYS_AUD = "astrasync:fleet-keys";
|
|
5610
|
+
var DEFAULT_HEARTBEAT_INTERVAL_SEC = 900;
|
|
5611
|
+
|
|
5612
|
+
// src/fleet/policy-verify.ts
|
|
5613
|
+
var FleetPolicyError = class extends Error {
|
|
5614
|
+
constructor(message) {
|
|
5615
|
+
super(message);
|
|
5616
|
+
this.name = "FleetPolicyError";
|
|
5617
|
+
}
|
|
5618
|
+
};
|
|
5619
|
+
function sha256Hex(text) {
|
|
5620
|
+
return createHash4("sha256").update(text, "utf8").digest("hex");
|
|
5621
|
+
}
|
|
5622
|
+
function parseSettings(raw) {
|
|
5623
|
+
if (!raw || typeof raw !== "object") throw new FleetPolicyError("settings missing");
|
|
5624
|
+
const s = raw;
|
|
5625
|
+
if (s.posture !== "active" && s.posture !== "passive") {
|
|
5626
|
+
throw new FleetPolicyError("settings.posture must be active or passive");
|
|
5627
|
+
}
|
|
5628
|
+
if (s.failOpen !== void 0 && typeof s.failOpen !== "boolean") {
|
|
5629
|
+
throw new FleetPolicyError("settings.failOpen must be a boolean");
|
|
5630
|
+
}
|
|
5631
|
+
if (s.governMcp !== void 0 && typeof s.governMcp !== "boolean") {
|
|
5632
|
+
throw new FleetPolicyError("settings.governMcp must be a boolean");
|
|
5633
|
+
}
|
|
5634
|
+
if (s.skipTools !== void 0 && !(Array.isArray(s.skipTools) && s.skipTools.every((t) => typeof t === "string"))) {
|
|
5635
|
+
throw new FleetPolicyError("settings.skipTools must be a string array");
|
|
5636
|
+
}
|
|
5637
|
+
const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
|
|
5638
|
+
return {
|
|
5639
|
+
posture: s.posture,
|
|
5640
|
+
failOpen: s.failOpen === true,
|
|
5641
|
+
...typeof s.governMcp === "boolean" && { governMcp: s.governMcp },
|
|
5642
|
+
...Array.isArray(s.skipTools) && { skipTools: s.skipTools },
|
|
5643
|
+
...num(s.heartbeatIntervalSec) && { heartbeatIntervalSec: num(s.heartbeatIntervalSec) },
|
|
5644
|
+
...num(s.staleAfterSec) && { staleAfterSec: num(s.staleAfterSec) }
|
|
5645
|
+
};
|
|
5646
|
+
}
|
|
5647
|
+
async function verifyFleetPolicy(jws, jwks, options) {
|
|
5648
|
+
let payloadBytes;
|
|
5649
|
+
let header;
|
|
5650
|
+
try {
|
|
5651
|
+
const keySet = createLocalJWKSet(jwks);
|
|
5652
|
+
const result = await compactVerify(jws, keySet, { algorithms: ["ES256"] });
|
|
5653
|
+
payloadBytes = result.payload;
|
|
5654
|
+
header = result.protectedHeader;
|
|
5655
|
+
} catch (err) {
|
|
5656
|
+
throw new FleetPolicyError(
|
|
5657
|
+
`signature verification failed (${err instanceof Error ? err.message : String(err)})`
|
|
5658
|
+
);
|
|
5659
|
+
}
|
|
5660
|
+
if (header.typ !== FLEET_POLICY_TYP) throw new FleetPolicyError(`unexpected typ ${header.typ}`);
|
|
5661
|
+
let claims;
|
|
5662
|
+
try {
|
|
5663
|
+
claims = JSON.parse(new TextDecoder().decode(payloadBytes));
|
|
5664
|
+
} catch {
|
|
5665
|
+
throw new FleetPolicyError("payload is not JSON");
|
|
5666
|
+
}
|
|
5667
|
+
if (claims.aud !== FLEET_POLICY_AUD) throw new FleetPolicyError(`unexpected aud ${claims.aud}`);
|
|
5668
|
+
if (claims.iss !== FLEET_POLICY_ISS) throw new FleetPolicyError(`unexpected iss ${claims.iss}`);
|
|
5669
|
+
if (!options.expectedSubs.includes(claims.sub)) {
|
|
5670
|
+
throw new FleetPolicyError("policy was issued for a different organisation or device");
|
|
5671
|
+
}
|
|
5672
|
+
if (!Number.isInteger(claims.ver) || claims.ver < 1) {
|
|
5673
|
+
throw new FleetPolicyError("ver must be a positive integer");
|
|
5674
|
+
}
|
|
5675
|
+
if (options.minVer !== void 0 && claims.ver < options.minVer) {
|
|
5676
|
+
throw new FleetPolicyError(
|
|
5677
|
+
`policy version ${claims.ver} is older than the accepted version ${options.minVer} (rollback)`
|
|
5678
|
+
);
|
|
5679
|
+
}
|
|
5680
|
+
if (typeof claims.yaml !== "string" || sha256Hex(claims.yaml) !== claims.sha256) {
|
|
5681
|
+
throw new FleetPolicyError("policy hash mismatch");
|
|
5682
|
+
}
|
|
5683
|
+
const settings = parseSettings(claims.settings);
|
|
5684
|
+
const parsed = parseYaml(claims.yaml);
|
|
5685
|
+
if (!parsed.policy) {
|
|
5686
|
+
const first = parsed.validation.errors[0];
|
|
5687
|
+
throw new FleetPolicyError(
|
|
5688
|
+
`signed policy is invalid${first ? ` (${first.path}: ${first.message})` : ""}`
|
|
5689
|
+
);
|
|
5690
|
+
}
|
|
5691
|
+
return { kid: header.kid, claims: { ...claims, settings }, policy: parsed.policy, settings, jws };
|
|
5692
|
+
}
|
|
5693
|
+
async function resolveFleetJwks(pinned, chain, ownerId) {
|
|
5694
|
+
let trusted = pinned;
|
|
5695
|
+
let lastSeq = 0;
|
|
5696
|
+
for (const link of chain) {
|
|
5697
|
+
try {
|
|
5698
|
+
const { payload, protectedHeader } = await compactVerify(
|
|
5699
|
+
link,
|
|
5700
|
+
createLocalJWKSet(trusted),
|
|
5701
|
+
{ algorithms: ["ES256"] }
|
|
5702
|
+
);
|
|
5703
|
+
if (protectedHeader.typ !== FLEET_KEYS_TYP) continue;
|
|
5704
|
+
const c = JSON.parse(new TextDecoder().decode(payload));
|
|
5705
|
+
if (c.aud !== FLEET_KEYS_AUD || c.iss !== FLEET_POLICY_ISS || c.sub !== ownerId) continue;
|
|
5706
|
+
if (!Number.isInteger(c.seq) || c.seq <= lastSeq) continue;
|
|
5707
|
+
const keys = Array.isArray(c.keys) ? c.keys.filter((k) => k && k.kty === "EC" && k.crv === "P-256" && !("d" in k)) : [];
|
|
5708
|
+
if (keys.length === 0) continue;
|
|
5709
|
+
trusted = { keys };
|
|
5710
|
+
lastSeq = c.seq;
|
|
5711
|
+
} catch {
|
|
5712
|
+
}
|
|
5713
|
+
}
|
|
5714
|
+
return trusted;
|
|
5715
|
+
}
|
|
5716
|
+
async function pickNewestValid(candidates, jwks, options) {
|
|
5717
|
+
let best = null;
|
|
5718
|
+
let lastError = new FleetPolicyError("no cached fleet policy");
|
|
5719
|
+
for (const jws of candidates) {
|
|
5720
|
+
try {
|
|
5721
|
+
const v = await verifyFleetPolicy(jws, jwks, options);
|
|
5722
|
+
if (!best || v.claims.ver > best.claims.ver) best = v;
|
|
5723
|
+
} catch (err) {
|
|
5724
|
+
lastError = err instanceof Error ? err : new FleetPolicyError(String(err));
|
|
5725
|
+
}
|
|
5726
|
+
}
|
|
5727
|
+
if (!best) throw lastError;
|
|
5728
|
+
return best;
|
|
5729
|
+
}
|
|
5730
|
+
|
|
5731
|
+
// src/fleet/runtime.ts
|
|
5732
|
+
var FLEET_SYNC_BUDGET_MS = 1500;
|
|
5733
|
+
function expectedSubs(enrolment) {
|
|
5734
|
+
return [enrolment.org.ownerId, enrolment.deviceId];
|
|
5735
|
+
}
|
|
5736
|
+
function fleetJwks(ctx, chain = readKeyChain(ctx.paths)) {
|
|
5737
|
+
return resolveFleetJwks(ctx.enrolment.jwks, chain, ctx.enrolment.org.ownerId);
|
|
5738
|
+
}
|
|
5739
|
+
async function acceptFetched(ctx, fetched, verifyOpts) {
|
|
5740
|
+
const jwks = await fleetJwks(ctx, fetched.keyChain);
|
|
5741
|
+
const verified = await verifyFleetPolicy(fetched.policyJws, jwks, verifyOpts);
|
|
5742
|
+
if (fetched.keyChain.length > 0) writeKeyChain(ctx.paths, fetched.keyChain);
|
|
5743
|
+
writeCachedPolicy(ctx.paths, fetched.policyJws);
|
|
5744
|
+
return verified;
|
|
5745
|
+
}
|
|
5746
|
+
function remember(paths, state, verified) {
|
|
5747
|
+
state.appliedSha256 = verified.claims.sha256;
|
|
5748
|
+
state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
|
|
5749
|
+
writeState(paths, state);
|
|
5750
|
+
}
|
|
5751
|
+
async function loadFleetPolicy(ctx, options = {}) {
|
|
5752
|
+
const state = readState(ctx.paths);
|
|
5753
|
+
const verifyOpts = { expectedSubs: expectedSubs(ctx.enrolment), minVer: state.maxVer };
|
|
5754
|
+
const cached = readCachedPolicies(ctx.paths);
|
|
5755
|
+
let cacheError = null;
|
|
5756
|
+
if (cached.length > 0) {
|
|
5757
|
+
try {
|
|
5758
|
+
const verified = await pickNewestValid(cached, await fleetJwks(ctx), verifyOpts);
|
|
5759
|
+
if (verified.claims.sha256 !== state.appliedSha256 || verified.claims.ver !== state.maxVer) {
|
|
5760
|
+
remember(ctx.paths, state, verified);
|
|
5761
|
+
}
|
|
5762
|
+
return verified;
|
|
5763
|
+
} catch (err) {
|
|
5764
|
+
cacheError = err instanceof Error ? err : new FleetPolicyError(String(err));
|
|
5765
|
+
}
|
|
5766
|
+
}
|
|
5767
|
+
try {
|
|
5768
|
+
const fetched = await fetchFleetPolicy(
|
|
5769
|
+
ctx.enrolment,
|
|
5770
|
+
null,
|
|
5771
|
+
options.fetchTimeoutMs ?? FLEET_SYNC_BUDGET_MS
|
|
5772
|
+
);
|
|
5773
|
+
if (fetched.status === "ok") {
|
|
5774
|
+
const verified = await acceptFetched(ctx, fetched, verifyOpts);
|
|
5775
|
+
remember(ctx.paths, state, verified);
|
|
5776
|
+
return verified;
|
|
5777
|
+
}
|
|
5778
|
+
} catch (err) {
|
|
5779
|
+
if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
|
|
5780
|
+
state.revoked = true;
|
|
5781
|
+
writeState(ctx.paths, state);
|
|
5782
|
+
}
|
|
5783
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
5784
|
+
throw new FleetPolicyError(
|
|
5785
|
+
cacheError ? `${cacheError.message}; refresh failed (${detail})` : `no fleet policy (${detail})`
|
|
5786
|
+
);
|
|
5787
|
+
}
|
|
5788
|
+
throw cacheError ?? new FleetPolicyError("no fleet policy available");
|
|
5789
|
+
}
|
|
5790
|
+
async function recordDecisionAndHeartbeat(ctx, applied, decision, options) {
|
|
5791
|
+
const now = options.now ?? Date.now;
|
|
5792
|
+
const state = readState(ctx.paths);
|
|
5793
|
+
if (decision) state.counts[decision] += 1;
|
|
5794
|
+
const intervalSec = applied.settings.heartbeatIntervalSec ?? ctx.enrolment.heartbeatIntervalSec ?? DEFAULT_HEARTBEAT_INTERVAL_SEC;
|
|
5795
|
+
const last = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : 0;
|
|
5796
|
+
if (now() - last < intervalSec * 1e3) {
|
|
5797
|
+
writeState(ctx.paths, state);
|
|
5798
|
+
return "throttled";
|
|
5799
|
+
}
|
|
5800
|
+
const deadline = now() + (options.budgetMs ?? FLEET_SYNC_BUDGET_MS);
|
|
5801
|
+
const remaining = () => Math.max(1, deadline - now());
|
|
5802
|
+
state.lastHeartbeatAt = new Date(now()).toISOString();
|
|
5803
|
+
let outcome = "sent";
|
|
5804
|
+
try {
|
|
5805
|
+
const hb = await sendHeartbeat(
|
|
5806
|
+
ctx.enrolment,
|
|
5807
|
+
{
|
|
5808
|
+
appliedSha256: applied.claims.sha256,
|
|
5809
|
+
guardVersion: options.guardVersion,
|
|
5810
|
+
adapters: [{ kind: options.adapterKind, managed: true }],
|
|
5811
|
+
posture: applied.settings.posture,
|
|
5812
|
+
decisionCounts: { ...state.counts }
|
|
5813
|
+
},
|
|
5814
|
+
remaining()
|
|
5815
|
+
);
|
|
5816
|
+
state.counts = { allow: 0, deny: 0, ask: 0 };
|
|
5817
|
+
state.revoked = false;
|
|
5818
|
+
delete state.lastError;
|
|
5819
|
+
const policyChanged = !!hb.activeSha256 && hb.activeSha256 !== applied.claims.sha256;
|
|
5820
|
+
const keyChanged = !!hb.activeKid && !!applied.kid && hb.activeKid !== applied.kid;
|
|
5821
|
+
if (policyChanged || keyChanged) {
|
|
5822
|
+
const fetched = await fetchFleetPolicy(
|
|
5823
|
+
ctx.enrolment,
|
|
5824
|
+
policyEtag(applied.claims.sha256, applied.kid),
|
|
5825
|
+
remaining()
|
|
5826
|
+
);
|
|
5827
|
+
if (fetched.status === "ok") {
|
|
5828
|
+
const verified = await acceptFetched(ctx, fetched, {
|
|
5829
|
+
expectedSubs: expectedSubs(ctx.enrolment),
|
|
5830
|
+
minVer: Math.max(state.maxVer ?? 0, applied.claims.ver)
|
|
5831
|
+
});
|
|
5832
|
+
state.appliedSha256 = verified.claims.sha256;
|
|
5833
|
+
state.maxVer = Math.max(state.maxVer ?? 0, verified.claims.ver);
|
|
5834
|
+
outcome = "refreshed";
|
|
5835
|
+
}
|
|
5836
|
+
}
|
|
5837
|
+
} catch (err) {
|
|
5838
|
+
if (err instanceof FleetApiError && err.code === "DEVICE_REVOKED") {
|
|
5839
|
+
state.revoked = true;
|
|
5840
|
+
outcome = "revoked";
|
|
5841
|
+
} else {
|
|
5842
|
+
state.lastError = err instanceof Error ? err.message : String(err);
|
|
5843
|
+
outcome = "failed";
|
|
5844
|
+
}
|
|
5845
|
+
}
|
|
5846
|
+
writeState(ctx.paths, state);
|
|
5847
|
+
return outcome;
|
|
5848
|
+
}
|
|
5849
|
+
|
|
5135
5850
|
// src/cursor/extension.ts
|
|
5136
5851
|
var adapter = null;
|
|
5137
5852
|
var gateway = null;
|
|
5138
|
-
async function activate(vscodeApi) {
|
|
5139
|
-
const config = loadConfiguration();
|
|
5853
|
+
async function activate(vscodeApi, options = {}) {
|
|
5854
|
+
const config = await loadConfiguration(options);
|
|
5140
5855
|
gateway = new AstraSyncGateway(config.gatewayConfig);
|
|
5141
5856
|
adapter = new CursorAdapter({
|
|
5142
5857
|
vscode: vscodeApi,
|
|
@@ -5159,10 +5874,18 @@ Action: ${context.action} \u2192 ${context.target}`,
|
|
|
5159
5874
|
const channel = vscodeApi.window.createOutputChannel("AstraSync Policy");
|
|
5160
5875
|
channel.appendLine(`Mode: ${gateway.mode}`);
|
|
5161
5876
|
channel.appendLine(`Posture: ${gateway.posture}`);
|
|
5162
|
-
channel.appendLine(
|
|
5877
|
+
channel.appendLine(
|
|
5878
|
+
config.fleetManaged ? `Policy: organisation fleet policy (${config.fleetManaged})` : `Policy file: ${config.gatewayConfig.policyFile || "(inline/none)"}`
|
|
5879
|
+
);
|
|
5163
5880
|
channel.show();
|
|
5164
5881
|
});
|
|
5165
5882
|
vscodeApi.commands.registerCommand("astrasync.switchMode", async () => {
|
|
5883
|
+
if (config.fleetManaged) {
|
|
5884
|
+
vscodeApi.window.showInformationMessage(
|
|
5885
|
+
"AstraSync: this machine is governed by your organisation\u2019s fleet policy \u2014 mode is managed centrally."
|
|
5886
|
+
);
|
|
5887
|
+
return;
|
|
5888
|
+
}
|
|
5166
5889
|
if (!config.gatewayConfig.apiKey) {
|
|
5167
5890
|
vscodeApi.window.showInformationMessage(
|
|
5168
5891
|
"AstraSync: Set astrasync.apiKey in settings to enable online/hybrid mode."
|
|
@@ -5192,7 +5915,62 @@ async function deactivate() {
|
|
|
5192
5915
|
gateway = null;
|
|
5193
5916
|
}
|
|
5194
5917
|
}
|
|
5195
|
-
function
|
|
5918
|
+
function fleetLockdownPolicy() {
|
|
5919
|
+
return {
|
|
5920
|
+
version: "1.0",
|
|
5921
|
+
name: "fleet-enrolment-required",
|
|
5922
|
+
purposes: [
|
|
5923
|
+
"file.read",
|
|
5924
|
+
"file.write",
|
|
5925
|
+
"file.delete",
|
|
5926
|
+
"shell.exec",
|
|
5927
|
+
"network.fetch",
|
|
5928
|
+
"payment.execute",
|
|
5929
|
+
"email.send"
|
|
5930
|
+
].map((id) => ({ id, allowed: false }))
|
|
5931
|
+
};
|
|
5932
|
+
}
|
|
5933
|
+
async function loadConfiguration(options) {
|
|
5934
|
+
const env = options.env ?? process.env;
|
|
5935
|
+
const fleet = resolveFleet(env, options.home ?? homedir3(), options.fleetPaths);
|
|
5936
|
+
if (fleet?.kind === "fleet") {
|
|
5937
|
+
const ctx = { enrolment: fleet.enrolment, paths: fleet.paths };
|
|
5938
|
+
try {
|
|
5939
|
+
const verified = await loadFleetPolicy(ctx);
|
|
5940
|
+
void recordDecisionAndHeartbeat(ctx, verified, null, {
|
|
5941
|
+
guardVersion: SDK_VERSION,
|
|
5942
|
+
adapterKind: "cursor"
|
|
5943
|
+
}).catch(() => void 0);
|
|
5944
|
+
return {
|
|
5945
|
+
fleetManaged: `${fleet.enrolment.org.name ?? fleet.enrolment.org.ownerId} v${verified.claims.ver}`,
|
|
5946
|
+
gatewayConfig: {
|
|
5947
|
+
mode: "local",
|
|
5948
|
+
policy: verified.policy,
|
|
5949
|
+
posture: verified.settings.posture,
|
|
5950
|
+
traceEnabled: true,
|
|
5951
|
+
tracePath: join3(fleet.paths.userDir, "traces"),
|
|
5952
|
+
debug: false
|
|
5953
|
+
}
|
|
5954
|
+
};
|
|
5955
|
+
} catch {
|
|
5956
|
+
}
|
|
5957
|
+
}
|
|
5958
|
+
if (fleet) {
|
|
5959
|
+
return {
|
|
5960
|
+
fleetManaged: "unavailable \u2014 enrol this machine with `astrasync guard enroll <token>`",
|
|
5961
|
+
gatewayConfig: {
|
|
5962
|
+
mode: "local",
|
|
5963
|
+
policy: fleetLockdownPolicy(),
|
|
5964
|
+
posture: "active",
|
|
5965
|
+
traceEnabled: true,
|
|
5966
|
+
tracePath: join3(fleet.paths.userDir, "traces"),
|
|
5967
|
+
debug: false
|
|
5968
|
+
}
|
|
5969
|
+
};
|
|
5970
|
+
}
|
|
5971
|
+
return loadLocalConfiguration();
|
|
5972
|
+
}
|
|
5973
|
+
function loadLocalConfiguration() {
|
|
5196
5974
|
return {
|
|
5197
5975
|
gatewayConfig: {
|
|
5198
5976
|
mode: "local",
|