@astrasyncai/verification-gateway 2.0.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/adapter-interface/interface.d.mts +2 -2
  2. package/dist/adapter-interface/interface.d.ts +2 -2
  3. package/dist/adapters/express.d.mts +2 -2
  4. package/dist/adapters/express.d.ts +2 -2
  5. package/dist/adapters/express.js +42 -20
  6. package/dist/adapters/express.js.map +1 -1
  7. package/dist/adapters/express.mjs +42 -20
  8. package/dist/adapters/express.mjs.map +1 -1
  9. package/dist/adapters/nextjs.d.mts +2 -2
  10. package/dist/adapters/nextjs.d.ts +2 -2
  11. package/dist/adapters/nextjs.js +43 -20
  12. package/dist/adapters/nextjs.js.map +1 -1
  13. package/dist/adapters/nextjs.mjs +43 -20
  14. package/dist/adapters/nextjs.mjs.map +1 -1
  15. package/dist/adapters/sdk.d.mts +2 -2
  16. package/dist/adapters/sdk.d.ts +2 -2
  17. package/dist/adapters/sdk.js +25 -16
  18. package/dist/adapters/sdk.js.map +1 -1
  19. package/dist/adapters/sdk.mjs +25 -16
  20. package/dist/adapters/sdk.mjs.map +1 -1
  21. package/dist/agent/index.d.mts +2 -2
  22. package/dist/agent/index.d.ts +2 -2
  23. package/dist/agent/index.js +100 -1
  24. package/dist/agent/index.js.map +1 -1
  25. package/dist/agent/index.mjs +101 -1
  26. package/dist/agent/index.mjs.map +1 -1
  27. package/dist/browser/background.js +58 -16
  28. package/dist/browser/background.js.map +1 -1
  29. package/dist/browser/background.mjs +61 -16
  30. package/dist/browser/background.mjs.map +1 -1
  31. package/dist/browser/browser-adapter.d.mts +2 -2
  32. package/dist/browser/browser-adapter.d.ts +2 -2
  33. package/dist/cli/index.d.mts +2 -2
  34. package/dist/cli/index.d.ts +2 -2
  35. package/dist/cursor/cursor-adapter.d.mts +2 -2
  36. package/dist/cursor/cursor-adapter.d.ts +2 -2
  37. package/dist/cursor/extension.d.mts +2 -2
  38. package/dist/cursor/extension.d.ts +2 -2
  39. package/dist/cursor/extension.js +58 -16
  40. package/dist/cursor/extension.js.map +1 -1
  41. package/dist/cursor/extension.mjs +61 -16
  42. package/dist/cursor/extension.mjs.map +1 -1
  43. package/dist/{express-CtwDIZyF.d.mts → express-C9KqJNWV.d.mts} +1 -1
  44. package/dist/{express-Bcl-uBUE.d.ts → express-DpwYW08E.d.ts} +1 -1
  45. package/dist/gateway/gateway.d.mts +2 -2
  46. package/dist/gateway/gateway.d.ts +2 -2
  47. package/dist/gateway/gateway.js +58 -16
  48. package/dist/gateway/gateway.js.map +1 -1
  49. package/dist/gateway/gateway.mjs +61 -16
  50. package/dist/gateway/gateway.mjs.map +1 -1
  51. package/dist/git-trigger/git-hooks.d.mts +2 -2
  52. package/dist/git-trigger/git-hooks.d.ts +2 -2
  53. package/dist/{index-BY8yQ8N8.d.mts → index-BMZdjGT4.d.mts} +46 -3
  54. package/dist/index-DlsYN3Et.d.mts +1397 -0
  55. package/dist/{index-CtYSYwn3.d.ts → index-Dm2xA6j1.d.ts} +46 -3
  56. package/dist/index-gM-lgX_X.d.ts +1397 -0
  57. package/dist/index.d.mts +8 -7
  58. package/dist/index.d.ts +8 -7
  59. package/dist/index.js +2489 -66
  60. package/dist/index.js.map +1 -1
  61. package/dist/index.mjs +2492 -66
  62. package/dist/index.mjs.map +1 -1
  63. package/dist/local-evaluator/evaluator.d.mts +2 -2
  64. package/dist/local-evaluator/evaluator.d.ts +2 -2
  65. package/dist/{nextjs-BQyMCSx_.d.mts → nextjs-BEqidT0U.d.mts} +1 -1
  66. package/dist/{nextjs-CEldnIJ9.d.ts → nextjs-yNzimC3a.d.ts} +1 -1
  67. package/dist/{sdk-BhvuJSrH.d.mts → sdk-7fa9H0qa.d.mts} +1 -1
  68. package/dist/{sdk-BlyVSC_S.d.ts → sdk-CP9C9Qu0.d.ts} +1 -1
  69. package/dist/transport/index.d.mts +3 -2
  70. package/dist/transport/index.d.ts +3 -2
  71. package/dist/transport/index.js +2384 -2
  72. package/dist/transport/index.js.map +1 -1
  73. package/dist/transport/index.mjs +2327 -1
  74. package/dist/transport/index.mjs.map +1 -1
  75. package/dist/{types-CxQwJKbd.d.mts → types-CrVMq_Td.d.mts} +30 -3
  76. package/dist/{types-CxQwJKbd.d.ts → types-CrVMq_Td.d.ts} +30 -3
  77. package/dist/{types-jJnPXStc.d.mts → types-DE0ooQJ6.d.mts} +1 -1
  78. package/dist/{types-79qS7aON.d.ts → types-rigu2bH3.d.ts} +1 -1
  79. package/dist/ui/index.d.mts +1 -1
  80. package/dist/ui/index.d.ts +1 -1
  81. package/package.json +17 -3
  82. package/dist/index-B1ThcGZl.d.mts +0 -89
  83. package/dist/index-DnoXfdFd.d.ts +0 -89
package/dist/index.js CHANGED
@@ -278,21 +278,33 @@ async function callVerifyAccessAPI(config, request) {
278
278
  if (requestData.isSubAgentRequest) body.isSubAgentRequest = requestData.isSubAgentRequest;
279
279
  if (requestData.parentAgentId) body.parentAgentId = requestData.parentAgentId;
280
280
  if (requestData.subAgentDepth !== void 0) body.subAgentDepth = requestData.subAgentDepth;
281
- if (requestData.enableRuntimeChallenge) body.enableRuntimeChallenge = requestData.enableRuntimeChallenge;
281
+ if (requestData.enableRuntimeChallenge)
282
+ body.enableRuntimeChallenge = requestData.enableRuntimeChallenge;
282
283
  if (requestData.createSession) body.createSession = requestData.createSession;
283
284
  if (requestData.durationRequired) body.durationRequired = requestData.durationRequired;
284
285
  if (requestData.counterpartyType) body.counterpartyType = requestData.counterpartyType;
285
286
  if (requestData.counterpartyUrl) body.counterpartyUrl = requestData.counterpartyUrl;
286
- if (requestData.runtimeChallengeOptions) body.runtimeChallengeOptions = requestData.runtimeChallengeOptions;
287
+ if (requestData.runtimeChallengeOptions)
288
+ body.runtimeChallengeOptions = requestData.runtimeChallengeOptions;
289
+ if (requestData.callerMetadata || requestData.clientIp || requestData.userAgent) {
290
+ const meta = {
291
+ ...requestData.clientIp && { sourceIp: requestData.clientIp },
292
+ ...requestData.userAgent && { userAgent: requestData.userAgent },
293
+ ...requestData.callerMetadata
294
+ };
295
+ if (Object.keys(meta).length > 0) body.callerMetadata = meta;
296
+ }
287
297
  const headers = {
288
298
  "Content-Type": "application/json",
289
299
  ...config.customHeaders
290
300
  };
291
- if (config.apiKey) {
292
- headers["X-API-Key"] = config.apiKey;
293
- }
294
301
  if (credentials.authorizationHeader) {
295
302
  headers["Authorization"] = credentials.authorizationHeader;
303
+ } else if (config.apiKey) {
304
+ headers["Authorization"] = `Bearer ${config.apiKey}`;
305
+ }
306
+ if (config.apiKey) {
307
+ headers["X-API-Key"] = config.apiKey;
296
308
  }
297
309
  try {
298
310
  const response = await fetch(`${config.apiBaseUrl}/agents/verify-access`, {
@@ -393,16 +405,11 @@ async function verify(config, request) {
393
405
  } : void 0;
394
406
  const trustScore = agent?.trustScore || 0;
395
407
  const isOrgMember = false;
396
- const accessLevel = determineAccessLevel(
397
- true,
398
- trustScore,
399
- isOrgMember,
400
- {
401
- "read-only": 20,
402
- standard: mergedConfig.minTrustScore || 40,
403
- full: mergedConfig.minTrustScoreForFull || 70
404
- }
405
- );
408
+ const accessLevel = determineAccessLevel(true, trustScore, isOrgMember, {
409
+ "read-only": 20,
410
+ standard: mergedConfig.minTrustScore || 40,
411
+ full: mergedConfig.minTrustScoreForFull || 70
412
+ });
406
413
  const result = {
407
414
  verified: true,
408
415
  accessLevel,
@@ -424,7 +431,9 @@ async function verify(config, request) {
424
431
  if (result.recommendation === "deny") {
425
432
  result.verified = false;
426
433
  result.accessLevel = "none";
427
- result.denialReasons = result.recommendationReasons || ["Access denied by AstraSync recommendation"];
434
+ result.denialReasons = result.recommendationReasons || [
435
+ "Access denied by AstraSync recommendation"
436
+ ];
428
437
  if (result.runtimeChallenge) {
429
438
  result.guidance = {
430
439
  message: `Verification failed: ${result.runtimeChallenge.reason || "runtime challenge failed"}`,
@@ -446,7 +455,10 @@ async function verify(config, request) {
446
455
  }
447
456
  async function recordDecision(config, sessionId, decision, reason) {
448
457
  const headers = { "Content-Type": "application/json" };
449
- if (config.apiKey) headers["X-API-Key"] = config.apiKey;
458
+ if (config.apiKey) {
459
+ headers["Authorization"] = `Bearer ${config.apiKey}`;
460
+ headers["X-API-Key"] = config.apiKey;
461
+ }
450
462
  await fetch(`${config.apiBaseUrl}/agents/verify-access/${sessionId}/decision`, {
451
463
  method: "POST",
452
464
  headers,
@@ -744,18 +756,28 @@ function createMiddleware(options) {
744
756
  return;
745
757
  }
746
758
  const shouldRecordDecisions = recordDecisions !== false;
759
+ const forwardedFor = req.headers["x-forwarded-for"];
760
+ const forwardedForStr = Array.isArray(forwardedFor) ? forwardedFor.join(", ") : forwardedFor;
761
+ const originalClientIp = forwardedForStr ? forwardedForStr.split(",")[0].trim() : req.ip;
762
+ const agentCardUrl = typeof req.headers["x-astrasync-agent-card"] === "string" ? req.headers["x-astrasync-agent-card"] : void 0;
747
763
  const result = await verify(config, {
748
764
  credentials,
749
765
  purpose,
750
766
  action: req.method.toLowerCase(),
751
767
  resource: req.path,
752
- clientIp: req.ip,
753
- userAgent: req.headers["user-agent"],
754
768
  createSession: shouldRecordDecisions,
755
769
  counterpartyUrl,
756
770
  counterpartyType: config.counterpartyType || "api",
757
771
  enableRuntimeChallenge,
758
- durationRequired: astraCreds?.pdlss?.duration?.maxSessionDuration
772
+ durationRequired: astraCreds?.pdlss?.duration?.maxSessionDuration,
773
+ callerMetadata: {
774
+ sourceIp: originalClientIp,
775
+ userAgent: req.headers["user-agent"],
776
+ referer: req.headers.referer,
777
+ host: req.headers.host,
778
+ forwardedFor: forwardedForStr,
779
+ agentCardUrl
780
+ }
759
781
  });
760
782
  req.agentVerification = result;
761
783
  const sessionId = result.sessionId;
@@ -1027,7 +1049,13 @@ function generateCommerceShieldHtml(result, options) {
1027
1049
  `.trim();
1028
1050
  }
1029
1051
  function createMiddleware2(options) {
1030
- const { routes = [], skipPaths = [], showCommerceShield = true, enableRuntimeChallenge = true, ...config } = options;
1052
+ const {
1053
+ routes = [],
1054
+ skipPaths = [],
1055
+ showCommerceShield = true,
1056
+ enableRuntimeChallenge = true,
1057
+ ...config
1058
+ } = options;
1031
1059
  return async function middleware(request) {
1032
1060
  const { NextResponse } = await import("next/server");
1033
1061
  const pathname = request.nextUrl.pathname;
@@ -1139,17 +1167,25 @@ function createMiddleware2(options) {
1139
1167
  }
1140
1168
  return NextResponse.redirect(new URL("/unauthorized", request.url));
1141
1169
  }
1170
+ const forwardedFor = request.headers.get("x-forwarded-for") || void 0;
1171
+ const originalClientIp = forwardedFor?.split(",")[0]?.trim();
1142
1172
  const result = await verify(config, {
1143
1173
  credentials,
1144
1174
  purpose,
1145
1175
  action: request.method.toLowerCase(),
1146
1176
  resource: pathname,
1147
- clientIp: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || void 0,
1148
- userAgent: request.headers.get("user-agent") || void 0,
1149
1177
  counterpartyUrl,
1150
1178
  counterpartyType: config.counterpartyType || "website",
1151
1179
  enableRuntimeChallenge,
1152
- durationRequired: astraCreds?.pdlss?.duration?.maxSessionDuration
1180
+ durationRequired: astraCreds?.pdlss?.duration?.maxSessionDuration,
1181
+ callerMetadata: {
1182
+ sourceIp: originalClientIp,
1183
+ userAgent: request.headers.get("user-agent") || void 0,
1184
+ referer: request.headers.get("referer") || void 0,
1185
+ host: request.headers.get("host") || void 0,
1186
+ forwardedFor,
1187
+ agentCardUrl: request.headers.get("x-astrasync-agent-card") || void 0
1188
+ }
1153
1189
  });
1154
1190
  if (!hasMinimumAccess(result.accessLevel, routeConfig.minAccessLevel)) {
1155
1191
  if (pathname.startsWith("/api/")) {
@@ -1328,15 +1364,64 @@ async function verifyOnce(options) {
1328
1364
  // src/transport/index.ts
1329
1365
  var transport_exports = {};
1330
1366
  __export(transport_exports, {
1367
+ STRIPE_WEBHOOK_INFORMATIONAL_EVENTS: () => STRIPE_WEBHOOK_INFORMATIONAL_EVENTS,
1331
1368
  applyCredentials: () => applyCredentials,
1369
+ bindIdentity: () => bindIdentity,
1370
+ claim: () => claim,
1371
+ clearTransportExtractors: () => clearTransportExtractors,
1372
+ createMastercardRegistry: () => createMastercardRegistry,
1373
+ createVisaRegistry: () => createVisaRegistry,
1374
+ createWebBotAuthRegistry: () => createWebBotAuthRegistry,
1332
1375
  detectProtocol: () => detectProtocol,
1376
+ evaluatePaymentMethodAllowlist: () => evaluatePaymentMethodAllowlist,
1377
+ evaluateSpendingLimit: () => evaluateSpendingLimit,
1378
+ evaluateVIConstraints: () => evaluateVIConstraints,
1333
1379
  extractA2ACredentials: () => extractA2ACredentials,
1380
+ extractACPContext: () => extractACPContext,
1381
+ extractACPTransactionValue: () => extractACPTransactionValue,
1382
+ extractAP2Mandate: () => extractAP2Mandate,
1383
+ extractAP2Mandates: () => extractAP2Mandates,
1384
+ extractAP2TransactionValue: () => extractAP2TransactionValue,
1334
1385
  extractCredentialsFromProtocol: () => extractCredentialsFromProtocol,
1335
1386
  extractHttpCredentials: () => extractHttpCredentials,
1387
+ extractMPPContext: () => extractMPPContext,
1388
+ extractMPPFromRequest: () => extractMPPFromRequest,
1389
+ extractMPPFromResponse: () => extractMPPFromResponse,
1390
+ extractMPPTransactionValue: () => extractMPPTransactionValue,
1336
1391
  extractMcpCredentials: () => extractMcpCredentials,
1392
+ extractUCPContext: () => extractUCPContext,
1393
+ extractUCPTransactionValue: () => extractUCPTransactionValue,
1394
+ extractVIClaims: () => extractVIClaims,
1395
+ extractVITransactionValue: () => extractVITransactionValue,
1396
+ extractX402Context: () => extractX402Context,
1397
+ extractX402FromRequest: () => extractX402FromRequest,
1398
+ extractX402FromResponse: () => extractX402FromResponse,
1399
+ extractX402TransactionValue: () => extractX402TransactionValue,
1400
+ fetchUCPManifest: () => fetchUCPManifest,
1401
+ getTransportExtractor: () => getTransportExtractor,
1402
+ getTransportExtractors: () => getTransportExtractors,
1403
+ isStripeWebhookInformational: () => isStripeWebhookInformational,
1404
+ mapACPRequestToPurpose: () => mapACPRequestToPurpose,
1405
+ mapAP2MandateToPurpose: () => mapAP2MandateToPurpose,
1406
+ mapMPPRequestToPurpose: () => mapMPPRequestToPurpose,
1407
+ mapRFC9421TagToPurpose: () => mapRFC9421TagToPurpose,
1408
+ mapUCPRequestToPurpose: () => mapUCPRequestToPurpose,
1409
+ mapVIMandateToPurpose: () => mapVIMandateToPurpose,
1410
+ mapX402RequestToPurpose: () => mapX402RequestToPurpose,
1411
+ parseRFC9421: () => parseRFC9421,
1412
+ registerTransportExtractor: () => registerTransportExtractor,
1413
+ runCommercePipeline: () => runCommercePipeline,
1414
+ runMatchingExtractors: () => runMatchingExtractors,
1337
1415
  setA2AMetadata: () => setA2AMetadata,
1338
1416
  setHttpHeaders: () => setHttpHeaders,
1339
- setMcpMeta: () => setMcpMeta
1417
+ setMcpMeta: () => setMcpMeta,
1418
+ validateUCPManifest: () => validateUCPManifest,
1419
+ verifyACPSignature: () => verifyACPSignature,
1420
+ verifyAP2Chain: () => verifyAP2Chain,
1421
+ verifyMPP: () => verifyMPP,
1422
+ verifyRFC9421: () => verifyRFC9421,
1423
+ verifyStripeWebhook: () => verifyStripeWebhook,
1424
+ verifyVIChain: () => verifyVIChain
1340
1425
  });
1341
1426
 
1342
1427
  // src/transport/a2a.ts
@@ -1409,61 +1494,2399 @@ function extractMcpCredentials(params) {
1409
1494
  return credentials;
1410
1495
  }
1411
1496
 
1412
- // src/transport/index.ts
1413
- function detectProtocol(context) {
1414
- if (context.metadata && typeof context.metadata === "object") {
1415
- return "a2a";
1497
+ // src/transport/purpose-mapping.ts
1498
+ var UCP_ROUTES = [
1499
+ { method: "POST", pattern: /^\/checkout[-_]sessions\/?$/, purpose: "commerce.checkout.create" },
1500
+ {
1501
+ method: "PUT",
1502
+ pattern: /^\/checkout[-_]sessions\/[^/]+\/?$/,
1503
+ purpose: "commerce.checkout.update"
1504
+ },
1505
+ {
1506
+ method: "POST",
1507
+ pattern: /^\/checkout[-_]sessions\/[^/]+\/complete\/?$/,
1508
+ purpose: "commerce.payment.execute"
1509
+ },
1510
+ {
1511
+ method: "POST",
1512
+ pattern: /^\/checkout[-_]sessions\/[^/]+\/cancel\/?$/,
1513
+ purpose: "commerce.checkout.cancel"
1416
1514
  }
1417
- if (context._meta && typeof context._meta === "object") {
1418
- return "mcp";
1515
+ ];
1516
+ var ACP_ROUTES = [
1517
+ { method: "POST", pattern: /^\/checkout_sessions\/?$/, purpose: "commerce.checkout.create" },
1518
+ {
1519
+ method: "POST",
1520
+ pattern: /^\/checkout_sessions\/[^/]+\/?$/,
1521
+ purpose: "commerce.checkout.update"
1522
+ },
1523
+ {
1524
+ method: "POST",
1525
+ pattern: /^\/checkout_sessions\/[^/]+\/complete\/?$/,
1526
+ purpose: "commerce.payment.execute"
1527
+ },
1528
+ {
1529
+ method: "POST",
1530
+ pattern: /^\/checkout_sessions\/[^/]+\/cancel\/?$/,
1531
+ purpose: "commerce.checkout.cancel"
1532
+ },
1533
+ {
1534
+ method: "POST",
1535
+ pattern: /^\/agentic_commerce\/delegate_payment\/?$/,
1536
+ purpose: "commerce.delegation.payment"
1419
1537
  }
1420
- return "http";
1538
+ ];
1539
+ function mapUCPRequestToPurpose(method, path) {
1540
+ const normalizedMethod = method.toUpperCase();
1541
+ const normalizedPath = stripQuery(path);
1542
+ for (const route of UCP_ROUTES) {
1543
+ if (route.method === normalizedMethod && route.pattern.test(normalizedPath)) {
1544
+ return route.purpose;
1545
+ }
1546
+ }
1547
+ return null;
1421
1548
  }
1422
- function applyCredentials(protocol, target, credentials) {
1423
- switch (protocol) {
1424
- case "http":
1425
- return setHttpHeaders(target, credentials);
1426
- case "a2a":
1427
- return setA2AMetadata(target, credentials);
1428
- case "mcp":
1429
- return setMcpMeta(target, credentials);
1549
+ function mapACPRequestToPurpose(method, path) {
1550
+ const normalizedMethod = method.toUpperCase();
1551
+ const normalizedPath = stripQuery(path);
1552
+ for (const route of ACP_ROUTES) {
1553
+ if (route.method === normalizedMethod && route.pattern.test(normalizedPath)) {
1554
+ return route.purpose;
1555
+ }
1556
+ }
1557
+ return null;
1558
+ }
1559
+ function mapAP2MandateToPurpose(mandateType) {
1560
+ switch (mandateType) {
1561
+ case "intent_mandate":
1562
+ return "commerce.delegation.intent";
1563
+ case "cart_mandate":
1564
+ return "commerce.checkout.confirm";
1565
+ case "payment_mandate":
1566
+ return "commerce.payment.execute";
1567
+ }
1568
+ }
1569
+ function mapVIMandateToPurpose(mandateType) {
1570
+ switch (mandateType) {
1571
+ case "checkout":
1572
+ return "commerce.checkout.confirm";
1573
+ case "payment":
1574
+ return "commerce.payment.execute";
1575
+ case "checkout.open":
1576
+ return "commerce.delegation.checkout";
1577
+ case "payment.open":
1578
+ return "commerce.delegation.payment";
1579
+ }
1580
+ }
1581
+ function mapRFC9421TagToPurpose(tag) {
1582
+ if (tag === "purchase") return "commerce.payment.execute";
1583
+ return "commerce.browsing";
1584
+ }
1585
+ function mapMPPRequestToPurpose(intent, amount) {
1586
+ if (typeof amount === "number" && amount === 0) return "commerce.identity_probe";
1587
+ if (intent === "session") return "commerce.payment.stream";
1588
+ return "commerce.payment.execute";
1589
+ }
1590
+ function mapX402RequestToPurpose(amount) {
1591
+ if (typeof amount === "number" && amount === 0) return "commerce.identity_probe";
1592
+ return "commerce.payment.execute";
1593
+ }
1594
+ function stripQuery(path) {
1595
+ const q = path.indexOf("?");
1596
+ return q === -1 ? path : path.slice(0, q);
1597
+ }
1598
+ var STRIPE_WEBHOOK_INFORMATIONAL_EVENTS = [
1599
+ "payment_intent.succeeded",
1600
+ "payment_intent.payment_failed",
1601
+ "charge.refunded",
1602
+ "checkout.session.completed",
1603
+ "customer.subscription.created"
1604
+ ];
1605
+ function isStripeWebhookInformational(eventType) {
1606
+ return STRIPE_WEBHOOK_INFORMATIONAL_EVENTS.includes(eventType);
1607
+ }
1608
+
1609
+ // src/transport/transaction-value.ts
1610
+ function extractUCPTransactionValue(input) {
1611
+ const totals = input.totals ?? [];
1612
+ const total = totals.find((t) => t.type === "total") ?? totals[0];
1613
+ if (!total || typeof total.amount !== "number" || !total.currency) return null;
1614
+ return {
1615
+ protocol: "ucp",
1616
+ amount: total.amount / 100,
1617
+ currency: total.currency,
1618
+ source: `totals[type=${total.type ?? "unknown"}].amount`
1619
+ };
1620
+ }
1621
+ function extractACPTransactionValue(input) {
1622
+ const totals = input.totals ?? [];
1623
+ const total = totals.find((t) => t.type === "total") ?? totals[0];
1624
+ if (!total || typeof total.amount !== "number" || !total.currency) return null;
1625
+ return {
1626
+ protocol: "acp",
1627
+ amount: total.amount / 100,
1628
+ currency: total.currency,
1629
+ source: `totals[type=${total.type ?? "unknown"}].amount`
1630
+ };
1631
+ }
1632
+ function extractVITransactionValue(claims) {
1633
+ const l3a = claims.l3aPaymentAmount;
1634
+ if (l3a && typeof l3a.amount === "number" && l3a.currency) {
1635
+ return {
1636
+ protocol: "vi",
1637
+ amount: l3a.amount,
1638
+ currency: l3a.currency,
1639
+ source: "L3a.payment.amount"
1640
+ };
1641
+ }
1642
+ const bound = claims.constraints?.paymentAmount;
1643
+ if (bound && typeof bound.max === "number" && bound.currency) {
1644
+ return {
1645
+ protocol: "vi",
1646
+ amount: bound.max,
1647
+ currency: bound.currency,
1648
+ source: "L2.payment.constraints.amount.max"
1649
+ };
1650
+ }
1651
+ return null;
1652
+ }
1653
+ function extractAP2TransactionValue(mandate) {
1654
+ const amt = mandate?.payment_details_total?.amount;
1655
+ if (!amt || !amt.currency) return null;
1656
+ const n = typeof amt.value === "string" ? Number(amt.value) : amt.value;
1657
+ if (typeof n !== "number" || !Number.isFinite(n)) return null;
1658
+ return {
1659
+ protocol: "ap2",
1660
+ amount: n,
1661
+ currency: amt.currency,
1662
+ source: "payment_mandate.payment_details_total.amount"
1663
+ };
1664
+ }
1665
+ function extractMPPTransactionValue(challenge) {
1666
+ const req = challenge.request;
1667
+ if (!req || typeof req.amount !== "number" || !req.currency) return null;
1668
+ return {
1669
+ protocol: "mpp",
1670
+ amount: req.amount,
1671
+ currency: req.currency,
1672
+ source: `challenge.request.amount (method=${challenge.method ?? "unknown"})`
1673
+ };
1674
+ }
1675
+ function extractX402TransactionValue(req) {
1676
+ const amount = req.maxAmountRequired ?? req.amount;
1677
+ const currency = req.currency ?? req.asset;
1678
+ if (typeof amount !== "number" || !currency) return null;
1679
+ return {
1680
+ protocol: "x402",
1681
+ amount,
1682
+ currency,
1683
+ source: req.maxAmountRequired !== void 0 ? "maxAmountRequired" : "amount"
1684
+ };
1685
+ }
1686
+
1687
+ // src/transport/rfc9421.ts
1688
+ var import_structured_headers = require("structured-headers");
1689
+ function parseRFC9421(headers) {
1690
+ const sigInput = readHeader(headers, "signature-input");
1691
+ const sig = readHeader(headers, "signature");
1692
+ if (!sigInput || !sig) return null;
1693
+ let inputDict;
1694
+ let sigDict;
1695
+ try {
1696
+ inputDict = (0, import_structured_headers.parseDictionary)(sigInput);
1697
+ sigDict = (0, import_structured_headers.parseDictionary)(sig);
1698
+ } catch {
1699
+ return null;
1700
+ }
1701
+ const signatures = [];
1702
+ for (const [label, entry] of inputDict) {
1703
+ const innerList = Array.isArray(entry) ? entry[0] : entry.value;
1704
+ const params = Array.isArray(entry) ? entry[1] : entry.params;
1705
+ if (!Array.isArray(innerList) || !params) continue;
1706
+ const covered = [];
1707
+ for (const item of innerList) {
1708
+ const [bare] = Array.isArray(item) ? item : [item];
1709
+ if (typeof bare === "string") covered.push(bare);
1710
+ else if (bare && typeof bare === "object" && "toString" in bare) covered.push(String(bare));
1711
+ }
1712
+ const paramsMap = params;
1713
+ const kid = coerceString(paramsMap.get("keyid"));
1714
+ if (!kid) continue;
1715
+ const sigEntry = sigDict.get(label);
1716
+ if (!sigEntry) continue;
1717
+ const sigBare = Array.isArray(sigEntry) ? sigEntry[0] : sigEntry.value;
1718
+ const signatureBase64 = extractBase64(sigBare);
1719
+ if (!signatureBase64) continue;
1720
+ signatures.push({
1721
+ label,
1722
+ kid,
1723
+ alg: coerceString(paramsMap.get("alg")),
1724
+ covered,
1725
+ signatureBase64,
1726
+ created: coerceNumber(paramsMap.get("created")),
1727
+ expires: coerceNumber(paramsMap.get("expires")),
1728
+ nonce: coerceString(paramsMap.get("nonce")),
1729
+ tag: coerceString(paramsMap.get("tag"))
1730
+ });
1731
+ }
1732
+ if (signatures.length === 0) return null;
1733
+ return { signatures };
1734
+ }
1735
+ function readHeader(headers, name) {
1736
+ for (const key of Object.keys(headers)) {
1737
+ if (key.toLowerCase() === name) {
1738
+ const raw = headers[key];
1739
+ if (typeof raw === "string") return raw;
1740
+ if (Array.isArray(raw)) return raw.join(", ");
1741
+ return null;
1742
+ }
1743
+ }
1744
+ return null;
1745
+ }
1746
+ function coerceString(value) {
1747
+ if (typeof value === "string") return value;
1748
+ if (value == null) return void 0;
1749
+ if (typeof value === "object" && "toString" in value) {
1750
+ const s = String(value);
1751
+ return s.length > 0 ? s : void 0;
1752
+ }
1753
+ return void 0;
1754
+ }
1755
+ function coerceNumber(value) {
1756
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1757
+ if (typeof value === "bigint") return Number(value);
1758
+ return void 0;
1759
+ }
1760
+ function extractBase64(value) {
1761
+ if (value instanceof Uint8Array) return bufferToBase64(value);
1762
+ if (value instanceof ArrayBuffer) return bufferToBase64(new Uint8Array(value));
1763
+ if (ArrayBuffer.isView(value)) {
1764
+ const v = value;
1765
+ return bufferToBase64(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
1766
+ }
1767
+ if (typeof value === "string") {
1768
+ if (value.startsWith(":") && value.endsWith(":")) return value.slice(1, -1);
1769
+ return value;
1770
+ }
1771
+ return null;
1772
+ }
1773
+ function bufferToBase64(bytes) {
1774
+ return Buffer.from(bytes).toString("base64");
1775
+ }
1776
+
1777
+ // src/transport/rfc9421-verify.ts
1778
+ var import_http_message_signatures = require("http-message-signatures");
1779
+ async function verifyRFC9421(request, options) {
1780
+ const { resolver } = options;
1781
+ const tolerance = options.clockSkewSec ?? 300;
1782
+ const nowSec = options.now ? options.now() : Math.floor(Date.now() / 1e3);
1783
+ let resolvedKid;
1784
+ let resolvedAlg;
1785
+ const keyLookup = async (parameters) => {
1786
+ const kid = typeof parameters.keyid === "string" ? parameters.keyid : void 0;
1787
+ if (!kid) return null;
1788
+ resolvedKid = kid;
1789
+ const alg = typeof parameters.alg === "string" ? parameters.alg : void 0;
1790
+ if (alg) resolvedAlg = alg;
1791
+ const origin = safeOrigin(request.url);
1792
+ const jwk = await resolver.resolve(kid, { origin, algorithm: alg });
1793
+ if (!jwk) return null;
1794
+ const created = toUnixSeconds(parameters.created);
1795
+ const expires = toUnixSeconds(parameters.expires);
1796
+ if (created !== void 0 && Math.abs(nowSec - created) > tolerance) return null;
1797
+ if (expires !== void 0 && nowSec > expires + tolerance) return null;
1798
+ return jwkToVerifyingKey(kid, jwk, alg);
1799
+ };
1800
+ try {
1801
+ const result = await import_http_message_signatures.httpbis.verifyMessage(
1802
+ {
1803
+ keyLookup
1804
+ },
1805
+ normalizeRequest(request)
1806
+ );
1807
+ if (result === true) {
1808
+ return {
1809
+ ok: true,
1810
+ kid: resolvedKid,
1811
+ registry: resolver.name,
1812
+ algorithm: resolvedAlg
1813
+ };
1814
+ }
1815
+ return {
1816
+ ok: false,
1817
+ kid: resolvedKid,
1818
+ registry: resolver.name,
1819
+ algorithm: resolvedAlg,
1820
+ error: result === false ? "signature invalid" : "no signature found"
1821
+ };
1822
+ } catch (err) {
1823
+ return {
1824
+ ok: false,
1825
+ kid: resolvedKid,
1826
+ registry: resolver.name,
1827
+ algorithm: resolvedAlg,
1828
+ error: err instanceof Error ? err.message : "verification error"
1829
+ };
1830
+ }
1831
+ }
1832
+ function normalizeRequest(request) {
1833
+ return {
1834
+ method: request.method.toUpperCase(),
1835
+ url: request.url,
1836
+ headers: request.headers
1837
+ };
1838
+ }
1839
+ function safeOrigin(url) {
1840
+ try {
1841
+ return new URL(url).origin;
1842
+ } catch {
1843
+ return void 0;
1844
+ }
1845
+ }
1846
+ async function jwkToVerifyingKey(id, jwk, alg) {
1847
+ const algorithm = alg ?? inferAlgFromJwk(jwk);
1848
+ const { subtle } = await getCrypto();
1849
+ const importAlg = webCryptoImportAlgFor(algorithm);
1850
+ const verifyAlg = webCryptoAlgFor(algorithm);
1851
+ if (!importAlg || !verifyAlg) {
1852
+ return {
1853
+ id,
1854
+ algs: alg ? [alg] : void 0,
1855
+ verify: async () => false
1856
+ };
1857
+ }
1858
+ const key = await subtle.importKey("jwk", jwk, importAlg, false, ["verify"]);
1859
+ return {
1860
+ id,
1861
+ algs: alg ? [alg] : void 0,
1862
+ verify: async (data, signature) => {
1863
+ try {
1864
+ return await subtle.verify(verifyAlg, key, toArrayBuffer(signature), toArrayBuffer(data));
1865
+ } catch {
1866
+ return false;
1867
+ }
1868
+ }
1869
+ };
1870
+ }
1871
+ function inferAlgFromJwk(jwk) {
1872
+ if (jwk.kty === "OKP" && jwk.crv === "Ed25519") return "ed25519";
1873
+ if (jwk.kty === "EC" && jwk.crv === "P-256") return "ecdsa-p256-sha256";
1874
+ if (jwk.kty === "EC" && jwk.crv === "P-384") return "ecdsa-p384-sha384";
1875
+ if (jwk.kty === "RSA") return "rsa-v1_5-sha256";
1876
+ return "ecdsa-p256-sha256";
1877
+ }
1878
+ function webCryptoAlgFor(rfc9421Alg) {
1879
+ switch (rfc9421Alg) {
1880
+ case "ed25519":
1881
+ return { name: "Ed25519" };
1882
+ case "ecdsa-p256-sha256":
1883
+ return { name: "ECDSA", hash: "SHA-256" };
1884
+ case "ecdsa-p384-sha384":
1885
+ return { name: "ECDSA", hash: "SHA-384" };
1886
+ case "rsa-v1_5-sha256":
1887
+ return { name: "RSASSA-PKCS1-v1_5" };
1888
+ case "rsa-pss-sha512":
1889
+ return { name: "RSA-PSS", saltLength: 64 };
1430
1890
  default:
1431
- return target;
1891
+ return null;
1432
1892
  }
1433
1893
  }
1434
- function extractCredentialsFromProtocol(protocol, context) {
1435
- switch (protocol) {
1436
- case "http":
1437
- return extractHttpCredentials(context);
1438
- case "a2a":
1439
- return extractA2ACredentials(context);
1440
- case "mcp":
1441
- return extractMcpCredentials(context);
1894
+ function webCryptoImportAlgFor(rfc9421Alg) {
1895
+ switch (rfc9421Alg) {
1896
+ case "ed25519":
1897
+ return { name: "Ed25519" };
1898
+ case "ecdsa-p256-sha256":
1899
+ return { name: "ECDSA", namedCurve: "P-256" };
1900
+ case "ecdsa-p384-sha384":
1901
+ return { name: "ECDSA", namedCurve: "P-384" };
1902
+ case "rsa-v1_5-sha256":
1903
+ return { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
1904
+ case "rsa-pss-sha512":
1905
+ return { name: "RSA-PSS", hash: "SHA-512" };
1442
1906
  default:
1443
1907
  return null;
1444
1908
  }
1445
1909
  }
1910
+ function toArrayBuffer(buf) {
1911
+ const out = new ArrayBuffer(buf.byteLength);
1912
+ new Uint8Array(out).set(buf);
1913
+ return out;
1914
+ }
1915
+ function toUnixSeconds(v) {
1916
+ if (typeof v === "number" && Number.isFinite(v)) return v;
1917
+ if (v instanceof Date) return Math.floor(v.getTime() / 1e3);
1918
+ if (typeof v === "string") {
1919
+ const parsed = Date.parse(v);
1920
+ if (Number.isFinite(parsed)) return Math.floor(parsed / 1e3);
1921
+ }
1922
+ return void 0;
1923
+ }
1924
+ async function getCrypto() {
1925
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
1926
+ return { subtle: globalThis.crypto.subtle };
1927
+ }
1928
+ const nodeCrypto = await import("crypto");
1929
+ return { subtle: nodeCrypto.webcrypto.subtle };
1930
+ }
1446
1931
 
1447
- // src/agent/index.ts
1448
- var agent_exports = {};
1449
- __export(agent_exports, {
1450
- AgentClient: () => AgentClient,
1451
- ChallengeHandler: () => ChallengeHandler,
1452
- formatPDLSSForTransport: () => formatPDLSSForTransport,
1453
- parsePDLSSFromTransport: () => parsePDLSSFromTransport,
1454
- recordDecision: () => recordDecision2
1455
- });
1932
+ // src/transport/ucp.ts
1933
+ function extractUCPContext(request) {
1934
+ const { method, url } = request;
1935
+ if (!method || !url) return null;
1936
+ const parsedUrl = safeParseUrl(url);
1937
+ const path = parsedUrl?.pathname ?? url.split("?")[0];
1938
+ const purpose = mapUCPRequestToPurpose(method, path);
1939
+ const endpoint = `${method.toUpperCase()} ${path}`;
1940
+ const sessionId = extractSessionId(path);
1941
+ const body = request.body ?? {};
1942
+ const totals = Array.isArray(body.totals) ? body.totals : void 0;
1943
+ const paymentMethod = coerceString2(body.payment_method ?? body.paymentMethod);
1944
+ const manifestUrl = coerceString2(body.manifest_url ?? body.manifestUrl);
1945
+ const merchantDomain = extractMerchantDomain(body, parsedUrl);
1946
+ return {
1947
+ sessionId,
1948
+ endpoint,
1949
+ purpose,
1950
+ merchantDomain,
1951
+ totals,
1952
+ paymentMethod,
1953
+ manifestUrl
1954
+ };
1955
+ }
1956
+ async function fetchUCPManifest(manifestUrl, options = {}) {
1957
+ const timeoutMs = options.timeoutMs ?? 3e3;
1958
+ const controller = new AbortController();
1959
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1960
+ try {
1961
+ const res = await fetch(manifestUrl, { signal: controller.signal });
1962
+ if (!res.ok) return null;
1963
+ return await res.json();
1964
+ } catch {
1965
+ return null;
1966
+ } finally {
1967
+ clearTimeout(timer);
1968
+ }
1969
+ }
1970
+ function validateUCPManifest(manifest, options = {}) {
1971
+ if (options.validator) return options.validator(manifest);
1972
+ const errors = [];
1973
+ if (!manifest || typeof manifest !== "object") {
1974
+ return { ok: false, errors: ["manifest is not an object"] };
1975
+ }
1976
+ const m = manifest;
1977
+ if (typeof m.version !== "string") errors.push("version is required and must be a string");
1978
+ if (!Array.isArray(m.capabilities)) errors.push("capabilities must be an array");
1979
+ if (!m.endpoints || typeof m.endpoints !== "object") errors.push("endpoints must be an object");
1980
+ return { ok: errors.length === 0, errors };
1981
+ }
1982
+ function safeParseUrl(url) {
1983
+ try {
1984
+ return new URL(url, "http://placeholder.invalid");
1985
+ } catch {
1986
+ return null;
1987
+ }
1988
+ }
1989
+ function extractSessionId(path) {
1990
+ const match = path.match(/\/checkout[-_]sessions\/([^/?#]+)/);
1991
+ return match?.[1];
1992
+ }
1993
+ function extractMerchantDomain(body, parsedUrl) {
1994
+ const explicit = coerceString2(body.merchant_domain ?? body.merchantDomain);
1995
+ if (explicit) return explicit;
1996
+ if (parsedUrl && parsedUrl.hostname !== "placeholder.invalid") return parsedUrl.hostname;
1997
+ return void 0;
1998
+ }
1999
+ function coerceString2(v) {
2000
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2001
+ }
1456
2002
 
1457
- // src/agent/client.ts
1458
- var AgentClient = class {
1459
- constructor(config) {
1460
- this.credentials = {
1461
- agentId: config.agentId,
1462
- verifyUrl: config.verifyUrl ?? "https://api.astrasync.ai/agents/verify-access",
1463
- challengeUrl: config.challengeUrl,
1464
- pdlss: config.pdlss
2003
+ // src/transport/acp.ts
2004
+ function extractACPContext(request) {
2005
+ const { method, url } = request;
2006
+ if (!method || !url) return null;
2007
+ const path = stripQuery2(url.startsWith("http") ? new URL(url).pathname : url);
2008
+ const endpoint = classifyEndpoint(method, path);
2009
+ const purpose = mapACPRequestToPurpose(method, path);
2010
+ const sessionId = extractSessionId2(path);
2011
+ const headers = request.headers ?? {};
2012
+ const signatureHeader = readHeader2(headers, "signature");
2013
+ const timestampHeader = readHeader2(headers, "timestamp");
2014
+ const idempotencyKey = readHeader2(headers, "idempotency-key");
2015
+ const apiVersion = readHeader2(headers, "api-version");
2016
+ const bearer = extractBearer(readHeader2(headers, "authorization"));
2017
+ const body = request.body ?? {};
2018
+ const merchantId = coerceString3(body.merchant_id ?? body.merchantId);
2019
+ const totals = Array.isArray(body.totals) ? body.totals : void 0;
2020
+ const fulfillmentOption = extractFulfillmentOption(body);
2021
+ const paymentToken = extractPaymentToken(body);
2022
+ return {
2023
+ endpoint,
2024
+ purpose,
2025
+ sessionId,
2026
+ merchantId,
2027
+ apiVersion,
2028
+ bearer,
2029
+ signatureHeader,
2030
+ timestampHeader,
2031
+ idempotencyKey,
2032
+ paymentToken,
2033
+ totals,
2034
+ fulfillmentOption,
2035
+ rawBody: request.rawBody
2036
+ };
2037
+ }
2038
+ function classifyEndpoint(method, path) {
2039
+ const m = method.toUpperCase();
2040
+ if (m !== "POST") return "unknown";
2041
+ if (/^\/agentic_commerce\/delegate_payment\/?$/.test(path)) return "delegate_payment";
2042
+ if (/^\/checkout_sessions\/?$/.test(path)) return "checkout_sessions.create";
2043
+ if (/^\/checkout_sessions\/[^/]+\/?$/.test(path)) return "checkout_sessions.update";
2044
+ if (/^\/checkout_sessions\/[^/]+\/complete\/?$/.test(path)) return "checkout_sessions.complete";
2045
+ if (/^\/checkout_sessions\/[^/]+\/cancel\/?$/.test(path)) return "checkout_sessions.cancel";
2046
+ return "unknown";
2047
+ }
2048
+ function extractSessionId2(path) {
2049
+ const match = path.match(/\/checkout_sessions\/([^/?#]+)/);
2050
+ return match?.[1];
2051
+ }
2052
+ function extractBearer(authHeader) {
2053
+ if (!authHeader) return void 0;
2054
+ const match = authHeader.match(/^Bearer\s+(.+)$/i);
2055
+ return match ? match[1].trim() : void 0;
2056
+ }
2057
+ function extractPaymentToken(body) {
2058
+ const paymentData = body.payment_data;
2059
+ if (!paymentData) return void 0;
2060
+ const raw = coerceString3(paymentData.token);
2061
+ const provider = coerceString3(paymentData.provider);
2062
+ if (!raw) return { raw: void 0, type: null, provider };
2063
+ const type = classifyPaymentToken(raw);
2064
+ return { raw, type, provider };
2065
+ }
2066
+ function classifyPaymentToken(token) {
2067
+ if (token.startsWith("spt_")) return "stripe-spt";
2068
+ if (token.startsWith("vt_")) return "acp-vt";
2069
+ return "other";
2070
+ }
2071
+ function extractFulfillmentOption(body) {
2072
+ const direct = coerceString3(body.fulfillment_option ?? body.fulfillmentOption);
2073
+ if (direct) return direct;
2074
+ const options = body.fulfillment_options;
2075
+ if (Array.isArray(options) && options.length > 0) {
2076
+ const first = options[0];
2077
+ if (first && typeof first === "object") {
2078
+ const id = coerceString3(first.id);
2079
+ if (id) return id;
2080
+ }
2081
+ }
2082
+ return void 0;
2083
+ }
2084
+ function readHeader2(headers, name) {
2085
+ for (const key of Object.keys(headers)) {
2086
+ if (key.toLowerCase() === name) {
2087
+ const raw = headers[key];
2088
+ if (typeof raw === "string") return raw;
2089
+ if (Array.isArray(raw)) return raw[0];
2090
+ }
2091
+ }
2092
+ return void 0;
2093
+ }
2094
+ function stripQuery2(path) {
2095
+ const q = path.indexOf("?");
2096
+ return q === -1 ? path : path.slice(0, q);
2097
+ }
2098
+ function coerceString3(v) {
2099
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2100
+ }
2101
+
2102
+ // src/transport/vi.ts
2103
+ var import_decode = require("@sd-jwt/decode");
2104
+ var import_node_crypto = require("crypto");
2105
+ function extractVIClaims(sdJwtCompact) {
2106
+ if (!sdJwtCompact || typeof sdJwtCompact !== "string") return null;
2107
+ let decoded;
2108
+ try {
2109
+ decoded = (0, import_decode.decodeSdJwtSync)(sdJwtCompact, sha256Sync);
2110
+ } catch {
2111
+ return null;
2112
+ }
2113
+ const split = safeSplit(sdJwtCompact);
2114
+ const payload = decoded.jwt?.payload ?? {};
2115
+ const disclosures = decoded.disclosures ?? [];
2116
+ const claims = applyDisclosures(
2117
+ payload,
2118
+ disclosures
2119
+ );
2120
+ const mandateType = coerceMandateType(
2121
+ claims.mandate_type ?? claims.mandateType ?? payload.mandate_type ?? payload.mandateType
2122
+ );
2123
+ if (!mandateType) return null;
2124
+ const kid = coerceString4(
2125
+ decoded.jwt?.header?.kid ?? claims.kid ?? payload.kid
2126
+ );
2127
+ const executionMode = coerceExecutionMode(claims.execution_mode ?? claims.executionMode);
2128
+ const credentialProvider = coerceString4(claims.iss ?? payload.iss);
2129
+ const constraints = extractConstraints(
2130
+ claims.constraints ?? claims.default_constraints ?? {}
2131
+ );
2132
+ const transactionId = coerceString4(claims.transaction_id ?? claims.transactionId);
2133
+ const checkoutHash = coerceString4(
2134
+ claims.checkout_hash ?? claims.conditional_transaction_id ?? claims.payment_reference?.checkout_hash
2135
+ );
2136
+ return {
2137
+ mandateType,
2138
+ kid,
2139
+ executionMode,
2140
+ credentialProvider,
2141
+ constraints,
2142
+ checkoutHash,
2143
+ transactionId,
2144
+ rawLayers: split
2145
+ };
2146
+ }
2147
+ function safeSplit(compact) {
2148
+ try {
2149
+ const { jwt, kbJwt } = (0, import_decode.splitSdJwt)(compact);
2150
+ return { l3: jwt, l2: kbJwt };
2151
+ } catch {
2152
+ return {};
2153
+ }
2154
+ }
2155
+ function applyDisclosures(payload, disclosures) {
2156
+ const result = { ...payload };
2157
+ for (const d of disclosures) {
2158
+ if (d.key && d.value !== void 0 && !(d.key in result)) {
2159
+ result[d.key] = d.value;
2160
+ }
2161
+ }
2162
+ return result;
2163
+ }
2164
+ function extractConstraints(raw) {
2165
+ return {
2166
+ allowedMerchants: toAllowedPartyArray(raw.allowed_merchants ?? raw.allowedMerchants),
2167
+ allowedPayees: toAllowedPartyArray(raw.allowed_payees ?? raw.allowedPayees),
2168
+ lineItems: toLineItemArray(raw.line_items ?? raw.lineItems),
2169
+ paymentAmount: toPaymentAmount(raw.payment_amount ?? raw.paymentAmount),
2170
+ budgetLimit: toBudgetLimit(raw.budget_limit ?? raw.budgetLimit ?? raw.budget),
2171
+ recurrence: toRecurrence(raw.recurrence),
2172
+ agentRecurrence: toRecurrence(raw.agent_recurrence ?? raw.agentRecurrence)
2173
+ };
2174
+ }
2175
+ function toAllowedPartyArray(v) {
2176
+ if (!Array.isArray(v)) return void 0;
2177
+ const out = [];
2178
+ for (const item of v) {
2179
+ if (item && typeof item === "object") {
2180
+ const r = item;
2181
+ out.push({
2182
+ id: coerceString4(r.id),
2183
+ name: coerceString4(r.name),
2184
+ website: coerceString4(r.website)
2185
+ });
2186
+ }
2187
+ }
2188
+ return out.length > 0 ? out : void 0;
2189
+ }
2190
+ function toLineItemArray(v) {
2191
+ if (!Array.isArray(v)) return void 0;
2192
+ const out = [];
2193
+ for (const item of v) {
2194
+ if (item && typeof item === "object") {
2195
+ const r = item;
2196
+ const acc = r.acceptable_items ?? r.acceptableItems;
2197
+ out.push({
2198
+ id: coerceString4(r.id),
2199
+ acceptableItems: Array.isArray(acc) ? acc.filter((a) => typeof a === "string") : void 0,
2200
+ quantity: coerceNumber2(r.quantity)
2201
+ });
2202
+ }
2203
+ }
2204
+ return out.length > 0 ? out : void 0;
2205
+ }
2206
+ function toPaymentAmount(v) {
2207
+ if (!v || typeof v !== "object") return void 0;
2208
+ const r = v;
2209
+ return {
2210
+ currency: coerceString4(r.currency),
2211
+ min: coerceNumber2(r.min),
2212
+ max: coerceNumber2(r.max)
2213
+ };
2214
+ }
2215
+ function toBudgetLimit(v) {
2216
+ if (!v || typeof v !== "object") return void 0;
2217
+ const r = v;
2218
+ return {
2219
+ currency: coerceString4(r.currency),
2220
+ max: coerceNumber2(r.max)
2221
+ };
2222
+ }
2223
+ function toRecurrence(v) {
2224
+ if (!v || typeof v !== "object") return void 0;
2225
+ const r = v;
2226
+ return {
2227
+ frequency: coerceString4(r.frequency),
2228
+ startDate: coerceString4(r.start_date ?? r.startDate),
2229
+ endDate: coerceString4(r.end_date ?? r.endDate),
2230
+ maxOccurrences: coerceNumber2(r.max_occurrences ?? r.maxOccurrences)
2231
+ };
2232
+ }
2233
+ function coerceMandateType(v) {
2234
+ if (v === "checkout" || v === "payment" || v === "checkout.open" || v === "payment.open") {
2235
+ return v;
2236
+ }
2237
+ return null;
2238
+ }
2239
+ function coerceExecutionMode(v) {
2240
+ return v === "Immediate" || v === "Autonomous" || v === "Both" ? v : void 0;
2241
+ }
2242
+ function coerceString4(v) {
2243
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2244
+ }
2245
+ function coerceNumber2(v) {
2246
+ if (typeof v === "number" && Number.isFinite(v)) return v;
2247
+ if (typeof v === "string") {
2248
+ const n = Number(v);
2249
+ return Number.isFinite(n) ? n : void 0;
2250
+ }
2251
+ return void 0;
2252
+ }
2253
+ function sha256Sync(data) {
2254
+ const buf = typeof data === "string" ? Buffer.from(data, "utf-8") : Buffer.from(new Uint8Array(data));
2255
+ const hash = (0, import_node_crypto.createHash)("sha256").update(buf).digest();
2256
+ return new Uint8Array(hash.buffer, hash.byteOffset, hash.byteLength);
2257
+ }
2258
+
2259
+ // src/transport/stripe-webhook.ts
2260
+ var import_node_crypto2 = require("crypto");
2261
+ function verifyStripeWebhook(payload, signatureHeader, secret, options = {}) {
2262
+ if (!signatureHeader) return { ok: false, error: "missing Stripe-Signature header" };
2263
+ if (!secret) return { ok: false, error: "missing webhook secret" };
2264
+ const parsed = parseStripeSignature(signatureHeader);
2265
+ if (!parsed.timestamp) return { ok: false, error: "malformed Stripe-Signature (missing t=)" };
2266
+ if (parsed.v1Signatures.length === 0) {
2267
+ return { ok: false, error: "malformed Stripe-Signature (no v1=)" };
2268
+ }
2269
+ const tolerance = options.toleranceSec ?? 300;
2270
+ const now = options.now ? options.now() : Math.floor(Date.now() / 1e3);
2271
+ if (Math.abs(now - parsed.timestamp) > tolerance) {
2272
+ return {
2273
+ ok: false,
2274
+ timestamp: parsed.timestamp,
2275
+ error: `timestamp outside tolerance (${tolerance}s)`
1465
2276
  };
1466
2277
  }
2278
+ const signedPayload = `${parsed.timestamp}.${payload}`;
2279
+ const expected = (0, import_node_crypto2.createHmac)("sha256", secret).update(signedPayload).digest();
2280
+ for (const candidateHex of parsed.v1Signatures) {
2281
+ const candidate = hexToBuffer(candidateHex);
2282
+ if (!candidate) continue;
2283
+ if (candidate.length !== expected.length) continue;
2284
+ if ((0, import_node_crypto2.timingSafeEqual)(candidate, expected)) {
2285
+ return { ok: true, timestamp: parsed.timestamp };
2286
+ }
2287
+ }
2288
+ return { ok: false, timestamp: parsed.timestamp, error: "signature mismatch" };
2289
+ }
2290
+ function parseStripeSignature(header) {
2291
+ let timestamp = null;
2292
+ const v1Signatures = [];
2293
+ for (const part of header.split(",")) {
2294
+ const [rawKey, rawValue] = part.split("=");
2295
+ if (!rawKey || !rawValue) continue;
2296
+ const key = rawKey.trim();
2297
+ const value = rawValue.trim();
2298
+ if (key === "t") {
2299
+ const n = Number(value);
2300
+ if (Number.isFinite(n)) timestamp = n;
2301
+ } else if (key === "v1") {
2302
+ v1Signatures.push(value);
2303
+ }
2304
+ }
2305
+ return { timestamp, v1Signatures };
2306
+ }
2307
+ function hexToBuffer(hex) {
2308
+ if (!/^[0-9a-fA-F]+$/.test(hex) || hex.length % 2 !== 0) return null;
2309
+ return Buffer.from(hex, "hex");
2310
+ }
2311
+
2312
+ // src/transport/constraint-eval.ts
2313
+ function evaluateVIConstraints(input) {
2314
+ const { constraints, transaction } = input;
2315
+ const results = {};
2316
+ if (constraints.allowedMerchants && constraints.allowedMerchants.length > 0) {
2317
+ results.merchant = evaluateAllowlist(
2318
+ "merchant",
2319
+ constraints.allowedMerchants,
2320
+ transaction.merchant
2321
+ );
2322
+ }
2323
+ if (constraints.allowedPayees && constraints.allowedPayees.length > 0) {
2324
+ results.payee = evaluateAllowlist("payee", constraints.allowedPayees, transaction.payee);
2325
+ }
2326
+ if (constraints.lineItems && constraints.lineItems.length > 0) {
2327
+ results.lineItems = evaluateLineItems(constraints.lineItems, transaction.lineItems ?? []);
2328
+ }
2329
+ if (constraints.paymentAmount) {
2330
+ results.amount = evaluatePaymentAmount(constraints.paymentAmount, transaction);
2331
+ }
2332
+ const reasons = [];
2333
+ let ok = true;
2334
+ for (const [key, r] of Object.entries(results)) {
2335
+ if (!r.ok) {
2336
+ ok = false;
2337
+ reasons.push(r.reason ?? `${key} failed`);
2338
+ }
2339
+ }
2340
+ return { ok, results, reasons };
2341
+ }
2342
+ function evaluatePaymentMethodAllowlist(input) {
2343
+ const allow = input.allowedMethods ?? [];
2344
+ if (allow.length === 0) return { ok: true };
2345
+ if (!input.requestedMethod) {
2346
+ return { ok: false, reason: "no payment method in request; allowlist configured" };
2347
+ }
2348
+ const lowered = input.requestedMethod.toLowerCase();
2349
+ const allowed = allow.some((m) => m.toLowerCase() === lowered);
2350
+ if (!allowed) {
2351
+ return {
2352
+ ok: false,
2353
+ reason: `payment method "${input.requestedMethod}" not in allowlist [${allow.join(", ")}]`
2354
+ };
2355
+ }
2356
+ return { ok: true };
2357
+ }
2358
+ function evaluateSpendingLimit(input) {
2359
+ const { limit, requested } = input;
2360
+ if (!limit || typeof limit.amount !== "number") return { ok: true };
2361
+ if (!requested || typeof requested.amount !== "number") return { ok: true };
2362
+ if (limit.currency && requested.currency && limit.currency !== requested.currency) {
2363
+ return {
2364
+ ok: false,
2365
+ reason: `currency mismatch: limit ${limit.currency} vs requested ${requested.currency}`
2366
+ };
2367
+ }
2368
+ if (requested.amount > limit.amount) {
2369
+ return {
2370
+ ok: false,
2371
+ reason: `requested ${requested.amount} ${requested.currency ?? ""} exceeds limit ${limit.amount} ${limit.currency ?? ""}`.trim()
2372
+ };
2373
+ }
2374
+ return { ok: true };
2375
+ }
2376
+ function evaluateAllowlist(kind, allowlist, actual) {
2377
+ if (!actual || !actual.id && !actual.website) {
2378
+ return { ok: false, reason: `no ${kind} in transaction; allowlist configured` };
2379
+ }
2380
+ for (const entry of allowlist) {
2381
+ if (entry.id && actual.id && entry.id === actual.id) return { ok: true };
2382
+ if (entry.website && actual.website && domainsMatch(entry.website, actual.website)) {
2383
+ return { ok: true };
2384
+ }
2385
+ }
2386
+ const allowedDescriptors = allowlist.map(describeParty).join(", ");
2387
+ const actualDescriptor = describeParty(actual);
2388
+ return {
2389
+ ok: false,
2390
+ reason: `${kind} ${actualDescriptor} not in allowlist [${allowedDescriptors}]`
2391
+ };
2392
+ }
2393
+ function evaluateLineItems(allowlist, actualItems) {
2394
+ if (actualItems.length === 0) {
2395
+ return { ok: false, reason: "no line items in transaction; allowlist configured" };
2396
+ }
2397
+ const reasons = [];
2398
+ for (const item of actualItems) {
2399
+ const match = allowlist.find(
2400
+ (a) => a.id && a.id === item.id || (a.acceptableItems ?? []).includes(item.id ?? "")
2401
+ );
2402
+ if (!match) {
2403
+ reasons.push(`line item "${item.id ?? "(unnamed)"}" not in allowlist`);
2404
+ continue;
2405
+ }
2406
+ if (typeof match.quantity === "number" && typeof item.quantity === "number" && item.quantity > match.quantity) {
2407
+ reasons.push(
2408
+ `line item "${item.id}" quantity ${item.quantity} exceeds allowed ${match.quantity}`
2409
+ );
2410
+ }
2411
+ }
2412
+ return reasons.length === 0 ? { ok: true } : { ok: false, reason: reasons.join("; ") };
2413
+ }
2414
+ function evaluatePaymentAmount(bound, transaction) {
2415
+ if (typeof transaction.amount !== "number") {
2416
+ return { ok: false, reason: "no amount in transaction; paymentAmount bound configured" };
2417
+ }
2418
+ if (bound.currency && transaction.currency && bound.currency !== transaction.currency) {
2419
+ return {
2420
+ ok: false,
2421
+ reason: `currency mismatch: bound ${bound.currency} vs transaction ${transaction.currency}`
2422
+ };
2423
+ }
2424
+ if (typeof bound.min === "number" && transaction.amount < bound.min) {
2425
+ return {
2426
+ ok: false,
2427
+ reason: `amount ${transaction.amount} below min ${bound.min}`
2428
+ };
2429
+ }
2430
+ if (typeof bound.max === "number" && transaction.amount > bound.max) {
2431
+ return {
2432
+ ok: false,
2433
+ reason: `amount ${transaction.amount} above max ${bound.max}`
2434
+ };
2435
+ }
2436
+ return { ok: true };
2437
+ }
2438
+ function domainsMatch(allow, actual) {
2439
+ const a = normalizeDomain(allow);
2440
+ const b = normalizeDomain(actual);
2441
+ return a === b || b.endsWith(`.${a}`);
2442
+ }
2443
+ function normalizeDomain(value) {
2444
+ try {
2445
+ const withScheme = /^https?:\/\//.test(value) ? value : `https://${value}`;
2446
+ return new URL(withScheme).hostname.toLowerCase();
2447
+ } catch {
2448
+ return value.toLowerCase();
2449
+ }
2450
+ }
2451
+ function describeParty(party) {
2452
+ if (party.id) return `id:${party.id}`;
2453
+ if (party.website) return party.website;
2454
+ if (party.name) return party.name;
2455
+ return "(unnamed)";
2456
+ }
2457
+
2458
+ // src/transport/identity-binding.ts
2459
+ async function bindIdentity(claims, resolver) {
2460
+ const resolutions = [];
2461
+ for (const claim2 of claims) {
2462
+ if (!claim2.value) {
2463
+ resolutions.push({ claim: claim2, agentId: null });
2464
+ continue;
2465
+ }
2466
+ const agentId = await resolver(claim2);
2467
+ resolutions.push({ claim: claim2, agentId });
2468
+ }
2469
+ const resolvedIds = resolutions.map((r) => r.agentId).filter((id) => typeof id === "string" && id.length > 0);
2470
+ const unique = Array.from(new Set(resolvedIds));
2471
+ const mismatchAcrossLayers = unique.length > 1;
2472
+ const mappedAstraSyncAgentId = unique.length === 1 ? unique[0] : void 0;
2473
+ return {
2474
+ claims,
2475
+ mappedAstraSyncAgentId,
2476
+ mismatchAcrossLayers,
2477
+ resolutions
2478
+ };
2479
+ }
2480
+ var claim = {
2481
+ viKid: (value) => ({ protocol: "vi", field: "kid", value }),
2482
+ ap2AgentId: (value) => ({ protocol: "ap2", field: "agent_id", value }),
2483
+ acpBearer: (value) => ({ protocol: "acp", field: "bearer", value }),
2484
+ mppSource: (value) => ({ protocol: "mpp", field: "source", value }),
2485
+ x402Wallet: (value) => ({ protocol: "x402", field: "wallet", value }),
2486
+ agentPayKid: (value) => ({ protocol: "agentpay", field: "kid", value }),
2487
+ tapKid: (value) => ({ protocol: "tap", field: "kid", value }),
2488
+ webBotAuthKid: (value) => ({
2489
+ protocol: "webbotauth",
2490
+ field: "kid",
2491
+ value
2492
+ })
2493
+ };
2494
+
2495
+ // src/transport/ap2.ts
2496
+ var import_decode2 = require("@sd-jwt/decode");
2497
+ var import_node_crypto3 = require("crypto");
2498
+ function extractAP2Mandate(sdJwtCompact) {
2499
+ if (!sdJwtCompact || typeof sdJwtCompact !== "string") return null;
2500
+ let decoded;
2501
+ try {
2502
+ decoded = (0, import_decode2.decodeSdJwtSync)(sdJwtCompact, sha256Sync2);
2503
+ } catch {
2504
+ return null;
2505
+ }
2506
+ const payload = decoded.jwt?.payload ?? {};
2507
+ const disclosures = decoded.disclosures ?? [];
2508
+ const claims = applyDisclosures2(
2509
+ payload,
2510
+ disclosures
2511
+ );
2512
+ const type = coerceMandateType2(claims.type ?? claims.mandate_type ?? claims.mandateType);
2513
+ if (!type) return null;
2514
+ if (type === "intent_mandate") return buildIntent(claims);
2515
+ if (type === "cart_mandate") return buildCart(claims);
2516
+ return buildPayment(claims);
2517
+ }
2518
+ function extractAP2Mandates(input) {
2519
+ const intent = input.intent ? extractAP2Mandate(input.intent) : null;
2520
+ const cart = input.cart ? extractAP2Mandate(input.cart) : null;
2521
+ const payment = input.payment ? extractAP2Mandate(input.payment) : null;
2522
+ return {
2523
+ intent: intent ?? void 0,
2524
+ cart: cart ?? void 0,
2525
+ payment: payment ?? void 0,
2526
+ rawLayers: {
2527
+ intentJwt: input.intent,
2528
+ cartJwt: input.cart,
2529
+ paymentJwt: input.payment
2530
+ }
2531
+ };
2532
+ }
2533
+ function buildIntent(claims) {
2534
+ return {
2535
+ type: "intent_mandate",
2536
+ agent_id: coerceString5(claims.agent_id ?? claims.agentId),
2537
+ user_id: coerceString5(claims.user_id ?? claims.userId ?? claims.sub),
2538
+ merchant_category: coerceString5(claims.merchant_category ?? claims.merchantCategory),
2539
+ allowedMerchantDomains: toStringArray(
2540
+ claims.allowed_merchant_domains ?? claims.allowedMerchantDomains
2541
+ ),
2542
+ paymentMethods: toStringArray(claims.payment_methods ?? claims.paymentMethods),
2543
+ expires: coerceString5(claims.expires ?? claims.exp),
2544
+ payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
2545
+ raw: claims
2546
+ };
2547
+ }
2548
+ function buildCart(claims) {
2549
+ return {
2550
+ type: "cart_mandate",
2551
+ agent_id: coerceString5(claims.agent_id ?? claims.agentId),
2552
+ intent_mandate_id: coerceString5(claims.intent_mandate_id ?? claims.intentMandateId),
2553
+ merchant_id: coerceString5(claims.merchant_id ?? claims.merchantId),
2554
+ line_items: toLineItems(claims.line_items ?? claims.lineItems),
2555
+ payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
2556
+ expires: coerceString5(claims.expires ?? claims.exp),
2557
+ raw: claims
2558
+ };
2559
+ }
2560
+ function buildPayment(claims) {
2561
+ return {
2562
+ type: "payment_mandate",
2563
+ agent_id: coerceString5(claims.agent_id ?? claims.agentId),
2564
+ cart_mandate_id: coerceString5(claims.cart_mandate_id ?? claims.cartMandateId),
2565
+ payment_method: coerceString5(claims.payment_method ?? claims.paymentMethod),
2566
+ payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
2567
+ credential_provider: coerceString5(claims.credential_provider ?? claims.credentialProvider),
2568
+ raw: claims
2569
+ };
2570
+ }
2571
+ function toPaymentDetails(v) {
2572
+ if (!v || typeof v !== "object") return void 0;
2573
+ const r = v;
2574
+ const amount = r.amount;
2575
+ return {
2576
+ amount: amount ? {
2577
+ value: coerceStringOrNumber(amount.value),
2578
+ currency: coerceString5(amount.currency)
2579
+ } : void 0,
2580
+ label: coerceString5(r.label)
2581
+ };
2582
+ }
2583
+ function toLineItems(v) {
2584
+ if (!Array.isArray(v)) return void 0;
2585
+ const items = [];
2586
+ for (const item of v) {
2587
+ if (!item || typeof item !== "object") continue;
2588
+ const r = item;
2589
+ const price = r.price;
2590
+ items.push({
2591
+ id: coerceString5(r.id),
2592
+ quantity: coerceNumber3(r.quantity),
2593
+ price: price ? {
2594
+ value: coerceStringOrNumber(price.value),
2595
+ currency: coerceString5(price.currency)
2596
+ } : void 0
2597
+ });
2598
+ }
2599
+ return items.length > 0 ? items : void 0;
2600
+ }
2601
+ function toStringArray(v) {
2602
+ if (!Array.isArray(v)) return void 0;
2603
+ const out = v.filter((i) => typeof i === "string" && i.length > 0);
2604
+ return out.length > 0 ? out : void 0;
2605
+ }
2606
+ function applyDisclosures2(payload, disclosures) {
2607
+ const result = { ...payload };
2608
+ for (const d of disclosures) {
2609
+ if (d.key && d.value !== void 0 && !(d.key in result)) {
2610
+ result[d.key] = d.value;
2611
+ }
2612
+ }
2613
+ return result;
2614
+ }
2615
+ function coerceMandateType2(v) {
2616
+ if (v === "intent_mandate" || v === "cart_mandate" || v === "payment_mandate") return v;
2617
+ return null;
2618
+ }
2619
+ function coerceString5(v) {
2620
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2621
+ }
2622
+ function coerceNumber3(v) {
2623
+ if (typeof v === "number" && Number.isFinite(v)) return v;
2624
+ if (typeof v === "string") {
2625
+ const n = Number(v);
2626
+ return Number.isFinite(n) ? n : void 0;
2627
+ }
2628
+ return void 0;
2629
+ }
2630
+ function coerceStringOrNumber(v) {
2631
+ if (typeof v === "number" && Number.isFinite(v)) return v;
2632
+ if (typeof v === "string" && v.length > 0) return v;
2633
+ return void 0;
2634
+ }
2635
+ function sha256Sync2(data) {
2636
+ const buf = typeof data === "string" ? Buffer.from(data, "utf-8") : Buffer.from(new Uint8Array(data));
2637
+ const hash = (0, import_node_crypto3.createHash)("sha256").update(buf).digest();
2638
+ return new Uint8Array(hash.buffer, hash.byteOffset, hash.byteLength);
2639
+ }
2640
+
2641
+ // src/transport/ap2-verify.ts
2642
+ function verifyAP2Chain(input) {
2643
+ const { triple } = input;
2644
+ const errors = [];
2645
+ const intentPresent = triple.intent !== void 0;
2646
+ const cartRefOk = checkCartRef(triple, errors);
2647
+ const paymentRefOk = checkPaymentRef(triple, errors);
2648
+ const { ok: agentIdContinuity, agentId } = checkAgentContinuity(triple, errors);
2649
+ const paymentMethodAllowed = checkPaymentMethod(triple, errors);
2650
+ const totalsConsistent = checkTotals(triple, errors);
2651
+ const expiryOk = checkExpiries(triple, input.clockSkewSec ?? 300, input.now, errors);
2652
+ const ok = cartRefOk && paymentRefOk && agentIdContinuity && paymentMethodAllowed && totalsConsistent && expiryOk;
2653
+ return {
2654
+ ok,
2655
+ checks: {
2656
+ intentPresent,
2657
+ cartRefOk,
2658
+ paymentRefOk,
2659
+ agentIdContinuity,
2660
+ paymentMethodAllowed,
2661
+ totalsConsistent,
2662
+ expiryOk
2663
+ },
2664
+ agentId,
2665
+ errors
2666
+ };
2667
+ }
2668
+ function checkCartRef(triple, errors) {
2669
+ const cart = triple.cart;
2670
+ if (!cart) return true;
2671
+ if (!cart.intent_mandate_id) return true;
2672
+ const intentId = triple.intent?.raw?.id;
2673
+ if (intentId && cart.intent_mandate_id !== intentId) {
2674
+ errors.push(
2675
+ `cart.intent_mandate_id (${cart.intent_mandate_id}) does not match intent.id (${intentId})`
2676
+ );
2677
+ return false;
2678
+ }
2679
+ return true;
2680
+ }
2681
+ function checkPaymentRef(triple, errors) {
2682
+ const payment = triple.payment;
2683
+ if (!payment) return true;
2684
+ if (!payment.cart_mandate_id) return true;
2685
+ const cartId = triple.cart?.raw?.id;
2686
+ if (cartId && payment.cart_mandate_id !== cartId) {
2687
+ errors.push(
2688
+ `payment.cart_mandate_id (${payment.cart_mandate_id}) does not match cart.id (${cartId})`
2689
+ );
2690
+ return false;
2691
+ }
2692
+ return true;
2693
+ }
2694
+ function checkAgentContinuity(triple, errors) {
2695
+ const ids = [triple.intent?.agent_id, triple.cart?.agent_id, triple.payment?.agent_id].filter(
2696
+ (id) => typeof id === "string" && id.length > 0
2697
+ );
2698
+ if (ids.length === 0) return { ok: true };
2699
+ const unique = new Set(ids);
2700
+ if (unique.size > 1) {
2701
+ errors.push(`agent_id mismatch across mandates: ${Array.from(unique).join(", ")}`);
2702
+ return { ok: false, agentId: void 0 };
2703
+ }
2704
+ return { ok: true, agentId: ids[0] };
2705
+ }
2706
+ function checkPaymentMethod(triple, errors) {
2707
+ const paymentMethod = triple.payment?.payment_method;
2708
+ const allowed = triple.intent?.paymentMethods;
2709
+ if (!paymentMethod || !allowed || allowed.length === 0) return true;
2710
+ if (!allowed.includes(paymentMethod)) {
2711
+ errors.push(
2712
+ `payment_method "${paymentMethod}" not in intent.paymentMethods [${allowed.join(", ")}]`
2713
+ );
2714
+ return false;
2715
+ }
2716
+ return true;
2717
+ }
2718
+ function checkTotals(triple, errors) {
2719
+ const intentTotal = toNumericAmount(triple.intent?.payment_details_total);
2720
+ const cartTotal = toNumericAmount(triple.cart?.payment_details_total);
2721
+ const paymentTotal = toNumericAmount(triple.payment?.payment_details_total);
2722
+ if (intentTotal && cartTotal && intentTotal.currency === cartTotal.currency) {
2723
+ if (cartTotal.value > intentTotal.value) {
2724
+ errors.push(
2725
+ `cart total ${cartTotal.value} ${cartTotal.currency} exceeds intent cap ${intentTotal.value}`
2726
+ );
2727
+ return false;
2728
+ }
2729
+ }
2730
+ if (cartTotal && paymentTotal && cartTotal.currency === paymentTotal.currency) {
2731
+ if (paymentTotal.value > cartTotal.value) {
2732
+ errors.push(
2733
+ `payment total ${paymentTotal.value} ${paymentTotal.currency} exceeds cart total ${cartTotal.value}`
2734
+ );
2735
+ return false;
2736
+ }
2737
+ }
2738
+ return true;
2739
+ }
2740
+ function checkExpiries(triple, toleranceSec, nowFn, errors) {
2741
+ const now = nowFn ? nowFn() : Math.floor(Date.now() / 1e3);
2742
+ let ok = true;
2743
+ for (const [name, mandate] of [
2744
+ ["intent", triple.intent],
2745
+ ["cart", triple.cart]
2746
+ ]) {
2747
+ if (!mandate?.expires) continue;
2748
+ const parsed = parseExpiry(mandate.expires);
2749
+ if (parsed === null) {
2750
+ errors.push(`${name}.expires unparseable`);
2751
+ ok = false;
2752
+ continue;
2753
+ }
2754
+ if (now > parsed + toleranceSec) {
2755
+ errors.push(`${name} mandate expired at ${mandate.expires}`);
2756
+ ok = false;
2757
+ }
2758
+ }
2759
+ return ok;
2760
+ }
2761
+ function toNumericAmount(total) {
2762
+ if (!total?.amount?.value || !total.amount.currency) return null;
2763
+ const n = typeof total.amount.value === "string" ? Number(total.amount.value) : total.amount.value;
2764
+ if (!Number.isFinite(n)) return null;
2765
+ return { value: n, currency: total.amount.currency };
2766
+ }
2767
+ function parseExpiry(value) {
2768
+ const asInt = Number(value);
2769
+ if (Number.isFinite(asInt) && asInt > 0) {
2770
+ return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
2771
+ }
2772
+ const parsedDate = Date.parse(value);
2773
+ if (Number.isFinite(parsedDate)) return Math.floor(parsedDate / 1e3);
2774
+ return null;
2775
+ }
2776
+
2777
+ // src/transport/acp-verify.ts
2778
+ async function verifyACPSignature(input) {
2779
+ if (!input.signatureHeader) {
2780
+ return { ok: false, error: "missing Signature header" };
2781
+ }
2782
+ const freshness = checkTimestamp(input.timestampHeader, input.clockSkewSec ?? 300, input.now);
2783
+ if (!freshness.ok) {
2784
+ return { ok: false, error: freshness.error, timestampStale: true };
2785
+ }
2786
+ const signatureBytes = decodeBase64(input.signatureHeader);
2787
+ if (!signatureBytes) {
2788
+ return { ok: false, error: "signature header is not valid base64" };
2789
+ }
2790
+ const bodyBytes = new TextEncoder().encode(input.rawBody);
2791
+ const { subtle } = await getSubtle();
2792
+ for (const candidate of input.candidateKeys) {
2793
+ const declaredAlg = normalizeAlgorithm(candidate.alg);
2794
+ const algsToTry = declaredAlg && declaredAlg !== "unsupported" ? [declaredAlg] : ["ed25519", "es256"];
2795
+ for (const alg of algsToTry) {
2796
+ try {
2797
+ const verified = await tryVerify(subtle, candidate.jwk, signatureBytes, bodyBytes, alg);
2798
+ if (verified) return { ok: true, algorithm: alg };
2799
+ } catch {
2800
+ }
2801
+ }
2802
+ }
2803
+ return {
2804
+ ok: false,
2805
+ algorithm: "unsupported",
2806
+ error: "no candidate key verified the signature under Ed25519 or ES256"
2807
+ };
2808
+ }
2809
+ async function tryVerify(subtle, jwk, signature, body, alg) {
2810
+ if (alg === "ed25519") {
2811
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519") return false;
2812
+ const key = await subtle.importKey("jwk", jwk, { name: "Ed25519" }, false, [
2813
+ "verify"
2814
+ ]);
2815
+ return await subtle.verify({ name: "Ed25519" }, key, toBuf(signature), toBuf(body));
2816
+ }
2817
+ if (alg === "es256") {
2818
+ if (jwk.kty !== "EC" || jwk.crv !== "P-256") return false;
2819
+ const key = await subtle.importKey(
2820
+ "jwk",
2821
+ jwk,
2822
+ { name: "ECDSA", namedCurve: "P-256" },
2823
+ false,
2824
+ ["verify"]
2825
+ );
2826
+ return await subtle.verify(
2827
+ { name: "ECDSA", hash: "SHA-256" },
2828
+ key,
2829
+ toBuf(signature),
2830
+ toBuf(body)
2831
+ );
2832
+ }
2833
+ return false;
2834
+ }
2835
+ function toBuf(bytes) {
2836
+ const out = new ArrayBuffer(bytes.byteLength);
2837
+ new Uint8Array(out).set(bytes);
2838
+ return out;
2839
+ }
2840
+ function checkTimestamp(headerValue, toleranceSec, nowFn) {
2841
+ if (!headerValue) return { ok: false, error: "missing Timestamp header" };
2842
+ const ts = parseTimestamp(headerValue);
2843
+ if (ts === null) return { ok: false, error: "unparseable Timestamp header" };
2844
+ const now = nowFn ? nowFn() : Math.floor(Date.now() / 1e3);
2845
+ if (Math.abs(now - ts) > toleranceSec) {
2846
+ return { ok: false, error: `timestamp outside ${toleranceSec}s tolerance` };
2847
+ }
2848
+ return { ok: true };
2849
+ }
2850
+ function parseTimestamp(value) {
2851
+ const asInt = Number(value);
2852
+ if (Number.isFinite(asInt) && asInt > 0) {
2853
+ return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
2854
+ }
2855
+ const parsedDate = Date.parse(value);
2856
+ if (Number.isFinite(parsedDate)) return Math.floor(parsedDate / 1e3);
2857
+ return null;
2858
+ }
2859
+ function normalizeAlgorithm(alg) {
2860
+ if (!alg) return void 0;
2861
+ const lowered = alg.toLowerCase();
2862
+ if (lowered === "ed25519" || lowered === "eddsa") return "ed25519";
2863
+ if (lowered === "es256" || lowered.startsWith("ecdsa-p256")) return "es256";
2864
+ return "unsupported";
2865
+ }
2866
+ function decodeBase64(value) {
2867
+ try {
2868
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
2869
+ const pad = normalized.length % 4 === 0 ? "" : "=".repeat(4 - normalized.length % 4);
2870
+ return new Uint8Array(Buffer.from(normalized + pad, "base64"));
2871
+ } catch {
2872
+ return null;
2873
+ }
2874
+ }
2875
+ async function getSubtle() {
2876
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
2877
+ return { subtle: globalThis.crypto.subtle };
2878
+ }
2879
+ const nodeCrypto = await import("crypto");
2880
+ return { subtle: nodeCrypto.webcrypto.subtle };
2881
+ }
2882
+
2883
+ // src/transport/mpp.ts
2884
+ var import_mppx = require("mppx");
2885
+ function extractMPPFromRequest(request) {
2886
+ const auth = readHeader3(request.headers, "authorization");
2887
+ if (!auth || !/^\s*Payment\s+/i.test(auth)) return null;
2888
+ try {
2889
+ const credential = import_mppx.Credential.deserialize(auth);
2890
+ return {
2891
+ kind: "credential",
2892
+ credential: {
2893
+ challenge: summarizeChallenge(credential.challenge),
2894
+ source: credential.source,
2895
+ payload: credential.payload
2896
+ },
2897
+ rawBody: request.rawBody
2898
+ };
2899
+ } catch {
2900
+ return { kind: "error", error: { type: "invalid-credential-encoding" } };
2901
+ }
2902
+ }
2903
+ function extractMPPFromResponse(response) {
2904
+ if (response.status === 402) {
2905
+ const challenges = collectChallenges(response);
2906
+ if (challenges.length === 0) return null;
2907
+ const methods = Array.from(new Set(challenges.map((c) => c.method)));
2908
+ return {
2909
+ kind: "challenge",
2910
+ challenges,
2911
+ offeredMethods: methods
2912
+ };
2913
+ }
2914
+ const receiptHeader = readHeader3(response.headers, "payment-receipt");
2915
+ if (receiptHeader) {
2916
+ try {
2917
+ const parsed = import_mppx.Receipt.deserialize(receiptHeader);
2918
+ const r = parsed;
2919
+ return {
2920
+ kind: "receipt",
2921
+ receipt: {
2922
+ method: coerceString6(r.method),
2923
+ reference: coerceString6(r.reference),
2924
+ externalId: coerceString6(r.externalId ?? r.external_id),
2925
+ status: coerceString6(r.status),
2926
+ timestamp: coerceString6(r.timestamp),
2927
+ raw: r
2928
+ }
2929
+ };
2930
+ } catch {
2931
+ return { kind: "error", error: { type: "invalid-receipt-encoding" } };
2932
+ }
2933
+ }
2934
+ const contentType = readHeader3(response.headers, "content-type");
2935
+ if (contentType && /application\/problem\+json/i.test(contentType)) {
2936
+ const body = typeof response.body === "object" && response.body !== null ? response.body : {};
2937
+ return {
2938
+ kind: "error",
2939
+ error: {
2940
+ type: coerceString6(body.type),
2941
+ title: coerceString6(body.title),
2942
+ detail: coerceString6(body.detail)
2943
+ }
2944
+ };
2945
+ }
2946
+ return null;
2947
+ }
2948
+ function extractMPPContext(message) {
2949
+ if ("request" in message) return extractMPPFromRequest(message.request);
2950
+ if ("response" in message) return extractMPPFromResponse(message.response);
2951
+ if (typeof message.status === "number") {
2952
+ return extractMPPFromResponse(message);
2953
+ }
2954
+ return extractMPPFromRequest(message);
2955
+ }
2956
+ function collectChallenges(response) {
2957
+ const wwwAuth = readHeader3(response.headers, "www-authenticate");
2958
+ if (!wwwAuth) return [];
2959
+ const headers = new Headers();
2960
+ headers.set("www-authenticate", wwwAuth);
2961
+ const out = [];
2962
+ try {
2963
+ const list = import_mppx.Challenge.fromHeadersList(headers);
2964
+ for (const ch of list) {
2965
+ out.push(summarizeChallenge(ch));
2966
+ }
2967
+ } catch {
2968
+ }
2969
+ return out;
2970
+ }
2971
+ function summarizeChallenge(ch) {
2972
+ const raw = ch;
2973
+ return {
2974
+ id: coerceString6(raw.id) ?? "",
2975
+ realm: coerceString6(raw.realm) ?? "",
2976
+ method: coerceString6(raw.method) ?? "",
2977
+ intent: coerceString6(raw.intent) ?? "",
2978
+ request: raw.request ?? {},
2979
+ expires: coerceString6(raw.expires),
2980
+ digest: coerceString6(raw.digest),
2981
+ description: coerceString6(raw.description),
2982
+ opaque: raw.opaque
2983
+ };
2984
+ }
2985
+ function readHeader3(headers, name) {
2986
+ for (const key of Object.keys(headers)) {
2987
+ if (key.toLowerCase() === name) {
2988
+ const raw = headers[key];
2989
+ if (typeof raw === "string") return raw;
2990
+ if (Array.isArray(raw)) return raw.join(", ");
2991
+ }
2992
+ }
2993
+ return void 0;
2994
+ }
2995
+ function coerceString6(v) {
2996
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2997
+ }
2998
+
2999
+ // src/transport/mpp-verify.ts
3000
+ var import_mppx2 = require("mppx");
3001
+ function verifyMPP(input) {
3002
+ const { context } = input;
3003
+ const tolerance = input.clockSkewSec ?? 300;
3004
+ const nowSec = input.now ? input.now() : Math.floor(Date.now() / 1e3);
3005
+ const challenge = context.credential?.challenge ?? (context.challenges && context.challenges[0]);
3006
+ const source = context.credential?.source;
3007
+ const method = challenge?.method;
3008
+ let expiryOk = true;
3009
+ if (challenge?.expires) {
3010
+ const parsedExpiry = Date.parse(challenge.expires);
3011
+ if (!Number.isFinite(parsedExpiry)) {
3012
+ return {
3013
+ ok: false,
3014
+ expiryOk: false,
3015
+ bodyDigestOk: null,
3016
+ source,
3017
+ method,
3018
+ error: "unparseable challenge.expires"
3019
+ };
3020
+ }
3021
+ const expiresSec = Math.floor(parsedExpiry / 1e3);
3022
+ if (nowSec > expiresSec + tolerance) {
3023
+ expiryOk = false;
3024
+ }
3025
+ }
3026
+ let bodyDigestOk = null;
3027
+ if (challenge?.digest && input.rawBody !== void 0) {
3028
+ try {
3029
+ if (!/^sha-256=/.test(challenge.digest)) {
3030
+ bodyDigestOk = false;
3031
+ } else {
3032
+ bodyDigestOk = import_mppx2.BodyDigest.verify(challenge.digest, input.rawBody);
3033
+ }
3034
+ } catch {
3035
+ bodyDigestOk = false;
3036
+ }
3037
+ }
3038
+ const ok = expiryOk && (bodyDigestOk === null || bodyDigestOk === true);
3039
+ const errors = [];
3040
+ if (!expiryOk) errors.push("challenge expired");
3041
+ if (bodyDigestOk === false) errors.push("body digest mismatch");
3042
+ return {
3043
+ ok,
3044
+ expiryOk,
3045
+ bodyDigestOk,
3046
+ source,
3047
+ method,
3048
+ error: errors.length > 0 ? errors.join("; ") : void 0
3049
+ };
3050
+ }
3051
+
3052
+ // src/transport/x402.ts
3053
+ var import_schemas = require("@x402/core/schemas");
3054
+ var import_utils = require("@x402/core/utils");
3055
+ function extractX402FromRequest(request) {
3056
+ const headerValue = readHeader4(request.headers, "x-payment");
3057
+ if (request.body && typeof request.body === "object") {
3058
+ const parsed = tryParsePayload(request.body);
3059
+ if (parsed) return buildPayloadContext(parsed, "body");
3060
+ }
3061
+ if (headerValue) {
3062
+ try {
3063
+ const decoded = (0, import_utils.safeBase64Decode)(headerValue);
3064
+ if (decoded) {
3065
+ const json = JSON.parse(decoded);
3066
+ const parsed = tryParsePayload(json);
3067
+ if (parsed) return buildPayloadContext(parsed, "header");
3068
+ }
3069
+ } catch {
3070
+ return {
3071
+ kind: "error",
3072
+ version: 1,
3073
+ source: "header",
3074
+ error: { type: "invalid-x402-payload" }
3075
+ };
3076
+ }
3077
+ }
3078
+ return null;
3079
+ }
3080
+ function extractX402FromResponse(response) {
3081
+ if (response.status !== 402) return null;
3082
+ if (response.body && typeof response.body === "object") {
3083
+ const parsed = tryParseRequired(response.body);
3084
+ if (parsed) return buildRequiredContext(parsed, "body");
3085
+ }
3086
+ const headerValue = readHeader4(response.headers, "x-payment-required");
3087
+ if (headerValue) {
3088
+ try {
3089
+ const decoded = (0, import_utils.safeBase64Decode)(headerValue);
3090
+ if (decoded) {
3091
+ const json = JSON.parse(decoded);
3092
+ const parsed = tryParseRequired(json);
3093
+ if (parsed) return buildRequiredContext(parsed, "header");
3094
+ }
3095
+ } catch {
3096
+ return {
3097
+ kind: "error",
3098
+ version: 1,
3099
+ source: "header",
3100
+ error: { type: "invalid-x402-required" }
3101
+ };
3102
+ }
3103
+ }
3104
+ return null;
3105
+ }
3106
+ function extractX402Context(message) {
3107
+ if ("request" in message) return extractX402FromRequest(message.request);
3108
+ if ("response" in message) return extractX402FromResponse(message.response);
3109
+ if (typeof message.status === "number") {
3110
+ return extractX402FromResponse(message);
3111
+ }
3112
+ return extractX402FromRequest(message);
3113
+ }
3114
+ function tryParseRequired(data) {
3115
+ try {
3116
+ return (0, import_schemas.validatePaymentRequired)(data);
3117
+ } catch {
3118
+ return null;
3119
+ }
3120
+ }
3121
+ function tryParsePayload(data) {
3122
+ try {
3123
+ return (0, import_schemas.validatePaymentPayload)(data);
3124
+ } catch {
3125
+ return null;
3126
+ }
3127
+ }
3128
+ function buildRequiredContext(parsed, source) {
3129
+ const asRecord = parsed;
3130
+ const version = coerceVersion(asRecord.x402Version);
3131
+ const accepts = asRecord.accepts ?? [];
3132
+ return {
3133
+ kind: "required",
3134
+ version,
3135
+ source,
3136
+ paymentRequired: {
3137
+ resource: resolveResource(asRecord.resource),
3138
+ accepts: accepts.map(summarizeRequirement),
3139
+ extensions: asRecord.extensions,
3140
+ error: typeof asRecord.error === "string" ? asRecord.error : void 0
3141
+ }
3142
+ };
3143
+ }
3144
+ function buildPayloadContext(parsed, source) {
3145
+ const asRecord = parsed;
3146
+ const version = coerceVersion(asRecord.x402Version);
3147
+ const accepted = asRecord.accepted;
3148
+ const payload = asRecord.payload ?? {};
3149
+ return {
3150
+ kind: "payload",
3151
+ version,
3152
+ source,
3153
+ paymentPayload: {
3154
+ scheme: accepted?.scheme ?? (typeof asRecord.scheme === "string" ? asRecord.scheme : ""),
3155
+ network: accepted?.network ?? (typeof asRecord.network === "string" ? asRecord.network : ""),
3156
+ payload,
3157
+ extensions: asRecord.extensions
3158
+ }
3159
+ };
3160
+ }
3161
+ function summarizeRequirement(req) {
3162
+ const r = req;
3163
+ const amount = r.amount ?? r.maxAmountRequired ?? "0";
3164
+ return {
3165
+ scheme: r.scheme ?? "",
3166
+ network: r.network ?? "",
3167
+ asset: r.asset ?? "",
3168
+ amount: String(amount),
3169
+ payTo: r.payTo ?? "",
3170
+ maxTimeoutSeconds: typeof r.maxTimeoutSeconds === "number" ? r.maxTimeoutSeconds : void 0,
3171
+ resource: typeof r.resource === "string" ? r.resource : void 0,
3172
+ description: typeof r.description === "string" ? r.description : void 0
3173
+ };
3174
+ }
3175
+ function resolveResource(v) {
3176
+ if (typeof v === "string") return v;
3177
+ if (v && typeof v === "object" && "url" in v && typeof v.url === "string") {
3178
+ return v.url;
3179
+ }
3180
+ return "";
3181
+ }
3182
+ function coerceVersion(v) {
3183
+ if (v === 1 || v === 2) return v;
3184
+ return null;
3185
+ }
3186
+ function readHeader4(headers, name) {
3187
+ if (!headers) return void 0;
3188
+ for (const key of Object.keys(headers)) {
3189
+ if (key.toLowerCase() === name) {
3190
+ const raw = headers[key];
3191
+ if (typeof raw === "string") return raw;
3192
+ if (Array.isArray(raw)) return raw[0];
3193
+ }
3194
+ }
3195
+ return void 0;
3196
+ }
3197
+
3198
+ // src/transport/vi-verify.ts
3199
+ var import_node_crypto4 = require("crypto");
3200
+ async function verifyVIChain(input) {
3201
+ const errors = [];
3202
+ const tolerance = input.clockSkewSec ?? 300;
3203
+ const now = input.now ? input.now() : Math.floor(Date.now() / 1e3);
3204
+ const { l1, l2, l3a, l3b } = input.layers;
3205
+ const l1SigOk = l1 ? await input.verifySignature(l1, null) : null;
3206
+ if (l1 && !l1SigOk) errors.push("L1 signature invalid");
3207
+ const l1Cnf = extractCnfJwk(l1?.payload);
3208
+ const l2SigOk = await input.verifySignature(l2, l1Cnf ?? null);
3209
+ if (!l2SigOk) errors.push("L2 signature invalid");
3210
+ const l2Cnf = extractCnfJwk(l2.payload);
3211
+ const l3aSigOk = l3a ? await input.verifySignature(l3a, l2Cnf ?? null) : null;
3212
+ if (l3a && !l3aSigOk) errors.push("L3a signature invalid");
3213
+ const l3bSigOk = l3b ? await input.verifySignature(l3b, l2Cnf ?? null) : null;
3214
+ if (l3b && !l3bSigOk) errors.push("L3b signature invalid");
3215
+ let l1BindsL2 = true;
3216
+ if (l1Cnf) {
3217
+ const l2KeyFromHeader = await jwkForLayer(l2);
3218
+ l1BindsL2 = l2KeyFromHeader ? await thumbprintsMatch(l1Cnf, l2KeyFromHeader) : false;
3219
+ if (!l1BindsL2) errors.push("L1.cnf.jwk does not bind L2 signing key");
3220
+ }
3221
+ let l2BindsL3 = true;
3222
+ if (l2Cnf && (l3a || l3b)) {
3223
+ const l3Layer = l3a ?? l3b;
3224
+ const l3KeyFromHeader = await jwkForLayer(l3Layer);
3225
+ l2BindsL3 = l3KeyFromHeader ? await thumbprintsMatch(l2Cnf, l3KeyFromHeader) : false;
3226
+ if (!l2BindsL3) errors.push("L2.cnf.jwk does not bind L3 signing key");
3227
+ }
3228
+ let l3aL3bTxnIdMatch = null;
3229
+ if (l3a && l3b) {
3230
+ const a = coerceString7(l3a.payload.transaction_id ?? l3a.payload.transactionId);
3231
+ const b = coerceString7(l3b.payload.transaction_id ?? l3b.payload.transactionId);
3232
+ if (a && b) {
3233
+ l3aL3bTxnIdMatch = a === b;
3234
+ if (!l3aL3bTxnIdMatch) {
3235
+ errors.push(`L3a.transaction_id (${a}) does not match L3b.transaction_id (${b})`);
3236
+ }
3237
+ }
3238
+ }
3239
+ let checkoutHashOk = null;
3240
+ if (l3b) {
3241
+ const declaredHash = coerceString7(
3242
+ l3b.payload.checkout_hash ?? l3b.payload.conditional_transaction_id ?? l3b.payload.payment_reference?.checkout_hash
3243
+ );
3244
+ if (declaredHash) {
3245
+ const computed = computeCheckoutHashFromL2(l2);
3246
+ checkoutHashOk = computed ? declaredHash === computed : false;
3247
+ if (!checkoutHashOk) {
3248
+ errors.push("L3b.checkout_hash does not match SHA-256 of L2 checkout disclosure");
3249
+ }
3250
+ }
3251
+ }
3252
+ const expiryOk = checkExpiryAcross([l1, l2, l3a, l3b], tolerance, now, errors);
3253
+ const ok = l1SigOk !== false && l2SigOk && l3aSigOk !== false && l3bSigOk !== false && l1BindsL2 && l2BindsL3 && l3aL3bTxnIdMatch !== false && checkoutHashOk !== false && expiryOk;
3254
+ return {
3255
+ ok,
3256
+ checks: {
3257
+ l1SigOk,
3258
+ l2SigOk,
3259
+ l3aSigOk,
3260
+ l3bSigOk,
3261
+ l1BindsL2,
3262
+ l2BindsL3,
3263
+ l3aL3bTxnIdMatch,
3264
+ checkoutHashOk,
3265
+ expiryOk
3266
+ },
3267
+ errors
3268
+ };
3269
+ }
3270
+ function extractCnfJwk(payload) {
3271
+ if (!payload) return null;
3272
+ const cnf = payload.cnf;
3273
+ if (!cnf) return null;
3274
+ const jwk = cnf.jwk;
3275
+ return jwk ?? null;
3276
+ }
3277
+ async function jwkForLayer(layer) {
3278
+ const fromHeader = extractCnfJwk(layer.header);
3279
+ if (fromHeader) return fromHeader;
3280
+ const fromPayload = extractCnfJwk(layer.payload);
3281
+ return fromPayload;
3282
+ }
3283
+ async function thumbprintsMatch(a, b) {
3284
+ try {
3285
+ const ta = await jwkThumbprint(a);
3286
+ const tb = await jwkThumbprint(b);
3287
+ return ta === tb;
3288
+ } catch {
3289
+ return false;
3290
+ }
3291
+ }
3292
+ async function jwkThumbprint(jwk) {
3293
+ const canonical = canonicalJwk(jwk);
3294
+ const bytes = new TextEncoder().encode(JSON.stringify(canonical));
3295
+ const subtle = import_node_crypto4.webcrypto.subtle;
3296
+ const buffer = await new Promise((resolve, reject) => {
3297
+ const source = new ArrayBuffer(bytes.byteLength);
3298
+ new Uint8Array(source).set(bytes);
3299
+ subtle.digest("SHA-256", source).then(resolve).catch(reject);
3300
+ });
3301
+ return Buffer.from(new Uint8Array(buffer)).toString("base64url").replace(/=+$/, "");
3302
+ }
3303
+ function canonicalJwk(jwk) {
3304
+ if (jwk.kty === "EC") {
3305
+ return { crv: jwk.crv ?? "", kty: "EC", x: jwk.x ?? "", y: jwk.y ?? "" };
3306
+ }
3307
+ if (jwk.kty === "OKP") {
3308
+ return { crv: jwk.crv ?? "", kty: "OKP", x: jwk.x ?? "" };
3309
+ }
3310
+ if (jwk.kty === "RSA") {
3311
+ return { e: jwk.e ?? "", kty: "RSA", n: jwk.n ?? "" };
3312
+ }
3313
+ return { kty: jwk.kty ?? "" };
3314
+ }
3315
+ function computeCheckoutHashFromL2(l2) {
3316
+ const checkoutDisclosure = l2.payload.checkout ?? l2.payload.checkout_mandate;
3317
+ if (!checkoutDisclosure) return null;
3318
+ const canonical = canonicalStringify(checkoutDisclosure);
3319
+ const hash = (0, import_node_crypto4.createHash)("sha256").update(canonical).digest("base64url").replace(/=+$/, "");
3320
+ return hash;
3321
+ }
3322
+ function canonicalStringify(value) {
3323
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
3324
+ if (Array.isArray(value)) return "[" + value.map(canonicalStringify).join(",") + "]";
3325
+ const entries = Object.entries(value).sort(
3326
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
3327
+ );
3328
+ return "{" + entries.map(([k, v]) => JSON.stringify(k) + ":" + canonicalStringify(v)).join(",") + "}";
3329
+ }
3330
+ function checkExpiryAcross(layers, toleranceSec, nowSec, errors) {
3331
+ let ok = true;
3332
+ const names = ["L1", "L2", "L3a", "L3b"];
3333
+ layers.forEach((layer, idx) => {
3334
+ if (!layer) return;
3335
+ const exp = toUnixSeconds2(layer.payload.exp ?? layer.payload.expires);
3336
+ if (exp === void 0) return;
3337
+ if (nowSec > exp + toleranceSec) {
3338
+ errors.push(`${names[idx]} mandate expired at ${exp}`);
3339
+ ok = false;
3340
+ }
3341
+ });
3342
+ return ok;
3343
+ }
3344
+ function toUnixSeconds2(v) {
3345
+ if (typeof v === "number" && Number.isFinite(v)) return v;
3346
+ if (typeof v === "string") {
3347
+ const asInt = Number(v);
3348
+ if (Number.isFinite(asInt) && asInt > 0) {
3349
+ return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
3350
+ }
3351
+ const parsed = Date.parse(v);
3352
+ if (Number.isFinite(parsed)) return Math.floor(parsed / 1e3);
3353
+ }
3354
+ return void 0;
3355
+ }
3356
+ function coerceString7(v) {
3357
+ return typeof v === "string" && v.length > 0 ? v : void 0;
3358
+ }
3359
+
3360
+ // src/transport/commerce-pipeline.ts
3361
+ async function runCommercePipeline(input) {
3362
+ const trustSignals = [];
3363
+ const signatures = {};
3364
+ const timings = { extractMs: 0, verifyMs: 0, evalMs: 0 };
3365
+ const extractStart = performance.now();
3366
+ const purpose = resolvePurpose(input);
3367
+ const transactionValue = resolveTransactionValue(input);
3368
+ const identityClaims = collectIdentityClaims(input);
3369
+ const paymentToken = resolvePaymentToken(input);
3370
+ timings.extractMs = Math.round(performance.now() - extractStart);
3371
+ const verifyStart = performance.now();
3372
+ let hardDeny = false;
3373
+ if (input.vi?.verifyInput) {
3374
+ signatures.vi = await verifyVIChain(input.vi.verifyInput);
3375
+ if (!signatures.vi.ok) hardDeny = true;
3376
+ }
3377
+ if (input.ap2) {
3378
+ signatures.ap2 = verifyAP2Chain({
3379
+ triple: input.ap2.triple,
3380
+ clockSkewSec: input.clockSkewSec,
3381
+ now: input.now
3382
+ });
3383
+ if (!signatures.ap2.ok) hardDeny = true;
3384
+ }
3385
+ if (input.acp?.verifyInput) {
3386
+ signatures.acp = await verifyACPSignature(input.acp.verifyInput);
3387
+ if (!signatures.acp.ok && signatures.acp.timestampStale) hardDeny = true;
3388
+ if (signatures.acp.algorithm === "unsupported") {
3389
+ trustSignals.push("acp-signature-algorithm-unsupported");
3390
+ } else if (!signatures.acp.ok) {
3391
+ hardDeny = true;
3392
+ }
3393
+ }
3394
+ if (input.rfc9421) {
3395
+ signatures.rfc9421 = await verifyRFC9421(input.rfc9421.request, input.rfc9421.verifyOptions);
3396
+ if (!signatures.rfc9421.ok) hardDeny = true;
3397
+ }
3398
+ if (input.mpp) {
3399
+ signatures.mpp = verifyMPP({
3400
+ context: input.mpp.context,
3401
+ rawBody: input.mpp.rawBody,
3402
+ clockSkewSec: input.clockSkewSec,
3403
+ now: input.now
3404
+ });
3405
+ if (!signatures.mpp.ok) hardDeny = true;
3406
+ if (input.mpp.context.credential?.source) {
3407
+ trustSignals.push(`mpp-source-${shortSource(input.mpp.context.credential.source)}`);
3408
+ }
3409
+ }
3410
+ if (input.stripeWebhook) {
3411
+ signatures.stripeWebhook = verifyStripeWebhook(
3412
+ input.stripeWebhook.payload,
3413
+ input.stripeWebhook.signatureHeader,
3414
+ input.stripeWebhook.secret,
3415
+ { now: input.now ? () => input.now() : void 0 }
3416
+ );
3417
+ if (!signatures.stripeWebhook.ok) {
3418
+ trustSignals.push("stripe-webhook-hmac-failed");
3419
+ }
3420
+ }
3421
+ timings.verifyMs = Math.round(performance.now() - verifyStart);
3422
+ let identity;
3423
+ if (input.identityResolver && identityClaims.length > 0) {
3424
+ const bound = await bindIdentity(identityClaims, input.identityResolver);
3425
+ identity = {
3426
+ claims: identityClaims,
3427
+ mappedAstraSyncAgentId: bound.mappedAstraSyncAgentId,
3428
+ mismatchAcrossLayers: bound.mismatchAcrossLayers
3429
+ };
3430
+ if (bound.mismatchAcrossLayers) trustSignals.push("identity-mismatch-across-layers");
3431
+ } else if (identityClaims.length > 0) {
3432
+ identity = {
3433
+ claims: identityClaims,
3434
+ mappedAstraSyncAgentId: void 0,
3435
+ mismatchAcrossLayers: false
3436
+ };
3437
+ }
3438
+ const evalStart = performance.now();
3439
+ const constraints = runConstraintEval(input);
3440
+ if (constraints && !constraints.ok) hardDeny = true;
3441
+ timings.evalMs = Math.round(performance.now() - evalStart);
3442
+ if (paymentToken?.type === "stripe-spt") trustSignals.push("stripe-spt-present");
3443
+ if (paymentToken?.type === "acp-vt") trustSignals.push("acp-vault-token-present");
3444
+ if (paymentToken?.type === "tempo-tx") trustSignals.push("tempo-transaction-present");
3445
+ const mppReceipt = input.mpp?.context.receipt;
3446
+ return {
3447
+ protocol: input.protocol,
3448
+ purpose,
3449
+ transactionValue,
3450
+ signatures,
3451
+ identity,
3452
+ paymentToken,
3453
+ mppMethodsOffered: input.mpp?.context.offeredMethods,
3454
+ constraints,
3455
+ receipt: mppReceipt ? {
3456
+ method: mppReceipt.method,
3457
+ reference: mppReceipt.reference,
3458
+ status: mppReceipt.status,
3459
+ timestamp: mppReceipt.timestamp
3460
+ } : void 0,
3461
+ trustSignals,
3462
+ timings,
3463
+ ok: !hardDeny
3464
+ };
3465
+ }
3466
+ function resolvePurpose(input) {
3467
+ if (input.vi?.claims.mandateType) {
3468
+ return mapVIMandateToPurpose(input.vi.claims.mandateType);
3469
+ }
3470
+ if (input.ap2?.triple.payment) return "commerce.payment.execute";
3471
+ if (input.ap2?.triple.cart) return "commerce.checkout.confirm";
3472
+ if (input.ap2?.triple.intent) return "commerce.delegation.intent";
3473
+ if (input.ucp?.endpoint) {
3474
+ const [method, path] = input.ucp.endpoint.split(" ");
3475
+ return mapUCPRequestToPurpose(method ?? "POST", path ?? "/");
3476
+ }
3477
+ if (input.acp?.context.endpoint) {
3478
+ switch (input.acp.context.endpoint) {
3479
+ case "checkout_sessions.create":
3480
+ return "commerce.checkout.create";
3481
+ case "checkout_sessions.update":
3482
+ return "commerce.checkout.update";
3483
+ case "checkout_sessions.complete":
3484
+ return "commerce.payment.execute";
3485
+ case "checkout_sessions.cancel":
3486
+ return "commerce.checkout.cancel";
3487
+ case "delegate_payment":
3488
+ return "commerce.delegation.payment";
3489
+ default:
3490
+ return mapACPRequestToPurpose("POST", "/checkout_sessions");
3491
+ }
3492
+ }
3493
+ if (input.rfc9421?.tag) {
3494
+ return mapRFC9421TagToPurpose(
3495
+ input.rfc9421.tag === "browse" || input.rfc9421.tag === "purchase" ? input.rfc9421.tag : void 0
3496
+ );
3497
+ }
3498
+ if (input.mpp?.context.credential?.challenge || input.mpp?.context.challenges?.[0]) {
3499
+ const challenge = input.mpp.context.credential?.challenge ?? input.mpp.context.challenges?.[0];
3500
+ const amount = parseFloat(String(challenge?.request?.amount ?? "NaN"));
3501
+ return mapMPPRequestToPurpose(
3502
+ challenge?.intent === "session" ? "session" : "charge",
3503
+ Number.isFinite(amount) ? amount : void 0
3504
+ );
3505
+ }
3506
+ if (input.x402?.paymentRequired) {
3507
+ const amt = input.x402.paymentRequired.accepts[0]?.amount;
3508
+ return mapX402RequestToPurpose(Number(amt));
3509
+ }
3510
+ if (input.x402?.paymentPayload) return "commerce.payment.execute";
3511
+ return null;
3512
+ }
3513
+ function resolveTransactionValue(input) {
3514
+ if (input.vi?.claims) {
3515
+ const v = extractVITransactionValue({
3516
+ constraints: input.vi.claims.constraints,
3517
+ l3aPaymentAmount: input.vi.claims.constraints.paymentAmount && typeof input.vi.claims.constraints.paymentAmount.max === "number" ? {
3518
+ amount: input.vi.claims.constraints.paymentAmount.max,
3519
+ currency: input.vi.claims.constraints.paymentAmount.currency
3520
+ } : void 0
3521
+ });
3522
+ if (v) return v;
3523
+ }
3524
+ if (input.ucp?.totals) {
3525
+ const v = extractUCPTransactionValue({ totals: input.ucp.totals });
3526
+ if (v) return v;
3527
+ }
3528
+ if (input.acp?.context.totals) {
3529
+ const v = extractACPTransactionValue({ totals: input.acp.context.totals });
3530
+ if (v) return v;
3531
+ }
3532
+ if (input.mpp?.context.credential?.challenge) {
3533
+ const ch = input.mpp.context.credential.challenge;
3534
+ const v = extractMPPTransactionValue({ method: ch.method, request: ch.request });
3535
+ if (v) return v;
3536
+ }
3537
+ if (input.x402?.paymentRequired) {
3538
+ const first = input.x402.paymentRequired.accepts[0];
3539
+ if (first) {
3540
+ const v = extractX402TransactionValue({
3541
+ maxAmountRequired: Number(first.amount),
3542
+ asset: first.asset
3543
+ });
3544
+ if (v) return v;
3545
+ }
3546
+ }
3547
+ return void 0;
3548
+ }
3549
+ function collectIdentityClaims(input) {
3550
+ const claims = [];
3551
+ if (input.vi?.claims.kid)
3552
+ claims.push({ protocol: "vi", field: "kid", value: input.vi.claims.kid });
3553
+ if (input.ap2?.triple) {
3554
+ const agentId = input.ap2.triple.intent?.agent_id ?? input.ap2.triple.cart?.agent_id ?? input.ap2.triple.payment?.agent_id;
3555
+ if (agentId) claims.push({ protocol: "ap2", field: "agent_id", value: agentId });
3556
+ }
3557
+ if (input.acp?.context.bearer) {
3558
+ claims.push({ protocol: "acp", field: "bearer", value: input.acp.context.bearer });
3559
+ }
3560
+ if (input.mpp?.context.credential?.source) {
3561
+ claims.push({ protocol: "mpp", field: "source", value: input.mpp.context.credential.source });
3562
+ }
3563
+ if (input.rfc9421) {
3564
+ }
3565
+ return claims;
3566
+ }
3567
+ function resolvePaymentToken(input) {
3568
+ if (input.acp?.context.paymentToken?.type) {
3569
+ return { present: true, type: input.acp.context.paymentToken.type };
3570
+ }
3571
+ const mppMethod = input.mpp?.context.credential?.challenge?.method;
3572
+ if (mppMethod === "tempo") return { present: true, type: "tempo-tx" };
3573
+ if (mppMethod === "stripe") return { present: true, type: "stripe-spt" };
3574
+ return void 0;
3575
+ }
3576
+ function runConstraintEval(input) {
3577
+ const transaction = input.transaction ?? {};
3578
+ const results = {};
3579
+ const reasons = [];
3580
+ let hasAny = false;
3581
+ if (input.vi?.claims) {
3582
+ const viResult = evaluateVIConstraints({
3583
+ constraints: input.vi.claims.constraints,
3584
+ transaction
3585
+ });
3586
+ for (const [k, v] of Object.entries(viResult.results)) {
3587
+ results[k] = v;
3588
+ if (!v.ok && v.reason) reasons.push(v.reason);
3589
+ }
3590
+ if (Object.keys(viResult.results).length > 0) hasAny = true;
3591
+ }
3592
+ const registered = input.registeredConstraints;
3593
+ if (registered?.allowedPaymentMethods) {
3594
+ const pm = evaluatePaymentMethodAllowlist({
3595
+ allowedMethods: registered.allowedPaymentMethods,
3596
+ requestedMethod: transaction.paymentMethod
3597
+ });
3598
+ results.paymentMethod = pm;
3599
+ if (!pm.ok && pm.reason) reasons.push(pm.reason);
3600
+ hasAny = true;
3601
+ }
3602
+ if (registered?.spendingLimit) {
3603
+ const sp = evaluateSpendingLimit({
3604
+ limit: registered.spendingLimit,
3605
+ requested: { amount: transaction.amount, currency: transaction.currency }
3606
+ });
3607
+ results.spendingLimit = sp;
3608
+ if (!sp.ok && sp.reason) reasons.push(sp.reason);
3609
+ hasAny = true;
3610
+ }
3611
+ if (!hasAny) return void 0;
3612
+ return { ok: reasons.length === 0, results, reasons };
3613
+ }
3614
+ function shortSource(source) {
3615
+ return source.replace(/^did:[a-z0-9]+:/, "").slice(0, 16);
3616
+ }
3617
+
3618
+ // src/transport/extractor-registry.ts
3619
+ var registry = /* @__PURE__ */ new Map();
3620
+ function registerTransportExtractor(extractor) {
3621
+ if (!extractor || typeof extractor.name !== "string" || extractor.name.length === 0) {
3622
+ throw new Error("registerTransportExtractor: extractor must have a non-empty name");
3623
+ }
3624
+ registry.set(extractor.name, extractor);
3625
+ }
3626
+ function getTransportExtractors() {
3627
+ return Array.from(registry.values());
3628
+ }
3629
+ function getTransportExtractor(name) {
3630
+ return registry.get(name);
3631
+ }
3632
+ function clearTransportExtractors() {
3633
+ registry.clear();
3634
+ }
3635
+ async function runMatchingExtractors(request) {
3636
+ const out = {};
3637
+ for (const extractor of registry.values()) {
3638
+ if (!extractor.match(request)) continue;
3639
+ const result = await extractor.extract(request);
3640
+ if (result !== null && result !== void 0) out[extractor.name] = result;
3641
+ }
3642
+ return out;
3643
+ }
3644
+
3645
+ // src/transport/registry/visa.ts
3646
+ var import_jose = require("jose");
3647
+ var DEFAULT_VISA_JWKS_URL = "https://mcp.visa.com/.well-known/jwks";
3648
+ function createVisaRegistry(options = {}) {
3649
+ const url = new URL(options.jwksUrl ?? DEFAULT_VISA_JWKS_URL);
3650
+ const jwks = (0, import_jose.createRemoteJWKSet)(url, {
3651
+ cacheMaxAge: options.cacheMaxAge,
3652
+ cooldownDuration: options.cooldownDuration
3653
+ });
3654
+ return {
3655
+ name: "visa",
3656
+ async resolve(kid, context) {
3657
+ if (!kid) return null;
3658
+ try {
3659
+ const key = await jwks({
3660
+ kid,
3661
+ alg: context?.algorithm ?? "ES256",
3662
+ typ: "JWT"
3663
+ });
3664
+ return exportJwkFromKeyLike(key);
3665
+ } catch {
3666
+ return null;
3667
+ }
3668
+ }
3669
+ };
3670
+ }
3671
+ async function exportJwkFromKeyLike(keyLike) {
3672
+ if (!keyLike) return null;
3673
+ if (typeof keyLike === "object" && "kty" in keyLike) {
3674
+ return keyLike;
3675
+ }
3676
+ const { exportJWK } = await import("jose");
3677
+ try {
3678
+ return await exportJWK(keyLike);
3679
+ } catch {
3680
+ return null;
3681
+ }
3682
+ }
3683
+
3684
+ // src/transport/registry/mastercard.ts
3685
+ function createMastercardRegistry(options = {}) {
3686
+ const cache = /* @__PURE__ */ new Map();
3687
+ const ttlSec = options.cacheTtlSec ?? 3600;
3688
+ const fetchFn = options.fetch ?? globalThis.fetch;
3689
+ let warned = false;
3690
+ return {
3691
+ name: "mastercard",
3692
+ async resolve(kid) {
3693
+ if (!kid) return null;
3694
+ if (!options.registryUrl) {
3695
+ if (!warned && !options.silent) {
3696
+ warned = true;
3697
+ console.warn(
3698
+ "[mastercard-registry] registryUrl not configured \u2014 key resolution disabled. Kid lookups will return null until a partnership registry is supplied."
3699
+ );
3700
+ }
3701
+ return null;
3702
+ }
3703
+ const cached = cache.get(kid);
3704
+ if (cached && cached.expiresAt > Date.now()) return cached.jwk;
3705
+ try {
3706
+ const res = await fetchFn(options.registryUrl);
3707
+ if (!res.ok) return null;
3708
+ const body = await res.json();
3709
+ const keys = body.keys ?? [];
3710
+ for (const k of keys) {
3711
+ if (k.kid === kid) {
3712
+ cache.set(kid, { jwk: k, expiresAt: Date.now() + ttlSec * 1e3 });
3713
+ return k;
3714
+ }
3715
+ }
3716
+ return null;
3717
+ } catch {
3718
+ return null;
3719
+ }
3720
+ }
3721
+ };
3722
+ }
3723
+
3724
+ // src/transport/registry/web-bot-auth.ts
3725
+ var DIRECTORY_PATH = "/.well-known/http-message-signatures-directory";
3726
+ function createWebBotAuthRegistry(options = {}) {
3727
+ const cache = /* @__PURE__ */ new Map();
3728
+ const ttlSec = options.cacheTtlSec ?? 3600;
3729
+ const fetchFn = options.fetch ?? globalThis.fetch;
3730
+ return {
3731
+ name: "web-bot-auth",
3732
+ async resolve(kid, context) {
3733
+ if (!kid) return null;
3734
+ const directoryUrl = resolveDirectoryUrl(options.directoryUrl, context?.origin);
3735
+ if (!directoryUrl) return null;
3736
+ const cached = cache.get(directoryUrl);
3737
+ const now = Date.now();
3738
+ if (cached && cached.expiresAt > now) {
3739
+ return findKeyByKid(cached.keys, kid);
3740
+ }
3741
+ try {
3742
+ const res = await fetchFn(directoryUrl);
3743
+ if (!res.ok) return null;
3744
+ const body = await res.json();
3745
+ const keys = body.keys ?? [];
3746
+ cache.set(directoryUrl, { keys, expiresAt: now + ttlSec * 1e3 });
3747
+ return findKeyByKid(keys, kid);
3748
+ } catch {
3749
+ return null;
3750
+ }
3751
+ }
3752
+ };
3753
+ }
3754
+ function resolveDirectoryUrl(explicit, origin) {
3755
+ if (explicit) return explicit;
3756
+ if (!origin) return null;
3757
+ try {
3758
+ const url = new URL(origin);
3759
+ return `${url.origin}${DIRECTORY_PATH}`;
3760
+ } catch {
3761
+ return null;
3762
+ }
3763
+ }
3764
+ function findKeyByKid(keys, kid) {
3765
+ for (const k of keys) {
3766
+ if (k.kid === kid) return k;
3767
+ }
3768
+ return null;
3769
+ }
3770
+
3771
+ // src/transport/index.ts
3772
+ function detectProtocol(context) {
3773
+ if (context.metadata && typeof context.metadata === "object") {
3774
+ return "a2a";
3775
+ }
3776
+ if (context._meta && typeof context._meta === "object") {
3777
+ return "mcp";
3778
+ }
3779
+ return "http";
3780
+ }
3781
+ function applyCredentials(protocol, target, credentials) {
3782
+ switch (protocol) {
3783
+ case "http":
3784
+ return setHttpHeaders(target, credentials);
3785
+ case "a2a":
3786
+ return setA2AMetadata(target, credentials);
3787
+ case "mcp":
3788
+ return setMcpMeta(target, credentials);
3789
+ default:
3790
+ return target;
3791
+ }
3792
+ }
3793
+ function extractCredentialsFromProtocol(protocol, context) {
3794
+ switch (protocol) {
3795
+ case "http":
3796
+ return extractHttpCredentials(context);
3797
+ case "a2a":
3798
+ return extractA2ACredentials(context);
3799
+ case "mcp":
3800
+ return extractMcpCredentials(context);
3801
+ default:
3802
+ return null;
3803
+ }
3804
+ }
3805
+
3806
+ // src/agent/index.ts
3807
+ var agent_exports = {};
3808
+ __export(agent_exports, {
3809
+ AgentClient: () => AgentClient,
3810
+ AstraSyncSdkError: () => AstraSyncSdkError,
3811
+ ChallengeHandler: () => ChallengeHandler,
3812
+ OwnershipMismatchError: () => OwnershipMismatchError,
3813
+ formatPDLSSForTransport: () => formatPDLSSForTransport,
3814
+ parsePDLSSFromTransport: () => parsePDLSSFromTransport,
3815
+ recordDecision: () => recordDecision2
3816
+ });
3817
+
3818
+ // src/agent/errors.ts
3819
+ var AstraSyncSdkError = class extends Error {
3820
+ constructor(code, message) {
3821
+ super(message);
3822
+ this.name = "AstraSyncSdkError";
3823
+ this.code = code;
3824
+ }
3825
+ };
3826
+ var OwnershipMismatchError = class extends AstraSyncSdkError {
3827
+ constructor(astraId) {
3828
+ super(
3829
+ "ownership_mismatch",
3830
+ `The configured API key does not own agent ${astraId}. Refusing to initialise.`
3831
+ );
3832
+ this.name = "OwnershipMismatchError";
3833
+ this.astraId = astraId;
3834
+ }
3835
+ };
3836
+
3837
+ // src/agent/client.ts
3838
+ var AgentClient = class _AgentClient {
3839
+ constructor(config) {
3840
+ this.credentials = {
3841
+ agentId: config.agentId,
3842
+ verifyUrl: config.verifyUrl ?? "https://api.astrasync.ai/agents/verify-access",
3843
+ challengeUrl: config.challengeUrl,
3844
+ pdlss: config.pdlss
3845
+ };
3846
+ this.apiBaseUrl = config.apiBaseUrl ?? "https://api.astrasync.ai";
3847
+ this.apiKey = config.apiKey;
3848
+ }
3849
+ /**
3850
+ * Async factory that validates the API key's account owns the configured
3851
+ * ASTRA-id before returning a usable client. Refuses to initialise on
3852
+ * mismatch so a stolen ASTRA-id cannot be paired with a valid (different)
3853
+ * API key.
3854
+ *
3855
+ * Set env `ASTRASYNC_SKIP_OWNERSHIP_CHECK=true` to bypass — intended for
3856
+ * test environments only.
3857
+ */
3858
+ static async create(config) {
3859
+ const client = new _AgentClient(config);
3860
+ const skip = typeof process !== "undefined" && process.env?.ASTRASYNC_SKIP_OWNERSHIP_CHECK === "true";
3861
+ if (skip) return client;
3862
+ if (!config.apiKey) {
3863
+ throw new OwnershipMismatchError(config.agentId);
3864
+ }
3865
+ const owned = await client.verifyOwnership();
3866
+ if (!owned) throw new OwnershipMismatchError(config.agentId);
3867
+ return client;
3868
+ }
3869
+ /**
3870
+ * Calls GET /api/agents/:astraId/ownership with the configured API key.
3871
+ * Returns true only when the backend confirms this API key's account
3872
+ * owns the configured agent.
3873
+ */
3874
+ async verifyOwnership() {
3875
+ if (!this.apiKey) return false;
3876
+ const url = `${this.apiBaseUrl.replace(/\/+$/, "")}/api/agents/${encodeURIComponent(
3877
+ this.credentials.agentId
3878
+ )}/ownership`;
3879
+ const resp = await fetch(url, {
3880
+ method: "GET",
3881
+ headers: {
3882
+ Authorization: `Bearer ${this.apiKey}`,
3883
+ "Content-Type": "application/json"
3884
+ }
3885
+ });
3886
+ if (!resp.ok) return false;
3887
+ const body = await resp.json().catch(() => null);
3888
+ return Boolean(body?.data?.owned);
3889
+ }
1467
3890
  /**
1468
3891
  * Make an HTTP request with AstraSync headers automatically injected.
1469
3892
  */