@astrasyncai/verification-gateway 2.0.0 → 2.1.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 (101) 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 +118 -5
  6. package/dist/adapters/express.js.map +1 -1
  7. package/dist/adapters/express.mjs +118 -5
  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 +189 -9
  12. package/dist/adapters/nextjs.js.map +1 -1
  13. package/dist/adapters/nextjs.mjs +189 -9
  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 +1 -0
  18. package/dist/adapters/sdk.js.map +1 -1
  19. package/dist/adapters/sdk.mjs +1 -0
  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 +33 -0
  24. package/dist/agent/index.js.map +1 -1
  25. package/dist/agent/index.mjs +36 -0
  26. package/dist/agent/index.mjs.map +1 -1
  27. package/dist/browser/background.d.mts +2 -0
  28. package/dist/browser/background.d.ts +2 -0
  29. package/dist/browser/background.js +4123 -0
  30. package/dist/browser/background.js.map +1 -0
  31. package/dist/browser/background.mjs +4124 -0
  32. package/dist/browser/background.mjs.map +1 -0
  33. package/dist/browser/browser-adapter.d.mts +10 -6
  34. package/dist/browser/browser-adapter.d.ts +10 -6
  35. package/dist/browser/browser-adapter.js +16 -5
  36. package/dist/browser/browser-adapter.js.map +1 -1
  37. package/dist/browser/browser-adapter.mjs +14 -4
  38. package/dist/browser/browser-adapter.mjs.map +1 -1
  39. package/dist/cli/index.d.mts +2 -2
  40. package/dist/cli/index.d.ts +2 -2
  41. package/dist/cli/index.js +1 -1
  42. package/dist/cli/index.js.map +1 -1
  43. package/dist/cli/index.mjs +1 -1
  44. package/dist/cli/index.mjs.map +1 -1
  45. package/dist/cursor/cursor-adapter.d.mts +3 -4
  46. package/dist/cursor/cursor-adapter.d.ts +3 -4
  47. package/dist/cursor/cursor-adapter.js.map +1 -1
  48. package/dist/cursor/cursor-adapter.mjs.map +1 -1
  49. package/dist/cursor/extension.d.mts +27 -0
  50. package/dist/cursor/extension.d.ts +27 -0
  51. package/dist/cursor/extension.js +4090 -0
  52. package/dist/cursor/extension.js.map +1 -0
  53. package/dist/cursor/extension.mjs +4065 -0
  54. package/dist/cursor/extension.mjs.map +1 -0
  55. package/dist/{express-DIEyq1Tz.d.ts → express-Bcl-uBUE.d.ts} +1 -1
  56. package/dist/{express-Cp4eg77F.d.mts → express-CtwDIZyF.d.mts} +1 -1
  57. package/dist/gateway/gateway.d.mts +2 -2
  58. package/dist/gateway/gateway.d.ts +2 -2
  59. package/dist/gateway/gateway.js +50 -17
  60. package/dist/gateway/gateway.js.map +1 -1
  61. package/dist/gateway/gateway.mjs +47 -18
  62. package/dist/gateway/gateway.mjs.map +1 -1
  63. package/dist/git-trigger/git-hooks.d.mts +2 -2
  64. package/dist/git-trigger/git-hooks.d.ts +2 -2
  65. package/dist/git-trigger/git-hooks.js +1 -2
  66. package/dist/git-trigger/git-hooks.js.map +1 -1
  67. package/dist/git-trigger/git-hooks.mjs +1 -9
  68. package/dist/git-trigger/git-hooks.mjs.map +1 -1
  69. package/dist/index-3NRaBNvp.d.mts +1397 -0
  70. package/dist/{index-BhTbGU-o.d.mts → index-BY8yQ8N8.d.mts} +1 -1
  71. package/dist/index-CME6r4uH.d.ts +1397 -0
  72. package/dist/{index-Bhfxq9xI.d.ts → index-CtYSYwn3.d.ts} +1 -1
  73. package/dist/index.d.mts +8 -7
  74. package/dist/index.d.ts +8 -7
  75. package/dist/index.js +2525 -15
  76. package/dist/index.js.map +1 -1
  77. package/dist/index.mjs +2528 -15
  78. package/dist/index.mjs.map +1 -1
  79. package/dist/local-evaluator/evaluator.d.mts +2 -2
  80. package/dist/local-evaluator/evaluator.d.ts +2 -2
  81. package/dist/local-evaluator/evaluator.js.map +1 -1
  82. package/dist/local-evaluator/evaluator.mjs.map +1 -1
  83. package/dist/{nextjs-_C_FcJY5.d.mts → nextjs-BQyMCSx_.d.mts} +1 -1
  84. package/dist/{nextjs-Cag7libc.d.ts → nextjs-CEldnIJ9.d.ts} +1 -1
  85. package/dist/{sdk-DAJahT3p.d.mts → sdk-BhvuJSrH.d.mts} +1 -1
  86. package/dist/{sdk-CMPDFUjo.d.ts → sdk-BlyVSC_S.d.ts} +1 -1
  87. package/dist/transport/index.d.mts +3 -2
  88. package/dist/transport/index.d.ts +3 -2
  89. package/dist/transport/index.js +2384 -2
  90. package/dist/transport/index.js.map +1 -1
  91. package/dist/transport/index.mjs +2327 -1
  92. package/dist/transport/index.mjs.map +1 -1
  93. package/dist/{types-Ce2mFJkO.d.ts → types-79qS7aON.d.ts} +2 -2
  94. package/dist/{types-Bf8pML07.d.mts → types-CxQwJKbd.d.mts} +17 -2
  95. package/dist/{types-Bf8pML07.d.ts → types-CxQwJKbd.d.ts} +17 -2
  96. package/dist/{types-BvpGdsv1.d.mts → types-jJnPXStc.d.mts} +2 -2
  97. package/dist/ui/index.d.mts +1 -1
  98. package/dist/ui/index.d.ts +1 -1
  99. package/package.json +18 -3
  100. package/dist/index-CNkmHmpi.d.ts +0 -89
  101. package/dist/index-CoLebmwv.d.mts +0 -89
package/dist/index.mjs CHANGED
@@ -228,6 +228,7 @@ async function callVerifyAccessAPI(config, request) {
228
228
  if (requestData.subAgentDepth !== void 0) body.subAgentDepth = requestData.subAgentDepth;
229
229
  if (requestData.enableRuntimeChallenge) body.enableRuntimeChallenge = requestData.enableRuntimeChallenge;
230
230
  if (requestData.createSession) body.createSession = requestData.createSession;
231
+ if (requestData.durationRequired) body.durationRequired = requestData.durationRequired;
231
232
  if (requestData.counterpartyType) body.counterpartyType = requestData.counterpartyType;
232
233
  if (requestData.counterpartyUrl) body.counterpartyUrl = requestData.counterpartyUrl;
233
234
  if (requestData.runtimeChallengeOptions) body.runtimeChallengeOptions = requestData.runtimeChallengeOptions;
@@ -401,6 +402,24 @@ async function recordDecision(config, sessionId, decision, reason) {
401
402
  }).catch(() => {
402
403
  });
403
404
  }
405
+ async function reportUnregisteredAttempt(config, data) {
406
+ const apiBaseUrl = config.apiBaseUrl || DEFAULT_CONFIG.apiBaseUrl;
407
+ await fetch(`${apiBaseUrl}/verification-activity/unregistered-attempt`, {
408
+ method: "POST",
409
+ headers: { "Content-Type": "application/json" },
410
+ body: JSON.stringify(data)
411
+ }).catch(() => {
412
+ });
413
+ }
414
+ async function reportCounterpartyPreCheckFailure(config, data) {
415
+ const apiBaseUrl = config.apiBaseUrl || DEFAULT_CONFIG.apiBaseUrl;
416
+ await fetch(`${apiBaseUrl}/verification-activity/counterparty-pre-check-failure`, {
417
+ method: "POST",
418
+ headers: { "Content-Type": "application/json" },
419
+ body: JSON.stringify(data)
420
+ }).catch(() => {
421
+ });
422
+ }
404
423
  async function quickVerify(config, credentials) {
405
424
  const result = await verify(config, {
406
425
  credentials,
@@ -482,6 +501,54 @@ function extractHttpCredentials(headers) {
482
501
  return credentials;
483
502
  }
484
503
 
504
+ // src/pdlss-pre-check.ts
505
+ function performCounterpartyPreCheck(routeConfig, astraCreds, purpose) {
506
+ const failures = [];
507
+ if (routeConfig.allowedPurposes && routeConfig.allowedPurposes.length > 0 && purpose) {
508
+ if (!routeConfig.allowedPurposes.includes(purpose)) {
509
+ failures.push({
510
+ field: "purpose",
511
+ requested: purpose,
512
+ limit: routeConfig.allowedPurposes,
513
+ message: `Purpose "${purpose}" is not in the allowed list: [${routeConfig.allowedPurposes.join(", ")}]`
514
+ });
515
+ }
516
+ }
517
+ if (routeConfig.requiredPurposes && routeConfig.requiredPurposes.length > 0 && purpose) {
518
+ if (!routeConfig.requiredPurposes.includes(purpose)) {
519
+ failures.push({
520
+ field: "purpose",
521
+ requested: purpose,
522
+ limit: routeConfig.requiredPurposes,
523
+ message: `Purpose "${purpose}" is not in the required list: [${routeConfig.requiredPurposes.join(", ")}]`
524
+ });
525
+ }
526
+ }
527
+ if (routeConfig.maxDuration && astraCreds?.pdlss?.duration?.maxSessionDuration) {
528
+ const requested = astraCreds.pdlss.duration.maxSessionDuration;
529
+ if (requested > routeConfig.maxDuration) {
530
+ failures.push({
531
+ field: "duration",
532
+ requested,
533
+ limit: routeConfig.maxDuration,
534
+ message: `Requested duration ${requested}s exceeds maximum ${routeConfig.maxDuration}s`
535
+ });
536
+ }
537
+ }
538
+ if (routeConfig.allowedJurisdictions && routeConfig.allowedJurisdictions.length > 0 && astraCreds?.pdlss?.scope?.jurisdiction) {
539
+ const requested = astraCreds.pdlss.scope.jurisdiction;
540
+ if (!routeConfig.allowedJurisdictions.includes(requested)) {
541
+ failures.push({
542
+ field: "jurisdiction",
543
+ requested,
544
+ limit: routeConfig.allowedJurisdictions,
545
+ message: `Jurisdiction "${requested}" is not in the allowed list: [${routeConfig.allowedJurisdictions.join(", ")}]`
546
+ });
547
+ }
548
+ }
549
+ return failures;
550
+ }
551
+
485
552
  // src/adapters/express.ts
486
553
  function defaultExtractCredentials(req) {
487
554
  return extractCredentials(
@@ -493,6 +560,12 @@ function extractAstraSyncCredentials(req) {
493
560
  return extractHttpCredentials(req.headers);
494
561
  }
495
562
  function defaultExtractPurpose(req) {
563
+ const astraPurpose = req.headers["x-astra-purpose"];
564
+ if (astraPurpose) {
565
+ const value = Array.isArray(astraPurpose) ? astraPurpose[0] : astraPurpose;
566
+ const category = value.split(":")[0];
567
+ return category;
568
+ }
496
569
  const purposeHeader = req.headers["x-purpose"] || req.headers["X-Purpose"];
497
570
  if (purposeHeader) {
498
571
  return Array.isArray(purposeHeader) ? purposeHeader[0] : purposeHeader;
@@ -502,14 +575,14 @@ function defaultExtractPurpose(req) {
502
575
  }
503
576
  switch (req.method) {
504
577
  case "GET":
505
- return "read";
578
+ return "read_data";
506
579
  case "POST":
507
- return "create";
580
+ return "write_data";
508
581
  case "PUT":
509
582
  case "PATCH":
510
- return "update";
583
+ return "write_data";
511
584
  case "DELETE":
512
- return "delete";
585
+ return "delete_data";
513
586
  default:
514
587
  return "general";
515
588
  }
@@ -546,6 +619,7 @@ function createMiddleware(options) {
546
619
  skipPaths = [],
547
620
  onDenied = defaultOnDenied,
548
621
  recordDecisions,
622
+ enableRuntimeChallenge = true,
549
623
  ...config
550
624
  } = options;
551
625
  return async (req, res, next) => {
@@ -563,6 +637,16 @@ function createMiddleware(options) {
563
637
  }
564
638
  const credentials = customExtractCredentials ? customExtractCredentials(req) : defaultExtractCredentials(req);
565
639
  if (!hasCredentials(credentials) && routeConfig.minAccessLevel !== "guidance") {
640
+ const counterpartyUrl2 = config.counterpartyUrl || `${req.protocol}://${req.get("host")}`;
641
+ reportUnregisteredAttempt(config, {
642
+ counterpartyUrl: counterpartyUrl2,
643
+ counterpartyType: config.counterpartyType || "api",
644
+ sourceIp: req.ip,
645
+ userAgent: req.headers["user-agent"],
646
+ requestPath: req.path,
647
+ requestMethod: req.method
648
+ }).catch(() => {
649
+ });
566
650
  const result2 = {
567
651
  verified: false,
568
652
  accessLevel: "none",
@@ -579,7 +663,34 @@ function createMiddleware(options) {
579
663
  return;
580
664
  }
581
665
  const purpose = customExtractPurpose ? customExtractPurpose(req) : defaultExtractPurpose(req);
666
+ const astraCreds = extractAstraSyncCredentials(req);
582
667
  const counterpartyUrl = config.counterpartyUrl || `${req.protocol}://${req.get("host")}`;
668
+ const preCheckFailures = performCounterpartyPreCheck(routeConfig, astraCreds, purpose);
669
+ if (preCheckFailures.length > 0) {
670
+ const result2 = {
671
+ verified: false,
672
+ accessLevel: "none",
673
+ denialReasons: preCheckFailures.map((f) => f.message),
674
+ guidance: {
675
+ message: "Request exceeds counterparty-defined PDLSS limits.",
676
+ registrationUrl: `${config.apiBaseUrl?.replace("/api", "")}/register`,
677
+ documentationUrl: `${config.apiBaseUrl?.replace("/api", "")}/docs/pdlss`
678
+ },
679
+ verifiedAt: /* @__PURE__ */ new Date()
680
+ };
681
+ req.agentVerification = result2;
682
+ reportCounterpartyPreCheckFailure(config, {
683
+ agentId: astraCreds?.agentId || credentials.astraId || "unknown",
684
+ counterpartyUrl,
685
+ counterpartyType: config.counterpartyType || "api",
686
+ failures: preCheckFailures,
687
+ requestPath: req.path,
688
+ requestMethod: req.method
689
+ }).catch(() => {
690
+ });
691
+ onDenied(result2, req, res);
692
+ return;
693
+ }
583
694
  const shouldRecordDecisions = recordDecisions !== false;
584
695
  const result = await verify(config, {
585
696
  credentials,
@@ -590,7 +701,9 @@ function createMiddleware(options) {
590
701
  userAgent: req.headers["user-agent"],
591
702
  createSession: shouldRecordDecisions,
592
703
  counterpartyUrl,
593
- counterpartyType: config.counterpartyType || "api"
704
+ counterpartyType: config.counterpartyType || "api",
705
+ enableRuntimeChallenge,
706
+ durationRequired: astraCreds?.pdlss?.duration?.maxSessionDuration
594
707
  });
595
708
  req.agentVerification = result;
596
709
  const sessionId = result.sessionId;
@@ -685,17 +798,32 @@ function findRouteConfig2(routes, path, method) {
685
798
  return methodMatches && pathMatches;
686
799
  });
687
800
  }
688
- function inferPurpose(method) {
689
- switch (method.toUpperCase()) {
801
+ function extractAstraSyncCredentialsFromNextRequest(request) {
802
+ const headers = {};
803
+ request.headers.forEach((value, key) => {
804
+ headers[key] = value;
805
+ });
806
+ return extractHttpCredentials(headers);
807
+ }
808
+ function extractPurpose(request) {
809
+ const astraPurpose = request.headers.get("x-astra-purpose");
810
+ if (astraPurpose) {
811
+ return astraPurpose.split(":")[0];
812
+ }
813
+ const purposeHeader = request.headers.get("x-purpose");
814
+ if (purposeHeader) {
815
+ return purposeHeader;
816
+ }
817
+ switch (request.method.toUpperCase()) {
690
818
  case "GET":
691
- return "read";
819
+ return "read_data";
692
820
  case "POST":
693
- return "create";
821
+ return "write_data";
694
822
  case "PUT":
695
823
  case "PATCH":
696
- return "update";
824
+ return "write_data";
697
825
  case "DELETE":
698
- return "delete";
826
+ return "delete_data";
699
827
  default:
700
828
  return "general";
701
829
  }
@@ -847,7 +975,7 @@ function generateCommerceShieldHtml(result, options) {
847
975
  `.trim();
848
976
  }
849
977
  function createMiddleware2(options) {
850
- const { routes = [], skipPaths = [], showCommerceShield = true, ...config } = options;
978
+ const { routes = [], skipPaths = [], showCommerceShield = true, enableRuntimeChallenge = true, ...config } = options;
851
979
  return async function middleware(request) {
852
980
  const { NextResponse } = await import("next/server");
853
981
  const pathname = request.nextUrl.pathname;
@@ -864,6 +992,16 @@ function createMiddleware2(options) {
864
992
  }
865
993
  const credentials = extractCredentialsFromNextRequest(request);
866
994
  if (!hasCredentials(credentials) && routeConfig.minAccessLevel !== "guidance") {
995
+ const counterpartyUrl2 = config.counterpartyUrl || request.nextUrl.origin;
996
+ reportUnregisteredAttempt(config, {
997
+ counterpartyUrl: counterpartyUrl2,
998
+ counterpartyType: config.counterpartyType || "website",
999
+ sourceIp: request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || void 0,
1000
+ userAgent: request.headers.get("user-agent") || void 0,
1001
+ requestPath: pathname,
1002
+ requestMethod: request.method
1003
+ }).catch(() => {
1004
+ });
867
1005
  const result2 = {
868
1006
  verified: false,
869
1007
  accessLevel: "none",
@@ -901,7 +1039,54 @@ function createMiddleware2(options) {
901
1039
  return NextResponse.redirect(new URL(registerUrl, request.url));
902
1040
  }
903
1041
  const counterpartyUrl = config.counterpartyUrl || request.nextUrl.origin;
904
- const purpose = request.headers.get("x-purpose") || inferPurpose(request.method);
1042
+ const purpose = extractPurpose(request);
1043
+ const astraCreds = extractAstraSyncCredentialsFromNextRequest(request);
1044
+ const preCheckFailures = performCounterpartyPreCheck(routeConfig, astraCreds, purpose);
1045
+ if (preCheckFailures.length > 0) {
1046
+ const preCheckResult = {
1047
+ verified: false,
1048
+ accessLevel: "none",
1049
+ denialReasons: preCheckFailures.map((f) => f.message),
1050
+ guidance: {
1051
+ message: "Request exceeds counterparty-defined PDLSS limits.",
1052
+ registrationUrl: `${config.apiBaseUrl?.replace("/api", "")}/register`,
1053
+ documentationUrl: `${config.apiBaseUrl?.replace("/api", "")}/docs/pdlss`
1054
+ },
1055
+ verifiedAt: /* @__PURE__ */ new Date()
1056
+ };
1057
+ reportCounterpartyPreCheckFailure(config, {
1058
+ agentId: astraCreds?.agentId || credentials.astraId || "unknown",
1059
+ counterpartyUrl,
1060
+ counterpartyType: config.counterpartyType || "website",
1061
+ failures: preCheckFailures,
1062
+ requestPath: pathname,
1063
+ requestMethod: request.method
1064
+ }).catch(() => {
1065
+ });
1066
+ if (pathname.startsWith("/api/")) {
1067
+ return NextResponse.json(
1068
+ {
1069
+ success: false,
1070
+ error: {
1071
+ code: "PDLSS_PRE_CHECK_FAILED",
1072
+ message: preCheckResult.denialReasons?.[0] || "PDLSS pre-check failed",
1073
+ guidance: preCheckResult.guidance
1074
+ }
1075
+ },
1076
+ { status: 403 }
1077
+ );
1078
+ }
1079
+ if (showCommerceShield) {
1080
+ return new NextResponse(generateCommerceShieldHtml(preCheckResult, options), {
1081
+ status: 200,
1082
+ headers: {
1083
+ "Content-Type": "text/html",
1084
+ "X-AstraSync-Verification": "commerce-shield"
1085
+ }
1086
+ });
1087
+ }
1088
+ return NextResponse.redirect(new URL("/unauthorized", request.url));
1089
+ }
905
1090
  const result = await verify(config, {
906
1091
  credentials,
907
1092
  purpose,
@@ -910,7 +1095,9 @@ function createMiddleware2(options) {
910
1095
  clientIp: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || void 0,
911
1096
  userAgent: request.headers.get("user-agent") || void 0,
912
1097
  counterpartyUrl,
913
- counterpartyType: config.counterpartyType || "website"
1098
+ counterpartyType: config.counterpartyType || "website",
1099
+ enableRuntimeChallenge,
1100
+ durationRequired: astraCreds?.pdlss?.duration?.maxSessionDuration
914
1101
  });
915
1102
  if (!hasMinimumAccess(result.accessLevel, routeConfig.minAccessLevel)) {
916
1103
  if (pathname.startsWith("/api/")) {
@@ -1089,15 +1276,64 @@ async function verifyOnce(options) {
1089
1276
  // src/transport/index.ts
1090
1277
  var transport_exports = {};
1091
1278
  __export(transport_exports, {
1279
+ STRIPE_WEBHOOK_INFORMATIONAL_EVENTS: () => STRIPE_WEBHOOK_INFORMATIONAL_EVENTS,
1092
1280
  applyCredentials: () => applyCredentials,
1281
+ bindIdentity: () => bindIdentity,
1282
+ claim: () => claim,
1283
+ clearTransportExtractors: () => clearTransportExtractors,
1284
+ createMastercardRegistry: () => createMastercardRegistry,
1285
+ createVisaRegistry: () => createVisaRegistry,
1286
+ createWebBotAuthRegistry: () => createWebBotAuthRegistry,
1093
1287
  detectProtocol: () => detectProtocol,
1288
+ evaluatePaymentMethodAllowlist: () => evaluatePaymentMethodAllowlist,
1289
+ evaluateSpendingLimit: () => evaluateSpendingLimit,
1290
+ evaluateVIConstraints: () => evaluateVIConstraints,
1094
1291
  extractA2ACredentials: () => extractA2ACredentials,
1292
+ extractACPContext: () => extractACPContext,
1293
+ extractACPTransactionValue: () => extractACPTransactionValue,
1294
+ extractAP2Mandate: () => extractAP2Mandate,
1295
+ extractAP2Mandates: () => extractAP2Mandates,
1296
+ extractAP2TransactionValue: () => extractAP2TransactionValue,
1095
1297
  extractCredentialsFromProtocol: () => extractCredentialsFromProtocol,
1096
1298
  extractHttpCredentials: () => extractHttpCredentials,
1299
+ extractMPPContext: () => extractMPPContext,
1300
+ extractMPPFromRequest: () => extractMPPFromRequest,
1301
+ extractMPPFromResponse: () => extractMPPFromResponse,
1302
+ extractMPPTransactionValue: () => extractMPPTransactionValue,
1097
1303
  extractMcpCredentials: () => extractMcpCredentials,
1304
+ extractUCPContext: () => extractUCPContext,
1305
+ extractUCPTransactionValue: () => extractUCPTransactionValue,
1306
+ extractVIClaims: () => extractVIClaims,
1307
+ extractVITransactionValue: () => extractVITransactionValue,
1308
+ extractX402Context: () => extractX402Context,
1309
+ extractX402FromRequest: () => extractX402FromRequest,
1310
+ extractX402FromResponse: () => extractX402FromResponse,
1311
+ extractX402TransactionValue: () => extractX402TransactionValue,
1312
+ fetchUCPManifest: () => fetchUCPManifest,
1313
+ getTransportExtractor: () => getTransportExtractor,
1314
+ getTransportExtractors: () => getTransportExtractors,
1315
+ isStripeWebhookInformational: () => isStripeWebhookInformational,
1316
+ mapACPRequestToPurpose: () => mapACPRequestToPurpose,
1317
+ mapAP2MandateToPurpose: () => mapAP2MandateToPurpose,
1318
+ mapMPPRequestToPurpose: () => mapMPPRequestToPurpose,
1319
+ mapRFC9421TagToPurpose: () => mapRFC9421TagToPurpose,
1320
+ mapUCPRequestToPurpose: () => mapUCPRequestToPurpose,
1321
+ mapVIMandateToPurpose: () => mapVIMandateToPurpose,
1322
+ mapX402RequestToPurpose: () => mapX402RequestToPurpose,
1323
+ parseRFC9421: () => parseRFC9421,
1324
+ registerTransportExtractor: () => registerTransportExtractor,
1325
+ runCommercePipeline: () => runCommercePipeline,
1326
+ runMatchingExtractors: () => runMatchingExtractors,
1098
1327
  setA2AMetadata: () => setA2AMetadata,
1099
1328
  setHttpHeaders: () => setHttpHeaders,
1100
- setMcpMeta: () => setMcpMeta
1329
+ setMcpMeta: () => setMcpMeta,
1330
+ validateUCPManifest: () => validateUCPManifest,
1331
+ verifyACPSignature: () => verifyACPSignature,
1332
+ verifyAP2Chain: () => verifyAP2Chain,
1333
+ verifyMPP: () => verifyMPP,
1334
+ verifyRFC9421: () => verifyRFC9421,
1335
+ verifyStripeWebhook: () => verifyStripeWebhook,
1336
+ verifyVIChain: () => verifyVIChain
1101
1337
  });
1102
1338
 
1103
1339
  // src/transport/a2a.ts
@@ -1170,6 +1406,2283 @@ function extractMcpCredentials(params) {
1170
1406
  return credentials;
1171
1407
  }
1172
1408
 
1409
+ // src/transport/purpose-mapping.ts
1410
+ var UCP_ROUTES = [
1411
+ { method: "POST", pattern: /^\/checkout[-_]sessions\/?$/, purpose: "commerce.checkout.create" },
1412
+ {
1413
+ method: "PUT",
1414
+ pattern: /^\/checkout[-_]sessions\/[^/]+\/?$/,
1415
+ purpose: "commerce.checkout.update"
1416
+ },
1417
+ {
1418
+ method: "POST",
1419
+ pattern: /^\/checkout[-_]sessions\/[^/]+\/complete\/?$/,
1420
+ purpose: "commerce.payment.execute"
1421
+ },
1422
+ {
1423
+ method: "POST",
1424
+ pattern: /^\/checkout[-_]sessions\/[^/]+\/cancel\/?$/,
1425
+ purpose: "commerce.checkout.cancel"
1426
+ }
1427
+ ];
1428
+ var ACP_ROUTES = [
1429
+ { method: "POST", pattern: /^\/checkout_sessions\/?$/, purpose: "commerce.checkout.create" },
1430
+ {
1431
+ method: "POST",
1432
+ pattern: /^\/checkout_sessions\/[^/]+\/?$/,
1433
+ purpose: "commerce.checkout.update"
1434
+ },
1435
+ {
1436
+ method: "POST",
1437
+ pattern: /^\/checkout_sessions\/[^/]+\/complete\/?$/,
1438
+ purpose: "commerce.payment.execute"
1439
+ },
1440
+ {
1441
+ method: "POST",
1442
+ pattern: /^\/checkout_sessions\/[^/]+\/cancel\/?$/,
1443
+ purpose: "commerce.checkout.cancel"
1444
+ },
1445
+ {
1446
+ method: "POST",
1447
+ pattern: /^\/agentic_commerce\/delegate_payment\/?$/,
1448
+ purpose: "commerce.delegation.payment"
1449
+ }
1450
+ ];
1451
+ function mapUCPRequestToPurpose(method, path) {
1452
+ const normalizedMethod = method.toUpperCase();
1453
+ const normalizedPath = stripQuery(path);
1454
+ for (const route of UCP_ROUTES) {
1455
+ if (route.method === normalizedMethod && route.pattern.test(normalizedPath)) {
1456
+ return route.purpose;
1457
+ }
1458
+ }
1459
+ return null;
1460
+ }
1461
+ function mapACPRequestToPurpose(method, path) {
1462
+ const normalizedMethod = method.toUpperCase();
1463
+ const normalizedPath = stripQuery(path);
1464
+ for (const route of ACP_ROUTES) {
1465
+ if (route.method === normalizedMethod && route.pattern.test(normalizedPath)) {
1466
+ return route.purpose;
1467
+ }
1468
+ }
1469
+ return null;
1470
+ }
1471
+ function mapAP2MandateToPurpose(mandateType) {
1472
+ switch (mandateType) {
1473
+ case "intent_mandate":
1474
+ return "commerce.delegation.intent";
1475
+ case "cart_mandate":
1476
+ return "commerce.checkout.confirm";
1477
+ case "payment_mandate":
1478
+ return "commerce.payment.execute";
1479
+ }
1480
+ }
1481
+ function mapVIMandateToPurpose(mandateType) {
1482
+ switch (mandateType) {
1483
+ case "checkout":
1484
+ return "commerce.checkout.confirm";
1485
+ case "payment":
1486
+ return "commerce.payment.execute";
1487
+ case "checkout.open":
1488
+ return "commerce.delegation.checkout";
1489
+ case "payment.open":
1490
+ return "commerce.delegation.payment";
1491
+ }
1492
+ }
1493
+ function mapRFC9421TagToPurpose(tag) {
1494
+ if (tag === "purchase") return "commerce.payment.execute";
1495
+ return "commerce.browsing";
1496
+ }
1497
+ function mapMPPRequestToPurpose(intent, amount) {
1498
+ if (typeof amount === "number" && amount === 0) return "commerce.identity_probe";
1499
+ if (intent === "session") return "commerce.payment.stream";
1500
+ return "commerce.payment.execute";
1501
+ }
1502
+ function mapX402RequestToPurpose(amount) {
1503
+ if (typeof amount === "number" && amount === 0) return "commerce.identity_probe";
1504
+ return "commerce.payment.execute";
1505
+ }
1506
+ function stripQuery(path) {
1507
+ const q = path.indexOf("?");
1508
+ return q === -1 ? path : path.slice(0, q);
1509
+ }
1510
+ var STRIPE_WEBHOOK_INFORMATIONAL_EVENTS = [
1511
+ "payment_intent.succeeded",
1512
+ "payment_intent.payment_failed",
1513
+ "charge.refunded",
1514
+ "checkout.session.completed",
1515
+ "customer.subscription.created"
1516
+ ];
1517
+ function isStripeWebhookInformational(eventType) {
1518
+ return STRIPE_WEBHOOK_INFORMATIONAL_EVENTS.includes(eventType);
1519
+ }
1520
+
1521
+ // src/transport/transaction-value.ts
1522
+ function extractUCPTransactionValue(input) {
1523
+ const totals = input.totals ?? [];
1524
+ const total = totals.find((t) => t.type === "total") ?? totals[0];
1525
+ if (!total || typeof total.amount !== "number" || !total.currency) return null;
1526
+ return {
1527
+ protocol: "ucp",
1528
+ amount: total.amount / 100,
1529
+ currency: total.currency,
1530
+ source: `totals[type=${total.type ?? "unknown"}].amount`
1531
+ };
1532
+ }
1533
+ function extractACPTransactionValue(input) {
1534
+ const totals = input.totals ?? [];
1535
+ const total = totals.find((t) => t.type === "total") ?? totals[0];
1536
+ if (!total || typeof total.amount !== "number" || !total.currency) return null;
1537
+ return {
1538
+ protocol: "acp",
1539
+ amount: total.amount / 100,
1540
+ currency: total.currency,
1541
+ source: `totals[type=${total.type ?? "unknown"}].amount`
1542
+ };
1543
+ }
1544
+ function extractVITransactionValue(claims) {
1545
+ const l3a = claims.l3aPaymentAmount;
1546
+ if (l3a && typeof l3a.amount === "number" && l3a.currency) {
1547
+ return {
1548
+ protocol: "vi",
1549
+ amount: l3a.amount,
1550
+ currency: l3a.currency,
1551
+ source: "L3a.payment.amount"
1552
+ };
1553
+ }
1554
+ const bound = claims.constraints?.paymentAmount;
1555
+ if (bound && typeof bound.max === "number" && bound.currency) {
1556
+ return {
1557
+ protocol: "vi",
1558
+ amount: bound.max,
1559
+ currency: bound.currency,
1560
+ source: "L2.payment.constraints.amount.max"
1561
+ };
1562
+ }
1563
+ return null;
1564
+ }
1565
+ function extractAP2TransactionValue(mandate) {
1566
+ const amt = mandate?.payment_details_total?.amount;
1567
+ if (!amt || !amt.currency) return null;
1568
+ const n = typeof amt.value === "string" ? Number(amt.value) : amt.value;
1569
+ if (typeof n !== "number" || !Number.isFinite(n)) return null;
1570
+ return {
1571
+ protocol: "ap2",
1572
+ amount: n,
1573
+ currency: amt.currency,
1574
+ source: "payment_mandate.payment_details_total.amount"
1575
+ };
1576
+ }
1577
+ function extractMPPTransactionValue(challenge) {
1578
+ const req = challenge.request;
1579
+ if (!req || typeof req.amount !== "number" || !req.currency) return null;
1580
+ return {
1581
+ protocol: "mpp",
1582
+ amount: req.amount,
1583
+ currency: req.currency,
1584
+ source: `challenge.request.amount (method=${challenge.method ?? "unknown"})`
1585
+ };
1586
+ }
1587
+ function extractX402TransactionValue(req) {
1588
+ const amount = req.maxAmountRequired ?? req.amount;
1589
+ const currency = req.currency ?? req.asset;
1590
+ if (typeof amount !== "number" || !currency) return null;
1591
+ return {
1592
+ protocol: "x402",
1593
+ amount,
1594
+ currency,
1595
+ source: req.maxAmountRequired !== void 0 ? "maxAmountRequired" : "amount"
1596
+ };
1597
+ }
1598
+
1599
+ // src/transport/rfc9421.ts
1600
+ import { parseDictionary } from "structured-headers";
1601
+ function parseRFC9421(headers) {
1602
+ const sigInput = readHeader(headers, "signature-input");
1603
+ const sig = readHeader(headers, "signature");
1604
+ if (!sigInput || !sig) return null;
1605
+ let inputDict;
1606
+ let sigDict;
1607
+ try {
1608
+ inputDict = parseDictionary(sigInput);
1609
+ sigDict = parseDictionary(sig);
1610
+ } catch {
1611
+ return null;
1612
+ }
1613
+ const signatures = [];
1614
+ for (const [label, entry] of inputDict) {
1615
+ const innerList = Array.isArray(entry) ? entry[0] : entry.value;
1616
+ const params = Array.isArray(entry) ? entry[1] : entry.params;
1617
+ if (!Array.isArray(innerList) || !params) continue;
1618
+ const covered = [];
1619
+ for (const item of innerList) {
1620
+ const [bare] = Array.isArray(item) ? item : [item];
1621
+ if (typeof bare === "string") covered.push(bare);
1622
+ else if (bare && typeof bare === "object" && "toString" in bare) covered.push(String(bare));
1623
+ }
1624
+ const paramsMap = params;
1625
+ const kid = coerceString(paramsMap.get("keyid"));
1626
+ if (!kid) continue;
1627
+ const sigEntry = sigDict.get(label);
1628
+ if (!sigEntry) continue;
1629
+ const sigBare = Array.isArray(sigEntry) ? sigEntry[0] : sigEntry.value;
1630
+ const signatureBase64 = extractBase64(sigBare);
1631
+ if (!signatureBase64) continue;
1632
+ signatures.push({
1633
+ label,
1634
+ kid,
1635
+ alg: coerceString(paramsMap.get("alg")),
1636
+ covered,
1637
+ signatureBase64,
1638
+ created: coerceNumber(paramsMap.get("created")),
1639
+ expires: coerceNumber(paramsMap.get("expires")),
1640
+ nonce: coerceString(paramsMap.get("nonce")),
1641
+ tag: coerceString(paramsMap.get("tag"))
1642
+ });
1643
+ }
1644
+ if (signatures.length === 0) return null;
1645
+ return { signatures };
1646
+ }
1647
+ function readHeader(headers, name) {
1648
+ for (const key of Object.keys(headers)) {
1649
+ if (key.toLowerCase() === name) {
1650
+ const raw = headers[key];
1651
+ if (typeof raw === "string") return raw;
1652
+ if (Array.isArray(raw)) return raw.join(", ");
1653
+ return null;
1654
+ }
1655
+ }
1656
+ return null;
1657
+ }
1658
+ function coerceString(value) {
1659
+ if (typeof value === "string") return value;
1660
+ if (value == null) return void 0;
1661
+ if (typeof value === "object" && "toString" in value) {
1662
+ const s = String(value);
1663
+ return s.length > 0 ? s : void 0;
1664
+ }
1665
+ return void 0;
1666
+ }
1667
+ function coerceNumber(value) {
1668
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1669
+ if (typeof value === "bigint") return Number(value);
1670
+ return void 0;
1671
+ }
1672
+ function extractBase64(value) {
1673
+ if (value instanceof Uint8Array) return bufferToBase64(value);
1674
+ if (value instanceof ArrayBuffer) return bufferToBase64(new Uint8Array(value));
1675
+ if (ArrayBuffer.isView(value)) {
1676
+ const v = value;
1677
+ return bufferToBase64(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
1678
+ }
1679
+ if (typeof value === "string") {
1680
+ if (value.startsWith(":") && value.endsWith(":")) return value.slice(1, -1);
1681
+ return value;
1682
+ }
1683
+ return null;
1684
+ }
1685
+ function bufferToBase64(bytes) {
1686
+ return Buffer.from(bytes).toString("base64");
1687
+ }
1688
+
1689
+ // src/transport/rfc9421-verify.ts
1690
+ import { httpbis } from "http-message-signatures";
1691
+ async function verifyRFC9421(request, options) {
1692
+ const { resolver } = options;
1693
+ const tolerance = options.clockSkewSec ?? 300;
1694
+ const nowSec = options.now ? options.now() : Math.floor(Date.now() / 1e3);
1695
+ let resolvedKid;
1696
+ let resolvedAlg;
1697
+ const keyLookup = async (parameters) => {
1698
+ const kid = typeof parameters.keyid === "string" ? parameters.keyid : void 0;
1699
+ if (!kid) return null;
1700
+ resolvedKid = kid;
1701
+ const alg = typeof parameters.alg === "string" ? parameters.alg : void 0;
1702
+ if (alg) resolvedAlg = alg;
1703
+ const origin = safeOrigin(request.url);
1704
+ const jwk = await resolver.resolve(kid, { origin, algorithm: alg });
1705
+ if (!jwk) return null;
1706
+ const created = toUnixSeconds(parameters.created);
1707
+ const expires = toUnixSeconds(parameters.expires);
1708
+ if (created !== void 0 && Math.abs(nowSec - created) > tolerance) return null;
1709
+ if (expires !== void 0 && nowSec > expires + tolerance) return null;
1710
+ return jwkToVerifyingKey(kid, jwk, alg);
1711
+ };
1712
+ try {
1713
+ const result = await httpbis.verifyMessage(
1714
+ {
1715
+ keyLookup
1716
+ },
1717
+ normalizeRequest(request)
1718
+ );
1719
+ if (result === true) {
1720
+ return {
1721
+ ok: true,
1722
+ kid: resolvedKid,
1723
+ registry: resolver.name,
1724
+ algorithm: resolvedAlg
1725
+ };
1726
+ }
1727
+ return {
1728
+ ok: false,
1729
+ kid: resolvedKid,
1730
+ registry: resolver.name,
1731
+ algorithm: resolvedAlg,
1732
+ error: result === false ? "signature invalid" : "no signature found"
1733
+ };
1734
+ } catch (err) {
1735
+ return {
1736
+ ok: false,
1737
+ kid: resolvedKid,
1738
+ registry: resolver.name,
1739
+ algorithm: resolvedAlg,
1740
+ error: err instanceof Error ? err.message : "verification error"
1741
+ };
1742
+ }
1743
+ }
1744
+ function normalizeRequest(request) {
1745
+ return {
1746
+ method: request.method.toUpperCase(),
1747
+ url: request.url,
1748
+ headers: request.headers
1749
+ };
1750
+ }
1751
+ function safeOrigin(url) {
1752
+ try {
1753
+ return new URL(url).origin;
1754
+ } catch {
1755
+ return void 0;
1756
+ }
1757
+ }
1758
+ async function jwkToVerifyingKey(id, jwk, alg) {
1759
+ const algorithm = alg ?? inferAlgFromJwk(jwk);
1760
+ const { subtle } = await getCrypto();
1761
+ const importAlg = webCryptoImportAlgFor(algorithm);
1762
+ const verifyAlg = webCryptoAlgFor(algorithm);
1763
+ if (!importAlg || !verifyAlg) {
1764
+ return {
1765
+ id,
1766
+ algs: alg ? [alg] : void 0,
1767
+ verify: async () => false
1768
+ };
1769
+ }
1770
+ const key = await subtle.importKey("jwk", jwk, importAlg, false, ["verify"]);
1771
+ return {
1772
+ id,
1773
+ algs: alg ? [alg] : void 0,
1774
+ verify: async (data, signature) => {
1775
+ try {
1776
+ return await subtle.verify(verifyAlg, key, toArrayBuffer(signature), toArrayBuffer(data));
1777
+ } catch {
1778
+ return false;
1779
+ }
1780
+ }
1781
+ };
1782
+ }
1783
+ function inferAlgFromJwk(jwk) {
1784
+ if (jwk.kty === "OKP" && jwk.crv === "Ed25519") return "ed25519";
1785
+ if (jwk.kty === "EC" && jwk.crv === "P-256") return "ecdsa-p256-sha256";
1786
+ if (jwk.kty === "EC" && jwk.crv === "P-384") return "ecdsa-p384-sha384";
1787
+ if (jwk.kty === "RSA") return "rsa-v1_5-sha256";
1788
+ return "ecdsa-p256-sha256";
1789
+ }
1790
+ function webCryptoAlgFor(rfc9421Alg) {
1791
+ switch (rfc9421Alg) {
1792
+ case "ed25519":
1793
+ return { name: "Ed25519" };
1794
+ case "ecdsa-p256-sha256":
1795
+ return { name: "ECDSA", hash: "SHA-256" };
1796
+ case "ecdsa-p384-sha384":
1797
+ return { name: "ECDSA", hash: "SHA-384" };
1798
+ case "rsa-v1_5-sha256":
1799
+ return { name: "RSASSA-PKCS1-v1_5" };
1800
+ case "rsa-pss-sha512":
1801
+ return { name: "RSA-PSS", saltLength: 64 };
1802
+ default:
1803
+ return null;
1804
+ }
1805
+ }
1806
+ function webCryptoImportAlgFor(rfc9421Alg) {
1807
+ switch (rfc9421Alg) {
1808
+ case "ed25519":
1809
+ return { name: "Ed25519" };
1810
+ case "ecdsa-p256-sha256":
1811
+ return { name: "ECDSA", namedCurve: "P-256" };
1812
+ case "ecdsa-p384-sha384":
1813
+ return { name: "ECDSA", namedCurve: "P-384" };
1814
+ case "rsa-v1_5-sha256":
1815
+ return { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
1816
+ case "rsa-pss-sha512":
1817
+ return { name: "RSA-PSS", hash: "SHA-512" };
1818
+ default:
1819
+ return null;
1820
+ }
1821
+ }
1822
+ function toArrayBuffer(buf) {
1823
+ const out = new ArrayBuffer(buf.byteLength);
1824
+ new Uint8Array(out).set(buf);
1825
+ return out;
1826
+ }
1827
+ function toUnixSeconds(v) {
1828
+ if (typeof v === "number" && Number.isFinite(v)) return v;
1829
+ if (v instanceof Date) return Math.floor(v.getTime() / 1e3);
1830
+ if (typeof v === "string") {
1831
+ const parsed = Date.parse(v);
1832
+ if (Number.isFinite(parsed)) return Math.floor(parsed / 1e3);
1833
+ }
1834
+ return void 0;
1835
+ }
1836
+ async function getCrypto() {
1837
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
1838
+ return { subtle: globalThis.crypto.subtle };
1839
+ }
1840
+ const nodeCrypto = await import("crypto");
1841
+ return { subtle: nodeCrypto.webcrypto.subtle };
1842
+ }
1843
+
1844
+ // src/transport/ucp.ts
1845
+ function extractUCPContext(request) {
1846
+ const { method, url } = request;
1847
+ if (!method || !url) return null;
1848
+ const parsedUrl = safeParseUrl(url);
1849
+ const path = parsedUrl?.pathname ?? url.split("?")[0];
1850
+ const purpose = mapUCPRequestToPurpose(method, path);
1851
+ const endpoint = `${method.toUpperCase()} ${path}`;
1852
+ const sessionId = extractSessionId(path);
1853
+ const body = request.body ?? {};
1854
+ const totals = Array.isArray(body.totals) ? body.totals : void 0;
1855
+ const paymentMethod = coerceString2(body.payment_method ?? body.paymentMethod);
1856
+ const manifestUrl = coerceString2(body.manifest_url ?? body.manifestUrl);
1857
+ const merchantDomain = extractMerchantDomain(body, parsedUrl);
1858
+ return {
1859
+ sessionId,
1860
+ endpoint,
1861
+ purpose,
1862
+ merchantDomain,
1863
+ totals,
1864
+ paymentMethod,
1865
+ manifestUrl
1866
+ };
1867
+ }
1868
+ async function fetchUCPManifest(manifestUrl, options = {}) {
1869
+ const timeoutMs = options.timeoutMs ?? 3e3;
1870
+ const controller = new AbortController();
1871
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1872
+ try {
1873
+ const res = await fetch(manifestUrl, { signal: controller.signal });
1874
+ if (!res.ok) return null;
1875
+ return await res.json();
1876
+ } catch {
1877
+ return null;
1878
+ } finally {
1879
+ clearTimeout(timer);
1880
+ }
1881
+ }
1882
+ function validateUCPManifest(manifest, options = {}) {
1883
+ if (options.validator) return options.validator(manifest);
1884
+ const errors = [];
1885
+ if (!manifest || typeof manifest !== "object") {
1886
+ return { ok: false, errors: ["manifest is not an object"] };
1887
+ }
1888
+ const m = manifest;
1889
+ if (typeof m.version !== "string") errors.push("version is required and must be a string");
1890
+ if (!Array.isArray(m.capabilities)) errors.push("capabilities must be an array");
1891
+ if (!m.endpoints || typeof m.endpoints !== "object") errors.push("endpoints must be an object");
1892
+ return { ok: errors.length === 0, errors };
1893
+ }
1894
+ function safeParseUrl(url) {
1895
+ try {
1896
+ return new URL(url, "http://placeholder.invalid");
1897
+ } catch {
1898
+ return null;
1899
+ }
1900
+ }
1901
+ function extractSessionId(path) {
1902
+ const match = path.match(/\/checkout[-_]sessions\/([^/?#]+)/);
1903
+ return match?.[1];
1904
+ }
1905
+ function extractMerchantDomain(body, parsedUrl) {
1906
+ const explicit = coerceString2(body.merchant_domain ?? body.merchantDomain);
1907
+ if (explicit) return explicit;
1908
+ if (parsedUrl && parsedUrl.hostname !== "placeholder.invalid") return parsedUrl.hostname;
1909
+ return void 0;
1910
+ }
1911
+ function coerceString2(v) {
1912
+ return typeof v === "string" && v.length > 0 ? v : void 0;
1913
+ }
1914
+
1915
+ // src/transport/acp.ts
1916
+ function extractACPContext(request) {
1917
+ const { method, url } = request;
1918
+ if (!method || !url) return null;
1919
+ const path = stripQuery2(url.startsWith("http") ? new URL(url).pathname : url);
1920
+ const endpoint = classifyEndpoint(method, path);
1921
+ const purpose = mapACPRequestToPurpose(method, path);
1922
+ const sessionId = extractSessionId2(path);
1923
+ const headers = request.headers ?? {};
1924
+ const signatureHeader = readHeader2(headers, "signature");
1925
+ const timestampHeader = readHeader2(headers, "timestamp");
1926
+ const idempotencyKey = readHeader2(headers, "idempotency-key");
1927
+ const apiVersion = readHeader2(headers, "api-version");
1928
+ const bearer = extractBearer(readHeader2(headers, "authorization"));
1929
+ const body = request.body ?? {};
1930
+ const merchantId = coerceString3(body.merchant_id ?? body.merchantId);
1931
+ const totals = Array.isArray(body.totals) ? body.totals : void 0;
1932
+ const fulfillmentOption = extractFulfillmentOption(body);
1933
+ const paymentToken = extractPaymentToken(body);
1934
+ return {
1935
+ endpoint,
1936
+ purpose,
1937
+ sessionId,
1938
+ merchantId,
1939
+ apiVersion,
1940
+ bearer,
1941
+ signatureHeader,
1942
+ timestampHeader,
1943
+ idempotencyKey,
1944
+ paymentToken,
1945
+ totals,
1946
+ fulfillmentOption,
1947
+ rawBody: request.rawBody
1948
+ };
1949
+ }
1950
+ function classifyEndpoint(method, path) {
1951
+ const m = method.toUpperCase();
1952
+ if (m !== "POST") return "unknown";
1953
+ if (/^\/agentic_commerce\/delegate_payment\/?$/.test(path)) return "delegate_payment";
1954
+ if (/^\/checkout_sessions\/?$/.test(path)) return "checkout_sessions.create";
1955
+ if (/^\/checkout_sessions\/[^/]+\/?$/.test(path)) return "checkout_sessions.update";
1956
+ if (/^\/checkout_sessions\/[^/]+\/complete\/?$/.test(path)) return "checkout_sessions.complete";
1957
+ if (/^\/checkout_sessions\/[^/]+\/cancel\/?$/.test(path)) return "checkout_sessions.cancel";
1958
+ return "unknown";
1959
+ }
1960
+ function extractSessionId2(path) {
1961
+ const match = path.match(/\/checkout_sessions\/([^/?#]+)/);
1962
+ return match?.[1];
1963
+ }
1964
+ function extractBearer(authHeader) {
1965
+ if (!authHeader) return void 0;
1966
+ const match = authHeader.match(/^Bearer\s+(.+)$/i);
1967
+ return match ? match[1].trim() : void 0;
1968
+ }
1969
+ function extractPaymentToken(body) {
1970
+ const paymentData = body.payment_data;
1971
+ if (!paymentData) return void 0;
1972
+ const raw = coerceString3(paymentData.token);
1973
+ const provider = coerceString3(paymentData.provider);
1974
+ if (!raw) return { raw: void 0, type: null, provider };
1975
+ const type = classifyPaymentToken(raw);
1976
+ return { raw, type, provider };
1977
+ }
1978
+ function classifyPaymentToken(token) {
1979
+ if (token.startsWith("spt_")) return "stripe-spt";
1980
+ if (token.startsWith("vt_")) return "acp-vt";
1981
+ return "other";
1982
+ }
1983
+ function extractFulfillmentOption(body) {
1984
+ const direct = coerceString3(body.fulfillment_option ?? body.fulfillmentOption);
1985
+ if (direct) return direct;
1986
+ const options = body.fulfillment_options;
1987
+ if (Array.isArray(options) && options.length > 0) {
1988
+ const first = options[0];
1989
+ if (first && typeof first === "object") {
1990
+ const id = coerceString3(first.id);
1991
+ if (id) return id;
1992
+ }
1993
+ }
1994
+ return void 0;
1995
+ }
1996
+ function readHeader2(headers, name) {
1997
+ for (const key of Object.keys(headers)) {
1998
+ if (key.toLowerCase() === name) {
1999
+ const raw = headers[key];
2000
+ if (typeof raw === "string") return raw;
2001
+ if (Array.isArray(raw)) return raw[0];
2002
+ }
2003
+ }
2004
+ return void 0;
2005
+ }
2006
+ function stripQuery2(path) {
2007
+ const q = path.indexOf("?");
2008
+ return q === -1 ? path : path.slice(0, q);
2009
+ }
2010
+ function coerceString3(v) {
2011
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2012
+ }
2013
+
2014
+ // src/transport/vi.ts
2015
+ import { splitSdJwt, decodeSdJwtSync } from "@sd-jwt/decode";
2016
+ import { createHash } from "crypto";
2017
+ function extractVIClaims(sdJwtCompact) {
2018
+ if (!sdJwtCompact || typeof sdJwtCompact !== "string") return null;
2019
+ let decoded;
2020
+ try {
2021
+ decoded = decodeSdJwtSync(sdJwtCompact, sha256Sync);
2022
+ } catch {
2023
+ return null;
2024
+ }
2025
+ const split = safeSplit(sdJwtCompact);
2026
+ const payload = decoded.jwt?.payload ?? {};
2027
+ const disclosures = decoded.disclosures ?? [];
2028
+ const claims = applyDisclosures(
2029
+ payload,
2030
+ disclosures
2031
+ );
2032
+ const mandateType = coerceMandateType(
2033
+ claims.mandate_type ?? claims.mandateType ?? payload.mandate_type ?? payload.mandateType
2034
+ );
2035
+ if (!mandateType) return null;
2036
+ const kid = coerceString4(
2037
+ decoded.jwt?.header?.kid ?? claims.kid ?? payload.kid
2038
+ );
2039
+ const executionMode = coerceExecutionMode(claims.execution_mode ?? claims.executionMode);
2040
+ const credentialProvider = coerceString4(claims.iss ?? payload.iss);
2041
+ const constraints = extractConstraints(
2042
+ claims.constraints ?? claims.default_constraints ?? {}
2043
+ );
2044
+ const transactionId = coerceString4(claims.transaction_id ?? claims.transactionId);
2045
+ const checkoutHash = coerceString4(
2046
+ claims.checkout_hash ?? claims.conditional_transaction_id ?? claims.payment_reference?.checkout_hash
2047
+ );
2048
+ return {
2049
+ mandateType,
2050
+ kid,
2051
+ executionMode,
2052
+ credentialProvider,
2053
+ constraints,
2054
+ checkoutHash,
2055
+ transactionId,
2056
+ rawLayers: split
2057
+ };
2058
+ }
2059
+ function safeSplit(compact) {
2060
+ try {
2061
+ const { jwt, kbJwt } = splitSdJwt(compact);
2062
+ return { l3: jwt, l2: kbJwt };
2063
+ } catch {
2064
+ return {};
2065
+ }
2066
+ }
2067
+ function applyDisclosures(payload, disclosures) {
2068
+ const result = { ...payload };
2069
+ for (const d of disclosures) {
2070
+ if (d.key && d.value !== void 0 && !(d.key in result)) {
2071
+ result[d.key] = d.value;
2072
+ }
2073
+ }
2074
+ return result;
2075
+ }
2076
+ function extractConstraints(raw) {
2077
+ return {
2078
+ allowedMerchants: toAllowedPartyArray(raw.allowed_merchants ?? raw.allowedMerchants),
2079
+ allowedPayees: toAllowedPartyArray(raw.allowed_payees ?? raw.allowedPayees),
2080
+ lineItems: toLineItemArray(raw.line_items ?? raw.lineItems),
2081
+ paymentAmount: toPaymentAmount(raw.payment_amount ?? raw.paymentAmount),
2082
+ budgetLimit: toBudgetLimit(raw.budget_limit ?? raw.budgetLimit ?? raw.budget),
2083
+ recurrence: toRecurrence(raw.recurrence),
2084
+ agentRecurrence: toRecurrence(raw.agent_recurrence ?? raw.agentRecurrence)
2085
+ };
2086
+ }
2087
+ function toAllowedPartyArray(v) {
2088
+ if (!Array.isArray(v)) return void 0;
2089
+ const out = [];
2090
+ for (const item of v) {
2091
+ if (item && typeof item === "object") {
2092
+ const r = item;
2093
+ out.push({
2094
+ id: coerceString4(r.id),
2095
+ name: coerceString4(r.name),
2096
+ website: coerceString4(r.website)
2097
+ });
2098
+ }
2099
+ }
2100
+ return out.length > 0 ? out : void 0;
2101
+ }
2102
+ function toLineItemArray(v) {
2103
+ if (!Array.isArray(v)) return void 0;
2104
+ const out = [];
2105
+ for (const item of v) {
2106
+ if (item && typeof item === "object") {
2107
+ const r = item;
2108
+ const acc = r.acceptable_items ?? r.acceptableItems;
2109
+ out.push({
2110
+ id: coerceString4(r.id),
2111
+ acceptableItems: Array.isArray(acc) ? acc.filter((a) => typeof a === "string") : void 0,
2112
+ quantity: coerceNumber2(r.quantity)
2113
+ });
2114
+ }
2115
+ }
2116
+ return out.length > 0 ? out : void 0;
2117
+ }
2118
+ function toPaymentAmount(v) {
2119
+ if (!v || typeof v !== "object") return void 0;
2120
+ const r = v;
2121
+ return {
2122
+ currency: coerceString4(r.currency),
2123
+ min: coerceNumber2(r.min),
2124
+ max: coerceNumber2(r.max)
2125
+ };
2126
+ }
2127
+ function toBudgetLimit(v) {
2128
+ if (!v || typeof v !== "object") return void 0;
2129
+ const r = v;
2130
+ return {
2131
+ currency: coerceString4(r.currency),
2132
+ max: coerceNumber2(r.max)
2133
+ };
2134
+ }
2135
+ function toRecurrence(v) {
2136
+ if (!v || typeof v !== "object") return void 0;
2137
+ const r = v;
2138
+ return {
2139
+ frequency: coerceString4(r.frequency),
2140
+ startDate: coerceString4(r.start_date ?? r.startDate),
2141
+ endDate: coerceString4(r.end_date ?? r.endDate),
2142
+ maxOccurrences: coerceNumber2(r.max_occurrences ?? r.maxOccurrences)
2143
+ };
2144
+ }
2145
+ function coerceMandateType(v) {
2146
+ if (v === "checkout" || v === "payment" || v === "checkout.open" || v === "payment.open") {
2147
+ return v;
2148
+ }
2149
+ return null;
2150
+ }
2151
+ function coerceExecutionMode(v) {
2152
+ return v === "Immediate" || v === "Autonomous" || v === "Both" ? v : void 0;
2153
+ }
2154
+ function coerceString4(v) {
2155
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2156
+ }
2157
+ function coerceNumber2(v) {
2158
+ if (typeof v === "number" && Number.isFinite(v)) return v;
2159
+ if (typeof v === "string") {
2160
+ const n = Number(v);
2161
+ return Number.isFinite(n) ? n : void 0;
2162
+ }
2163
+ return void 0;
2164
+ }
2165
+ function sha256Sync(data) {
2166
+ const buf = typeof data === "string" ? Buffer.from(data, "utf-8") : Buffer.from(new Uint8Array(data));
2167
+ const hash = createHash("sha256").update(buf).digest();
2168
+ return new Uint8Array(hash.buffer, hash.byteOffset, hash.byteLength);
2169
+ }
2170
+
2171
+ // src/transport/stripe-webhook.ts
2172
+ import { createHmac, timingSafeEqual } from "crypto";
2173
+ function verifyStripeWebhook(payload, signatureHeader, secret, options = {}) {
2174
+ if (!signatureHeader) return { ok: false, error: "missing Stripe-Signature header" };
2175
+ if (!secret) return { ok: false, error: "missing webhook secret" };
2176
+ const parsed = parseStripeSignature(signatureHeader);
2177
+ if (!parsed.timestamp) return { ok: false, error: "malformed Stripe-Signature (missing t=)" };
2178
+ if (parsed.v1Signatures.length === 0) {
2179
+ return { ok: false, error: "malformed Stripe-Signature (no v1=)" };
2180
+ }
2181
+ const tolerance = options.toleranceSec ?? 300;
2182
+ const now = options.now ? options.now() : Math.floor(Date.now() / 1e3);
2183
+ if (Math.abs(now - parsed.timestamp) > tolerance) {
2184
+ return {
2185
+ ok: false,
2186
+ timestamp: parsed.timestamp,
2187
+ error: `timestamp outside tolerance (${tolerance}s)`
2188
+ };
2189
+ }
2190
+ const signedPayload = `${parsed.timestamp}.${payload}`;
2191
+ const expected = createHmac("sha256", secret).update(signedPayload).digest();
2192
+ for (const candidateHex of parsed.v1Signatures) {
2193
+ const candidate = hexToBuffer(candidateHex);
2194
+ if (!candidate) continue;
2195
+ if (candidate.length !== expected.length) continue;
2196
+ if (timingSafeEqual(candidate, expected)) {
2197
+ return { ok: true, timestamp: parsed.timestamp };
2198
+ }
2199
+ }
2200
+ return { ok: false, timestamp: parsed.timestamp, error: "signature mismatch" };
2201
+ }
2202
+ function parseStripeSignature(header) {
2203
+ let timestamp = null;
2204
+ const v1Signatures = [];
2205
+ for (const part of header.split(",")) {
2206
+ const [rawKey, rawValue] = part.split("=");
2207
+ if (!rawKey || !rawValue) continue;
2208
+ const key = rawKey.trim();
2209
+ const value = rawValue.trim();
2210
+ if (key === "t") {
2211
+ const n = Number(value);
2212
+ if (Number.isFinite(n)) timestamp = n;
2213
+ } else if (key === "v1") {
2214
+ v1Signatures.push(value);
2215
+ }
2216
+ }
2217
+ return { timestamp, v1Signatures };
2218
+ }
2219
+ function hexToBuffer(hex) {
2220
+ if (!/^[0-9a-fA-F]+$/.test(hex) || hex.length % 2 !== 0) return null;
2221
+ return Buffer.from(hex, "hex");
2222
+ }
2223
+
2224
+ // src/transport/constraint-eval.ts
2225
+ function evaluateVIConstraints(input) {
2226
+ const { constraints, transaction } = input;
2227
+ const results = {};
2228
+ if (constraints.allowedMerchants && constraints.allowedMerchants.length > 0) {
2229
+ results.merchant = evaluateAllowlist(
2230
+ "merchant",
2231
+ constraints.allowedMerchants,
2232
+ transaction.merchant
2233
+ );
2234
+ }
2235
+ if (constraints.allowedPayees && constraints.allowedPayees.length > 0) {
2236
+ results.payee = evaluateAllowlist("payee", constraints.allowedPayees, transaction.payee);
2237
+ }
2238
+ if (constraints.lineItems && constraints.lineItems.length > 0) {
2239
+ results.lineItems = evaluateLineItems(constraints.lineItems, transaction.lineItems ?? []);
2240
+ }
2241
+ if (constraints.paymentAmount) {
2242
+ results.amount = evaluatePaymentAmount(constraints.paymentAmount, transaction);
2243
+ }
2244
+ const reasons = [];
2245
+ let ok = true;
2246
+ for (const [key, r] of Object.entries(results)) {
2247
+ if (!r.ok) {
2248
+ ok = false;
2249
+ reasons.push(r.reason ?? `${key} failed`);
2250
+ }
2251
+ }
2252
+ return { ok, results, reasons };
2253
+ }
2254
+ function evaluatePaymentMethodAllowlist(input) {
2255
+ const allow = input.allowedMethods ?? [];
2256
+ if (allow.length === 0) return { ok: true };
2257
+ if (!input.requestedMethod) {
2258
+ return { ok: false, reason: "no payment method in request; allowlist configured" };
2259
+ }
2260
+ const lowered = input.requestedMethod.toLowerCase();
2261
+ const allowed = allow.some((m) => m.toLowerCase() === lowered);
2262
+ if (!allowed) {
2263
+ return {
2264
+ ok: false,
2265
+ reason: `payment method "${input.requestedMethod}" not in allowlist [${allow.join(", ")}]`
2266
+ };
2267
+ }
2268
+ return { ok: true };
2269
+ }
2270
+ function evaluateSpendingLimit(input) {
2271
+ const { limit, requested } = input;
2272
+ if (!limit || typeof limit.amount !== "number") return { ok: true };
2273
+ if (!requested || typeof requested.amount !== "number") return { ok: true };
2274
+ if (limit.currency && requested.currency && limit.currency !== requested.currency) {
2275
+ return {
2276
+ ok: false,
2277
+ reason: `currency mismatch: limit ${limit.currency} vs requested ${requested.currency}`
2278
+ };
2279
+ }
2280
+ if (requested.amount > limit.amount) {
2281
+ return {
2282
+ ok: false,
2283
+ reason: `requested ${requested.amount} ${requested.currency ?? ""} exceeds limit ${limit.amount} ${limit.currency ?? ""}`.trim()
2284
+ };
2285
+ }
2286
+ return { ok: true };
2287
+ }
2288
+ function evaluateAllowlist(kind, allowlist, actual) {
2289
+ if (!actual || !actual.id && !actual.website) {
2290
+ return { ok: false, reason: `no ${kind} in transaction; allowlist configured` };
2291
+ }
2292
+ for (const entry of allowlist) {
2293
+ if (entry.id && actual.id && entry.id === actual.id) return { ok: true };
2294
+ if (entry.website && actual.website && domainsMatch(entry.website, actual.website)) {
2295
+ return { ok: true };
2296
+ }
2297
+ }
2298
+ const allowedDescriptors = allowlist.map(describeParty).join(", ");
2299
+ const actualDescriptor = describeParty(actual);
2300
+ return {
2301
+ ok: false,
2302
+ reason: `${kind} ${actualDescriptor} not in allowlist [${allowedDescriptors}]`
2303
+ };
2304
+ }
2305
+ function evaluateLineItems(allowlist, actualItems) {
2306
+ if (actualItems.length === 0) {
2307
+ return { ok: false, reason: "no line items in transaction; allowlist configured" };
2308
+ }
2309
+ const reasons = [];
2310
+ for (const item of actualItems) {
2311
+ const match = allowlist.find(
2312
+ (a) => a.id && a.id === item.id || (a.acceptableItems ?? []).includes(item.id ?? "")
2313
+ );
2314
+ if (!match) {
2315
+ reasons.push(`line item "${item.id ?? "(unnamed)"}" not in allowlist`);
2316
+ continue;
2317
+ }
2318
+ if (typeof match.quantity === "number" && typeof item.quantity === "number" && item.quantity > match.quantity) {
2319
+ reasons.push(
2320
+ `line item "${item.id}" quantity ${item.quantity} exceeds allowed ${match.quantity}`
2321
+ );
2322
+ }
2323
+ }
2324
+ return reasons.length === 0 ? { ok: true } : { ok: false, reason: reasons.join("; ") };
2325
+ }
2326
+ function evaluatePaymentAmount(bound, transaction) {
2327
+ if (typeof transaction.amount !== "number") {
2328
+ return { ok: false, reason: "no amount in transaction; paymentAmount bound configured" };
2329
+ }
2330
+ if (bound.currency && transaction.currency && bound.currency !== transaction.currency) {
2331
+ return {
2332
+ ok: false,
2333
+ reason: `currency mismatch: bound ${bound.currency} vs transaction ${transaction.currency}`
2334
+ };
2335
+ }
2336
+ if (typeof bound.min === "number" && transaction.amount < bound.min) {
2337
+ return {
2338
+ ok: false,
2339
+ reason: `amount ${transaction.amount} below min ${bound.min}`
2340
+ };
2341
+ }
2342
+ if (typeof bound.max === "number" && transaction.amount > bound.max) {
2343
+ return {
2344
+ ok: false,
2345
+ reason: `amount ${transaction.amount} above max ${bound.max}`
2346
+ };
2347
+ }
2348
+ return { ok: true };
2349
+ }
2350
+ function domainsMatch(allow, actual) {
2351
+ const a = normalizeDomain(allow);
2352
+ const b = normalizeDomain(actual);
2353
+ return a === b || b.endsWith(`.${a}`);
2354
+ }
2355
+ function normalizeDomain(value) {
2356
+ try {
2357
+ const withScheme = /^https?:\/\//.test(value) ? value : `https://${value}`;
2358
+ return new URL(withScheme).hostname.toLowerCase();
2359
+ } catch {
2360
+ return value.toLowerCase();
2361
+ }
2362
+ }
2363
+ function describeParty(party) {
2364
+ if (party.id) return `id:${party.id}`;
2365
+ if (party.website) return party.website;
2366
+ if (party.name) return party.name;
2367
+ return "(unnamed)";
2368
+ }
2369
+
2370
+ // src/transport/identity-binding.ts
2371
+ async function bindIdentity(claims, resolver) {
2372
+ const resolutions = [];
2373
+ for (const claim2 of claims) {
2374
+ if (!claim2.value) {
2375
+ resolutions.push({ claim: claim2, agentId: null });
2376
+ continue;
2377
+ }
2378
+ const agentId = await resolver(claim2);
2379
+ resolutions.push({ claim: claim2, agentId });
2380
+ }
2381
+ const resolvedIds = resolutions.map((r) => r.agentId).filter((id) => typeof id === "string" && id.length > 0);
2382
+ const unique = Array.from(new Set(resolvedIds));
2383
+ const mismatchAcrossLayers = unique.length > 1;
2384
+ const mappedAstraSyncAgentId = unique.length === 1 ? unique[0] : void 0;
2385
+ return {
2386
+ claims,
2387
+ mappedAstraSyncAgentId,
2388
+ mismatchAcrossLayers,
2389
+ resolutions
2390
+ };
2391
+ }
2392
+ var claim = {
2393
+ viKid: (value) => ({ protocol: "vi", field: "kid", value }),
2394
+ ap2AgentId: (value) => ({ protocol: "ap2", field: "agent_id", value }),
2395
+ acpBearer: (value) => ({ protocol: "acp", field: "bearer", value }),
2396
+ mppSource: (value) => ({ protocol: "mpp", field: "source", value }),
2397
+ x402Wallet: (value) => ({ protocol: "x402", field: "wallet", value }),
2398
+ agentPayKid: (value) => ({ protocol: "agentpay", field: "kid", value }),
2399
+ tapKid: (value) => ({ protocol: "tap", field: "kid", value }),
2400
+ webBotAuthKid: (value) => ({
2401
+ protocol: "webbotauth",
2402
+ field: "kid",
2403
+ value
2404
+ })
2405
+ };
2406
+
2407
+ // src/transport/ap2.ts
2408
+ import { decodeSdJwtSync as decodeSdJwtSync2 } from "@sd-jwt/decode";
2409
+ import { createHash as createHash2 } from "crypto";
2410
+ function extractAP2Mandate(sdJwtCompact) {
2411
+ if (!sdJwtCompact || typeof sdJwtCompact !== "string") return null;
2412
+ let decoded;
2413
+ try {
2414
+ decoded = decodeSdJwtSync2(sdJwtCompact, sha256Sync2);
2415
+ } catch {
2416
+ return null;
2417
+ }
2418
+ const payload = decoded.jwt?.payload ?? {};
2419
+ const disclosures = decoded.disclosures ?? [];
2420
+ const claims = applyDisclosures2(
2421
+ payload,
2422
+ disclosures
2423
+ );
2424
+ const type = coerceMandateType2(claims.type ?? claims.mandate_type ?? claims.mandateType);
2425
+ if (!type) return null;
2426
+ if (type === "intent_mandate") return buildIntent(claims);
2427
+ if (type === "cart_mandate") return buildCart(claims);
2428
+ return buildPayment(claims);
2429
+ }
2430
+ function extractAP2Mandates(input) {
2431
+ const intent = input.intent ? extractAP2Mandate(input.intent) : null;
2432
+ const cart = input.cart ? extractAP2Mandate(input.cart) : null;
2433
+ const payment = input.payment ? extractAP2Mandate(input.payment) : null;
2434
+ return {
2435
+ intent: intent ?? void 0,
2436
+ cart: cart ?? void 0,
2437
+ payment: payment ?? void 0,
2438
+ rawLayers: {
2439
+ intentJwt: input.intent,
2440
+ cartJwt: input.cart,
2441
+ paymentJwt: input.payment
2442
+ }
2443
+ };
2444
+ }
2445
+ function buildIntent(claims) {
2446
+ return {
2447
+ type: "intent_mandate",
2448
+ agent_id: coerceString5(claims.agent_id ?? claims.agentId),
2449
+ user_id: coerceString5(claims.user_id ?? claims.userId ?? claims.sub),
2450
+ merchant_category: coerceString5(claims.merchant_category ?? claims.merchantCategory),
2451
+ allowedMerchantDomains: toStringArray(
2452
+ claims.allowed_merchant_domains ?? claims.allowedMerchantDomains
2453
+ ),
2454
+ paymentMethods: toStringArray(claims.payment_methods ?? claims.paymentMethods),
2455
+ expires: coerceString5(claims.expires ?? claims.exp),
2456
+ payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
2457
+ raw: claims
2458
+ };
2459
+ }
2460
+ function buildCart(claims) {
2461
+ return {
2462
+ type: "cart_mandate",
2463
+ agent_id: coerceString5(claims.agent_id ?? claims.agentId),
2464
+ intent_mandate_id: coerceString5(claims.intent_mandate_id ?? claims.intentMandateId),
2465
+ merchant_id: coerceString5(claims.merchant_id ?? claims.merchantId),
2466
+ line_items: toLineItems(claims.line_items ?? claims.lineItems),
2467
+ payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
2468
+ expires: coerceString5(claims.expires ?? claims.exp),
2469
+ raw: claims
2470
+ };
2471
+ }
2472
+ function buildPayment(claims) {
2473
+ return {
2474
+ type: "payment_mandate",
2475
+ agent_id: coerceString5(claims.agent_id ?? claims.agentId),
2476
+ cart_mandate_id: coerceString5(claims.cart_mandate_id ?? claims.cartMandateId),
2477
+ payment_method: coerceString5(claims.payment_method ?? claims.paymentMethod),
2478
+ payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
2479
+ credential_provider: coerceString5(claims.credential_provider ?? claims.credentialProvider),
2480
+ raw: claims
2481
+ };
2482
+ }
2483
+ function toPaymentDetails(v) {
2484
+ if (!v || typeof v !== "object") return void 0;
2485
+ const r = v;
2486
+ const amount = r.amount;
2487
+ return {
2488
+ amount: amount ? {
2489
+ value: coerceStringOrNumber(amount.value),
2490
+ currency: coerceString5(amount.currency)
2491
+ } : void 0,
2492
+ label: coerceString5(r.label)
2493
+ };
2494
+ }
2495
+ function toLineItems(v) {
2496
+ if (!Array.isArray(v)) return void 0;
2497
+ const items = [];
2498
+ for (const item of v) {
2499
+ if (!item || typeof item !== "object") continue;
2500
+ const r = item;
2501
+ const price = r.price;
2502
+ items.push({
2503
+ id: coerceString5(r.id),
2504
+ quantity: coerceNumber3(r.quantity),
2505
+ price: price ? {
2506
+ value: coerceStringOrNumber(price.value),
2507
+ currency: coerceString5(price.currency)
2508
+ } : void 0
2509
+ });
2510
+ }
2511
+ return items.length > 0 ? items : void 0;
2512
+ }
2513
+ function toStringArray(v) {
2514
+ if (!Array.isArray(v)) return void 0;
2515
+ const out = v.filter((i) => typeof i === "string" && i.length > 0);
2516
+ return out.length > 0 ? out : void 0;
2517
+ }
2518
+ function applyDisclosures2(payload, disclosures) {
2519
+ const result = { ...payload };
2520
+ for (const d of disclosures) {
2521
+ if (d.key && d.value !== void 0 && !(d.key in result)) {
2522
+ result[d.key] = d.value;
2523
+ }
2524
+ }
2525
+ return result;
2526
+ }
2527
+ function coerceMandateType2(v) {
2528
+ if (v === "intent_mandate" || v === "cart_mandate" || v === "payment_mandate") return v;
2529
+ return null;
2530
+ }
2531
+ function coerceString5(v) {
2532
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2533
+ }
2534
+ function coerceNumber3(v) {
2535
+ if (typeof v === "number" && Number.isFinite(v)) return v;
2536
+ if (typeof v === "string") {
2537
+ const n = Number(v);
2538
+ return Number.isFinite(n) ? n : void 0;
2539
+ }
2540
+ return void 0;
2541
+ }
2542
+ function coerceStringOrNumber(v) {
2543
+ if (typeof v === "number" && Number.isFinite(v)) return v;
2544
+ if (typeof v === "string" && v.length > 0) return v;
2545
+ return void 0;
2546
+ }
2547
+ function sha256Sync2(data) {
2548
+ const buf = typeof data === "string" ? Buffer.from(data, "utf-8") : Buffer.from(new Uint8Array(data));
2549
+ const hash = createHash2("sha256").update(buf).digest();
2550
+ return new Uint8Array(hash.buffer, hash.byteOffset, hash.byteLength);
2551
+ }
2552
+
2553
+ // src/transport/ap2-verify.ts
2554
+ function verifyAP2Chain(input) {
2555
+ const { triple } = input;
2556
+ const errors = [];
2557
+ const intentPresent = triple.intent !== void 0;
2558
+ const cartRefOk = checkCartRef(triple, errors);
2559
+ const paymentRefOk = checkPaymentRef(triple, errors);
2560
+ const { ok: agentIdContinuity, agentId } = checkAgentContinuity(triple, errors);
2561
+ const paymentMethodAllowed = checkPaymentMethod(triple, errors);
2562
+ const totalsConsistent = checkTotals(triple, errors);
2563
+ const expiryOk = checkExpiries(triple, input.clockSkewSec ?? 300, input.now, errors);
2564
+ const ok = cartRefOk && paymentRefOk && agentIdContinuity && paymentMethodAllowed && totalsConsistent && expiryOk;
2565
+ return {
2566
+ ok,
2567
+ checks: {
2568
+ intentPresent,
2569
+ cartRefOk,
2570
+ paymentRefOk,
2571
+ agentIdContinuity,
2572
+ paymentMethodAllowed,
2573
+ totalsConsistent,
2574
+ expiryOk
2575
+ },
2576
+ agentId,
2577
+ errors
2578
+ };
2579
+ }
2580
+ function checkCartRef(triple, errors) {
2581
+ const cart = triple.cart;
2582
+ if (!cart) return true;
2583
+ if (!cart.intent_mandate_id) return true;
2584
+ const intentId = triple.intent?.raw?.id;
2585
+ if (intentId && cart.intent_mandate_id !== intentId) {
2586
+ errors.push(
2587
+ `cart.intent_mandate_id (${cart.intent_mandate_id}) does not match intent.id (${intentId})`
2588
+ );
2589
+ return false;
2590
+ }
2591
+ return true;
2592
+ }
2593
+ function checkPaymentRef(triple, errors) {
2594
+ const payment = triple.payment;
2595
+ if (!payment) return true;
2596
+ if (!payment.cart_mandate_id) return true;
2597
+ const cartId = triple.cart?.raw?.id;
2598
+ if (cartId && payment.cart_mandate_id !== cartId) {
2599
+ errors.push(
2600
+ `payment.cart_mandate_id (${payment.cart_mandate_id}) does not match cart.id (${cartId})`
2601
+ );
2602
+ return false;
2603
+ }
2604
+ return true;
2605
+ }
2606
+ function checkAgentContinuity(triple, errors) {
2607
+ const ids = [triple.intent?.agent_id, triple.cart?.agent_id, triple.payment?.agent_id].filter(
2608
+ (id) => typeof id === "string" && id.length > 0
2609
+ );
2610
+ if (ids.length === 0) return { ok: true };
2611
+ const unique = new Set(ids);
2612
+ if (unique.size > 1) {
2613
+ errors.push(`agent_id mismatch across mandates: ${Array.from(unique).join(", ")}`);
2614
+ return { ok: false, agentId: void 0 };
2615
+ }
2616
+ return { ok: true, agentId: ids[0] };
2617
+ }
2618
+ function checkPaymentMethod(triple, errors) {
2619
+ const paymentMethod = triple.payment?.payment_method;
2620
+ const allowed = triple.intent?.paymentMethods;
2621
+ if (!paymentMethod || !allowed || allowed.length === 0) return true;
2622
+ if (!allowed.includes(paymentMethod)) {
2623
+ errors.push(
2624
+ `payment_method "${paymentMethod}" not in intent.paymentMethods [${allowed.join(", ")}]`
2625
+ );
2626
+ return false;
2627
+ }
2628
+ return true;
2629
+ }
2630
+ function checkTotals(triple, errors) {
2631
+ const intentTotal = toNumericAmount(triple.intent?.payment_details_total);
2632
+ const cartTotal = toNumericAmount(triple.cart?.payment_details_total);
2633
+ const paymentTotal = toNumericAmount(triple.payment?.payment_details_total);
2634
+ if (intentTotal && cartTotal && intentTotal.currency === cartTotal.currency) {
2635
+ if (cartTotal.value > intentTotal.value) {
2636
+ errors.push(
2637
+ `cart total ${cartTotal.value} ${cartTotal.currency} exceeds intent cap ${intentTotal.value}`
2638
+ );
2639
+ return false;
2640
+ }
2641
+ }
2642
+ if (cartTotal && paymentTotal && cartTotal.currency === paymentTotal.currency) {
2643
+ if (paymentTotal.value > cartTotal.value) {
2644
+ errors.push(
2645
+ `payment total ${paymentTotal.value} ${paymentTotal.currency} exceeds cart total ${cartTotal.value}`
2646
+ );
2647
+ return false;
2648
+ }
2649
+ }
2650
+ return true;
2651
+ }
2652
+ function checkExpiries(triple, toleranceSec, nowFn, errors) {
2653
+ const now = nowFn ? nowFn() : Math.floor(Date.now() / 1e3);
2654
+ let ok = true;
2655
+ for (const [name, mandate] of [
2656
+ ["intent", triple.intent],
2657
+ ["cart", triple.cart]
2658
+ ]) {
2659
+ if (!mandate?.expires) continue;
2660
+ const parsed = parseExpiry(mandate.expires);
2661
+ if (parsed === null) {
2662
+ errors.push(`${name}.expires unparseable`);
2663
+ ok = false;
2664
+ continue;
2665
+ }
2666
+ if (now > parsed + toleranceSec) {
2667
+ errors.push(`${name} mandate expired at ${mandate.expires}`);
2668
+ ok = false;
2669
+ }
2670
+ }
2671
+ return ok;
2672
+ }
2673
+ function toNumericAmount(total) {
2674
+ if (!total?.amount?.value || !total.amount.currency) return null;
2675
+ const n = typeof total.amount.value === "string" ? Number(total.amount.value) : total.amount.value;
2676
+ if (!Number.isFinite(n)) return null;
2677
+ return { value: n, currency: total.amount.currency };
2678
+ }
2679
+ function parseExpiry(value) {
2680
+ const asInt = Number(value);
2681
+ if (Number.isFinite(asInt) && asInt > 0) {
2682
+ return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
2683
+ }
2684
+ const parsedDate = Date.parse(value);
2685
+ if (Number.isFinite(parsedDate)) return Math.floor(parsedDate / 1e3);
2686
+ return null;
2687
+ }
2688
+
2689
+ // src/transport/acp-verify.ts
2690
+ async function verifyACPSignature(input) {
2691
+ if (!input.signatureHeader) {
2692
+ return { ok: false, error: "missing Signature header" };
2693
+ }
2694
+ const freshness = checkTimestamp(input.timestampHeader, input.clockSkewSec ?? 300, input.now);
2695
+ if (!freshness.ok) {
2696
+ return { ok: false, error: freshness.error, timestampStale: true };
2697
+ }
2698
+ const signatureBytes = decodeBase64(input.signatureHeader);
2699
+ if (!signatureBytes) {
2700
+ return { ok: false, error: "signature header is not valid base64" };
2701
+ }
2702
+ const bodyBytes = new TextEncoder().encode(input.rawBody);
2703
+ const { subtle } = await getSubtle();
2704
+ for (const candidate of input.candidateKeys) {
2705
+ const declaredAlg = normalizeAlgorithm(candidate.alg);
2706
+ const algsToTry = declaredAlg && declaredAlg !== "unsupported" ? [declaredAlg] : ["ed25519", "es256"];
2707
+ for (const alg of algsToTry) {
2708
+ try {
2709
+ const verified = await tryVerify(subtle, candidate.jwk, signatureBytes, bodyBytes, alg);
2710
+ if (verified) return { ok: true, algorithm: alg };
2711
+ } catch {
2712
+ }
2713
+ }
2714
+ }
2715
+ return {
2716
+ ok: false,
2717
+ algorithm: "unsupported",
2718
+ error: "no candidate key verified the signature under Ed25519 or ES256"
2719
+ };
2720
+ }
2721
+ async function tryVerify(subtle, jwk, signature, body, alg) {
2722
+ if (alg === "ed25519") {
2723
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519") return false;
2724
+ const key = await subtle.importKey("jwk", jwk, { name: "Ed25519" }, false, [
2725
+ "verify"
2726
+ ]);
2727
+ return await subtle.verify({ name: "Ed25519" }, key, toBuf(signature), toBuf(body));
2728
+ }
2729
+ if (alg === "es256") {
2730
+ if (jwk.kty !== "EC" || jwk.crv !== "P-256") return false;
2731
+ const key = await subtle.importKey(
2732
+ "jwk",
2733
+ jwk,
2734
+ { name: "ECDSA", namedCurve: "P-256" },
2735
+ false,
2736
+ ["verify"]
2737
+ );
2738
+ return await subtle.verify(
2739
+ { name: "ECDSA", hash: "SHA-256" },
2740
+ key,
2741
+ toBuf(signature),
2742
+ toBuf(body)
2743
+ );
2744
+ }
2745
+ return false;
2746
+ }
2747
+ function toBuf(bytes) {
2748
+ const out = new ArrayBuffer(bytes.byteLength);
2749
+ new Uint8Array(out).set(bytes);
2750
+ return out;
2751
+ }
2752
+ function checkTimestamp(headerValue, toleranceSec, nowFn) {
2753
+ if (!headerValue) return { ok: false, error: "missing Timestamp header" };
2754
+ const ts = parseTimestamp(headerValue);
2755
+ if (ts === null) return { ok: false, error: "unparseable Timestamp header" };
2756
+ const now = nowFn ? nowFn() : Math.floor(Date.now() / 1e3);
2757
+ if (Math.abs(now - ts) > toleranceSec) {
2758
+ return { ok: false, error: `timestamp outside ${toleranceSec}s tolerance` };
2759
+ }
2760
+ return { ok: true };
2761
+ }
2762
+ function parseTimestamp(value) {
2763
+ const asInt = Number(value);
2764
+ if (Number.isFinite(asInt) && asInt > 0) {
2765
+ return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
2766
+ }
2767
+ const parsedDate = Date.parse(value);
2768
+ if (Number.isFinite(parsedDate)) return Math.floor(parsedDate / 1e3);
2769
+ return null;
2770
+ }
2771
+ function normalizeAlgorithm(alg) {
2772
+ if (!alg) return void 0;
2773
+ const lowered = alg.toLowerCase();
2774
+ if (lowered === "ed25519" || lowered === "eddsa") return "ed25519";
2775
+ if (lowered === "es256" || lowered.startsWith("ecdsa-p256")) return "es256";
2776
+ return "unsupported";
2777
+ }
2778
+ function decodeBase64(value) {
2779
+ try {
2780
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
2781
+ const pad = normalized.length % 4 === 0 ? "" : "=".repeat(4 - normalized.length % 4);
2782
+ return new Uint8Array(Buffer.from(normalized + pad, "base64"));
2783
+ } catch {
2784
+ return null;
2785
+ }
2786
+ }
2787
+ async function getSubtle() {
2788
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
2789
+ return { subtle: globalThis.crypto.subtle };
2790
+ }
2791
+ const nodeCrypto = await import("crypto");
2792
+ return { subtle: nodeCrypto.webcrypto.subtle };
2793
+ }
2794
+
2795
+ // src/transport/mpp.ts
2796
+ import { Challenge, Credential, Receipt } from "mppx";
2797
+ function extractMPPFromRequest(request) {
2798
+ const auth = readHeader3(request.headers, "authorization");
2799
+ if (!auth || !/^\s*Payment\s+/i.test(auth)) return null;
2800
+ try {
2801
+ const credential = Credential.deserialize(auth);
2802
+ return {
2803
+ kind: "credential",
2804
+ credential: {
2805
+ challenge: summarizeChallenge(credential.challenge),
2806
+ source: credential.source,
2807
+ payload: credential.payload
2808
+ },
2809
+ rawBody: request.rawBody
2810
+ };
2811
+ } catch {
2812
+ return { kind: "error", error: { type: "invalid-credential-encoding" } };
2813
+ }
2814
+ }
2815
+ function extractMPPFromResponse(response) {
2816
+ if (response.status === 402) {
2817
+ const challenges = collectChallenges(response);
2818
+ if (challenges.length === 0) return null;
2819
+ const methods = Array.from(new Set(challenges.map((c) => c.method)));
2820
+ return {
2821
+ kind: "challenge",
2822
+ challenges,
2823
+ offeredMethods: methods
2824
+ };
2825
+ }
2826
+ const receiptHeader = readHeader3(response.headers, "payment-receipt");
2827
+ if (receiptHeader) {
2828
+ try {
2829
+ const parsed = Receipt.deserialize(receiptHeader);
2830
+ const r = parsed;
2831
+ return {
2832
+ kind: "receipt",
2833
+ receipt: {
2834
+ method: coerceString6(r.method),
2835
+ reference: coerceString6(r.reference),
2836
+ externalId: coerceString6(r.externalId ?? r.external_id),
2837
+ status: coerceString6(r.status),
2838
+ timestamp: coerceString6(r.timestamp),
2839
+ raw: r
2840
+ }
2841
+ };
2842
+ } catch {
2843
+ return { kind: "error", error: { type: "invalid-receipt-encoding" } };
2844
+ }
2845
+ }
2846
+ const contentType = readHeader3(response.headers, "content-type");
2847
+ if (contentType && /application\/problem\+json/i.test(contentType)) {
2848
+ const body = typeof response.body === "object" && response.body !== null ? response.body : {};
2849
+ return {
2850
+ kind: "error",
2851
+ error: {
2852
+ type: coerceString6(body.type),
2853
+ title: coerceString6(body.title),
2854
+ detail: coerceString6(body.detail)
2855
+ }
2856
+ };
2857
+ }
2858
+ return null;
2859
+ }
2860
+ function extractMPPContext(message) {
2861
+ if ("request" in message) return extractMPPFromRequest(message.request);
2862
+ if ("response" in message) return extractMPPFromResponse(message.response);
2863
+ if (typeof message.status === "number") {
2864
+ return extractMPPFromResponse(message);
2865
+ }
2866
+ return extractMPPFromRequest(message);
2867
+ }
2868
+ function collectChallenges(response) {
2869
+ const wwwAuth = readHeader3(response.headers, "www-authenticate");
2870
+ if (!wwwAuth) return [];
2871
+ const headers = new Headers();
2872
+ headers.set("www-authenticate", wwwAuth);
2873
+ const out = [];
2874
+ try {
2875
+ const list = Challenge.fromHeadersList(headers);
2876
+ for (const ch of list) {
2877
+ out.push(summarizeChallenge(ch));
2878
+ }
2879
+ } catch {
2880
+ }
2881
+ return out;
2882
+ }
2883
+ function summarizeChallenge(ch) {
2884
+ const raw = ch;
2885
+ return {
2886
+ id: coerceString6(raw.id) ?? "",
2887
+ realm: coerceString6(raw.realm) ?? "",
2888
+ method: coerceString6(raw.method) ?? "",
2889
+ intent: coerceString6(raw.intent) ?? "",
2890
+ request: raw.request ?? {},
2891
+ expires: coerceString6(raw.expires),
2892
+ digest: coerceString6(raw.digest),
2893
+ description: coerceString6(raw.description),
2894
+ opaque: raw.opaque
2895
+ };
2896
+ }
2897
+ function readHeader3(headers, name) {
2898
+ for (const key of Object.keys(headers)) {
2899
+ if (key.toLowerCase() === name) {
2900
+ const raw = headers[key];
2901
+ if (typeof raw === "string") return raw;
2902
+ if (Array.isArray(raw)) return raw.join(", ");
2903
+ }
2904
+ }
2905
+ return void 0;
2906
+ }
2907
+ function coerceString6(v) {
2908
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2909
+ }
2910
+
2911
+ // src/transport/mpp-verify.ts
2912
+ import { BodyDigest } from "mppx";
2913
+ function verifyMPP(input) {
2914
+ const { context } = input;
2915
+ const tolerance = input.clockSkewSec ?? 300;
2916
+ const nowSec = input.now ? input.now() : Math.floor(Date.now() / 1e3);
2917
+ const challenge = context.credential?.challenge ?? (context.challenges && context.challenges[0]);
2918
+ const source = context.credential?.source;
2919
+ const method = challenge?.method;
2920
+ let expiryOk = true;
2921
+ if (challenge?.expires) {
2922
+ const parsedExpiry = Date.parse(challenge.expires);
2923
+ if (!Number.isFinite(parsedExpiry)) {
2924
+ return {
2925
+ ok: false,
2926
+ expiryOk: false,
2927
+ bodyDigestOk: null,
2928
+ source,
2929
+ method,
2930
+ error: "unparseable challenge.expires"
2931
+ };
2932
+ }
2933
+ const expiresSec = Math.floor(parsedExpiry / 1e3);
2934
+ if (nowSec > expiresSec + tolerance) {
2935
+ expiryOk = false;
2936
+ }
2937
+ }
2938
+ let bodyDigestOk = null;
2939
+ if (challenge?.digest && input.rawBody !== void 0) {
2940
+ try {
2941
+ if (!/^sha-256=/.test(challenge.digest)) {
2942
+ bodyDigestOk = false;
2943
+ } else {
2944
+ bodyDigestOk = BodyDigest.verify(challenge.digest, input.rawBody);
2945
+ }
2946
+ } catch {
2947
+ bodyDigestOk = false;
2948
+ }
2949
+ }
2950
+ const ok = expiryOk && (bodyDigestOk === null || bodyDigestOk === true);
2951
+ const errors = [];
2952
+ if (!expiryOk) errors.push("challenge expired");
2953
+ if (bodyDigestOk === false) errors.push("body digest mismatch");
2954
+ return {
2955
+ ok,
2956
+ expiryOk,
2957
+ bodyDigestOk,
2958
+ source,
2959
+ method,
2960
+ error: errors.length > 0 ? errors.join("; ") : void 0
2961
+ };
2962
+ }
2963
+
2964
+ // src/transport/x402.ts
2965
+ import {
2966
+ validatePaymentRequired,
2967
+ validatePaymentPayload
2968
+ } from "@x402/core/schemas";
2969
+ import { safeBase64Decode } from "@x402/core/utils";
2970
+ function extractX402FromRequest(request) {
2971
+ const headerValue = readHeader4(request.headers, "x-payment");
2972
+ if (request.body && typeof request.body === "object") {
2973
+ const parsed = tryParsePayload(request.body);
2974
+ if (parsed) return buildPayloadContext(parsed, "body");
2975
+ }
2976
+ if (headerValue) {
2977
+ try {
2978
+ const decoded = safeBase64Decode(headerValue);
2979
+ if (decoded) {
2980
+ const json = JSON.parse(decoded);
2981
+ const parsed = tryParsePayload(json);
2982
+ if (parsed) return buildPayloadContext(parsed, "header");
2983
+ }
2984
+ } catch {
2985
+ return {
2986
+ kind: "error",
2987
+ version: 1,
2988
+ source: "header",
2989
+ error: { type: "invalid-x402-payload" }
2990
+ };
2991
+ }
2992
+ }
2993
+ return null;
2994
+ }
2995
+ function extractX402FromResponse(response) {
2996
+ if (response.status !== 402) return null;
2997
+ if (response.body && typeof response.body === "object") {
2998
+ const parsed = tryParseRequired(response.body);
2999
+ if (parsed) return buildRequiredContext(parsed, "body");
3000
+ }
3001
+ const headerValue = readHeader4(response.headers, "x-payment-required");
3002
+ if (headerValue) {
3003
+ try {
3004
+ const decoded = safeBase64Decode(headerValue);
3005
+ if (decoded) {
3006
+ const json = JSON.parse(decoded);
3007
+ const parsed = tryParseRequired(json);
3008
+ if (parsed) return buildRequiredContext(parsed, "header");
3009
+ }
3010
+ } catch {
3011
+ return {
3012
+ kind: "error",
3013
+ version: 1,
3014
+ source: "header",
3015
+ error: { type: "invalid-x402-required" }
3016
+ };
3017
+ }
3018
+ }
3019
+ return null;
3020
+ }
3021
+ function extractX402Context(message) {
3022
+ if ("request" in message) return extractX402FromRequest(message.request);
3023
+ if ("response" in message) return extractX402FromResponse(message.response);
3024
+ if (typeof message.status === "number") {
3025
+ return extractX402FromResponse(message);
3026
+ }
3027
+ return extractX402FromRequest(message);
3028
+ }
3029
+ function tryParseRequired(data) {
3030
+ try {
3031
+ return validatePaymentRequired(data);
3032
+ } catch {
3033
+ return null;
3034
+ }
3035
+ }
3036
+ function tryParsePayload(data) {
3037
+ try {
3038
+ return validatePaymentPayload(data);
3039
+ } catch {
3040
+ return null;
3041
+ }
3042
+ }
3043
+ function buildRequiredContext(parsed, source) {
3044
+ const asRecord = parsed;
3045
+ const version = coerceVersion(asRecord.x402Version);
3046
+ const accepts = asRecord.accepts ?? [];
3047
+ return {
3048
+ kind: "required",
3049
+ version,
3050
+ source,
3051
+ paymentRequired: {
3052
+ resource: resolveResource(asRecord.resource),
3053
+ accepts: accepts.map(summarizeRequirement),
3054
+ extensions: asRecord.extensions,
3055
+ error: typeof asRecord.error === "string" ? asRecord.error : void 0
3056
+ }
3057
+ };
3058
+ }
3059
+ function buildPayloadContext(parsed, source) {
3060
+ const asRecord = parsed;
3061
+ const version = coerceVersion(asRecord.x402Version);
3062
+ const accepted = asRecord.accepted;
3063
+ const payload = asRecord.payload ?? {};
3064
+ return {
3065
+ kind: "payload",
3066
+ version,
3067
+ source,
3068
+ paymentPayload: {
3069
+ scheme: accepted?.scheme ?? (typeof asRecord.scheme === "string" ? asRecord.scheme : ""),
3070
+ network: accepted?.network ?? (typeof asRecord.network === "string" ? asRecord.network : ""),
3071
+ payload,
3072
+ extensions: asRecord.extensions
3073
+ }
3074
+ };
3075
+ }
3076
+ function summarizeRequirement(req) {
3077
+ const r = req;
3078
+ const amount = r.amount ?? r.maxAmountRequired ?? "0";
3079
+ return {
3080
+ scheme: r.scheme ?? "",
3081
+ network: r.network ?? "",
3082
+ asset: r.asset ?? "",
3083
+ amount: String(amount),
3084
+ payTo: r.payTo ?? "",
3085
+ maxTimeoutSeconds: typeof r.maxTimeoutSeconds === "number" ? r.maxTimeoutSeconds : void 0,
3086
+ resource: typeof r.resource === "string" ? r.resource : void 0,
3087
+ description: typeof r.description === "string" ? r.description : void 0
3088
+ };
3089
+ }
3090
+ function resolveResource(v) {
3091
+ if (typeof v === "string") return v;
3092
+ if (v && typeof v === "object" && "url" in v && typeof v.url === "string") {
3093
+ return v.url;
3094
+ }
3095
+ return "";
3096
+ }
3097
+ function coerceVersion(v) {
3098
+ if (v === 1 || v === 2) return v;
3099
+ return null;
3100
+ }
3101
+ function readHeader4(headers, name) {
3102
+ if (!headers) return void 0;
3103
+ for (const key of Object.keys(headers)) {
3104
+ if (key.toLowerCase() === name) {
3105
+ const raw = headers[key];
3106
+ if (typeof raw === "string") return raw;
3107
+ if (Array.isArray(raw)) return raw[0];
3108
+ }
3109
+ }
3110
+ return void 0;
3111
+ }
3112
+
3113
+ // src/transport/vi-verify.ts
3114
+ import { createHash as createHash3, webcrypto } from "crypto";
3115
+ async function verifyVIChain(input) {
3116
+ const errors = [];
3117
+ const tolerance = input.clockSkewSec ?? 300;
3118
+ const now = input.now ? input.now() : Math.floor(Date.now() / 1e3);
3119
+ const { l1, l2, l3a, l3b } = input.layers;
3120
+ const l1SigOk = l1 ? await input.verifySignature(l1, null) : null;
3121
+ if (l1 && !l1SigOk) errors.push("L1 signature invalid");
3122
+ const l1Cnf = extractCnfJwk(l1?.payload);
3123
+ const l2SigOk = await input.verifySignature(l2, l1Cnf ?? null);
3124
+ if (!l2SigOk) errors.push("L2 signature invalid");
3125
+ const l2Cnf = extractCnfJwk(l2.payload);
3126
+ const l3aSigOk = l3a ? await input.verifySignature(l3a, l2Cnf ?? null) : null;
3127
+ if (l3a && !l3aSigOk) errors.push("L3a signature invalid");
3128
+ const l3bSigOk = l3b ? await input.verifySignature(l3b, l2Cnf ?? null) : null;
3129
+ if (l3b && !l3bSigOk) errors.push("L3b signature invalid");
3130
+ let l1BindsL2 = true;
3131
+ if (l1Cnf) {
3132
+ const l2KeyFromHeader = await jwkForLayer(l2);
3133
+ l1BindsL2 = l2KeyFromHeader ? await thumbprintsMatch(l1Cnf, l2KeyFromHeader) : false;
3134
+ if (!l1BindsL2) errors.push("L1.cnf.jwk does not bind L2 signing key");
3135
+ }
3136
+ let l2BindsL3 = true;
3137
+ if (l2Cnf && (l3a || l3b)) {
3138
+ const l3Layer = l3a ?? l3b;
3139
+ const l3KeyFromHeader = await jwkForLayer(l3Layer);
3140
+ l2BindsL3 = l3KeyFromHeader ? await thumbprintsMatch(l2Cnf, l3KeyFromHeader) : false;
3141
+ if (!l2BindsL3) errors.push("L2.cnf.jwk does not bind L3 signing key");
3142
+ }
3143
+ let l3aL3bTxnIdMatch = null;
3144
+ if (l3a && l3b) {
3145
+ const a = coerceString7(l3a.payload.transaction_id ?? l3a.payload.transactionId);
3146
+ const b = coerceString7(l3b.payload.transaction_id ?? l3b.payload.transactionId);
3147
+ if (a && b) {
3148
+ l3aL3bTxnIdMatch = a === b;
3149
+ if (!l3aL3bTxnIdMatch) {
3150
+ errors.push(`L3a.transaction_id (${a}) does not match L3b.transaction_id (${b})`);
3151
+ }
3152
+ }
3153
+ }
3154
+ let checkoutHashOk = null;
3155
+ if (l3b) {
3156
+ const declaredHash = coerceString7(
3157
+ l3b.payload.checkout_hash ?? l3b.payload.conditional_transaction_id ?? l3b.payload.payment_reference?.checkout_hash
3158
+ );
3159
+ if (declaredHash) {
3160
+ const computed = computeCheckoutHashFromL2(l2);
3161
+ checkoutHashOk = computed ? declaredHash === computed : false;
3162
+ if (!checkoutHashOk) {
3163
+ errors.push("L3b.checkout_hash does not match SHA-256 of L2 checkout disclosure");
3164
+ }
3165
+ }
3166
+ }
3167
+ const expiryOk = checkExpiryAcross([l1, l2, l3a, l3b], tolerance, now, errors);
3168
+ const ok = l1SigOk !== false && l2SigOk && l3aSigOk !== false && l3bSigOk !== false && l1BindsL2 && l2BindsL3 && l3aL3bTxnIdMatch !== false && checkoutHashOk !== false && expiryOk;
3169
+ return {
3170
+ ok,
3171
+ checks: {
3172
+ l1SigOk,
3173
+ l2SigOk,
3174
+ l3aSigOk,
3175
+ l3bSigOk,
3176
+ l1BindsL2,
3177
+ l2BindsL3,
3178
+ l3aL3bTxnIdMatch,
3179
+ checkoutHashOk,
3180
+ expiryOk
3181
+ },
3182
+ errors
3183
+ };
3184
+ }
3185
+ function extractCnfJwk(payload) {
3186
+ if (!payload) return null;
3187
+ const cnf = payload.cnf;
3188
+ if (!cnf) return null;
3189
+ const jwk = cnf.jwk;
3190
+ return jwk ?? null;
3191
+ }
3192
+ async function jwkForLayer(layer) {
3193
+ const fromHeader = extractCnfJwk(layer.header);
3194
+ if (fromHeader) return fromHeader;
3195
+ const fromPayload = extractCnfJwk(layer.payload);
3196
+ return fromPayload;
3197
+ }
3198
+ async function thumbprintsMatch(a, b) {
3199
+ try {
3200
+ const ta = await jwkThumbprint(a);
3201
+ const tb = await jwkThumbprint(b);
3202
+ return ta === tb;
3203
+ } catch {
3204
+ return false;
3205
+ }
3206
+ }
3207
+ async function jwkThumbprint(jwk) {
3208
+ const canonical = canonicalJwk(jwk);
3209
+ const bytes = new TextEncoder().encode(JSON.stringify(canonical));
3210
+ const subtle = webcrypto.subtle;
3211
+ const buffer = await new Promise((resolve, reject) => {
3212
+ const source = new ArrayBuffer(bytes.byteLength);
3213
+ new Uint8Array(source).set(bytes);
3214
+ subtle.digest("SHA-256", source).then(resolve).catch(reject);
3215
+ });
3216
+ return Buffer.from(new Uint8Array(buffer)).toString("base64url").replace(/=+$/, "");
3217
+ }
3218
+ function canonicalJwk(jwk) {
3219
+ if (jwk.kty === "EC") {
3220
+ return { crv: jwk.crv ?? "", kty: "EC", x: jwk.x ?? "", y: jwk.y ?? "" };
3221
+ }
3222
+ if (jwk.kty === "OKP") {
3223
+ return { crv: jwk.crv ?? "", kty: "OKP", x: jwk.x ?? "" };
3224
+ }
3225
+ if (jwk.kty === "RSA") {
3226
+ return { e: jwk.e ?? "", kty: "RSA", n: jwk.n ?? "" };
3227
+ }
3228
+ return { kty: jwk.kty ?? "" };
3229
+ }
3230
+ function computeCheckoutHashFromL2(l2) {
3231
+ const checkoutDisclosure = l2.payload.checkout ?? l2.payload.checkout_mandate;
3232
+ if (!checkoutDisclosure) return null;
3233
+ const canonical = canonicalStringify(checkoutDisclosure);
3234
+ const hash = createHash3("sha256").update(canonical).digest("base64url").replace(/=+$/, "");
3235
+ return hash;
3236
+ }
3237
+ function canonicalStringify(value) {
3238
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
3239
+ if (Array.isArray(value)) return "[" + value.map(canonicalStringify).join(",") + "]";
3240
+ const entries = Object.entries(value).sort(
3241
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
3242
+ );
3243
+ return "{" + entries.map(([k, v]) => JSON.stringify(k) + ":" + canonicalStringify(v)).join(",") + "}";
3244
+ }
3245
+ function checkExpiryAcross(layers, toleranceSec, nowSec, errors) {
3246
+ let ok = true;
3247
+ const names = ["L1", "L2", "L3a", "L3b"];
3248
+ layers.forEach((layer, idx) => {
3249
+ if (!layer) return;
3250
+ const exp = toUnixSeconds2(layer.payload.exp ?? layer.payload.expires);
3251
+ if (exp === void 0) return;
3252
+ if (nowSec > exp + toleranceSec) {
3253
+ errors.push(`${names[idx]} mandate expired at ${exp}`);
3254
+ ok = false;
3255
+ }
3256
+ });
3257
+ return ok;
3258
+ }
3259
+ function toUnixSeconds2(v) {
3260
+ if (typeof v === "number" && Number.isFinite(v)) return v;
3261
+ if (typeof v === "string") {
3262
+ const asInt = Number(v);
3263
+ if (Number.isFinite(asInt) && asInt > 0) {
3264
+ return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
3265
+ }
3266
+ const parsed = Date.parse(v);
3267
+ if (Number.isFinite(parsed)) return Math.floor(parsed / 1e3);
3268
+ }
3269
+ return void 0;
3270
+ }
3271
+ function coerceString7(v) {
3272
+ return typeof v === "string" && v.length > 0 ? v : void 0;
3273
+ }
3274
+
3275
+ // src/transport/commerce-pipeline.ts
3276
+ async function runCommercePipeline(input) {
3277
+ const trustSignals = [];
3278
+ const signatures = {};
3279
+ const timings = { extractMs: 0, verifyMs: 0, evalMs: 0 };
3280
+ const extractStart = performance.now();
3281
+ const purpose = resolvePurpose(input);
3282
+ const transactionValue = resolveTransactionValue(input);
3283
+ const identityClaims = collectIdentityClaims(input);
3284
+ const paymentToken = resolvePaymentToken(input);
3285
+ timings.extractMs = Math.round(performance.now() - extractStart);
3286
+ const verifyStart = performance.now();
3287
+ let hardDeny = false;
3288
+ if (input.vi?.verifyInput) {
3289
+ signatures.vi = await verifyVIChain(input.vi.verifyInput);
3290
+ if (!signatures.vi.ok) hardDeny = true;
3291
+ }
3292
+ if (input.ap2) {
3293
+ signatures.ap2 = verifyAP2Chain({
3294
+ triple: input.ap2.triple,
3295
+ clockSkewSec: input.clockSkewSec,
3296
+ now: input.now
3297
+ });
3298
+ if (!signatures.ap2.ok) hardDeny = true;
3299
+ }
3300
+ if (input.acp?.verifyInput) {
3301
+ signatures.acp = await verifyACPSignature(input.acp.verifyInput);
3302
+ if (!signatures.acp.ok && signatures.acp.timestampStale) hardDeny = true;
3303
+ if (signatures.acp.algorithm === "unsupported") {
3304
+ trustSignals.push("acp-signature-algorithm-unsupported");
3305
+ } else if (!signatures.acp.ok) {
3306
+ hardDeny = true;
3307
+ }
3308
+ }
3309
+ if (input.rfc9421) {
3310
+ signatures.rfc9421 = await verifyRFC9421(input.rfc9421.request, input.rfc9421.verifyOptions);
3311
+ if (!signatures.rfc9421.ok) hardDeny = true;
3312
+ }
3313
+ if (input.mpp) {
3314
+ signatures.mpp = verifyMPP({
3315
+ context: input.mpp.context,
3316
+ rawBody: input.mpp.rawBody,
3317
+ clockSkewSec: input.clockSkewSec,
3318
+ now: input.now
3319
+ });
3320
+ if (!signatures.mpp.ok) hardDeny = true;
3321
+ if (input.mpp.context.credential?.source) {
3322
+ trustSignals.push(`mpp-source-${shortSource(input.mpp.context.credential.source)}`);
3323
+ }
3324
+ }
3325
+ if (input.stripeWebhook) {
3326
+ signatures.stripeWebhook = verifyStripeWebhook(
3327
+ input.stripeWebhook.payload,
3328
+ input.stripeWebhook.signatureHeader,
3329
+ input.stripeWebhook.secret,
3330
+ { now: input.now ? () => input.now() : void 0 }
3331
+ );
3332
+ if (!signatures.stripeWebhook.ok) {
3333
+ trustSignals.push("stripe-webhook-hmac-failed");
3334
+ }
3335
+ }
3336
+ timings.verifyMs = Math.round(performance.now() - verifyStart);
3337
+ let identity;
3338
+ if (input.identityResolver && identityClaims.length > 0) {
3339
+ const bound = await bindIdentity(identityClaims, input.identityResolver);
3340
+ identity = {
3341
+ claims: identityClaims,
3342
+ mappedAstraSyncAgentId: bound.mappedAstraSyncAgentId,
3343
+ mismatchAcrossLayers: bound.mismatchAcrossLayers
3344
+ };
3345
+ if (bound.mismatchAcrossLayers) trustSignals.push("identity-mismatch-across-layers");
3346
+ } else if (identityClaims.length > 0) {
3347
+ identity = {
3348
+ claims: identityClaims,
3349
+ mappedAstraSyncAgentId: void 0,
3350
+ mismatchAcrossLayers: false
3351
+ };
3352
+ }
3353
+ const evalStart = performance.now();
3354
+ const constraints = runConstraintEval(input);
3355
+ if (constraints && !constraints.ok) hardDeny = true;
3356
+ timings.evalMs = Math.round(performance.now() - evalStart);
3357
+ if (paymentToken?.type === "stripe-spt") trustSignals.push("stripe-spt-present");
3358
+ if (paymentToken?.type === "acp-vt") trustSignals.push("acp-vault-token-present");
3359
+ if (paymentToken?.type === "tempo-tx") trustSignals.push("tempo-transaction-present");
3360
+ const mppReceipt = input.mpp?.context.receipt;
3361
+ return {
3362
+ protocol: input.protocol,
3363
+ purpose,
3364
+ transactionValue,
3365
+ signatures,
3366
+ identity,
3367
+ paymentToken,
3368
+ mppMethodsOffered: input.mpp?.context.offeredMethods,
3369
+ constraints,
3370
+ receipt: mppReceipt ? {
3371
+ method: mppReceipt.method,
3372
+ reference: mppReceipt.reference,
3373
+ status: mppReceipt.status,
3374
+ timestamp: mppReceipt.timestamp
3375
+ } : void 0,
3376
+ trustSignals,
3377
+ timings,
3378
+ ok: !hardDeny
3379
+ };
3380
+ }
3381
+ function resolvePurpose(input) {
3382
+ if (input.vi?.claims.mandateType) {
3383
+ return mapVIMandateToPurpose(input.vi.claims.mandateType);
3384
+ }
3385
+ if (input.ap2?.triple.payment) return "commerce.payment.execute";
3386
+ if (input.ap2?.triple.cart) return "commerce.checkout.confirm";
3387
+ if (input.ap2?.triple.intent) return "commerce.delegation.intent";
3388
+ if (input.ucp?.endpoint) {
3389
+ const [method, path] = input.ucp.endpoint.split(" ");
3390
+ return mapUCPRequestToPurpose(method ?? "POST", path ?? "/");
3391
+ }
3392
+ if (input.acp?.context.endpoint) {
3393
+ switch (input.acp.context.endpoint) {
3394
+ case "checkout_sessions.create":
3395
+ return "commerce.checkout.create";
3396
+ case "checkout_sessions.update":
3397
+ return "commerce.checkout.update";
3398
+ case "checkout_sessions.complete":
3399
+ return "commerce.payment.execute";
3400
+ case "checkout_sessions.cancel":
3401
+ return "commerce.checkout.cancel";
3402
+ case "delegate_payment":
3403
+ return "commerce.delegation.payment";
3404
+ default:
3405
+ return mapACPRequestToPurpose("POST", "/checkout_sessions");
3406
+ }
3407
+ }
3408
+ if (input.rfc9421?.tag) {
3409
+ return mapRFC9421TagToPurpose(
3410
+ input.rfc9421.tag === "browse" || input.rfc9421.tag === "purchase" ? input.rfc9421.tag : void 0
3411
+ );
3412
+ }
3413
+ if (input.mpp?.context.credential?.challenge || input.mpp?.context.challenges?.[0]) {
3414
+ const challenge = input.mpp.context.credential?.challenge ?? input.mpp.context.challenges?.[0];
3415
+ const amount = parseFloat(String(challenge?.request?.amount ?? "NaN"));
3416
+ return mapMPPRequestToPurpose(
3417
+ challenge?.intent === "session" ? "session" : "charge",
3418
+ Number.isFinite(amount) ? amount : void 0
3419
+ );
3420
+ }
3421
+ if (input.x402?.paymentRequired) {
3422
+ const amt = input.x402.paymentRequired.accepts[0]?.amount;
3423
+ return mapX402RequestToPurpose(Number(amt));
3424
+ }
3425
+ if (input.x402?.paymentPayload) return "commerce.payment.execute";
3426
+ return null;
3427
+ }
3428
+ function resolveTransactionValue(input) {
3429
+ if (input.vi?.claims) {
3430
+ const v = extractVITransactionValue({
3431
+ constraints: input.vi.claims.constraints,
3432
+ l3aPaymentAmount: input.vi.claims.constraints.paymentAmount && typeof input.vi.claims.constraints.paymentAmount.max === "number" ? {
3433
+ amount: input.vi.claims.constraints.paymentAmount.max,
3434
+ currency: input.vi.claims.constraints.paymentAmount.currency
3435
+ } : void 0
3436
+ });
3437
+ if (v) return v;
3438
+ }
3439
+ if (input.ucp?.totals) {
3440
+ const v = extractUCPTransactionValue({ totals: input.ucp.totals });
3441
+ if (v) return v;
3442
+ }
3443
+ if (input.acp?.context.totals) {
3444
+ const v = extractACPTransactionValue({ totals: input.acp.context.totals });
3445
+ if (v) return v;
3446
+ }
3447
+ if (input.mpp?.context.credential?.challenge) {
3448
+ const ch = input.mpp.context.credential.challenge;
3449
+ const v = extractMPPTransactionValue({ method: ch.method, request: ch.request });
3450
+ if (v) return v;
3451
+ }
3452
+ if (input.x402?.paymentRequired) {
3453
+ const first = input.x402.paymentRequired.accepts[0];
3454
+ if (first) {
3455
+ const v = extractX402TransactionValue({
3456
+ maxAmountRequired: Number(first.amount),
3457
+ asset: first.asset
3458
+ });
3459
+ if (v) return v;
3460
+ }
3461
+ }
3462
+ return void 0;
3463
+ }
3464
+ function collectIdentityClaims(input) {
3465
+ const claims = [];
3466
+ if (input.vi?.claims.kid)
3467
+ claims.push({ protocol: "vi", field: "kid", value: input.vi.claims.kid });
3468
+ if (input.ap2?.triple) {
3469
+ const agentId = input.ap2.triple.intent?.agent_id ?? input.ap2.triple.cart?.agent_id ?? input.ap2.triple.payment?.agent_id;
3470
+ if (agentId) claims.push({ protocol: "ap2", field: "agent_id", value: agentId });
3471
+ }
3472
+ if (input.acp?.context.bearer) {
3473
+ claims.push({ protocol: "acp", field: "bearer", value: input.acp.context.bearer });
3474
+ }
3475
+ if (input.mpp?.context.credential?.source) {
3476
+ claims.push({ protocol: "mpp", field: "source", value: input.mpp.context.credential.source });
3477
+ }
3478
+ if (input.rfc9421) {
3479
+ }
3480
+ return claims;
3481
+ }
3482
+ function resolvePaymentToken(input) {
3483
+ if (input.acp?.context.paymentToken?.type) {
3484
+ return { present: true, type: input.acp.context.paymentToken.type };
3485
+ }
3486
+ const mppMethod = input.mpp?.context.credential?.challenge?.method;
3487
+ if (mppMethod === "tempo") return { present: true, type: "tempo-tx" };
3488
+ if (mppMethod === "stripe") return { present: true, type: "stripe-spt" };
3489
+ return void 0;
3490
+ }
3491
+ function runConstraintEval(input) {
3492
+ const transaction = input.transaction ?? {};
3493
+ const results = {};
3494
+ const reasons = [];
3495
+ let hasAny = false;
3496
+ if (input.vi?.claims) {
3497
+ const viResult = evaluateVIConstraints({
3498
+ constraints: input.vi.claims.constraints,
3499
+ transaction
3500
+ });
3501
+ for (const [k, v] of Object.entries(viResult.results)) {
3502
+ results[k] = v;
3503
+ if (!v.ok && v.reason) reasons.push(v.reason);
3504
+ }
3505
+ if (Object.keys(viResult.results).length > 0) hasAny = true;
3506
+ }
3507
+ const registered = input.registeredConstraints;
3508
+ if (registered?.allowedPaymentMethods) {
3509
+ const pm = evaluatePaymentMethodAllowlist({
3510
+ allowedMethods: registered.allowedPaymentMethods,
3511
+ requestedMethod: transaction.paymentMethod
3512
+ });
3513
+ results.paymentMethod = pm;
3514
+ if (!pm.ok && pm.reason) reasons.push(pm.reason);
3515
+ hasAny = true;
3516
+ }
3517
+ if (registered?.spendingLimit) {
3518
+ const sp = evaluateSpendingLimit({
3519
+ limit: registered.spendingLimit,
3520
+ requested: { amount: transaction.amount, currency: transaction.currency }
3521
+ });
3522
+ results.spendingLimit = sp;
3523
+ if (!sp.ok && sp.reason) reasons.push(sp.reason);
3524
+ hasAny = true;
3525
+ }
3526
+ if (!hasAny) return void 0;
3527
+ return { ok: reasons.length === 0, results, reasons };
3528
+ }
3529
+ function shortSource(source) {
3530
+ return source.replace(/^did:[a-z0-9]+:/, "").slice(0, 16);
3531
+ }
3532
+
3533
+ // src/transport/extractor-registry.ts
3534
+ var registry = /* @__PURE__ */ new Map();
3535
+ function registerTransportExtractor(extractor) {
3536
+ if (!extractor || typeof extractor.name !== "string" || extractor.name.length === 0) {
3537
+ throw new Error("registerTransportExtractor: extractor must have a non-empty name");
3538
+ }
3539
+ registry.set(extractor.name, extractor);
3540
+ }
3541
+ function getTransportExtractors() {
3542
+ return Array.from(registry.values());
3543
+ }
3544
+ function getTransportExtractor(name) {
3545
+ return registry.get(name);
3546
+ }
3547
+ function clearTransportExtractors() {
3548
+ registry.clear();
3549
+ }
3550
+ async function runMatchingExtractors(request) {
3551
+ const out = {};
3552
+ for (const extractor of registry.values()) {
3553
+ if (!extractor.match(request)) continue;
3554
+ const result = await extractor.extract(request);
3555
+ if (result !== null && result !== void 0) out[extractor.name] = result;
3556
+ }
3557
+ return out;
3558
+ }
3559
+
3560
+ // src/transport/registry/visa.ts
3561
+ import { createRemoteJWKSet } from "jose";
3562
+ var DEFAULT_VISA_JWKS_URL = "https://mcp.visa.com/.well-known/jwks";
3563
+ function createVisaRegistry(options = {}) {
3564
+ const url = new URL(options.jwksUrl ?? DEFAULT_VISA_JWKS_URL);
3565
+ const jwks = createRemoteJWKSet(url, {
3566
+ cacheMaxAge: options.cacheMaxAge,
3567
+ cooldownDuration: options.cooldownDuration
3568
+ });
3569
+ return {
3570
+ name: "visa",
3571
+ async resolve(kid, context) {
3572
+ if (!kid) return null;
3573
+ try {
3574
+ const key = await jwks({
3575
+ kid,
3576
+ alg: context?.algorithm ?? "ES256",
3577
+ typ: "JWT"
3578
+ });
3579
+ return exportJwkFromKeyLike(key);
3580
+ } catch {
3581
+ return null;
3582
+ }
3583
+ }
3584
+ };
3585
+ }
3586
+ async function exportJwkFromKeyLike(keyLike) {
3587
+ if (!keyLike) return null;
3588
+ if (typeof keyLike === "object" && "kty" in keyLike) {
3589
+ return keyLike;
3590
+ }
3591
+ const { exportJWK } = await import("jose");
3592
+ try {
3593
+ return await exportJWK(keyLike);
3594
+ } catch {
3595
+ return null;
3596
+ }
3597
+ }
3598
+
3599
+ // src/transport/registry/mastercard.ts
3600
+ function createMastercardRegistry(options = {}) {
3601
+ const cache = /* @__PURE__ */ new Map();
3602
+ const ttlSec = options.cacheTtlSec ?? 3600;
3603
+ const fetchFn = options.fetch ?? globalThis.fetch;
3604
+ let warned = false;
3605
+ return {
3606
+ name: "mastercard",
3607
+ async resolve(kid) {
3608
+ if (!kid) return null;
3609
+ if (!options.registryUrl) {
3610
+ if (!warned && !options.silent) {
3611
+ warned = true;
3612
+ console.warn(
3613
+ "[mastercard-registry] registryUrl not configured \u2014 key resolution disabled. Kid lookups will return null until a partnership registry is supplied."
3614
+ );
3615
+ }
3616
+ return null;
3617
+ }
3618
+ const cached = cache.get(kid);
3619
+ if (cached && cached.expiresAt > Date.now()) return cached.jwk;
3620
+ try {
3621
+ const res = await fetchFn(options.registryUrl);
3622
+ if (!res.ok) return null;
3623
+ const body = await res.json();
3624
+ const keys = body.keys ?? [];
3625
+ for (const k of keys) {
3626
+ if (k.kid === kid) {
3627
+ cache.set(kid, { jwk: k, expiresAt: Date.now() + ttlSec * 1e3 });
3628
+ return k;
3629
+ }
3630
+ }
3631
+ return null;
3632
+ } catch {
3633
+ return null;
3634
+ }
3635
+ }
3636
+ };
3637
+ }
3638
+
3639
+ // src/transport/registry/web-bot-auth.ts
3640
+ var DIRECTORY_PATH = "/.well-known/http-message-signatures-directory";
3641
+ function createWebBotAuthRegistry(options = {}) {
3642
+ const cache = /* @__PURE__ */ new Map();
3643
+ const ttlSec = options.cacheTtlSec ?? 3600;
3644
+ const fetchFn = options.fetch ?? globalThis.fetch;
3645
+ return {
3646
+ name: "web-bot-auth",
3647
+ async resolve(kid, context) {
3648
+ if (!kid) return null;
3649
+ const directoryUrl = resolveDirectoryUrl(options.directoryUrl, context?.origin);
3650
+ if (!directoryUrl) return null;
3651
+ const cached = cache.get(directoryUrl);
3652
+ const now = Date.now();
3653
+ if (cached && cached.expiresAt > now) {
3654
+ return findKeyByKid(cached.keys, kid);
3655
+ }
3656
+ try {
3657
+ const res = await fetchFn(directoryUrl);
3658
+ if (!res.ok) return null;
3659
+ const body = await res.json();
3660
+ const keys = body.keys ?? [];
3661
+ cache.set(directoryUrl, { keys, expiresAt: now + ttlSec * 1e3 });
3662
+ return findKeyByKid(keys, kid);
3663
+ } catch {
3664
+ return null;
3665
+ }
3666
+ }
3667
+ };
3668
+ }
3669
+ function resolveDirectoryUrl(explicit, origin) {
3670
+ if (explicit) return explicit;
3671
+ if (!origin) return null;
3672
+ try {
3673
+ const url = new URL(origin);
3674
+ return `${url.origin}${DIRECTORY_PATH}`;
3675
+ } catch {
3676
+ return null;
3677
+ }
3678
+ }
3679
+ function findKeyByKid(keys, kid) {
3680
+ for (const k of keys) {
3681
+ if (k.kid === kid) return k;
3682
+ }
3683
+ return null;
3684
+ }
3685
+
1173
3686
  // src/transport/index.ts
1174
3687
  function detectProtocol(context) {
1175
3688
  if (context.metadata && typeof context.metadata === "object") {