@astrasyncai/verification-gateway 2.4.6 → 2.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/adapters/express.js +1 -1
  2. package/dist/adapters/express.js.map +1 -1
  3. package/dist/adapters/express.mjs +1 -1
  4. package/dist/adapters/express.mjs.map +1 -1
  5. package/dist/adapters/mcp.js +1 -1
  6. package/dist/adapters/mcp.js.map +1 -1
  7. package/dist/adapters/mcp.mjs +1 -1
  8. package/dist/adapters/mcp.mjs.map +1 -1
  9. package/dist/adapters/nextjs.js +1 -1
  10. package/dist/adapters/nextjs.js.map +1 -1
  11. package/dist/adapters/nextjs.mjs +1 -1
  12. package/dist/adapters/nextjs.mjs.map +1 -1
  13. package/dist/adapters/sdk.js +1 -1
  14. package/dist/adapters/sdk.js.map +1 -1
  15. package/dist/adapters/sdk.mjs +1 -1
  16. package/dist/adapters/sdk.mjs.map +1 -1
  17. package/dist/browser/background.js +1 -1
  18. package/dist/browser/background.js.map +1 -1
  19. package/dist/browser/background.mjs +1 -1
  20. package/dist/browser/background.mjs.map +1 -1
  21. package/dist/cursor/extension.js +1 -1
  22. package/dist/cursor/extension.js.map +1 -1
  23. package/dist/cursor/extension.mjs +1 -1
  24. package/dist/cursor/extension.mjs.map +1 -1
  25. package/dist/gateway/gateway.js +1 -1
  26. package/dist/gateway/gateway.js.map +1 -1
  27. package/dist/gateway/gateway.mjs +1 -1
  28. package/dist/gateway/gateway.mjs.map +1 -1
  29. package/dist/{index-Bstl43HI.d.ts → index-WL4d9e9_.d.ts} +1 -1
  30. package/dist/{index-TS4SGvf4.d.mts → index-ZkHvXsMo.d.mts} +1 -1
  31. package/dist/index.d.mts +3 -1
  32. package/dist/index.d.ts +3 -1
  33. package/dist/index.js +716 -1
  34. package/dist/index.js.map +1 -1
  35. package/dist/index.mjs +706 -1
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/transport/index.d.mts +1 -1
  38. package/dist/transport/index.d.ts +1 -1
  39. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -126,7 +126,7 @@ function getCapabilities(accessLevel) {
126
126
  }
127
127
 
128
128
  // src/version.ts
129
- var SDK_VERSION = "2.4.6";
129
+ var SDK_VERSION = "2.4.7";
130
130
 
131
131
  // src/verify.ts
132
132
  var DEFAULT_CONFIG = {
@@ -513,6 +513,26 @@ async function recordDecision(config, sessionId, decision, reason, override) {
513
513
  }).catch(() => {
514
514
  });
515
515
  }
516
+ async function recordAnonymousLocalOverride(config, correlationId, override, reason) {
517
+ const headers = { "Content-Type": "application/json" };
518
+ if (config.apiKey) {
519
+ headers["Authorization"] = `Bearer ${config.apiKey}`;
520
+ headers["X-API-Key"] = config.apiKey;
521
+ }
522
+ await fetch(`${config.apiBaseUrl}/agents/verify-access/local-override`, {
523
+ method: "POST",
524
+ headers,
525
+ body: JSON.stringify({
526
+ correlationId,
527
+ reason,
528
+ overriddenBy: override.overriddenBy,
529
+ toolName: override.toolName,
530
+ requestedLevel: override.requestedLevel,
531
+ grantedLevel: override.grantedLevel
532
+ })
533
+ }).catch(() => {
534
+ });
535
+ }
516
536
  async function fetchRoutes(config, counterpartyId) {
517
537
  if (!counterpartyId) return null;
518
538
  const headers = { "Content-Type": "application/json" };
@@ -3900,6 +3920,681 @@ function extractCredentialsFromProtocol(protocol, context) {
3900
3920
  }
3901
3921
  }
3902
3922
 
3923
+ // src/transport/mcp-server.ts
3924
+ var MCP_VERIFIED_HOP_HEADER = "X-Astra-Verified-Hop";
3925
+ var MCP_VERIFIED_HOP_MAX_AGE_MS = 6e4;
3926
+ function serializeVerifiedHop(marker) {
3927
+ return `${marker.astraId};${marker.sessionId ?? ""};${marker.checkedAt}`;
3928
+ }
3929
+ function parseVerifiedHop(value) {
3930
+ if (!value) return null;
3931
+ const parts = value.split(";");
3932
+ if (parts.length !== 3) return null;
3933
+ const [astraId, sessionId, checkedAtRaw] = parts;
3934
+ if (!astraId) return null;
3935
+ const checkedAt = Number(checkedAtRaw);
3936
+ if (!Number.isFinite(checkedAt) || checkedAt <= 0) return null;
3937
+ return {
3938
+ astraId,
3939
+ ...sessionId ? { sessionId } : {},
3940
+ checkedAt
3941
+ };
3942
+ }
3943
+ function isVerifiedHopValidFor(marker, expectedAstraId, opts = {}) {
3944
+ if (!marker) return false;
3945
+ if (marker.astraId !== expectedAstraId) return false;
3946
+ const maxAge = opts.maxAgeMs ?? MCP_VERIFIED_HOP_MAX_AGE_MS;
3947
+ const now = opts.now ?? Date.now();
3948
+ return now - marker.checkedAt <= maxAge && now >= marker.checkedAt;
3949
+ }
3950
+ function parseMcpJsonRpc(body) {
3951
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
3952
+ const obj = body;
3953
+ if (obj.jsonrpc !== "2.0" && obj.jsonrpc !== "1.0") return null;
3954
+ const method = typeof obj.method === "string" ? obj.method : null;
3955
+ if (!method) return null;
3956
+ const params = obj.params;
3957
+ let toolName;
3958
+ if (method === "tools/call" && params && typeof params.name === "string") {
3959
+ toolName = params.name;
3960
+ }
3961
+ let protocolVersion;
3962
+ if (method === "initialize" && params && typeof params.protocolVersion === "string") {
3963
+ protocolVersion = params.protocolVersion;
3964
+ }
3965
+ const meta = params?._meta;
3966
+ const astrasyncMeta = meta?.astrasync;
3967
+ const args = params?.arguments;
3968
+ let agentIdFromBody;
3969
+ if (astrasyncMeta && typeof astrasyncMeta.agentId === "string") {
3970
+ agentIdFromBody = astrasyncMeta.agentId;
3971
+ } else if (args && typeof args.agent_id === "string") {
3972
+ agentIdFromBody = args.agent_id;
3973
+ }
3974
+ const purposeBodyResult = extractFromMcpBody(astrasyncMeta, args, "purpose");
3975
+ const actionBodyResult = extractFromMcpBody(astrasyncMeta, args, "action");
3976
+ const isInitialize = method === "initialize";
3977
+ const isToolCall = method === "tools/call";
3978
+ const isIntrospection = method === "tools/list" || method === "prompts/list" || method === "resources/list" || method === "ping" || method === "notifications/initialized";
3979
+ return {
3980
+ method,
3981
+ ...toolName ? { toolName } : {},
3982
+ ...protocolVersion ? { protocolVersion } : {},
3983
+ ...agentIdFromBody ? { agentIdFromBody } : {},
3984
+ ...purposeBodyResult.value ? { purposeFromBody: purposeBodyResult.value } : {},
3985
+ ...purposeBodyResult.source ? { purposeSourceFromBody: purposeBodyResult.source } : {},
3986
+ ...actionBodyResult.value ? { actionFromBody: actionBodyResult.value } : {},
3987
+ ...actionBodyResult.source ? { actionSourceFromBody: actionBodyResult.source } : {},
3988
+ isInitialize,
3989
+ isToolCall,
3990
+ isIntrospection
3991
+ };
3992
+ }
3993
+ function extractFromMcpBody(astrasyncMeta, args, key) {
3994
+ if (astrasyncMeta && typeof astrasyncMeta[key] === "string") {
3995
+ return { value: astrasyncMeta[key], source: "meta" };
3996
+ }
3997
+ if (args && typeof args[key] === "string") {
3998
+ return { value: args[key], source: "tool_argument" };
3999
+ }
4000
+ return { value: void 0, source: void 0 };
4001
+ }
4002
+ function mcpToPdlss(parsed, headerPurpose, headerAction) {
4003
+ const resource = parsed.toolName ? `mcp:tool/${parsed.toolName}` : `mcp:method/${parsed.method}`;
4004
+ let purpose;
4005
+ let purposeSource;
4006
+ if (headerPurpose) {
4007
+ purpose = headerPurpose;
4008
+ purposeSource = "header";
4009
+ } else if (parsed.purposeFromBody && parsed.purposeSourceFromBody) {
4010
+ purpose = parsed.purposeFromBody;
4011
+ purposeSource = parsed.purposeSourceFromBody;
4012
+ } else {
4013
+ purpose = "mcp_invoke";
4014
+ purposeSource = "default_mcp_invoke";
4015
+ }
4016
+ let action;
4017
+ let actionSource;
4018
+ if (headerAction) {
4019
+ action = headerAction;
4020
+ actionSource = "header";
4021
+ } else if (parsed.actionFromBody && parsed.actionSourceFromBody) {
4022
+ action = parsed.actionFromBody;
4023
+ actionSource = parsed.actionSourceFromBody;
4024
+ } else {
4025
+ action = parsed.toolName ? `${parsed.method}:${parsed.toolName}` : parsed.method;
4026
+ actionSource = "transport_layer";
4027
+ }
4028
+ return { purpose, action, resource, purposeSource, actionSource };
4029
+ }
4030
+ function mcpRiskTier(parsed) {
4031
+ if (parsed.isInitialize || parsed.method === "notifications/initialized") return "none";
4032
+ if (parsed.isIntrospection) return "none";
4033
+ if (parsed.method === "resources/read") return "read-only";
4034
+ if (parsed.isToolCall) return "standard";
4035
+ return "standard";
4036
+ }
4037
+
4038
+ // src/adapters/mcp.ts
4039
+ function readSingleHeader(value) {
4040
+ if (typeof value === "string") return value;
4041
+ if (Array.isArray(value)) return value[0];
4042
+ return void 0;
4043
+ }
4044
+ function defaultMcpDenied(result, req, res) {
4045
+ const id = req.body?.id ?? null;
4046
+ const status = result.verified ? 403 : 401;
4047
+ res.setHeader("X-Astra-Gateway-Mode", "enforced");
4048
+ res.status(status).json({
4049
+ jsonrpc: "2.0",
4050
+ id,
4051
+ error: {
4052
+ code: result.verified ? -32001 : -32e3,
4053
+ message: result.denialReasons?.[0] ?? "Access denied",
4054
+ data: {
4055
+ accessLevel: result.accessLevel,
4056
+ guidance: result.guidance,
4057
+ // Round-10: aggregated per-dimension detail + correlation handle.
4058
+ failures: result.failures,
4059
+ correlationId: result.correlationId
4060
+ }
4061
+ }
4062
+ });
4063
+ }
4064
+ function resolveMinAccessLevel(parsed, opts) {
4065
+ if (parsed.toolName && opts.toolGates && opts.toolGates[parsed.toolName] !== void 0) {
4066
+ return { level: opts.toolGates[parsed.toolName], source: "toolGate" };
4067
+ }
4068
+ if (opts.methodGates && opts.methodGates[parsed.method] !== void 0) {
4069
+ return { level: opts.methodGates[parsed.method], source: "methodGate" };
4070
+ }
4071
+ return { level: mcpRiskTier(parsed), source: "tier" };
4072
+ }
4073
+ function createMcpMiddleware(options) {
4074
+ const {
4075
+ toolGates,
4076
+ methodGates,
4077
+ onAgentIdMismatch = "reject",
4078
+ skip = false,
4079
+ onDenied = defaultMcpDenied,
4080
+ trustVerifiedHop = true,
4081
+ verifiedHopMaxAgeMs,
4082
+ recordDecisions,
4083
+ enableRuntimeChallenge = true,
4084
+ ...config
4085
+ } = options;
4086
+ return async (req, res, next) => {
4087
+ try {
4088
+ if (skip) return next();
4089
+ const parsed = parseMcpJsonRpc(req.body);
4090
+ if (!parsed) {
4091
+ if (config.setPassThroughHeader) {
4092
+ res.setHeader("X-Astra-Gateway-Mode", "unenforced");
4093
+ res.setHeader("X-Astra-Gateway-Reason", "non-jsonrpc-body");
4094
+ }
4095
+ return next();
4096
+ }
4097
+ req.mcpRequest = parsed;
4098
+ const headerRaw = req.headers["x-astra-id"] ?? req.headers["x-astra-agentid"];
4099
+ const headerAstraId = typeof headerRaw === "string" ? headerRaw : Array.isArray(headerRaw) ? headerRaw[0] : void 0;
4100
+ const bodyAstraId = parsed.agentIdFromBody;
4101
+ let effectiveAstraId;
4102
+ if (headerAstraId && bodyAstraId && headerAstraId !== bodyAstraId) {
4103
+ if (onAgentIdMismatch === "reject") {
4104
+ const id = req.body?.id ?? null;
4105
+ res.status(400).json({
4106
+ jsonrpc: "2.0",
4107
+ id,
4108
+ error: {
4109
+ code: -32602,
4110
+ message: "AGENT_ID_MISMATCH",
4111
+ data: {
4112
+ detail: "The agent id in the X-Astra-Id header disagrees with params._meta.astrasync.agentId / params.arguments.agent_id. Reconcile before calling the tool \u2014 see https://astrasync.ai/docs/mcp-integration#identity-reconciliation.",
4113
+ headerAstraId,
4114
+ bodyAstraId
4115
+ }
4116
+ }
4117
+ });
4118
+ return;
4119
+ }
4120
+ effectiveAstraId = onAgentIdMismatch === "prefer-header" ? headerAstraId : bodyAstraId;
4121
+ } else {
4122
+ effectiveAstraId = headerAstraId ?? bodyAstraId;
4123
+ }
4124
+ if (trustVerifiedHop && effectiveAstraId) {
4125
+ const hopRaw = req.headers[MCP_VERIFIED_HOP_HEADER.toLowerCase()];
4126
+ const hopValue = typeof hopRaw === "string" ? hopRaw : Array.isArray(hopRaw) ? hopRaw[0] : void 0;
4127
+ const marker = parseVerifiedHop(hopValue);
4128
+ if (isVerifiedHopValidFor(marker, effectiveAstraId, {
4129
+ ...verifiedHopMaxAgeMs !== void 0 ? { maxAgeMs: verifiedHopMaxAgeMs } : {}
4130
+ })) {
4131
+ return next();
4132
+ }
4133
+ }
4134
+ const { level: minAccessLevel, source: gateSource } = resolveMinAccessLevel(parsed, {
4135
+ toolGates,
4136
+ methodGates
4137
+ });
4138
+ const credentials = extractCredentials(
4139
+ req.headers,
4140
+ req.query
4141
+ );
4142
+ if (effectiveAstraId) credentials.astraId = effectiveAstraId;
4143
+ const shouldEnforce = minAccessLevel !== "none";
4144
+ if (minAccessLevel === "none" && (!config.evaluateAlwaysIfCredentialed || !credentials.astraId)) {
4145
+ if (config.setPassThroughHeader) {
4146
+ res.setHeader("X-Astra-Gateway-Mode", "unenforced");
4147
+ res.setHeader("X-Astra-Gateway-Reason", "mcp-tier-none");
4148
+ }
4149
+ return next();
4150
+ }
4151
+ const headerPurpose = readSingleHeader(req.headers["x-astra-purpose"]);
4152
+ const headerAction = readSingleHeader(req.headers["x-astra-action"]);
4153
+ const pdlss = mcpToPdlss(parsed, headerPurpose, headerAction);
4154
+ if (config.debug) {
4155
+ console.debug("[mcp-middleware] pdlss resolved", {
4156
+ purpose_source: pdlss.purposeSource,
4157
+ resolved_purpose: pdlss.purpose,
4158
+ action_source: pdlss.actionSource,
4159
+ resolved_action: pdlss.action
4160
+ });
4161
+ }
4162
+ const counterpartyUrl = config.counterpartyUrl || `${req.protocol}://${req.get("host")}${req.path}`;
4163
+ const shouldRecordDecisions = recordDecisions !== false;
4164
+ const result = await verify(config, {
4165
+ credentials,
4166
+ purpose: pdlss.purpose,
4167
+ action: pdlss.action,
4168
+ resource: pdlss.resource,
4169
+ // Round-12 (F19): mark transport protocol separately from intent.
4170
+ // The MCP middleware always sets this to 'mcp'; non-MCP callers
4171
+ // leave it unset (server-side default is 'rest').
4172
+ invocationProtocol: "mcp",
4173
+ createSession: shouldRecordDecisions,
4174
+ counterpartyUrl,
4175
+ counterpartyType: config.counterpartyType || "mcp_server",
4176
+ enableRuntimeChallenge,
4177
+ callerMetadata: {
4178
+ sourceIp: req.ip,
4179
+ userAgent: req.headers["user-agent"],
4180
+ host: req.headers.host
4181
+ }
4182
+ });
4183
+ req.agentVerification = result;
4184
+ const sessionId = result.sessionId;
4185
+ const correlationId = result.correlationId;
4186
+ if (!result.verified) {
4187
+ if (shouldRecordDecisions && sessionId) {
4188
+ recordDecision(config, sessionId, "denied", result.denialReasons?.[0]).catch(() => {
4189
+ });
4190
+ }
4191
+ onDenied(result, req, res);
4192
+ return;
4193
+ }
4194
+ if (!shouldEnforce) {
4195
+ if (config.setPassThroughHeader) {
4196
+ res.setHeader("X-Astra-Gateway-Mode", "enforced");
4197
+ res.setHeader("X-Astra-Gateway-Reason", "evaluated-not-enforced");
4198
+ }
4199
+ if (shouldRecordDecisions && sessionId) {
4200
+ recordDecision(config, sessionId, "granted").catch(() => {
4201
+ });
4202
+ }
4203
+ return next();
4204
+ }
4205
+ if (!hasMinimumAccess(result.accessLevel, minAccessLevel)) {
4206
+ const insufficientFailure = {
4207
+ dimension: "access_level.insufficient",
4208
+ message: `Tool requires accessLevel '${minAccessLevel}'; agent has '${result.accessLevel}'.`,
4209
+ guidance: "Request elevated access via step-up verification (coming soon \u2014 ships this month). Step-up lets the agent owner approve a one-time elevation for this specific counterparty + purpose without changing the agent's baseline trust score."
4210
+ };
4211
+ result.failures = [...result.failures ?? [], insufficientFailure];
4212
+ result.denialReasons = [...result.denialReasons ?? [], insufficientFailure.message];
4213
+ if (shouldRecordDecisions) {
4214
+ const overrideKind = gateSource === "toolGate" ? "toolGate" : gateSource === "methodGate" ? "methodGate" : "other";
4215
+ const override = {
4216
+ overriddenBy: overrideKind,
4217
+ ...parsed.toolName && { toolName: parsed.toolName },
4218
+ requestedLevel: minAccessLevel,
4219
+ grantedLevel: result.accessLevel
4220
+ };
4221
+ if (sessionId) {
4222
+ recordDecision(config, sessionId, "denied", result.denialReasons?.[0], override).catch(
4223
+ () => {
4224
+ }
4225
+ );
4226
+ } else if (correlationId) {
4227
+ recordAnonymousLocalOverride(
4228
+ config,
4229
+ correlationId,
4230
+ override,
4231
+ result.denialReasons?.[0]
4232
+ ).catch(() => {
4233
+ });
4234
+ }
4235
+ }
4236
+ onDenied(result, req, res);
4237
+ return;
4238
+ }
4239
+ if (effectiveAstraId) {
4240
+ res.setHeader(
4241
+ MCP_VERIFIED_HOP_HEADER,
4242
+ serializeVerifiedHop({
4243
+ astraId: effectiveAstraId,
4244
+ ...sessionId ? { sessionId } : {},
4245
+ checkedAt: Date.now()
4246
+ })
4247
+ );
4248
+ }
4249
+ if (shouldRecordDecisions && sessionId) {
4250
+ recordDecision(config, sessionId, "granted").catch(() => {
4251
+ });
4252
+ }
4253
+ const enhancedResult = result;
4254
+ if (enhancedResult.warningHeader) {
4255
+ res.setHeader(enhancedResult.warningHeader.name, enhancedResult.warningHeader.value);
4256
+ }
4257
+ next();
4258
+ } catch (error) {
4259
+ console.error("[VerificationGateway/MCP] Middleware error:", error);
4260
+ next();
4261
+ }
4262
+ };
4263
+ }
4264
+
4265
+ // src/registration/errors.ts
4266
+ var AstraSyncError = class extends Error {
4267
+ constructor(message, statusCode, code) {
4268
+ super(message);
4269
+ this.name = "AstraSyncError";
4270
+ this.statusCode = statusCode;
4271
+ this.code = code;
4272
+ }
4273
+ };
4274
+ var KYDRequiredError = class extends AstraSyncError {
4275
+ constructor(response) {
4276
+ const kydUrl = response.kydUrl || "https://astrasync.ai/developer-profile";
4277
+ super(
4278
+ `KYD verification required before registering agents.
4279
+ Complete your KYD profile at: ${kydUrl}`,
4280
+ 403,
4281
+ "KYD_REQUIRED"
4282
+ );
4283
+ this.name = "KYDRequiredError";
4284
+ this.kydUrl = kydUrl;
4285
+ this.ownerNotified = response.ownerNotified || false;
4286
+ }
4287
+ };
4288
+ var AuthenticationError = class extends AstraSyncError {
4289
+ constructor(message) {
4290
+ super(message, 401, "AUTH_FAILED");
4291
+ this.name = "AuthenticationError";
4292
+ }
4293
+ };
4294
+ var RegistrationDeniedError = class extends AstraSyncError {
4295
+ constructor(requestId, reason) {
4296
+ super(
4297
+ `Registration request ${requestId} was denied by the account owner.${reason ? ` Reason: ${reason}` : ""}`,
4298
+ 403,
4299
+ "REGISTRATION_DENIED"
4300
+ );
4301
+ this.name = "RegistrationDeniedError";
4302
+ this.requestId = requestId;
4303
+ this.reason = reason;
4304
+ }
4305
+ };
4306
+ var RegistrationExpiredError = class extends AstraSyncError {
4307
+ constructor(requestId) {
4308
+ super(
4309
+ `Registration request ${requestId} expired before the owner approved it. Submit a new registration request.`,
4310
+ 410,
4311
+ "REGISTRATION_EXPIRED"
4312
+ );
4313
+ this.name = "RegistrationExpiredError";
4314
+ this.requestId = requestId;
4315
+ }
4316
+ };
4317
+ var RegistrationTimeoutError = class extends AstraSyncError {
4318
+ constructor(requestId) {
4319
+ super(
4320
+ `Timed out waiting for owner approval of registration request ${requestId}. The request is still active server-side; poll the request to resume waiting.`,
4321
+ 408,
4322
+ "REGISTRATION_TIMEOUT"
4323
+ );
4324
+ this.name = "RegistrationTimeoutError";
4325
+ this.requestId = requestId;
4326
+ }
4327
+ };
4328
+
4329
+ // src/registration/api.ts
4330
+ var DEFAULT_BASE_URL = "https://astrasync.ai";
4331
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
4332
+ var AstraSync = class {
4333
+ constructor(config = {}) {
4334
+ let raw = (config.baseUrl || process.env.ASTRASYNC_API_URL || DEFAULT_BASE_URL).replace(
4335
+ /\/+$/,
4336
+ ""
4337
+ );
4338
+ if (raw.toLowerCase().endsWith("/api")) {
4339
+ raw = raw.slice(0, -"/api".length);
4340
+ if (config.baseUrl && !config.silent) {
4341
+ console.warn(
4342
+ `[AstraSync] baseUrl '${config.baseUrl}' had a trailing /api \u2014 stripped to '${raw}'. Pass the bare origin (e.g. 'https://astrasync.ai' or 'https://staging.astrasync.ai') to AstraSync(). The /api suffix is the verify-gateway (GatewayConfig.apiBaseUrl) convention.`
4343
+ );
4344
+ }
4345
+ }
4346
+ this.baseUrl = raw;
4347
+ this.apiKey = config.apiKey || process.env.ASTRASYNC_API_KEY;
4348
+ this.email = config.email;
4349
+ this.password = config.password;
4350
+ this.privateKey = config.privateKey;
4351
+ if (!this.apiKey && !this.email) {
4352
+ throw new AuthenticationError(
4353
+ "Authentication required. Provide apiKey, or email+password. Set ASTRASYNC_API_KEY env var or pass config to constructor."
4354
+ );
4355
+ }
4356
+ if (this.email && !this.password) {
4357
+ throw new AuthenticationError("Password is required when using email authentication.");
4358
+ }
4359
+ }
4360
+ /**
4361
+ * Register a new AI agent on the AstraSync KYA Platform.
4362
+ *
4363
+ * The backend response depends on auth context:
4364
+ * - **Crypto-keypair signed** (`privateKey` configured): synchronous 201,
4365
+ * returns `{ status: 'active', agent }`.
4366
+ * - **API-key only** (no signature): 202 pending, returns
4367
+ * `{ status: 'pending_approval', requestId, pollUrl, expiresAt }`. The
4368
+ * owner is notified by email and a dashboard alert is emitted; the agent
4369
+ * becomes active only after the owner approves.
4370
+ *
4371
+ * Blocking mode: pass `{ waitForApproval: true }` to have the SDK poll the
4372
+ * request until it resolves, then return the live agent record. The promise
4373
+ * rejects with `RegistrationDeniedError`, `RegistrationExpiredError`, or
4374
+ * `RegistrationTimeoutError` on the corresponding terminal states.
4375
+ *
4376
+ * @example Non-blocking (default — best for serverless / scheduled agents):
4377
+ * ```typescript
4378
+ * const result = await sdk.register({ name, pdlss });
4379
+ * if (result.status === 'pending_approval') {
4380
+ * storeRequestId(result.requestId);
4381
+ * return; // function exits; resume later via pollRegistration()
4382
+ * }
4383
+ * ```
4384
+ *
4385
+ * @example Blocking (best for long-running services + CLI):
4386
+ * ```typescript
4387
+ * const agent = await sdk.register({
4388
+ * name, pdlss, waitForApproval: true, timeoutMs: 600_000,
4389
+ * onPending: ({ ageMs }) => console.log(`waiting ${ageMs}ms`),
4390
+ * });
4391
+ * ```
4392
+ */
4393
+ async register(options) {
4394
+ const body = {
4395
+ name: options.name,
4396
+ ...options.description && { description: options.description },
4397
+ ...options.agentType && { agentType: options.agentType },
4398
+ ...options.apiEndpoint && { apiEndpoint: options.apiEndpoint },
4399
+ ...options.model && { model: options.model },
4400
+ ...options.framework && { framework: options.framework },
4401
+ ...options.protocols && { protocols: options.protocols },
4402
+ ...options.metadata && { metadata: options.metadata },
4403
+ ...options.pdlss && { pdlss: options.pdlss }
4404
+ };
4405
+ const { status, body: raw } = await this.requestWithStatus("POST", "/api/agents/register", body);
4406
+ if (status === 201) {
4407
+ const activeBody = raw;
4408
+ const active = {
4409
+ status: "active",
4410
+ agent: activeBody.data.agent,
4411
+ // Round-12 (F16): pass backend advisories through verbatim.
4412
+ // Pre-fix the SDK whitelisted five fields and silently dropped
4413
+ // `warnings`, which left partners with no signal that
4414
+ // `no_callback_endpoint` (or future advisories) had fired.
4415
+ ...activeBody.warnings && { warnings: activeBody.warnings }
4416
+ };
4417
+ return active;
4418
+ }
4419
+ const pendingBody = raw;
4420
+ const pending = {
4421
+ status: "pending_approval",
4422
+ requestId: pendingBody.requestId,
4423
+ expiresAt: pendingBody.expiresAt,
4424
+ pollUrl: pendingBody.pollUrl,
4425
+ message: pendingBody.message,
4426
+ // Round-12 (F16): same pass-through on the pending path.
4427
+ ...pendingBody.warnings && { warnings: pendingBody.warnings }
4428
+ };
4429
+ if (!options.waitForApproval) return pending;
4430
+ return this.waitForApproval(pendingBody.requestId, options);
4431
+ }
4432
+ /**
4433
+ * Poll the current state of a pending-approval registration request.
4434
+ *
4435
+ * Useful for caller-driven polling when `waitForApproval: false` (the
4436
+ * default). The endpoint is unauthenticated — pass the `requestId` that
4437
+ * was returned from the 202 response.
4438
+ *
4439
+ * @returns `state: 'pending'` while awaiting; `'approved'` carries the
4440
+ * minted agent in `agent`; `'denied'` may carry the owner's
4441
+ * `reason`; `'expired'` is terminal after 14 days.
4442
+ */
4443
+ async pollRegistration(requestId) {
4444
+ const url = `${this.baseUrl}/api/agents/request-registration/${requestId}`;
4445
+ const res = await fetch(url, { headers: { Accept: "application/json" } });
4446
+ if (!res.ok) {
4447
+ const errBody = await res.json().catch(() => ({}));
4448
+ throw new AstraSyncError(
4449
+ errBody.error || `pollRegistration failed: ${res.status}`,
4450
+ res.status,
4451
+ errBody.code
4452
+ );
4453
+ }
4454
+ return await res.json();
4455
+ }
4456
+ /**
4457
+ * Block until a pending registration request resolves to a terminal state.
4458
+ * Resolves to the live `AgentRecord` on approval; rejects with the matching
4459
+ * Registration*Error on deny/expire/timeout. Usually called via
4460
+ * `register({ waitForApproval: true })`, but exposed for callers that want
4461
+ * to fire-and-forget the initial register call and resume waiting later
4462
+ * (e.g. after restoring a stored `requestId` on cold start).
4463
+ */
4464
+ async waitForApproval(requestId, options = {}) {
4465
+ const timeoutMs = options.timeoutMs ?? 10 * 60 * 1e3;
4466
+ const pollIntervalMs = options.pollIntervalMs ?? 5e3;
4467
+ const start = Date.now();
4468
+ const deadline = start + timeoutMs;
4469
+ while (Date.now() < deadline) {
4470
+ const result = await this.pollRegistration(requestId);
4471
+ const ageMs = Date.now() - start;
4472
+ options.onPending?.({ requestId, ageMs });
4473
+ if (result.state === "approved") {
4474
+ if (!result.agent) {
4475
+ throw new AstraSyncError(
4476
+ `Registration ${requestId} reported approved but no agent payload returned.`,
4477
+ 500
4478
+ );
4479
+ }
4480
+ return result.agent;
4481
+ }
4482
+ if (result.state === "denied") {
4483
+ throw new RegistrationDeniedError(requestId, result.reason);
4484
+ }
4485
+ if (result.state === "expired") {
4486
+ throw new RegistrationExpiredError(requestId);
4487
+ }
4488
+ await sleep(pollIntervalMs);
4489
+ }
4490
+ throw new RegistrationTimeoutError(requestId);
4491
+ }
4492
+ /**
4493
+ * Look up an agent's public profile by ASTRA ID or UUID.
4494
+ */
4495
+ async verify(agentId) {
4496
+ return this.request("GET", `/api/agents/verify/${agentId}`);
4497
+ }
4498
+ /**
4499
+ * Check API health.
4500
+ */
4501
+ async health() {
4502
+ const res = await fetch(`${this.baseUrl}/api/health/`);
4503
+ if (!res.ok) {
4504
+ throw new AstraSyncError(`Health check failed: ${res.status}`, res.status);
4505
+ }
4506
+ return res.json();
4507
+ }
4508
+ // ── Private helpers ──────────────────────────────────────────────
4509
+ async request(method, endpoint, body) {
4510
+ const { body: parsed } = await this.requestWithStatus(method, endpoint, body);
4511
+ return parsed;
4512
+ }
4513
+ /**
4514
+ * Variant of {@link request} that also returns the HTTP status code, so
4515
+ * callers can branch on 201 vs 202 (or other success codes) without losing
4516
+ * type information about the response body.
4517
+ */
4518
+ async requestWithStatus(method, endpoint, body) {
4519
+ const url = `${this.baseUrl}${endpoint}`;
4520
+ const headers = {
4521
+ "Content-Type": "application/json"
4522
+ };
4523
+ const token = await this.getAuthToken();
4524
+ headers["Authorization"] = `Bearer ${token}`;
4525
+ if (this.privateKey) {
4526
+ const signature = await this.signRequest(method, endpoint, body || {});
4527
+ headers["X-AstraSync-Signature"] = signature;
4528
+ }
4529
+ const res = await fetch(url, {
4530
+ method,
4531
+ headers,
4532
+ ...body ? { body: JSON.stringify(body) } : {}
4533
+ });
4534
+ if (!res.ok) {
4535
+ const errorBody = await res.json().catch(() => ({ error: res.statusText }));
4536
+ if (res.status === 403 && errorBody.code === "KYD_REQUIRED") {
4537
+ throw new KYDRequiredError(errorBody);
4538
+ }
4539
+ throw new AstraSyncError(
4540
+ errorBody.error || `Request failed: ${res.status}`,
4541
+ res.status,
4542
+ errorBody.code
4543
+ );
4544
+ }
4545
+ return { status: res.status, body: await res.json() };
4546
+ }
4547
+ async getAuthToken() {
4548
+ if (this.apiKey) {
4549
+ return this.apiKey;
4550
+ }
4551
+ if (this.cachedJwt && this.jwtExpiresAt && Date.now() < this.jwtExpiresAt) {
4552
+ return this.cachedJwt;
4553
+ }
4554
+ const res = await fetch(`${this.baseUrl}/api/auth/login`, {
4555
+ method: "POST",
4556
+ headers: { "Content-Type": "application/json" },
4557
+ body: JSON.stringify({ email: this.email, password: this.password })
4558
+ });
4559
+ if (!res.ok) {
4560
+ const errorBody = await res.json().catch(() => ({}));
4561
+ throw new AuthenticationError(
4562
+ errorBody.message || errorBody.error || "Login failed"
4563
+ );
4564
+ }
4565
+ const data = await res.json();
4566
+ this.cachedJwt = data.data.token;
4567
+ this.jwtExpiresAt = Date.now() + 6 * 24 * 60 * 60 * 1e3;
4568
+ return this.cachedJwt;
4569
+ }
4570
+ /**
4571
+ * Sign a request using secp256k1 (ethers.js).
4572
+ * Canonical message format: METHOD:ENDPOINT:SORTED_JSON_BODY
4573
+ * Must match apps/backend/src/services/signature-verify.service.ts exactly.
4574
+ */
4575
+ async signRequest(method, endpoint, body) {
4576
+ const { Wallet } = await import("ethers");
4577
+ const sorted = this.sortObjectKeys(body);
4578
+ const canonical = `${method}:${endpoint}:${JSON.stringify(sorted)}`;
4579
+ const wallet = new Wallet(this.privateKey);
4580
+ return wallet.signMessage(canonical);
4581
+ }
4582
+ /** Recursively sort object keys for canonical JSON representation. */
4583
+ sortObjectKeys(obj) {
4584
+ if (obj === null || typeof obj !== "object") {
4585
+ return obj;
4586
+ }
4587
+ if (Array.isArray(obj)) {
4588
+ return obj.map((item) => this.sortObjectKeys(item));
4589
+ }
4590
+ const sorted = {};
4591
+ for (const key of Object.keys(obj).sort()) {
4592
+ sorted[key] = this.sortObjectKeys(obj[key]);
4593
+ }
4594
+ return sorted;
4595
+ }
4596
+ };
4597
+
3903
4598
  // src/agent/index.ts
3904
4599
  var agent_exports = {};
3905
4600
  __export(agent_exports, {
@@ -4220,15 +4915,24 @@ export {
4220
4915
  ACCESS_LEVEL_DESCRIPTIONS,
4221
4916
  ACCESS_LEVEL_HIERARCHY,
4222
4917
  AgentClient,
4918
+ AstraSync,
4919
+ AstraSyncError,
4920
+ AuthenticationError,
4223
4921
  ChallengeHandler,
4224
4922
  DEFAULT_TRUST_THRESHOLDS,
4923
+ KYDRequiredError,
4924
+ RegistrationDeniedError,
4925
+ RegistrationExpiredError,
4926
+ RegistrationTimeoutError,
4225
4927
  TRUST_LEVEL_RANGES,
4226
4928
  VERSION,
4227
4929
  agent_exports as agent,
4228
4930
  clearCache,
4931
+ createMcpMiddleware,
4229
4932
  determineAccessLevel,
4230
4933
  express_exports as express,
4231
4934
  extractCredentials,
4935
+ extractMcpCredentials,
4232
4936
  getAccessLevelForScore,
4233
4937
  getCapabilities,
4234
4938
  getTrustLevel,
@@ -4238,6 +4942,7 @@ export {
4238
4942
  quickVerify,
4239
4943
  recordDecision2 as recordDecision,
4240
4944
  sdk_exports as sdk,
4945
+ setMcpMeta,
4241
4946
  transport_exports as transport,
4242
4947
  verify
4243
4948
  };