@astrasyncai/verification-gateway 2.0.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/adapter-interface/interface.d.mts +2 -2
  2. package/dist/adapter-interface/interface.d.ts +2 -2
  3. package/dist/adapters/express.d.mts +2 -2
  4. package/dist/adapters/express.d.ts +2 -2
  5. package/dist/adapters/express.js +42 -20
  6. package/dist/adapters/express.js.map +1 -1
  7. package/dist/adapters/express.mjs +42 -20
  8. package/dist/adapters/express.mjs.map +1 -1
  9. package/dist/adapters/nextjs.d.mts +2 -2
  10. package/dist/adapters/nextjs.d.ts +2 -2
  11. package/dist/adapters/nextjs.js +43 -20
  12. package/dist/adapters/nextjs.js.map +1 -1
  13. package/dist/adapters/nextjs.mjs +43 -20
  14. package/dist/adapters/nextjs.mjs.map +1 -1
  15. package/dist/adapters/sdk.d.mts +2 -2
  16. package/dist/adapters/sdk.d.ts +2 -2
  17. package/dist/adapters/sdk.js +25 -16
  18. package/dist/adapters/sdk.js.map +1 -1
  19. package/dist/adapters/sdk.mjs +25 -16
  20. package/dist/adapters/sdk.mjs.map +1 -1
  21. package/dist/agent/index.d.mts +2 -2
  22. package/dist/agent/index.d.ts +2 -2
  23. package/dist/agent/index.js +100 -1
  24. package/dist/agent/index.js.map +1 -1
  25. package/dist/agent/index.mjs +101 -1
  26. package/dist/agent/index.mjs.map +1 -1
  27. package/dist/browser/background.js +58 -16
  28. package/dist/browser/background.js.map +1 -1
  29. package/dist/browser/background.mjs +61 -16
  30. package/dist/browser/background.mjs.map +1 -1
  31. package/dist/browser/browser-adapter.d.mts +2 -2
  32. package/dist/browser/browser-adapter.d.ts +2 -2
  33. package/dist/cli/index.d.mts +2 -2
  34. package/dist/cli/index.d.ts +2 -2
  35. package/dist/cursor/cursor-adapter.d.mts +2 -2
  36. package/dist/cursor/cursor-adapter.d.ts +2 -2
  37. package/dist/cursor/extension.d.mts +2 -2
  38. package/dist/cursor/extension.d.ts +2 -2
  39. package/dist/cursor/extension.js +58 -16
  40. package/dist/cursor/extension.js.map +1 -1
  41. package/dist/cursor/extension.mjs +61 -16
  42. package/dist/cursor/extension.mjs.map +1 -1
  43. package/dist/{express-CtwDIZyF.d.mts → express-C9KqJNWV.d.mts} +1 -1
  44. package/dist/{express-Bcl-uBUE.d.ts → express-DpwYW08E.d.ts} +1 -1
  45. package/dist/gateway/gateway.d.mts +2 -2
  46. package/dist/gateway/gateway.d.ts +2 -2
  47. package/dist/gateway/gateway.js +58 -16
  48. package/dist/gateway/gateway.js.map +1 -1
  49. package/dist/gateway/gateway.mjs +61 -16
  50. package/dist/gateway/gateway.mjs.map +1 -1
  51. package/dist/git-trigger/git-hooks.d.mts +2 -2
  52. package/dist/git-trigger/git-hooks.d.ts +2 -2
  53. package/dist/{index-BY8yQ8N8.d.mts → index-BMZdjGT4.d.mts} +46 -3
  54. package/dist/index-DlsYN3Et.d.mts +1397 -0
  55. package/dist/{index-CtYSYwn3.d.ts → index-Dm2xA6j1.d.ts} +46 -3
  56. package/dist/index-gM-lgX_X.d.ts +1397 -0
  57. package/dist/index.d.mts +8 -7
  58. package/dist/index.d.ts +8 -7
  59. package/dist/index.js +2489 -66
  60. package/dist/index.js.map +1 -1
  61. package/dist/index.mjs +2492 -66
  62. package/dist/index.mjs.map +1 -1
  63. package/dist/local-evaluator/evaluator.d.mts +2 -2
  64. package/dist/local-evaluator/evaluator.d.ts +2 -2
  65. package/dist/{nextjs-BQyMCSx_.d.mts → nextjs-BEqidT0U.d.mts} +1 -1
  66. package/dist/{nextjs-CEldnIJ9.d.ts → nextjs-yNzimC3a.d.ts} +1 -1
  67. package/dist/{sdk-BhvuJSrH.d.mts → sdk-7fa9H0qa.d.mts} +1 -1
  68. package/dist/{sdk-BlyVSC_S.d.ts → sdk-CP9C9Qu0.d.ts} +1 -1
  69. package/dist/transport/index.d.mts +3 -2
  70. package/dist/transport/index.d.ts +3 -2
  71. package/dist/transport/index.js +2384 -2
  72. package/dist/transport/index.js.map +1 -1
  73. package/dist/transport/index.mjs +2327 -1
  74. package/dist/transport/index.mjs.map +1 -1
  75. package/dist/{types-CxQwJKbd.d.mts → types-CrVMq_Td.d.mts} +30 -3
  76. package/dist/{types-CxQwJKbd.d.ts → types-CrVMq_Td.d.ts} +30 -3
  77. package/dist/{types-jJnPXStc.d.mts → types-DE0ooQJ6.d.mts} +1 -1
  78. package/dist/{types-79qS7aON.d.ts → types-rigu2bH3.d.ts} +1 -1
  79. package/dist/ui/index.d.mts +1 -1
  80. package/dist/ui/index.d.ts +1 -1
  81. package/package.json +17 -3
  82. package/dist/index-B1ThcGZl.d.mts +0 -89
  83. package/dist/index-DnoXfdFd.d.ts +0 -89
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,20 +17,77 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/transport/index.ts
21
31
  var transport_exports = {};
22
32
  __export(transport_exports, {
33
+ STRIPE_WEBHOOK_INFORMATIONAL_EVENTS: () => STRIPE_WEBHOOK_INFORMATIONAL_EVENTS,
23
34
  applyCredentials: () => applyCredentials,
35
+ bindIdentity: () => bindIdentity,
36
+ claim: () => claim,
37
+ clearTransportExtractors: () => clearTransportExtractors,
38
+ createMastercardRegistry: () => createMastercardRegistry,
39
+ createVisaRegistry: () => createVisaRegistry,
40
+ createWebBotAuthRegistry: () => createWebBotAuthRegistry,
24
41
  detectProtocol: () => detectProtocol,
42
+ evaluatePaymentMethodAllowlist: () => evaluatePaymentMethodAllowlist,
43
+ evaluateSpendingLimit: () => evaluateSpendingLimit,
44
+ evaluateVIConstraints: () => evaluateVIConstraints,
25
45
  extractA2ACredentials: () => extractA2ACredentials,
46
+ extractACPContext: () => extractACPContext,
47
+ extractACPTransactionValue: () => extractACPTransactionValue,
48
+ extractAP2Mandate: () => extractAP2Mandate,
49
+ extractAP2Mandates: () => extractAP2Mandates,
50
+ extractAP2TransactionValue: () => extractAP2TransactionValue,
26
51
  extractCredentialsFromProtocol: () => extractCredentialsFromProtocol,
27
52
  extractHttpCredentials: () => extractHttpCredentials,
53
+ extractMPPContext: () => extractMPPContext,
54
+ extractMPPFromRequest: () => extractMPPFromRequest,
55
+ extractMPPFromResponse: () => extractMPPFromResponse,
56
+ extractMPPTransactionValue: () => extractMPPTransactionValue,
28
57
  extractMcpCredentials: () => extractMcpCredentials,
58
+ extractUCPContext: () => extractUCPContext,
59
+ extractUCPTransactionValue: () => extractUCPTransactionValue,
60
+ extractVIClaims: () => extractVIClaims,
61
+ extractVITransactionValue: () => extractVITransactionValue,
62
+ extractX402Context: () => extractX402Context,
63
+ extractX402FromRequest: () => extractX402FromRequest,
64
+ extractX402FromResponse: () => extractX402FromResponse,
65
+ extractX402TransactionValue: () => extractX402TransactionValue,
66
+ fetchUCPManifest: () => fetchUCPManifest,
67
+ getTransportExtractor: () => getTransportExtractor,
68
+ getTransportExtractors: () => getTransportExtractors,
69
+ isStripeWebhookInformational: () => isStripeWebhookInformational,
70
+ mapACPRequestToPurpose: () => mapACPRequestToPurpose,
71
+ mapAP2MandateToPurpose: () => mapAP2MandateToPurpose,
72
+ mapMPPRequestToPurpose: () => mapMPPRequestToPurpose,
73
+ mapRFC9421TagToPurpose: () => mapRFC9421TagToPurpose,
74
+ mapUCPRequestToPurpose: () => mapUCPRequestToPurpose,
75
+ mapVIMandateToPurpose: () => mapVIMandateToPurpose,
76
+ mapX402RequestToPurpose: () => mapX402RequestToPurpose,
77
+ parseRFC9421: () => parseRFC9421,
78
+ registerTransportExtractor: () => registerTransportExtractor,
79
+ runCommercePipeline: () => runCommercePipeline,
80
+ runMatchingExtractors: () => runMatchingExtractors,
29
81
  setA2AMetadata: () => setA2AMetadata,
30
82
  setHttpHeaders: () => setHttpHeaders,
31
- setMcpMeta: () => setMcpMeta
83
+ setMcpMeta: () => setMcpMeta,
84
+ validateUCPManifest: () => validateUCPManifest,
85
+ verifyACPSignature: () => verifyACPSignature,
86
+ verifyAP2Chain: () => verifyAP2Chain,
87
+ verifyMPP: () => verifyMPP,
88
+ verifyRFC9421: () => verifyRFC9421,
89
+ verifyStripeWebhook: () => verifyStripeWebhook,
90
+ verifyVIChain: () => verifyVIChain
32
91
  });
33
92
  module.exports = __toCommonJS(transport_exports);
34
93
 
@@ -162,6 +221,2280 @@ function extractMcpCredentials(params) {
162
221
  return credentials;
163
222
  }
164
223
 
224
+ // src/transport/purpose-mapping.ts
225
+ var UCP_ROUTES = [
226
+ { method: "POST", pattern: /^\/checkout[-_]sessions\/?$/, purpose: "commerce.checkout.create" },
227
+ {
228
+ method: "PUT",
229
+ pattern: /^\/checkout[-_]sessions\/[^/]+\/?$/,
230
+ purpose: "commerce.checkout.update"
231
+ },
232
+ {
233
+ method: "POST",
234
+ pattern: /^\/checkout[-_]sessions\/[^/]+\/complete\/?$/,
235
+ purpose: "commerce.payment.execute"
236
+ },
237
+ {
238
+ method: "POST",
239
+ pattern: /^\/checkout[-_]sessions\/[^/]+\/cancel\/?$/,
240
+ purpose: "commerce.checkout.cancel"
241
+ }
242
+ ];
243
+ var ACP_ROUTES = [
244
+ { method: "POST", pattern: /^\/checkout_sessions\/?$/, purpose: "commerce.checkout.create" },
245
+ {
246
+ method: "POST",
247
+ pattern: /^\/checkout_sessions\/[^/]+\/?$/,
248
+ purpose: "commerce.checkout.update"
249
+ },
250
+ {
251
+ method: "POST",
252
+ pattern: /^\/checkout_sessions\/[^/]+\/complete\/?$/,
253
+ purpose: "commerce.payment.execute"
254
+ },
255
+ {
256
+ method: "POST",
257
+ pattern: /^\/checkout_sessions\/[^/]+\/cancel\/?$/,
258
+ purpose: "commerce.checkout.cancel"
259
+ },
260
+ {
261
+ method: "POST",
262
+ pattern: /^\/agentic_commerce\/delegate_payment\/?$/,
263
+ purpose: "commerce.delegation.payment"
264
+ }
265
+ ];
266
+ function mapUCPRequestToPurpose(method, path) {
267
+ const normalizedMethod = method.toUpperCase();
268
+ const normalizedPath = stripQuery(path);
269
+ for (const route of UCP_ROUTES) {
270
+ if (route.method === normalizedMethod && route.pattern.test(normalizedPath)) {
271
+ return route.purpose;
272
+ }
273
+ }
274
+ return null;
275
+ }
276
+ function mapACPRequestToPurpose(method, path) {
277
+ const normalizedMethod = method.toUpperCase();
278
+ const normalizedPath = stripQuery(path);
279
+ for (const route of ACP_ROUTES) {
280
+ if (route.method === normalizedMethod && route.pattern.test(normalizedPath)) {
281
+ return route.purpose;
282
+ }
283
+ }
284
+ return null;
285
+ }
286
+ function mapAP2MandateToPurpose(mandateType) {
287
+ switch (mandateType) {
288
+ case "intent_mandate":
289
+ return "commerce.delegation.intent";
290
+ case "cart_mandate":
291
+ return "commerce.checkout.confirm";
292
+ case "payment_mandate":
293
+ return "commerce.payment.execute";
294
+ }
295
+ }
296
+ function mapVIMandateToPurpose(mandateType) {
297
+ switch (mandateType) {
298
+ case "checkout":
299
+ return "commerce.checkout.confirm";
300
+ case "payment":
301
+ return "commerce.payment.execute";
302
+ case "checkout.open":
303
+ return "commerce.delegation.checkout";
304
+ case "payment.open":
305
+ return "commerce.delegation.payment";
306
+ }
307
+ }
308
+ function mapRFC9421TagToPurpose(tag) {
309
+ if (tag === "purchase") return "commerce.payment.execute";
310
+ return "commerce.browsing";
311
+ }
312
+ function mapMPPRequestToPurpose(intent, amount) {
313
+ if (typeof amount === "number" && amount === 0) return "commerce.identity_probe";
314
+ if (intent === "session") return "commerce.payment.stream";
315
+ return "commerce.payment.execute";
316
+ }
317
+ function mapX402RequestToPurpose(amount) {
318
+ if (typeof amount === "number" && amount === 0) return "commerce.identity_probe";
319
+ return "commerce.payment.execute";
320
+ }
321
+ function stripQuery(path) {
322
+ const q = path.indexOf("?");
323
+ return q === -1 ? path : path.slice(0, q);
324
+ }
325
+ var STRIPE_WEBHOOK_INFORMATIONAL_EVENTS = [
326
+ "payment_intent.succeeded",
327
+ "payment_intent.payment_failed",
328
+ "charge.refunded",
329
+ "checkout.session.completed",
330
+ "customer.subscription.created"
331
+ ];
332
+ function isStripeWebhookInformational(eventType) {
333
+ return STRIPE_WEBHOOK_INFORMATIONAL_EVENTS.includes(eventType);
334
+ }
335
+
336
+ // src/transport/transaction-value.ts
337
+ function extractUCPTransactionValue(input) {
338
+ const totals = input.totals ?? [];
339
+ const total = totals.find((t) => t.type === "total") ?? totals[0];
340
+ if (!total || typeof total.amount !== "number" || !total.currency) return null;
341
+ return {
342
+ protocol: "ucp",
343
+ amount: total.amount / 100,
344
+ currency: total.currency,
345
+ source: `totals[type=${total.type ?? "unknown"}].amount`
346
+ };
347
+ }
348
+ function extractACPTransactionValue(input) {
349
+ const totals = input.totals ?? [];
350
+ const total = totals.find((t) => t.type === "total") ?? totals[0];
351
+ if (!total || typeof total.amount !== "number" || !total.currency) return null;
352
+ return {
353
+ protocol: "acp",
354
+ amount: total.amount / 100,
355
+ currency: total.currency,
356
+ source: `totals[type=${total.type ?? "unknown"}].amount`
357
+ };
358
+ }
359
+ function extractVITransactionValue(claims) {
360
+ const l3a = claims.l3aPaymentAmount;
361
+ if (l3a && typeof l3a.amount === "number" && l3a.currency) {
362
+ return {
363
+ protocol: "vi",
364
+ amount: l3a.amount,
365
+ currency: l3a.currency,
366
+ source: "L3a.payment.amount"
367
+ };
368
+ }
369
+ const bound = claims.constraints?.paymentAmount;
370
+ if (bound && typeof bound.max === "number" && bound.currency) {
371
+ return {
372
+ protocol: "vi",
373
+ amount: bound.max,
374
+ currency: bound.currency,
375
+ source: "L2.payment.constraints.amount.max"
376
+ };
377
+ }
378
+ return null;
379
+ }
380
+ function extractAP2TransactionValue(mandate) {
381
+ const amt = mandate?.payment_details_total?.amount;
382
+ if (!amt || !amt.currency) return null;
383
+ const n = typeof amt.value === "string" ? Number(amt.value) : amt.value;
384
+ if (typeof n !== "number" || !Number.isFinite(n)) return null;
385
+ return {
386
+ protocol: "ap2",
387
+ amount: n,
388
+ currency: amt.currency,
389
+ source: "payment_mandate.payment_details_total.amount"
390
+ };
391
+ }
392
+ function extractMPPTransactionValue(challenge) {
393
+ const req = challenge.request;
394
+ if (!req || typeof req.amount !== "number" || !req.currency) return null;
395
+ return {
396
+ protocol: "mpp",
397
+ amount: req.amount,
398
+ currency: req.currency,
399
+ source: `challenge.request.amount (method=${challenge.method ?? "unknown"})`
400
+ };
401
+ }
402
+ function extractX402TransactionValue(req) {
403
+ const amount = req.maxAmountRequired ?? req.amount;
404
+ const currency = req.currency ?? req.asset;
405
+ if (typeof amount !== "number" || !currency) return null;
406
+ return {
407
+ protocol: "x402",
408
+ amount,
409
+ currency,
410
+ source: req.maxAmountRequired !== void 0 ? "maxAmountRequired" : "amount"
411
+ };
412
+ }
413
+
414
+ // src/transport/rfc9421.ts
415
+ var import_structured_headers = require("structured-headers");
416
+ function parseRFC9421(headers) {
417
+ const sigInput = readHeader(headers, "signature-input");
418
+ const sig = readHeader(headers, "signature");
419
+ if (!sigInput || !sig) return null;
420
+ let inputDict;
421
+ let sigDict;
422
+ try {
423
+ inputDict = (0, import_structured_headers.parseDictionary)(sigInput);
424
+ sigDict = (0, import_structured_headers.parseDictionary)(sig);
425
+ } catch {
426
+ return null;
427
+ }
428
+ const signatures = [];
429
+ for (const [label, entry] of inputDict) {
430
+ const innerList = Array.isArray(entry) ? entry[0] : entry.value;
431
+ const params = Array.isArray(entry) ? entry[1] : entry.params;
432
+ if (!Array.isArray(innerList) || !params) continue;
433
+ const covered = [];
434
+ for (const item of innerList) {
435
+ const [bare] = Array.isArray(item) ? item : [item];
436
+ if (typeof bare === "string") covered.push(bare);
437
+ else if (bare && typeof bare === "object" && "toString" in bare) covered.push(String(bare));
438
+ }
439
+ const paramsMap = params;
440
+ const kid = coerceString(paramsMap.get("keyid"));
441
+ if (!kid) continue;
442
+ const sigEntry = sigDict.get(label);
443
+ if (!sigEntry) continue;
444
+ const sigBare = Array.isArray(sigEntry) ? sigEntry[0] : sigEntry.value;
445
+ const signatureBase64 = extractBase64(sigBare);
446
+ if (!signatureBase64) continue;
447
+ signatures.push({
448
+ label,
449
+ kid,
450
+ alg: coerceString(paramsMap.get("alg")),
451
+ covered,
452
+ signatureBase64,
453
+ created: coerceNumber(paramsMap.get("created")),
454
+ expires: coerceNumber(paramsMap.get("expires")),
455
+ nonce: coerceString(paramsMap.get("nonce")),
456
+ tag: coerceString(paramsMap.get("tag"))
457
+ });
458
+ }
459
+ if (signatures.length === 0) return null;
460
+ return { signatures };
461
+ }
462
+ function readHeader(headers, name) {
463
+ for (const key of Object.keys(headers)) {
464
+ if (key.toLowerCase() === name) {
465
+ const raw = headers[key];
466
+ if (typeof raw === "string") return raw;
467
+ if (Array.isArray(raw)) return raw.join(", ");
468
+ return null;
469
+ }
470
+ }
471
+ return null;
472
+ }
473
+ function coerceString(value) {
474
+ if (typeof value === "string") return value;
475
+ if (value == null) return void 0;
476
+ if (typeof value === "object" && "toString" in value) {
477
+ const s = String(value);
478
+ return s.length > 0 ? s : void 0;
479
+ }
480
+ return void 0;
481
+ }
482
+ function coerceNumber(value) {
483
+ if (typeof value === "number" && Number.isFinite(value)) return value;
484
+ if (typeof value === "bigint") return Number(value);
485
+ return void 0;
486
+ }
487
+ function extractBase64(value) {
488
+ if (value instanceof Uint8Array) return bufferToBase64(value);
489
+ if (value instanceof ArrayBuffer) return bufferToBase64(new Uint8Array(value));
490
+ if (ArrayBuffer.isView(value)) {
491
+ const v = value;
492
+ return bufferToBase64(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
493
+ }
494
+ if (typeof value === "string") {
495
+ if (value.startsWith(":") && value.endsWith(":")) return value.slice(1, -1);
496
+ return value;
497
+ }
498
+ return null;
499
+ }
500
+ function bufferToBase64(bytes) {
501
+ return Buffer.from(bytes).toString("base64");
502
+ }
503
+
504
+ // src/transport/rfc9421-verify.ts
505
+ var import_http_message_signatures = require("http-message-signatures");
506
+ async function verifyRFC9421(request, options) {
507
+ const { resolver } = options;
508
+ const tolerance = options.clockSkewSec ?? 300;
509
+ const nowSec = options.now ? options.now() : Math.floor(Date.now() / 1e3);
510
+ let resolvedKid;
511
+ let resolvedAlg;
512
+ const keyLookup = async (parameters) => {
513
+ const kid = typeof parameters.keyid === "string" ? parameters.keyid : void 0;
514
+ if (!kid) return null;
515
+ resolvedKid = kid;
516
+ const alg = typeof parameters.alg === "string" ? parameters.alg : void 0;
517
+ if (alg) resolvedAlg = alg;
518
+ const origin = safeOrigin(request.url);
519
+ const jwk = await resolver.resolve(kid, { origin, algorithm: alg });
520
+ if (!jwk) return null;
521
+ const created = toUnixSeconds(parameters.created);
522
+ const expires = toUnixSeconds(parameters.expires);
523
+ if (created !== void 0 && Math.abs(nowSec - created) > tolerance) return null;
524
+ if (expires !== void 0 && nowSec > expires + tolerance) return null;
525
+ return jwkToVerifyingKey(kid, jwk, alg);
526
+ };
527
+ try {
528
+ const result = await import_http_message_signatures.httpbis.verifyMessage(
529
+ {
530
+ keyLookup
531
+ },
532
+ normalizeRequest(request)
533
+ );
534
+ if (result === true) {
535
+ return {
536
+ ok: true,
537
+ kid: resolvedKid,
538
+ registry: resolver.name,
539
+ algorithm: resolvedAlg
540
+ };
541
+ }
542
+ return {
543
+ ok: false,
544
+ kid: resolvedKid,
545
+ registry: resolver.name,
546
+ algorithm: resolvedAlg,
547
+ error: result === false ? "signature invalid" : "no signature found"
548
+ };
549
+ } catch (err) {
550
+ return {
551
+ ok: false,
552
+ kid: resolvedKid,
553
+ registry: resolver.name,
554
+ algorithm: resolvedAlg,
555
+ error: err instanceof Error ? err.message : "verification error"
556
+ };
557
+ }
558
+ }
559
+ function normalizeRequest(request) {
560
+ return {
561
+ method: request.method.toUpperCase(),
562
+ url: request.url,
563
+ headers: request.headers
564
+ };
565
+ }
566
+ function safeOrigin(url) {
567
+ try {
568
+ return new URL(url).origin;
569
+ } catch {
570
+ return void 0;
571
+ }
572
+ }
573
+ async function jwkToVerifyingKey(id, jwk, alg) {
574
+ const algorithm = alg ?? inferAlgFromJwk(jwk);
575
+ const { subtle } = await getCrypto();
576
+ const importAlg = webCryptoImportAlgFor(algorithm);
577
+ const verifyAlg = webCryptoAlgFor(algorithm);
578
+ if (!importAlg || !verifyAlg) {
579
+ return {
580
+ id,
581
+ algs: alg ? [alg] : void 0,
582
+ verify: async () => false
583
+ };
584
+ }
585
+ const key = await subtle.importKey("jwk", jwk, importAlg, false, ["verify"]);
586
+ return {
587
+ id,
588
+ algs: alg ? [alg] : void 0,
589
+ verify: async (data, signature) => {
590
+ try {
591
+ return await subtle.verify(verifyAlg, key, toArrayBuffer(signature), toArrayBuffer(data));
592
+ } catch {
593
+ return false;
594
+ }
595
+ }
596
+ };
597
+ }
598
+ function inferAlgFromJwk(jwk) {
599
+ if (jwk.kty === "OKP" && jwk.crv === "Ed25519") return "ed25519";
600
+ if (jwk.kty === "EC" && jwk.crv === "P-256") return "ecdsa-p256-sha256";
601
+ if (jwk.kty === "EC" && jwk.crv === "P-384") return "ecdsa-p384-sha384";
602
+ if (jwk.kty === "RSA") return "rsa-v1_5-sha256";
603
+ return "ecdsa-p256-sha256";
604
+ }
605
+ function webCryptoAlgFor(rfc9421Alg) {
606
+ switch (rfc9421Alg) {
607
+ case "ed25519":
608
+ return { name: "Ed25519" };
609
+ case "ecdsa-p256-sha256":
610
+ return { name: "ECDSA", hash: "SHA-256" };
611
+ case "ecdsa-p384-sha384":
612
+ return { name: "ECDSA", hash: "SHA-384" };
613
+ case "rsa-v1_5-sha256":
614
+ return { name: "RSASSA-PKCS1-v1_5" };
615
+ case "rsa-pss-sha512":
616
+ return { name: "RSA-PSS", saltLength: 64 };
617
+ default:
618
+ return null;
619
+ }
620
+ }
621
+ function webCryptoImportAlgFor(rfc9421Alg) {
622
+ switch (rfc9421Alg) {
623
+ case "ed25519":
624
+ return { name: "Ed25519" };
625
+ case "ecdsa-p256-sha256":
626
+ return { name: "ECDSA", namedCurve: "P-256" };
627
+ case "ecdsa-p384-sha384":
628
+ return { name: "ECDSA", namedCurve: "P-384" };
629
+ case "rsa-v1_5-sha256":
630
+ return { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
631
+ case "rsa-pss-sha512":
632
+ return { name: "RSA-PSS", hash: "SHA-512" };
633
+ default:
634
+ return null;
635
+ }
636
+ }
637
+ function toArrayBuffer(buf) {
638
+ const out = new ArrayBuffer(buf.byteLength);
639
+ new Uint8Array(out).set(buf);
640
+ return out;
641
+ }
642
+ function toUnixSeconds(v) {
643
+ if (typeof v === "number" && Number.isFinite(v)) return v;
644
+ if (v instanceof Date) return Math.floor(v.getTime() / 1e3);
645
+ if (typeof v === "string") {
646
+ const parsed = Date.parse(v);
647
+ if (Number.isFinite(parsed)) return Math.floor(parsed / 1e3);
648
+ }
649
+ return void 0;
650
+ }
651
+ async function getCrypto() {
652
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
653
+ return { subtle: globalThis.crypto.subtle };
654
+ }
655
+ const nodeCrypto = await import("crypto");
656
+ return { subtle: nodeCrypto.webcrypto.subtle };
657
+ }
658
+
659
+ // src/transport/ucp.ts
660
+ function extractUCPContext(request) {
661
+ const { method, url } = request;
662
+ if (!method || !url) return null;
663
+ const parsedUrl = safeParseUrl(url);
664
+ const path = parsedUrl?.pathname ?? url.split("?")[0];
665
+ const purpose = mapUCPRequestToPurpose(method, path);
666
+ const endpoint = `${method.toUpperCase()} ${path}`;
667
+ const sessionId = extractSessionId(path);
668
+ const body = request.body ?? {};
669
+ const totals = Array.isArray(body.totals) ? body.totals : void 0;
670
+ const paymentMethod = coerceString2(body.payment_method ?? body.paymentMethod);
671
+ const manifestUrl = coerceString2(body.manifest_url ?? body.manifestUrl);
672
+ const merchantDomain = extractMerchantDomain(body, parsedUrl);
673
+ return {
674
+ sessionId,
675
+ endpoint,
676
+ purpose,
677
+ merchantDomain,
678
+ totals,
679
+ paymentMethod,
680
+ manifestUrl
681
+ };
682
+ }
683
+ async function fetchUCPManifest(manifestUrl, options = {}) {
684
+ const timeoutMs = options.timeoutMs ?? 3e3;
685
+ const controller = new AbortController();
686
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
687
+ try {
688
+ const res = await fetch(manifestUrl, { signal: controller.signal });
689
+ if (!res.ok) return null;
690
+ return await res.json();
691
+ } catch {
692
+ return null;
693
+ } finally {
694
+ clearTimeout(timer);
695
+ }
696
+ }
697
+ function validateUCPManifest(manifest, options = {}) {
698
+ if (options.validator) return options.validator(manifest);
699
+ const errors = [];
700
+ if (!manifest || typeof manifest !== "object") {
701
+ return { ok: false, errors: ["manifest is not an object"] };
702
+ }
703
+ const m = manifest;
704
+ if (typeof m.version !== "string") errors.push("version is required and must be a string");
705
+ if (!Array.isArray(m.capabilities)) errors.push("capabilities must be an array");
706
+ if (!m.endpoints || typeof m.endpoints !== "object") errors.push("endpoints must be an object");
707
+ return { ok: errors.length === 0, errors };
708
+ }
709
+ function safeParseUrl(url) {
710
+ try {
711
+ return new URL(url, "http://placeholder.invalid");
712
+ } catch {
713
+ return null;
714
+ }
715
+ }
716
+ function extractSessionId(path) {
717
+ const match = path.match(/\/checkout[-_]sessions\/([^/?#]+)/);
718
+ return match?.[1];
719
+ }
720
+ function extractMerchantDomain(body, parsedUrl) {
721
+ const explicit = coerceString2(body.merchant_domain ?? body.merchantDomain);
722
+ if (explicit) return explicit;
723
+ if (parsedUrl && parsedUrl.hostname !== "placeholder.invalid") return parsedUrl.hostname;
724
+ return void 0;
725
+ }
726
+ function coerceString2(v) {
727
+ return typeof v === "string" && v.length > 0 ? v : void 0;
728
+ }
729
+
730
+ // src/transport/acp.ts
731
+ function extractACPContext(request) {
732
+ const { method, url } = request;
733
+ if (!method || !url) return null;
734
+ const path = stripQuery2(url.startsWith("http") ? new URL(url).pathname : url);
735
+ const endpoint = classifyEndpoint(method, path);
736
+ const purpose = mapACPRequestToPurpose(method, path);
737
+ const sessionId = extractSessionId2(path);
738
+ const headers = request.headers ?? {};
739
+ const signatureHeader = readHeader2(headers, "signature");
740
+ const timestampHeader = readHeader2(headers, "timestamp");
741
+ const idempotencyKey = readHeader2(headers, "idempotency-key");
742
+ const apiVersion = readHeader2(headers, "api-version");
743
+ const bearer = extractBearer(readHeader2(headers, "authorization"));
744
+ const body = request.body ?? {};
745
+ const merchantId = coerceString3(body.merchant_id ?? body.merchantId);
746
+ const totals = Array.isArray(body.totals) ? body.totals : void 0;
747
+ const fulfillmentOption = extractFulfillmentOption(body);
748
+ const paymentToken = extractPaymentToken(body);
749
+ return {
750
+ endpoint,
751
+ purpose,
752
+ sessionId,
753
+ merchantId,
754
+ apiVersion,
755
+ bearer,
756
+ signatureHeader,
757
+ timestampHeader,
758
+ idempotencyKey,
759
+ paymentToken,
760
+ totals,
761
+ fulfillmentOption,
762
+ rawBody: request.rawBody
763
+ };
764
+ }
765
+ function classifyEndpoint(method, path) {
766
+ const m = method.toUpperCase();
767
+ if (m !== "POST") return "unknown";
768
+ if (/^\/agentic_commerce\/delegate_payment\/?$/.test(path)) return "delegate_payment";
769
+ if (/^\/checkout_sessions\/?$/.test(path)) return "checkout_sessions.create";
770
+ if (/^\/checkout_sessions\/[^/]+\/?$/.test(path)) return "checkout_sessions.update";
771
+ if (/^\/checkout_sessions\/[^/]+\/complete\/?$/.test(path)) return "checkout_sessions.complete";
772
+ if (/^\/checkout_sessions\/[^/]+\/cancel\/?$/.test(path)) return "checkout_sessions.cancel";
773
+ return "unknown";
774
+ }
775
+ function extractSessionId2(path) {
776
+ const match = path.match(/\/checkout_sessions\/([^/?#]+)/);
777
+ return match?.[1];
778
+ }
779
+ function extractBearer(authHeader) {
780
+ if (!authHeader) return void 0;
781
+ const match = authHeader.match(/^Bearer\s+(.+)$/i);
782
+ return match ? match[1].trim() : void 0;
783
+ }
784
+ function extractPaymentToken(body) {
785
+ const paymentData = body.payment_data;
786
+ if (!paymentData) return void 0;
787
+ const raw = coerceString3(paymentData.token);
788
+ const provider = coerceString3(paymentData.provider);
789
+ if (!raw) return { raw: void 0, type: null, provider };
790
+ const type = classifyPaymentToken(raw);
791
+ return { raw, type, provider };
792
+ }
793
+ function classifyPaymentToken(token) {
794
+ if (token.startsWith("spt_")) return "stripe-spt";
795
+ if (token.startsWith("vt_")) return "acp-vt";
796
+ return "other";
797
+ }
798
+ function extractFulfillmentOption(body) {
799
+ const direct = coerceString3(body.fulfillment_option ?? body.fulfillmentOption);
800
+ if (direct) return direct;
801
+ const options = body.fulfillment_options;
802
+ if (Array.isArray(options) && options.length > 0) {
803
+ const first = options[0];
804
+ if (first && typeof first === "object") {
805
+ const id = coerceString3(first.id);
806
+ if (id) return id;
807
+ }
808
+ }
809
+ return void 0;
810
+ }
811
+ function readHeader2(headers, name) {
812
+ for (const key of Object.keys(headers)) {
813
+ if (key.toLowerCase() === name) {
814
+ const raw = headers[key];
815
+ if (typeof raw === "string") return raw;
816
+ if (Array.isArray(raw)) return raw[0];
817
+ }
818
+ }
819
+ return void 0;
820
+ }
821
+ function stripQuery2(path) {
822
+ const q = path.indexOf("?");
823
+ return q === -1 ? path : path.slice(0, q);
824
+ }
825
+ function coerceString3(v) {
826
+ return typeof v === "string" && v.length > 0 ? v : void 0;
827
+ }
828
+
829
+ // src/transport/vi.ts
830
+ var import_decode = require("@sd-jwt/decode");
831
+ var import_node_crypto = require("crypto");
832
+ function extractVIClaims(sdJwtCompact) {
833
+ if (!sdJwtCompact || typeof sdJwtCompact !== "string") return null;
834
+ let decoded;
835
+ try {
836
+ decoded = (0, import_decode.decodeSdJwtSync)(sdJwtCompact, sha256Sync);
837
+ } catch {
838
+ return null;
839
+ }
840
+ const split = safeSplit(sdJwtCompact);
841
+ const payload = decoded.jwt?.payload ?? {};
842
+ const disclosures = decoded.disclosures ?? [];
843
+ const claims = applyDisclosures(
844
+ payload,
845
+ disclosures
846
+ );
847
+ const mandateType = coerceMandateType(
848
+ claims.mandate_type ?? claims.mandateType ?? payload.mandate_type ?? payload.mandateType
849
+ );
850
+ if (!mandateType) return null;
851
+ const kid = coerceString4(
852
+ decoded.jwt?.header?.kid ?? claims.kid ?? payload.kid
853
+ );
854
+ const executionMode = coerceExecutionMode(claims.execution_mode ?? claims.executionMode);
855
+ const credentialProvider = coerceString4(claims.iss ?? payload.iss);
856
+ const constraints = extractConstraints(
857
+ claims.constraints ?? claims.default_constraints ?? {}
858
+ );
859
+ const transactionId = coerceString4(claims.transaction_id ?? claims.transactionId);
860
+ const checkoutHash = coerceString4(
861
+ claims.checkout_hash ?? claims.conditional_transaction_id ?? claims.payment_reference?.checkout_hash
862
+ );
863
+ return {
864
+ mandateType,
865
+ kid,
866
+ executionMode,
867
+ credentialProvider,
868
+ constraints,
869
+ checkoutHash,
870
+ transactionId,
871
+ rawLayers: split
872
+ };
873
+ }
874
+ function safeSplit(compact) {
875
+ try {
876
+ const { jwt, kbJwt } = (0, import_decode.splitSdJwt)(compact);
877
+ return { l3: jwt, l2: kbJwt };
878
+ } catch {
879
+ return {};
880
+ }
881
+ }
882
+ function applyDisclosures(payload, disclosures) {
883
+ const result = { ...payload };
884
+ for (const d of disclosures) {
885
+ if (d.key && d.value !== void 0 && !(d.key in result)) {
886
+ result[d.key] = d.value;
887
+ }
888
+ }
889
+ return result;
890
+ }
891
+ function extractConstraints(raw) {
892
+ return {
893
+ allowedMerchants: toAllowedPartyArray(raw.allowed_merchants ?? raw.allowedMerchants),
894
+ allowedPayees: toAllowedPartyArray(raw.allowed_payees ?? raw.allowedPayees),
895
+ lineItems: toLineItemArray(raw.line_items ?? raw.lineItems),
896
+ paymentAmount: toPaymentAmount(raw.payment_amount ?? raw.paymentAmount),
897
+ budgetLimit: toBudgetLimit(raw.budget_limit ?? raw.budgetLimit ?? raw.budget),
898
+ recurrence: toRecurrence(raw.recurrence),
899
+ agentRecurrence: toRecurrence(raw.agent_recurrence ?? raw.agentRecurrence)
900
+ };
901
+ }
902
+ function toAllowedPartyArray(v) {
903
+ if (!Array.isArray(v)) return void 0;
904
+ const out = [];
905
+ for (const item of v) {
906
+ if (item && typeof item === "object") {
907
+ const r = item;
908
+ out.push({
909
+ id: coerceString4(r.id),
910
+ name: coerceString4(r.name),
911
+ website: coerceString4(r.website)
912
+ });
913
+ }
914
+ }
915
+ return out.length > 0 ? out : void 0;
916
+ }
917
+ function toLineItemArray(v) {
918
+ if (!Array.isArray(v)) return void 0;
919
+ const out = [];
920
+ for (const item of v) {
921
+ if (item && typeof item === "object") {
922
+ const r = item;
923
+ const acc = r.acceptable_items ?? r.acceptableItems;
924
+ out.push({
925
+ id: coerceString4(r.id),
926
+ acceptableItems: Array.isArray(acc) ? acc.filter((a) => typeof a === "string") : void 0,
927
+ quantity: coerceNumber2(r.quantity)
928
+ });
929
+ }
930
+ }
931
+ return out.length > 0 ? out : void 0;
932
+ }
933
+ function toPaymentAmount(v) {
934
+ if (!v || typeof v !== "object") return void 0;
935
+ const r = v;
936
+ return {
937
+ currency: coerceString4(r.currency),
938
+ min: coerceNumber2(r.min),
939
+ max: coerceNumber2(r.max)
940
+ };
941
+ }
942
+ function toBudgetLimit(v) {
943
+ if (!v || typeof v !== "object") return void 0;
944
+ const r = v;
945
+ return {
946
+ currency: coerceString4(r.currency),
947
+ max: coerceNumber2(r.max)
948
+ };
949
+ }
950
+ function toRecurrence(v) {
951
+ if (!v || typeof v !== "object") return void 0;
952
+ const r = v;
953
+ return {
954
+ frequency: coerceString4(r.frequency),
955
+ startDate: coerceString4(r.start_date ?? r.startDate),
956
+ endDate: coerceString4(r.end_date ?? r.endDate),
957
+ maxOccurrences: coerceNumber2(r.max_occurrences ?? r.maxOccurrences)
958
+ };
959
+ }
960
+ function coerceMandateType(v) {
961
+ if (v === "checkout" || v === "payment" || v === "checkout.open" || v === "payment.open") {
962
+ return v;
963
+ }
964
+ return null;
965
+ }
966
+ function coerceExecutionMode(v) {
967
+ return v === "Immediate" || v === "Autonomous" || v === "Both" ? v : void 0;
968
+ }
969
+ function coerceString4(v) {
970
+ return typeof v === "string" && v.length > 0 ? v : void 0;
971
+ }
972
+ function coerceNumber2(v) {
973
+ if (typeof v === "number" && Number.isFinite(v)) return v;
974
+ if (typeof v === "string") {
975
+ const n = Number(v);
976
+ return Number.isFinite(n) ? n : void 0;
977
+ }
978
+ return void 0;
979
+ }
980
+ function sha256Sync(data) {
981
+ const buf = typeof data === "string" ? Buffer.from(data, "utf-8") : Buffer.from(new Uint8Array(data));
982
+ const hash = (0, import_node_crypto.createHash)("sha256").update(buf).digest();
983
+ return new Uint8Array(hash.buffer, hash.byteOffset, hash.byteLength);
984
+ }
985
+
986
+ // src/transport/stripe-webhook.ts
987
+ var import_node_crypto2 = require("crypto");
988
+ function verifyStripeWebhook(payload, signatureHeader, secret, options = {}) {
989
+ if (!signatureHeader) return { ok: false, error: "missing Stripe-Signature header" };
990
+ if (!secret) return { ok: false, error: "missing webhook secret" };
991
+ const parsed = parseStripeSignature(signatureHeader);
992
+ if (!parsed.timestamp) return { ok: false, error: "malformed Stripe-Signature (missing t=)" };
993
+ if (parsed.v1Signatures.length === 0) {
994
+ return { ok: false, error: "malformed Stripe-Signature (no v1=)" };
995
+ }
996
+ const tolerance = options.toleranceSec ?? 300;
997
+ const now = options.now ? options.now() : Math.floor(Date.now() / 1e3);
998
+ if (Math.abs(now - parsed.timestamp) > tolerance) {
999
+ return {
1000
+ ok: false,
1001
+ timestamp: parsed.timestamp,
1002
+ error: `timestamp outside tolerance (${tolerance}s)`
1003
+ };
1004
+ }
1005
+ const signedPayload = `${parsed.timestamp}.${payload}`;
1006
+ const expected = (0, import_node_crypto2.createHmac)("sha256", secret).update(signedPayload).digest();
1007
+ for (const candidateHex of parsed.v1Signatures) {
1008
+ const candidate = hexToBuffer(candidateHex);
1009
+ if (!candidate) continue;
1010
+ if (candidate.length !== expected.length) continue;
1011
+ if ((0, import_node_crypto2.timingSafeEqual)(candidate, expected)) {
1012
+ return { ok: true, timestamp: parsed.timestamp };
1013
+ }
1014
+ }
1015
+ return { ok: false, timestamp: parsed.timestamp, error: "signature mismatch" };
1016
+ }
1017
+ function parseStripeSignature(header) {
1018
+ let timestamp = null;
1019
+ const v1Signatures = [];
1020
+ for (const part of header.split(",")) {
1021
+ const [rawKey, rawValue] = part.split("=");
1022
+ if (!rawKey || !rawValue) continue;
1023
+ const key = rawKey.trim();
1024
+ const value = rawValue.trim();
1025
+ if (key === "t") {
1026
+ const n = Number(value);
1027
+ if (Number.isFinite(n)) timestamp = n;
1028
+ } else if (key === "v1") {
1029
+ v1Signatures.push(value);
1030
+ }
1031
+ }
1032
+ return { timestamp, v1Signatures };
1033
+ }
1034
+ function hexToBuffer(hex) {
1035
+ if (!/^[0-9a-fA-F]+$/.test(hex) || hex.length % 2 !== 0) return null;
1036
+ return Buffer.from(hex, "hex");
1037
+ }
1038
+
1039
+ // src/transport/constraint-eval.ts
1040
+ function evaluateVIConstraints(input) {
1041
+ const { constraints, transaction } = input;
1042
+ const results = {};
1043
+ if (constraints.allowedMerchants && constraints.allowedMerchants.length > 0) {
1044
+ results.merchant = evaluateAllowlist(
1045
+ "merchant",
1046
+ constraints.allowedMerchants,
1047
+ transaction.merchant
1048
+ );
1049
+ }
1050
+ if (constraints.allowedPayees && constraints.allowedPayees.length > 0) {
1051
+ results.payee = evaluateAllowlist("payee", constraints.allowedPayees, transaction.payee);
1052
+ }
1053
+ if (constraints.lineItems && constraints.lineItems.length > 0) {
1054
+ results.lineItems = evaluateLineItems(constraints.lineItems, transaction.lineItems ?? []);
1055
+ }
1056
+ if (constraints.paymentAmount) {
1057
+ results.amount = evaluatePaymentAmount(constraints.paymentAmount, transaction);
1058
+ }
1059
+ const reasons = [];
1060
+ let ok = true;
1061
+ for (const [key, r] of Object.entries(results)) {
1062
+ if (!r.ok) {
1063
+ ok = false;
1064
+ reasons.push(r.reason ?? `${key} failed`);
1065
+ }
1066
+ }
1067
+ return { ok, results, reasons };
1068
+ }
1069
+ function evaluatePaymentMethodAllowlist(input) {
1070
+ const allow = input.allowedMethods ?? [];
1071
+ if (allow.length === 0) return { ok: true };
1072
+ if (!input.requestedMethod) {
1073
+ return { ok: false, reason: "no payment method in request; allowlist configured" };
1074
+ }
1075
+ const lowered = input.requestedMethod.toLowerCase();
1076
+ const allowed = allow.some((m) => m.toLowerCase() === lowered);
1077
+ if (!allowed) {
1078
+ return {
1079
+ ok: false,
1080
+ reason: `payment method "${input.requestedMethod}" not in allowlist [${allow.join(", ")}]`
1081
+ };
1082
+ }
1083
+ return { ok: true };
1084
+ }
1085
+ function evaluateSpendingLimit(input) {
1086
+ const { limit, requested } = input;
1087
+ if (!limit || typeof limit.amount !== "number") return { ok: true };
1088
+ if (!requested || typeof requested.amount !== "number") return { ok: true };
1089
+ if (limit.currency && requested.currency && limit.currency !== requested.currency) {
1090
+ return {
1091
+ ok: false,
1092
+ reason: `currency mismatch: limit ${limit.currency} vs requested ${requested.currency}`
1093
+ };
1094
+ }
1095
+ if (requested.amount > limit.amount) {
1096
+ return {
1097
+ ok: false,
1098
+ reason: `requested ${requested.amount} ${requested.currency ?? ""} exceeds limit ${limit.amount} ${limit.currency ?? ""}`.trim()
1099
+ };
1100
+ }
1101
+ return { ok: true };
1102
+ }
1103
+ function evaluateAllowlist(kind, allowlist, actual) {
1104
+ if (!actual || !actual.id && !actual.website) {
1105
+ return { ok: false, reason: `no ${kind} in transaction; allowlist configured` };
1106
+ }
1107
+ for (const entry of allowlist) {
1108
+ if (entry.id && actual.id && entry.id === actual.id) return { ok: true };
1109
+ if (entry.website && actual.website && domainsMatch(entry.website, actual.website)) {
1110
+ return { ok: true };
1111
+ }
1112
+ }
1113
+ const allowedDescriptors = allowlist.map(describeParty).join(", ");
1114
+ const actualDescriptor = describeParty(actual);
1115
+ return {
1116
+ ok: false,
1117
+ reason: `${kind} ${actualDescriptor} not in allowlist [${allowedDescriptors}]`
1118
+ };
1119
+ }
1120
+ function evaluateLineItems(allowlist, actualItems) {
1121
+ if (actualItems.length === 0) {
1122
+ return { ok: false, reason: "no line items in transaction; allowlist configured" };
1123
+ }
1124
+ const reasons = [];
1125
+ for (const item of actualItems) {
1126
+ const match = allowlist.find(
1127
+ (a) => a.id && a.id === item.id || (a.acceptableItems ?? []).includes(item.id ?? "")
1128
+ );
1129
+ if (!match) {
1130
+ reasons.push(`line item "${item.id ?? "(unnamed)"}" not in allowlist`);
1131
+ continue;
1132
+ }
1133
+ if (typeof match.quantity === "number" && typeof item.quantity === "number" && item.quantity > match.quantity) {
1134
+ reasons.push(
1135
+ `line item "${item.id}" quantity ${item.quantity} exceeds allowed ${match.quantity}`
1136
+ );
1137
+ }
1138
+ }
1139
+ return reasons.length === 0 ? { ok: true } : { ok: false, reason: reasons.join("; ") };
1140
+ }
1141
+ function evaluatePaymentAmount(bound, transaction) {
1142
+ if (typeof transaction.amount !== "number") {
1143
+ return { ok: false, reason: "no amount in transaction; paymentAmount bound configured" };
1144
+ }
1145
+ if (bound.currency && transaction.currency && bound.currency !== transaction.currency) {
1146
+ return {
1147
+ ok: false,
1148
+ reason: `currency mismatch: bound ${bound.currency} vs transaction ${transaction.currency}`
1149
+ };
1150
+ }
1151
+ if (typeof bound.min === "number" && transaction.amount < bound.min) {
1152
+ return {
1153
+ ok: false,
1154
+ reason: `amount ${transaction.amount} below min ${bound.min}`
1155
+ };
1156
+ }
1157
+ if (typeof bound.max === "number" && transaction.amount > bound.max) {
1158
+ return {
1159
+ ok: false,
1160
+ reason: `amount ${transaction.amount} above max ${bound.max}`
1161
+ };
1162
+ }
1163
+ return { ok: true };
1164
+ }
1165
+ function domainsMatch(allow, actual) {
1166
+ const a = normalizeDomain(allow);
1167
+ const b = normalizeDomain(actual);
1168
+ return a === b || b.endsWith(`.${a}`);
1169
+ }
1170
+ function normalizeDomain(value) {
1171
+ try {
1172
+ const withScheme = /^https?:\/\//.test(value) ? value : `https://${value}`;
1173
+ return new URL(withScheme).hostname.toLowerCase();
1174
+ } catch {
1175
+ return value.toLowerCase();
1176
+ }
1177
+ }
1178
+ function describeParty(party) {
1179
+ if (party.id) return `id:${party.id}`;
1180
+ if (party.website) return party.website;
1181
+ if (party.name) return party.name;
1182
+ return "(unnamed)";
1183
+ }
1184
+
1185
+ // src/transport/identity-binding.ts
1186
+ async function bindIdentity(claims, resolver) {
1187
+ const resolutions = [];
1188
+ for (const claim2 of claims) {
1189
+ if (!claim2.value) {
1190
+ resolutions.push({ claim: claim2, agentId: null });
1191
+ continue;
1192
+ }
1193
+ const agentId = await resolver(claim2);
1194
+ resolutions.push({ claim: claim2, agentId });
1195
+ }
1196
+ const resolvedIds = resolutions.map((r) => r.agentId).filter((id) => typeof id === "string" && id.length > 0);
1197
+ const unique = Array.from(new Set(resolvedIds));
1198
+ const mismatchAcrossLayers = unique.length > 1;
1199
+ const mappedAstraSyncAgentId = unique.length === 1 ? unique[0] : void 0;
1200
+ return {
1201
+ claims,
1202
+ mappedAstraSyncAgentId,
1203
+ mismatchAcrossLayers,
1204
+ resolutions
1205
+ };
1206
+ }
1207
+ var claim = {
1208
+ viKid: (value) => ({ protocol: "vi", field: "kid", value }),
1209
+ ap2AgentId: (value) => ({ protocol: "ap2", field: "agent_id", value }),
1210
+ acpBearer: (value) => ({ protocol: "acp", field: "bearer", value }),
1211
+ mppSource: (value) => ({ protocol: "mpp", field: "source", value }),
1212
+ x402Wallet: (value) => ({ protocol: "x402", field: "wallet", value }),
1213
+ agentPayKid: (value) => ({ protocol: "agentpay", field: "kid", value }),
1214
+ tapKid: (value) => ({ protocol: "tap", field: "kid", value }),
1215
+ webBotAuthKid: (value) => ({
1216
+ protocol: "webbotauth",
1217
+ field: "kid",
1218
+ value
1219
+ })
1220
+ };
1221
+
1222
+ // src/transport/ap2.ts
1223
+ var import_decode2 = require("@sd-jwt/decode");
1224
+ var import_node_crypto3 = require("crypto");
1225
+ function extractAP2Mandate(sdJwtCompact) {
1226
+ if (!sdJwtCompact || typeof sdJwtCompact !== "string") return null;
1227
+ let decoded;
1228
+ try {
1229
+ decoded = (0, import_decode2.decodeSdJwtSync)(sdJwtCompact, sha256Sync2);
1230
+ } catch {
1231
+ return null;
1232
+ }
1233
+ const payload = decoded.jwt?.payload ?? {};
1234
+ const disclosures = decoded.disclosures ?? [];
1235
+ const claims = applyDisclosures2(
1236
+ payload,
1237
+ disclosures
1238
+ );
1239
+ const type = coerceMandateType2(claims.type ?? claims.mandate_type ?? claims.mandateType);
1240
+ if (!type) return null;
1241
+ if (type === "intent_mandate") return buildIntent(claims);
1242
+ if (type === "cart_mandate") return buildCart(claims);
1243
+ return buildPayment(claims);
1244
+ }
1245
+ function extractAP2Mandates(input) {
1246
+ const intent = input.intent ? extractAP2Mandate(input.intent) : null;
1247
+ const cart = input.cart ? extractAP2Mandate(input.cart) : null;
1248
+ const payment = input.payment ? extractAP2Mandate(input.payment) : null;
1249
+ return {
1250
+ intent: intent ?? void 0,
1251
+ cart: cart ?? void 0,
1252
+ payment: payment ?? void 0,
1253
+ rawLayers: {
1254
+ intentJwt: input.intent,
1255
+ cartJwt: input.cart,
1256
+ paymentJwt: input.payment
1257
+ }
1258
+ };
1259
+ }
1260
+ function buildIntent(claims) {
1261
+ return {
1262
+ type: "intent_mandate",
1263
+ agent_id: coerceString5(claims.agent_id ?? claims.agentId),
1264
+ user_id: coerceString5(claims.user_id ?? claims.userId ?? claims.sub),
1265
+ merchant_category: coerceString5(claims.merchant_category ?? claims.merchantCategory),
1266
+ allowedMerchantDomains: toStringArray(
1267
+ claims.allowed_merchant_domains ?? claims.allowedMerchantDomains
1268
+ ),
1269
+ paymentMethods: toStringArray(claims.payment_methods ?? claims.paymentMethods),
1270
+ expires: coerceString5(claims.expires ?? claims.exp),
1271
+ payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
1272
+ raw: claims
1273
+ };
1274
+ }
1275
+ function buildCart(claims) {
1276
+ return {
1277
+ type: "cart_mandate",
1278
+ agent_id: coerceString5(claims.agent_id ?? claims.agentId),
1279
+ intent_mandate_id: coerceString5(claims.intent_mandate_id ?? claims.intentMandateId),
1280
+ merchant_id: coerceString5(claims.merchant_id ?? claims.merchantId),
1281
+ line_items: toLineItems(claims.line_items ?? claims.lineItems),
1282
+ payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
1283
+ expires: coerceString5(claims.expires ?? claims.exp),
1284
+ raw: claims
1285
+ };
1286
+ }
1287
+ function buildPayment(claims) {
1288
+ return {
1289
+ type: "payment_mandate",
1290
+ agent_id: coerceString5(claims.agent_id ?? claims.agentId),
1291
+ cart_mandate_id: coerceString5(claims.cart_mandate_id ?? claims.cartMandateId),
1292
+ payment_method: coerceString5(claims.payment_method ?? claims.paymentMethod),
1293
+ payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
1294
+ credential_provider: coerceString5(claims.credential_provider ?? claims.credentialProvider),
1295
+ raw: claims
1296
+ };
1297
+ }
1298
+ function toPaymentDetails(v) {
1299
+ if (!v || typeof v !== "object") return void 0;
1300
+ const r = v;
1301
+ const amount = r.amount;
1302
+ return {
1303
+ amount: amount ? {
1304
+ value: coerceStringOrNumber(amount.value),
1305
+ currency: coerceString5(amount.currency)
1306
+ } : void 0,
1307
+ label: coerceString5(r.label)
1308
+ };
1309
+ }
1310
+ function toLineItems(v) {
1311
+ if (!Array.isArray(v)) return void 0;
1312
+ const items = [];
1313
+ for (const item of v) {
1314
+ if (!item || typeof item !== "object") continue;
1315
+ const r = item;
1316
+ const price = r.price;
1317
+ items.push({
1318
+ id: coerceString5(r.id),
1319
+ quantity: coerceNumber3(r.quantity),
1320
+ price: price ? {
1321
+ value: coerceStringOrNumber(price.value),
1322
+ currency: coerceString5(price.currency)
1323
+ } : void 0
1324
+ });
1325
+ }
1326
+ return items.length > 0 ? items : void 0;
1327
+ }
1328
+ function toStringArray(v) {
1329
+ if (!Array.isArray(v)) return void 0;
1330
+ const out = v.filter((i) => typeof i === "string" && i.length > 0);
1331
+ return out.length > 0 ? out : void 0;
1332
+ }
1333
+ function applyDisclosures2(payload, disclosures) {
1334
+ const result = { ...payload };
1335
+ for (const d of disclosures) {
1336
+ if (d.key && d.value !== void 0 && !(d.key in result)) {
1337
+ result[d.key] = d.value;
1338
+ }
1339
+ }
1340
+ return result;
1341
+ }
1342
+ function coerceMandateType2(v) {
1343
+ if (v === "intent_mandate" || v === "cart_mandate" || v === "payment_mandate") return v;
1344
+ return null;
1345
+ }
1346
+ function coerceString5(v) {
1347
+ return typeof v === "string" && v.length > 0 ? v : void 0;
1348
+ }
1349
+ function coerceNumber3(v) {
1350
+ if (typeof v === "number" && Number.isFinite(v)) return v;
1351
+ if (typeof v === "string") {
1352
+ const n = Number(v);
1353
+ return Number.isFinite(n) ? n : void 0;
1354
+ }
1355
+ return void 0;
1356
+ }
1357
+ function coerceStringOrNumber(v) {
1358
+ if (typeof v === "number" && Number.isFinite(v)) return v;
1359
+ if (typeof v === "string" && v.length > 0) return v;
1360
+ return void 0;
1361
+ }
1362
+ function sha256Sync2(data) {
1363
+ const buf = typeof data === "string" ? Buffer.from(data, "utf-8") : Buffer.from(new Uint8Array(data));
1364
+ const hash = (0, import_node_crypto3.createHash)("sha256").update(buf).digest();
1365
+ return new Uint8Array(hash.buffer, hash.byteOffset, hash.byteLength);
1366
+ }
1367
+
1368
+ // src/transport/ap2-verify.ts
1369
+ function verifyAP2Chain(input) {
1370
+ const { triple } = input;
1371
+ const errors = [];
1372
+ const intentPresent = triple.intent !== void 0;
1373
+ const cartRefOk = checkCartRef(triple, errors);
1374
+ const paymentRefOk = checkPaymentRef(triple, errors);
1375
+ const { ok: agentIdContinuity, agentId } = checkAgentContinuity(triple, errors);
1376
+ const paymentMethodAllowed = checkPaymentMethod(triple, errors);
1377
+ const totalsConsistent = checkTotals(triple, errors);
1378
+ const expiryOk = checkExpiries(triple, input.clockSkewSec ?? 300, input.now, errors);
1379
+ const ok = cartRefOk && paymentRefOk && agentIdContinuity && paymentMethodAllowed && totalsConsistent && expiryOk;
1380
+ return {
1381
+ ok,
1382
+ checks: {
1383
+ intentPresent,
1384
+ cartRefOk,
1385
+ paymentRefOk,
1386
+ agentIdContinuity,
1387
+ paymentMethodAllowed,
1388
+ totalsConsistent,
1389
+ expiryOk
1390
+ },
1391
+ agentId,
1392
+ errors
1393
+ };
1394
+ }
1395
+ function checkCartRef(triple, errors) {
1396
+ const cart = triple.cart;
1397
+ if (!cart) return true;
1398
+ if (!cart.intent_mandate_id) return true;
1399
+ const intentId = triple.intent?.raw?.id;
1400
+ if (intentId && cart.intent_mandate_id !== intentId) {
1401
+ errors.push(
1402
+ `cart.intent_mandate_id (${cart.intent_mandate_id}) does not match intent.id (${intentId})`
1403
+ );
1404
+ return false;
1405
+ }
1406
+ return true;
1407
+ }
1408
+ function checkPaymentRef(triple, errors) {
1409
+ const payment = triple.payment;
1410
+ if (!payment) return true;
1411
+ if (!payment.cart_mandate_id) return true;
1412
+ const cartId = triple.cart?.raw?.id;
1413
+ if (cartId && payment.cart_mandate_id !== cartId) {
1414
+ errors.push(
1415
+ `payment.cart_mandate_id (${payment.cart_mandate_id}) does not match cart.id (${cartId})`
1416
+ );
1417
+ return false;
1418
+ }
1419
+ return true;
1420
+ }
1421
+ function checkAgentContinuity(triple, errors) {
1422
+ const ids = [triple.intent?.agent_id, triple.cart?.agent_id, triple.payment?.agent_id].filter(
1423
+ (id) => typeof id === "string" && id.length > 0
1424
+ );
1425
+ if (ids.length === 0) return { ok: true };
1426
+ const unique = new Set(ids);
1427
+ if (unique.size > 1) {
1428
+ errors.push(`agent_id mismatch across mandates: ${Array.from(unique).join(", ")}`);
1429
+ return { ok: false, agentId: void 0 };
1430
+ }
1431
+ return { ok: true, agentId: ids[0] };
1432
+ }
1433
+ function checkPaymentMethod(triple, errors) {
1434
+ const paymentMethod = triple.payment?.payment_method;
1435
+ const allowed = triple.intent?.paymentMethods;
1436
+ if (!paymentMethod || !allowed || allowed.length === 0) return true;
1437
+ if (!allowed.includes(paymentMethod)) {
1438
+ errors.push(
1439
+ `payment_method "${paymentMethod}" not in intent.paymentMethods [${allowed.join(", ")}]`
1440
+ );
1441
+ return false;
1442
+ }
1443
+ return true;
1444
+ }
1445
+ function checkTotals(triple, errors) {
1446
+ const intentTotal = toNumericAmount(triple.intent?.payment_details_total);
1447
+ const cartTotal = toNumericAmount(triple.cart?.payment_details_total);
1448
+ const paymentTotal = toNumericAmount(triple.payment?.payment_details_total);
1449
+ if (intentTotal && cartTotal && intentTotal.currency === cartTotal.currency) {
1450
+ if (cartTotal.value > intentTotal.value) {
1451
+ errors.push(
1452
+ `cart total ${cartTotal.value} ${cartTotal.currency} exceeds intent cap ${intentTotal.value}`
1453
+ );
1454
+ return false;
1455
+ }
1456
+ }
1457
+ if (cartTotal && paymentTotal && cartTotal.currency === paymentTotal.currency) {
1458
+ if (paymentTotal.value > cartTotal.value) {
1459
+ errors.push(
1460
+ `payment total ${paymentTotal.value} ${paymentTotal.currency} exceeds cart total ${cartTotal.value}`
1461
+ );
1462
+ return false;
1463
+ }
1464
+ }
1465
+ return true;
1466
+ }
1467
+ function checkExpiries(triple, toleranceSec, nowFn, errors) {
1468
+ const now = nowFn ? nowFn() : Math.floor(Date.now() / 1e3);
1469
+ let ok = true;
1470
+ for (const [name, mandate] of [
1471
+ ["intent", triple.intent],
1472
+ ["cart", triple.cart]
1473
+ ]) {
1474
+ if (!mandate?.expires) continue;
1475
+ const parsed = parseExpiry(mandate.expires);
1476
+ if (parsed === null) {
1477
+ errors.push(`${name}.expires unparseable`);
1478
+ ok = false;
1479
+ continue;
1480
+ }
1481
+ if (now > parsed + toleranceSec) {
1482
+ errors.push(`${name} mandate expired at ${mandate.expires}`);
1483
+ ok = false;
1484
+ }
1485
+ }
1486
+ return ok;
1487
+ }
1488
+ function toNumericAmount(total) {
1489
+ if (!total?.amount?.value || !total.amount.currency) return null;
1490
+ const n = typeof total.amount.value === "string" ? Number(total.amount.value) : total.amount.value;
1491
+ if (!Number.isFinite(n)) return null;
1492
+ return { value: n, currency: total.amount.currency };
1493
+ }
1494
+ function parseExpiry(value) {
1495
+ const asInt = Number(value);
1496
+ if (Number.isFinite(asInt) && asInt > 0) {
1497
+ return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
1498
+ }
1499
+ const parsedDate = Date.parse(value);
1500
+ if (Number.isFinite(parsedDate)) return Math.floor(parsedDate / 1e3);
1501
+ return null;
1502
+ }
1503
+
1504
+ // src/transport/acp-verify.ts
1505
+ async function verifyACPSignature(input) {
1506
+ if (!input.signatureHeader) {
1507
+ return { ok: false, error: "missing Signature header" };
1508
+ }
1509
+ const freshness = checkTimestamp(input.timestampHeader, input.clockSkewSec ?? 300, input.now);
1510
+ if (!freshness.ok) {
1511
+ return { ok: false, error: freshness.error, timestampStale: true };
1512
+ }
1513
+ const signatureBytes = decodeBase64(input.signatureHeader);
1514
+ if (!signatureBytes) {
1515
+ return { ok: false, error: "signature header is not valid base64" };
1516
+ }
1517
+ const bodyBytes = new TextEncoder().encode(input.rawBody);
1518
+ const { subtle } = await getSubtle();
1519
+ for (const candidate of input.candidateKeys) {
1520
+ const declaredAlg = normalizeAlgorithm(candidate.alg);
1521
+ const algsToTry = declaredAlg && declaredAlg !== "unsupported" ? [declaredAlg] : ["ed25519", "es256"];
1522
+ for (const alg of algsToTry) {
1523
+ try {
1524
+ const verified = await tryVerify(subtle, candidate.jwk, signatureBytes, bodyBytes, alg);
1525
+ if (verified) return { ok: true, algorithm: alg };
1526
+ } catch {
1527
+ }
1528
+ }
1529
+ }
1530
+ return {
1531
+ ok: false,
1532
+ algorithm: "unsupported",
1533
+ error: "no candidate key verified the signature under Ed25519 or ES256"
1534
+ };
1535
+ }
1536
+ async function tryVerify(subtle, jwk, signature, body, alg) {
1537
+ if (alg === "ed25519") {
1538
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519") return false;
1539
+ const key = await subtle.importKey("jwk", jwk, { name: "Ed25519" }, false, [
1540
+ "verify"
1541
+ ]);
1542
+ return await subtle.verify({ name: "Ed25519" }, key, toBuf(signature), toBuf(body));
1543
+ }
1544
+ if (alg === "es256") {
1545
+ if (jwk.kty !== "EC" || jwk.crv !== "P-256") return false;
1546
+ const key = await subtle.importKey(
1547
+ "jwk",
1548
+ jwk,
1549
+ { name: "ECDSA", namedCurve: "P-256" },
1550
+ false,
1551
+ ["verify"]
1552
+ );
1553
+ return await subtle.verify(
1554
+ { name: "ECDSA", hash: "SHA-256" },
1555
+ key,
1556
+ toBuf(signature),
1557
+ toBuf(body)
1558
+ );
1559
+ }
1560
+ return false;
1561
+ }
1562
+ function toBuf(bytes) {
1563
+ const out = new ArrayBuffer(bytes.byteLength);
1564
+ new Uint8Array(out).set(bytes);
1565
+ return out;
1566
+ }
1567
+ function checkTimestamp(headerValue, toleranceSec, nowFn) {
1568
+ if (!headerValue) return { ok: false, error: "missing Timestamp header" };
1569
+ const ts = parseTimestamp(headerValue);
1570
+ if (ts === null) return { ok: false, error: "unparseable Timestamp header" };
1571
+ const now = nowFn ? nowFn() : Math.floor(Date.now() / 1e3);
1572
+ if (Math.abs(now - ts) > toleranceSec) {
1573
+ return { ok: false, error: `timestamp outside ${toleranceSec}s tolerance` };
1574
+ }
1575
+ return { ok: true };
1576
+ }
1577
+ function parseTimestamp(value) {
1578
+ const asInt = Number(value);
1579
+ if (Number.isFinite(asInt) && asInt > 0) {
1580
+ return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
1581
+ }
1582
+ const parsedDate = Date.parse(value);
1583
+ if (Number.isFinite(parsedDate)) return Math.floor(parsedDate / 1e3);
1584
+ return null;
1585
+ }
1586
+ function normalizeAlgorithm(alg) {
1587
+ if (!alg) return void 0;
1588
+ const lowered = alg.toLowerCase();
1589
+ if (lowered === "ed25519" || lowered === "eddsa") return "ed25519";
1590
+ if (lowered === "es256" || lowered.startsWith("ecdsa-p256")) return "es256";
1591
+ return "unsupported";
1592
+ }
1593
+ function decodeBase64(value) {
1594
+ try {
1595
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
1596
+ const pad = normalized.length % 4 === 0 ? "" : "=".repeat(4 - normalized.length % 4);
1597
+ return new Uint8Array(Buffer.from(normalized + pad, "base64"));
1598
+ } catch {
1599
+ return null;
1600
+ }
1601
+ }
1602
+ async function getSubtle() {
1603
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
1604
+ return { subtle: globalThis.crypto.subtle };
1605
+ }
1606
+ const nodeCrypto = await import("crypto");
1607
+ return { subtle: nodeCrypto.webcrypto.subtle };
1608
+ }
1609
+
1610
+ // src/transport/mpp.ts
1611
+ var import_mppx = require("mppx");
1612
+ function extractMPPFromRequest(request) {
1613
+ const auth = readHeader3(request.headers, "authorization");
1614
+ if (!auth || !/^\s*Payment\s+/i.test(auth)) return null;
1615
+ try {
1616
+ const credential = import_mppx.Credential.deserialize(auth);
1617
+ return {
1618
+ kind: "credential",
1619
+ credential: {
1620
+ challenge: summarizeChallenge(credential.challenge),
1621
+ source: credential.source,
1622
+ payload: credential.payload
1623
+ },
1624
+ rawBody: request.rawBody
1625
+ };
1626
+ } catch {
1627
+ return { kind: "error", error: { type: "invalid-credential-encoding" } };
1628
+ }
1629
+ }
1630
+ function extractMPPFromResponse(response) {
1631
+ if (response.status === 402) {
1632
+ const challenges = collectChallenges(response);
1633
+ if (challenges.length === 0) return null;
1634
+ const methods = Array.from(new Set(challenges.map((c) => c.method)));
1635
+ return {
1636
+ kind: "challenge",
1637
+ challenges,
1638
+ offeredMethods: methods
1639
+ };
1640
+ }
1641
+ const receiptHeader = readHeader3(response.headers, "payment-receipt");
1642
+ if (receiptHeader) {
1643
+ try {
1644
+ const parsed = import_mppx.Receipt.deserialize(receiptHeader);
1645
+ const r = parsed;
1646
+ return {
1647
+ kind: "receipt",
1648
+ receipt: {
1649
+ method: coerceString6(r.method),
1650
+ reference: coerceString6(r.reference),
1651
+ externalId: coerceString6(r.externalId ?? r.external_id),
1652
+ status: coerceString6(r.status),
1653
+ timestamp: coerceString6(r.timestamp),
1654
+ raw: r
1655
+ }
1656
+ };
1657
+ } catch {
1658
+ return { kind: "error", error: { type: "invalid-receipt-encoding" } };
1659
+ }
1660
+ }
1661
+ const contentType = readHeader3(response.headers, "content-type");
1662
+ if (contentType && /application\/problem\+json/i.test(contentType)) {
1663
+ const body = typeof response.body === "object" && response.body !== null ? response.body : {};
1664
+ return {
1665
+ kind: "error",
1666
+ error: {
1667
+ type: coerceString6(body.type),
1668
+ title: coerceString6(body.title),
1669
+ detail: coerceString6(body.detail)
1670
+ }
1671
+ };
1672
+ }
1673
+ return null;
1674
+ }
1675
+ function extractMPPContext(message) {
1676
+ if ("request" in message) return extractMPPFromRequest(message.request);
1677
+ if ("response" in message) return extractMPPFromResponse(message.response);
1678
+ if (typeof message.status === "number") {
1679
+ return extractMPPFromResponse(message);
1680
+ }
1681
+ return extractMPPFromRequest(message);
1682
+ }
1683
+ function collectChallenges(response) {
1684
+ const wwwAuth = readHeader3(response.headers, "www-authenticate");
1685
+ if (!wwwAuth) return [];
1686
+ const headers = new Headers();
1687
+ headers.set("www-authenticate", wwwAuth);
1688
+ const out = [];
1689
+ try {
1690
+ const list = import_mppx.Challenge.fromHeadersList(headers);
1691
+ for (const ch of list) {
1692
+ out.push(summarizeChallenge(ch));
1693
+ }
1694
+ } catch {
1695
+ }
1696
+ return out;
1697
+ }
1698
+ function summarizeChallenge(ch) {
1699
+ const raw = ch;
1700
+ return {
1701
+ id: coerceString6(raw.id) ?? "",
1702
+ realm: coerceString6(raw.realm) ?? "",
1703
+ method: coerceString6(raw.method) ?? "",
1704
+ intent: coerceString6(raw.intent) ?? "",
1705
+ request: raw.request ?? {},
1706
+ expires: coerceString6(raw.expires),
1707
+ digest: coerceString6(raw.digest),
1708
+ description: coerceString6(raw.description),
1709
+ opaque: raw.opaque
1710
+ };
1711
+ }
1712
+ function readHeader3(headers, name) {
1713
+ for (const key of Object.keys(headers)) {
1714
+ if (key.toLowerCase() === name) {
1715
+ const raw = headers[key];
1716
+ if (typeof raw === "string") return raw;
1717
+ if (Array.isArray(raw)) return raw.join(", ");
1718
+ }
1719
+ }
1720
+ return void 0;
1721
+ }
1722
+ function coerceString6(v) {
1723
+ return typeof v === "string" && v.length > 0 ? v : void 0;
1724
+ }
1725
+
1726
+ // src/transport/mpp-verify.ts
1727
+ var import_mppx2 = require("mppx");
1728
+ function verifyMPP(input) {
1729
+ const { context } = input;
1730
+ const tolerance = input.clockSkewSec ?? 300;
1731
+ const nowSec = input.now ? input.now() : Math.floor(Date.now() / 1e3);
1732
+ const challenge = context.credential?.challenge ?? (context.challenges && context.challenges[0]);
1733
+ const source = context.credential?.source;
1734
+ const method = challenge?.method;
1735
+ let expiryOk = true;
1736
+ if (challenge?.expires) {
1737
+ const parsedExpiry = Date.parse(challenge.expires);
1738
+ if (!Number.isFinite(parsedExpiry)) {
1739
+ return {
1740
+ ok: false,
1741
+ expiryOk: false,
1742
+ bodyDigestOk: null,
1743
+ source,
1744
+ method,
1745
+ error: "unparseable challenge.expires"
1746
+ };
1747
+ }
1748
+ const expiresSec = Math.floor(parsedExpiry / 1e3);
1749
+ if (nowSec > expiresSec + tolerance) {
1750
+ expiryOk = false;
1751
+ }
1752
+ }
1753
+ let bodyDigestOk = null;
1754
+ if (challenge?.digest && input.rawBody !== void 0) {
1755
+ try {
1756
+ if (!/^sha-256=/.test(challenge.digest)) {
1757
+ bodyDigestOk = false;
1758
+ } else {
1759
+ bodyDigestOk = import_mppx2.BodyDigest.verify(challenge.digest, input.rawBody);
1760
+ }
1761
+ } catch {
1762
+ bodyDigestOk = false;
1763
+ }
1764
+ }
1765
+ const ok = expiryOk && (bodyDigestOk === null || bodyDigestOk === true);
1766
+ const errors = [];
1767
+ if (!expiryOk) errors.push("challenge expired");
1768
+ if (bodyDigestOk === false) errors.push("body digest mismatch");
1769
+ return {
1770
+ ok,
1771
+ expiryOk,
1772
+ bodyDigestOk,
1773
+ source,
1774
+ method,
1775
+ error: errors.length > 0 ? errors.join("; ") : void 0
1776
+ };
1777
+ }
1778
+
1779
+ // src/transport/x402.ts
1780
+ var import_schemas = require("@x402/core/schemas");
1781
+ var import_utils = require("@x402/core/utils");
1782
+ function extractX402FromRequest(request) {
1783
+ const headerValue = readHeader4(request.headers, "x-payment");
1784
+ if (request.body && typeof request.body === "object") {
1785
+ const parsed = tryParsePayload(request.body);
1786
+ if (parsed) return buildPayloadContext(parsed, "body");
1787
+ }
1788
+ if (headerValue) {
1789
+ try {
1790
+ const decoded = (0, import_utils.safeBase64Decode)(headerValue);
1791
+ if (decoded) {
1792
+ const json = JSON.parse(decoded);
1793
+ const parsed = tryParsePayload(json);
1794
+ if (parsed) return buildPayloadContext(parsed, "header");
1795
+ }
1796
+ } catch {
1797
+ return {
1798
+ kind: "error",
1799
+ version: 1,
1800
+ source: "header",
1801
+ error: { type: "invalid-x402-payload" }
1802
+ };
1803
+ }
1804
+ }
1805
+ return null;
1806
+ }
1807
+ function extractX402FromResponse(response) {
1808
+ if (response.status !== 402) return null;
1809
+ if (response.body && typeof response.body === "object") {
1810
+ const parsed = tryParseRequired(response.body);
1811
+ if (parsed) return buildRequiredContext(parsed, "body");
1812
+ }
1813
+ const headerValue = readHeader4(response.headers, "x-payment-required");
1814
+ if (headerValue) {
1815
+ try {
1816
+ const decoded = (0, import_utils.safeBase64Decode)(headerValue);
1817
+ if (decoded) {
1818
+ const json = JSON.parse(decoded);
1819
+ const parsed = tryParseRequired(json);
1820
+ if (parsed) return buildRequiredContext(parsed, "header");
1821
+ }
1822
+ } catch {
1823
+ return {
1824
+ kind: "error",
1825
+ version: 1,
1826
+ source: "header",
1827
+ error: { type: "invalid-x402-required" }
1828
+ };
1829
+ }
1830
+ }
1831
+ return null;
1832
+ }
1833
+ function extractX402Context(message) {
1834
+ if ("request" in message) return extractX402FromRequest(message.request);
1835
+ if ("response" in message) return extractX402FromResponse(message.response);
1836
+ if (typeof message.status === "number") {
1837
+ return extractX402FromResponse(message);
1838
+ }
1839
+ return extractX402FromRequest(message);
1840
+ }
1841
+ function tryParseRequired(data) {
1842
+ try {
1843
+ return (0, import_schemas.validatePaymentRequired)(data);
1844
+ } catch {
1845
+ return null;
1846
+ }
1847
+ }
1848
+ function tryParsePayload(data) {
1849
+ try {
1850
+ return (0, import_schemas.validatePaymentPayload)(data);
1851
+ } catch {
1852
+ return null;
1853
+ }
1854
+ }
1855
+ function buildRequiredContext(parsed, source) {
1856
+ const asRecord = parsed;
1857
+ const version = coerceVersion(asRecord.x402Version);
1858
+ const accepts = asRecord.accepts ?? [];
1859
+ return {
1860
+ kind: "required",
1861
+ version,
1862
+ source,
1863
+ paymentRequired: {
1864
+ resource: resolveResource(asRecord.resource),
1865
+ accepts: accepts.map(summarizeRequirement),
1866
+ extensions: asRecord.extensions,
1867
+ error: typeof asRecord.error === "string" ? asRecord.error : void 0
1868
+ }
1869
+ };
1870
+ }
1871
+ function buildPayloadContext(parsed, source) {
1872
+ const asRecord = parsed;
1873
+ const version = coerceVersion(asRecord.x402Version);
1874
+ const accepted = asRecord.accepted;
1875
+ const payload = asRecord.payload ?? {};
1876
+ return {
1877
+ kind: "payload",
1878
+ version,
1879
+ source,
1880
+ paymentPayload: {
1881
+ scheme: accepted?.scheme ?? (typeof asRecord.scheme === "string" ? asRecord.scheme : ""),
1882
+ network: accepted?.network ?? (typeof asRecord.network === "string" ? asRecord.network : ""),
1883
+ payload,
1884
+ extensions: asRecord.extensions
1885
+ }
1886
+ };
1887
+ }
1888
+ function summarizeRequirement(req) {
1889
+ const r = req;
1890
+ const amount = r.amount ?? r.maxAmountRequired ?? "0";
1891
+ return {
1892
+ scheme: r.scheme ?? "",
1893
+ network: r.network ?? "",
1894
+ asset: r.asset ?? "",
1895
+ amount: String(amount),
1896
+ payTo: r.payTo ?? "",
1897
+ maxTimeoutSeconds: typeof r.maxTimeoutSeconds === "number" ? r.maxTimeoutSeconds : void 0,
1898
+ resource: typeof r.resource === "string" ? r.resource : void 0,
1899
+ description: typeof r.description === "string" ? r.description : void 0
1900
+ };
1901
+ }
1902
+ function resolveResource(v) {
1903
+ if (typeof v === "string") return v;
1904
+ if (v && typeof v === "object" && "url" in v && typeof v.url === "string") {
1905
+ return v.url;
1906
+ }
1907
+ return "";
1908
+ }
1909
+ function coerceVersion(v) {
1910
+ if (v === 1 || v === 2) return v;
1911
+ return null;
1912
+ }
1913
+ function readHeader4(headers, name) {
1914
+ if (!headers) return void 0;
1915
+ for (const key of Object.keys(headers)) {
1916
+ if (key.toLowerCase() === name) {
1917
+ const raw = headers[key];
1918
+ if (typeof raw === "string") return raw;
1919
+ if (Array.isArray(raw)) return raw[0];
1920
+ }
1921
+ }
1922
+ return void 0;
1923
+ }
1924
+
1925
+ // src/transport/vi-verify.ts
1926
+ var import_node_crypto4 = require("crypto");
1927
+ async function verifyVIChain(input) {
1928
+ const errors = [];
1929
+ const tolerance = input.clockSkewSec ?? 300;
1930
+ const now = input.now ? input.now() : Math.floor(Date.now() / 1e3);
1931
+ const { l1, l2, l3a, l3b } = input.layers;
1932
+ const l1SigOk = l1 ? await input.verifySignature(l1, null) : null;
1933
+ if (l1 && !l1SigOk) errors.push("L1 signature invalid");
1934
+ const l1Cnf = extractCnfJwk(l1?.payload);
1935
+ const l2SigOk = await input.verifySignature(l2, l1Cnf ?? null);
1936
+ if (!l2SigOk) errors.push("L2 signature invalid");
1937
+ const l2Cnf = extractCnfJwk(l2.payload);
1938
+ const l3aSigOk = l3a ? await input.verifySignature(l3a, l2Cnf ?? null) : null;
1939
+ if (l3a && !l3aSigOk) errors.push("L3a signature invalid");
1940
+ const l3bSigOk = l3b ? await input.verifySignature(l3b, l2Cnf ?? null) : null;
1941
+ if (l3b && !l3bSigOk) errors.push("L3b signature invalid");
1942
+ let l1BindsL2 = true;
1943
+ if (l1Cnf) {
1944
+ const l2KeyFromHeader = await jwkForLayer(l2);
1945
+ l1BindsL2 = l2KeyFromHeader ? await thumbprintsMatch(l1Cnf, l2KeyFromHeader) : false;
1946
+ if (!l1BindsL2) errors.push("L1.cnf.jwk does not bind L2 signing key");
1947
+ }
1948
+ let l2BindsL3 = true;
1949
+ if (l2Cnf && (l3a || l3b)) {
1950
+ const l3Layer = l3a ?? l3b;
1951
+ const l3KeyFromHeader = await jwkForLayer(l3Layer);
1952
+ l2BindsL3 = l3KeyFromHeader ? await thumbprintsMatch(l2Cnf, l3KeyFromHeader) : false;
1953
+ if (!l2BindsL3) errors.push("L2.cnf.jwk does not bind L3 signing key");
1954
+ }
1955
+ let l3aL3bTxnIdMatch = null;
1956
+ if (l3a && l3b) {
1957
+ const a = coerceString7(l3a.payload.transaction_id ?? l3a.payload.transactionId);
1958
+ const b = coerceString7(l3b.payload.transaction_id ?? l3b.payload.transactionId);
1959
+ if (a && b) {
1960
+ l3aL3bTxnIdMatch = a === b;
1961
+ if (!l3aL3bTxnIdMatch) {
1962
+ errors.push(`L3a.transaction_id (${a}) does not match L3b.transaction_id (${b})`);
1963
+ }
1964
+ }
1965
+ }
1966
+ let checkoutHashOk = null;
1967
+ if (l3b) {
1968
+ const declaredHash = coerceString7(
1969
+ l3b.payload.checkout_hash ?? l3b.payload.conditional_transaction_id ?? l3b.payload.payment_reference?.checkout_hash
1970
+ );
1971
+ if (declaredHash) {
1972
+ const computed = computeCheckoutHashFromL2(l2);
1973
+ checkoutHashOk = computed ? declaredHash === computed : false;
1974
+ if (!checkoutHashOk) {
1975
+ errors.push("L3b.checkout_hash does not match SHA-256 of L2 checkout disclosure");
1976
+ }
1977
+ }
1978
+ }
1979
+ const expiryOk = checkExpiryAcross([l1, l2, l3a, l3b], tolerance, now, errors);
1980
+ const ok = l1SigOk !== false && l2SigOk && l3aSigOk !== false && l3bSigOk !== false && l1BindsL2 && l2BindsL3 && l3aL3bTxnIdMatch !== false && checkoutHashOk !== false && expiryOk;
1981
+ return {
1982
+ ok,
1983
+ checks: {
1984
+ l1SigOk,
1985
+ l2SigOk,
1986
+ l3aSigOk,
1987
+ l3bSigOk,
1988
+ l1BindsL2,
1989
+ l2BindsL3,
1990
+ l3aL3bTxnIdMatch,
1991
+ checkoutHashOk,
1992
+ expiryOk
1993
+ },
1994
+ errors
1995
+ };
1996
+ }
1997
+ function extractCnfJwk(payload) {
1998
+ if (!payload) return null;
1999
+ const cnf = payload.cnf;
2000
+ if (!cnf) return null;
2001
+ const jwk = cnf.jwk;
2002
+ return jwk ?? null;
2003
+ }
2004
+ async function jwkForLayer(layer) {
2005
+ const fromHeader = extractCnfJwk(layer.header);
2006
+ if (fromHeader) return fromHeader;
2007
+ const fromPayload = extractCnfJwk(layer.payload);
2008
+ return fromPayload;
2009
+ }
2010
+ async function thumbprintsMatch(a, b) {
2011
+ try {
2012
+ const ta = await jwkThumbprint(a);
2013
+ const tb = await jwkThumbprint(b);
2014
+ return ta === tb;
2015
+ } catch {
2016
+ return false;
2017
+ }
2018
+ }
2019
+ async function jwkThumbprint(jwk) {
2020
+ const canonical = canonicalJwk(jwk);
2021
+ const bytes = new TextEncoder().encode(JSON.stringify(canonical));
2022
+ const subtle = import_node_crypto4.webcrypto.subtle;
2023
+ const buffer = await new Promise((resolve, reject) => {
2024
+ const source = new ArrayBuffer(bytes.byteLength);
2025
+ new Uint8Array(source).set(bytes);
2026
+ subtle.digest("SHA-256", source).then(resolve).catch(reject);
2027
+ });
2028
+ return Buffer.from(new Uint8Array(buffer)).toString("base64url").replace(/=+$/, "");
2029
+ }
2030
+ function canonicalJwk(jwk) {
2031
+ if (jwk.kty === "EC") {
2032
+ return { crv: jwk.crv ?? "", kty: "EC", x: jwk.x ?? "", y: jwk.y ?? "" };
2033
+ }
2034
+ if (jwk.kty === "OKP") {
2035
+ return { crv: jwk.crv ?? "", kty: "OKP", x: jwk.x ?? "" };
2036
+ }
2037
+ if (jwk.kty === "RSA") {
2038
+ return { e: jwk.e ?? "", kty: "RSA", n: jwk.n ?? "" };
2039
+ }
2040
+ return { kty: jwk.kty ?? "" };
2041
+ }
2042
+ function computeCheckoutHashFromL2(l2) {
2043
+ const checkoutDisclosure = l2.payload.checkout ?? l2.payload.checkout_mandate;
2044
+ if (!checkoutDisclosure) return null;
2045
+ const canonical = canonicalStringify(checkoutDisclosure);
2046
+ const hash = (0, import_node_crypto4.createHash)("sha256").update(canonical).digest("base64url").replace(/=+$/, "");
2047
+ return hash;
2048
+ }
2049
+ function canonicalStringify(value) {
2050
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
2051
+ if (Array.isArray(value)) return "[" + value.map(canonicalStringify).join(",") + "]";
2052
+ const entries = Object.entries(value).sort(
2053
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2054
+ );
2055
+ return "{" + entries.map(([k, v]) => JSON.stringify(k) + ":" + canonicalStringify(v)).join(",") + "}";
2056
+ }
2057
+ function checkExpiryAcross(layers, toleranceSec, nowSec, errors) {
2058
+ let ok = true;
2059
+ const names = ["L1", "L2", "L3a", "L3b"];
2060
+ layers.forEach((layer, idx) => {
2061
+ if (!layer) return;
2062
+ const exp = toUnixSeconds2(layer.payload.exp ?? layer.payload.expires);
2063
+ if (exp === void 0) return;
2064
+ if (nowSec > exp + toleranceSec) {
2065
+ errors.push(`${names[idx]} mandate expired at ${exp}`);
2066
+ ok = false;
2067
+ }
2068
+ });
2069
+ return ok;
2070
+ }
2071
+ function toUnixSeconds2(v) {
2072
+ if (typeof v === "number" && Number.isFinite(v)) return v;
2073
+ if (typeof v === "string") {
2074
+ const asInt = Number(v);
2075
+ if (Number.isFinite(asInt) && asInt > 0) {
2076
+ return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
2077
+ }
2078
+ const parsed = Date.parse(v);
2079
+ if (Number.isFinite(parsed)) return Math.floor(parsed / 1e3);
2080
+ }
2081
+ return void 0;
2082
+ }
2083
+ function coerceString7(v) {
2084
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2085
+ }
2086
+
2087
+ // src/transport/commerce-pipeline.ts
2088
+ async function runCommercePipeline(input) {
2089
+ const trustSignals = [];
2090
+ const signatures = {};
2091
+ const timings = { extractMs: 0, verifyMs: 0, evalMs: 0 };
2092
+ const extractStart = performance.now();
2093
+ const purpose = resolvePurpose(input);
2094
+ const transactionValue = resolveTransactionValue(input);
2095
+ const identityClaims = collectIdentityClaims(input);
2096
+ const paymentToken = resolvePaymentToken(input);
2097
+ timings.extractMs = Math.round(performance.now() - extractStart);
2098
+ const verifyStart = performance.now();
2099
+ let hardDeny = false;
2100
+ if (input.vi?.verifyInput) {
2101
+ signatures.vi = await verifyVIChain(input.vi.verifyInput);
2102
+ if (!signatures.vi.ok) hardDeny = true;
2103
+ }
2104
+ if (input.ap2) {
2105
+ signatures.ap2 = verifyAP2Chain({
2106
+ triple: input.ap2.triple,
2107
+ clockSkewSec: input.clockSkewSec,
2108
+ now: input.now
2109
+ });
2110
+ if (!signatures.ap2.ok) hardDeny = true;
2111
+ }
2112
+ if (input.acp?.verifyInput) {
2113
+ signatures.acp = await verifyACPSignature(input.acp.verifyInput);
2114
+ if (!signatures.acp.ok && signatures.acp.timestampStale) hardDeny = true;
2115
+ if (signatures.acp.algorithm === "unsupported") {
2116
+ trustSignals.push("acp-signature-algorithm-unsupported");
2117
+ } else if (!signatures.acp.ok) {
2118
+ hardDeny = true;
2119
+ }
2120
+ }
2121
+ if (input.rfc9421) {
2122
+ signatures.rfc9421 = await verifyRFC9421(input.rfc9421.request, input.rfc9421.verifyOptions);
2123
+ if (!signatures.rfc9421.ok) hardDeny = true;
2124
+ }
2125
+ if (input.mpp) {
2126
+ signatures.mpp = verifyMPP({
2127
+ context: input.mpp.context,
2128
+ rawBody: input.mpp.rawBody,
2129
+ clockSkewSec: input.clockSkewSec,
2130
+ now: input.now
2131
+ });
2132
+ if (!signatures.mpp.ok) hardDeny = true;
2133
+ if (input.mpp.context.credential?.source) {
2134
+ trustSignals.push(`mpp-source-${shortSource(input.mpp.context.credential.source)}`);
2135
+ }
2136
+ }
2137
+ if (input.stripeWebhook) {
2138
+ signatures.stripeWebhook = verifyStripeWebhook(
2139
+ input.stripeWebhook.payload,
2140
+ input.stripeWebhook.signatureHeader,
2141
+ input.stripeWebhook.secret,
2142
+ { now: input.now ? () => input.now() : void 0 }
2143
+ );
2144
+ if (!signatures.stripeWebhook.ok) {
2145
+ trustSignals.push("stripe-webhook-hmac-failed");
2146
+ }
2147
+ }
2148
+ timings.verifyMs = Math.round(performance.now() - verifyStart);
2149
+ let identity;
2150
+ if (input.identityResolver && identityClaims.length > 0) {
2151
+ const bound = await bindIdentity(identityClaims, input.identityResolver);
2152
+ identity = {
2153
+ claims: identityClaims,
2154
+ mappedAstraSyncAgentId: bound.mappedAstraSyncAgentId,
2155
+ mismatchAcrossLayers: bound.mismatchAcrossLayers
2156
+ };
2157
+ if (bound.mismatchAcrossLayers) trustSignals.push("identity-mismatch-across-layers");
2158
+ } else if (identityClaims.length > 0) {
2159
+ identity = {
2160
+ claims: identityClaims,
2161
+ mappedAstraSyncAgentId: void 0,
2162
+ mismatchAcrossLayers: false
2163
+ };
2164
+ }
2165
+ const evalStart = performance.now();
2166
+ const constraints = runConstraintEval(input);
2167
+ if (constraints && !constraints.ok) hardDeny = true;
2168
+ timings.evalMs = Math.round(performance.now() - evalStart);
2169
+ if (paymentToken?.type === "stripe-spt") trustSignals.push("stripe-spt-present");
2170
+ if (paymentToken?.type === "acp-vt") trustSignals.push("acp-vault-token-present");
2171
+ if (paymentToken?.type === "tempo-tx") trustSignals.push("tempo-transaction-present");
2172
+ const mppReceipt = input.mpp?.context.receipt;
2173
+ return {
2174
+ protocol: input.protocol,
2175
+ purpose,
2176
+ transactionValue,
2177
+ signatures,
2178
+ identity,
2179
+ paymentToken,
2180
+ mppMethodsOffered: input.mpp?.context.offeredMethods,
2181
+ constraints,
2182
+ receipt: mppReceipt ? {
2183
+ method: mppReceipt.method,
2184
+ reference: mppReceipt.reference,
2185
+ status: mppReceipt.status,
2186
+ timestamp: mppReceipt.timestamp
2187
+ } : void 0,
2188
+ trustSignals,
2189
+ timings,
2190
+ ok: !hardDeny
2191
+ };
2192
+ }
2193
+ function resolvePurpose(input) {
2194
+ if (input.vi?.claims.mandateType) {
2195
+ return mapVIMandateToPurpose(input.vi.claims.mandateType);
2196
+ }
2197
+ if (input.ap2?.triple.payment) return "commerce.payment.execute";
2198
+ if (input.ap2?.triple.cart) return "commerce.checkout.confirm";
2199
+ if (input.ap2?.triple.intent) return "commerce.delegation.intent";
2200
+ if (input.ucp?.endpoint) {
2201
+ const [method, path] = input.ucp.endpoint.split(" ");
2202
+ return mapUCPRequestToPurpose(method ?? "POST", path ?? "/");
2203
+ }
2204
+ if (input.acp?.context.endpoint) {
2205
+ switch (input.acp.context.endpoint) {
2206
+ case "checkout_sessions.create":
2207
+ return "commerce.checkout.create";
2208
+ case "checkout_sessions.update":
2209
+ return "commerce.checkout.update";
2210
+ case "checkout_sessions.complete":
2211
+ return "commerce.payment.execute";
2212
+ case "checkout_sessions.cancel":
2213
+ return "commerce.checkout.cancel";
2214
+ case "delegate_payment":
2215
+ return "commerce.delegation.payment";
2216
+ default:
2217
+ return mapACPRequestToPurpose("POST", "/checkout_sessions");
2218
+ }
2219
+ }
2220
+ if (input.rfc9421?.tag) {
2221
+ return mapRFC9421TagToPurpose(
2222
+ input.rfc9421.tag === "browse" || input.rfc9421.tag === "purchase" ? input.rfc9421.tag : void 0
2223
+ );
2224
+ }
2225
+ if (input.mpp?.context.credential?.challenge || input.mpp?.context.challenges?.[0]) {
2226
+ const challenge = input.mpp.context.credential?.challenge ?? input.mpp.context.challenges?.[0];
2227
+ const amount = parseFloat(String(challenge?.request?.amount ?? "NaN"));
2228
+ return mapMPPRequestToPurpose(
2229
+ challenge?.intent === "session" ? "session" : "charge",
2230
+ Number.isFinite(amount) ? amount : void 0
2231
+ );
2232
+ }
2233
+ if (input.x402?.paymentRequired) {
2234
+ const amt = input.x402.paymentRequired.accepts[0]?.amount;
2235
+ return mapX402RequestToPurpose(Number(amt));
2236
+ }
2237
+ if (input.x402?.paymentPayload) return "commerce.payment.execute";
2238
+ return null;
2239
+ }
2240
+ function resolveTransactionValue(input) {
2241
+ if (input.vi?.claims) {
2242
+ const v = extractVITransactionValue({
2243
+ constraints: input.vi.claims.constraints,
2244
+ l3aPaymentAmount: input.vi.claims.constraints.paymentAmount && typeof input.vi.claims.constraints.paymentAmount.max === "number" ? {
2245
+ amount: input.vi.claims.constraints.paymentAmount.max,
2246
+ currency: input.vi.claims.constraints.paymentAmount.currency
2247
+ } : void 0
2248
+ });
2249
+ if (v) return v;
2250
+ }
2251
+ if (input.ucp?.totals) {
2252
+ const v = extractUCPTransactionValue({ totals: input.ucp.totals });
2253
+ if (v) return v;
2254
+ }
2255
+ if (input.acp?.context.totals) {
2256
+ const v = extractACPTransactionValue({ totals: input.acp.context.totals });
2257
+ if (v) return v;
2258
+ }
2259
+ if (input.mpp?.context.credential?.challenge) {
2260
+ const ch = input.mpp.context.credential.challenge;
2261
+ const v = extractMPPTransactionValue({ method: ch.method, request: ch.request });
2262
+ if (v) return v;
2263
+ }
2264
+ if (input.x402?.paymentRequired) {
2265
+ const first = input.x402.paymentRequired.accepts[0];
2266
+ if (first) {
2267
+ const v = extractX402TransactionValue({
2268
+ maxAmountRequired: Number(first.amount),
2269
+ asset: first.asset
2270
+ });
2271
+ if (v) return v;
2272
+ }
2273
+ }
2274
+ return void 0;
2275
+ }
2276
+ function collectIdentityClaims(input) {
2277
+ const claims = [];
2278
+ if (input.vi?.claims.kid)
2279
+ claims.push({ protocol: "vi", field: "kid", value: input.vi.claims.kid });
2280
+ if (input.ap2?.triple) {
2281
+ const agentId = input.ap2.triple.intent?.agent_id ?? input.ap2.triple.cart?.agent_id ?? input.ap2.triple.payment?.agent_id;
2282
+ if (agentId) claims.push({ protocol: "ap2", field: "agent_id", value: agentId });
2283
+ }
2284
+ if (input.acp?.context.bearer) {
2285
+ claims.push({ protocol: "acp", field: "bearer", value: input.acp.context.bearer });
2286
+ }
2287
+ if (input.mpp?.context.credential?.source) {
2288
+ claims.push({ protocol: "mpp", field: "source", value: input.mpp.context.credential.source });
2289
+ }
2290
+ if (input.rfc9421) {
2291
+ }
2292
+ return claims;
2293
+ }
2294
+ function resolvePaymentToken(input) {
2295
+ if (input.acp?.context.paymentToken?.type) {
2296
+ return { present: true, type: input.acp.context.paymentToken.type };
2297
+ }
2298
+ const mppMethod = input.mpp?.context.credential?.challenge?.method;
2299
+ if (mppMethod === "tempo") return { present: true, type: "tempo-tx" };
2300
+ if (mppMethod === "stripe") return { present: true, type: "stripe-spt" };
2301
+ return void 0;
2302
+ }
2303
+ function runConstraintEval(input) {
2304
+ const transaction = input.transaction ?? {};
2305
+ const results = {};
2306
+ const reasons = [];
2307
+ let hasAny = false;
2308
+ if (input.vi?.claims) {
2309
+ const viResult = evaluateVIConstraints({
2310
+ constraints: input.vi.claims.constraints,
2311
+ transaction
2312
+ });
2313
+ for (const [k, v] of Object.entries(viResult.results)) {
2314
+ results[k] = v;
2315
+ if (!v.ok && v.reason) reasons.push(v.reason);
2316
+ }
2317
+ if (Object.keys(viResult.results).length > 0) hasAny = true;
2318
+ }
2319
+ const registered = input.registeredConstraints;
2320
+ if (registered?.allowedPaymentMethods) {
2321
+ const pm = evaluatePaymentMethodAllowlist({
2322
+ allowedMethods: registered.allowedPaymentMethods,
2323
+ requestedMethod: transaction.paymentMethod
2324
+ });
2325
+ results.paymentMethod = pm;
2326
+ if (!pm.ok && pm.reason) reasons.push(pm.reason);
2327
+ hasAny = true;
2328
+ }
2329
+ if (registered?.spendingLimit) {
2330
+ const sp = evaluateSpendingLimit({
2331
+ limit: registered.spendingLimit,
2332
+ requested: { amount: transaction.amount, currency: transaction.currency }
2333
+ });
2334
+ results.spendingLimit = sp;
2335
+ if (!sp.ok && sp.reason) reasons.push(sp.reason);
2336
+ hasAny = true;
2337
+ }
2338
+ if (!hasAny) return void 0;
2339
+ return { ok: reasons.length === 0, results, reasons };
2340
+ }
2341
+ function shortSource(source) {
2342
+ return source.replace(/^did:[a-z0-9]+:/, "").slice(0, 16);
2343
+ }
2344
+
2345
+ // src/transport/extractor-registry.ts
2346
+ var registry = /* @__PURE__ */ new Map();
2347
+ function registerTransportExtractor(extractor) {
2348
+ if (!extractor || typeof extractor.name !== "string" || extractor.name.length === 0) {
2349
+ throw new Error("registerTransportExtractor: extractor must have a non-empty name");
2350
+ }
2351
+ registry.set(extractor.name, extractor);
2352
+ }
2353
+ function getTransportExtractors() {
2354
+ return Array.from(registry.values());
2355
+ }
2356
+ function getTransportExtractor(name) {
2357
+ return registry.get(name);
2358
+ }
2359
+ function clearTransportExtractors() {
2360
+ registry.clear();
2361
+ }
2362
+ async function runMatchingExtractors(request) {
2363
+ const out = {};
2364
+ for (const extractor of registry.values()) {
2365
+ if (!extractor.match(request)) continue;
2366
+ const result = await extractor.extract(request);
2367
+ if (result !== null && result !== void 0) out[extractor.name] = result;
2368
+ }
2369
+ return out;
2370
+ }
2371
+
2372
+ // src/transport/registry/visa.ts
2373
+ var import_jose = require("jose");
2374
+ var DEFAULT_VISA_JWKS_URL = "https://mcp.visa.com/.well-known/jwks";
2375
+ function createVisaRegistry(options = {}) {
2376
+ const url = new URL(options.jwksUrl ?? DEFAULT_VISA_JWKS_URL);
2377
+ const jwks = (0, import_jose.createRemoteJWKSet)(url, {
2378
+ cacheMaxAge: options.cacheMaxAge,
2379
+ cooldownDuration: options.cooldownDuration
2380
+ });
2381
+ return {
2382
+ name: "visa",
2383
+ async resolve(kid, context) {
2384
+ if (!kid) return null;
2385
+ try {
2386
+ const key = await jwks({
2387
+ kid,
2388
+ alg: context?.algorithm ?? "ES256",
2389
+ typ: "JWT"
2390
+ });
2391
+ return exportJwkFromKeyLike(key);
2392
+ } catch {
2393
+ return null;
2394
+ }
2395
+ }
2396
+ };
2397
+ }
2398
+ async function exportJwkFromKeyLike(keyLike) {
2399
+ if (!keyLike) return null;
2400
+ if (typeof keyLike === "object" && "kty" in keyLike) {
2401
+ return keyLike;
2402
+ }
2403
+ const { exportJWK } = await import("jose");
2404
+ try {
2405
+ return await exportJWK(keyLike);
2406
+ } catch {
2407
+ return null;
2408
+ }
2409
+ }
2410
+
2411
+ // src/transport/registry/mastercard.ts
2412
+ function createMastercardRegistry(options = {}) {
2413
+ const cache = /* @__PURE__ */ new Map();
2414
+ const ttlSec = options.cacheTtlSec ?? 3600;
2415
+ const fetchFn = options.fetch ?? globalThis.fetch;
2416
+ let warned = false;
2417
+ return {
2418
+ name: "mastercard",
2419
+ async resolve(kid) {
2420
+ if (!kid) return null;
2421
+ if (!options.registryUrl) {
2422
+ if (!warned && !options.silent) {
2423
+ warned = true;
2424
+ console.warn(
2425
+ "[mastercard-registry] registryUrl not configured \u2014 key resolution disabled. Kid lookups will return null until a partnership registry is supplied."
2426
+ );
2427
+ }
2428
+ return null;
2429
+ }
2430
+ const cached = cache.get(kid);
2431
+ if (cached && cached.expiresAt > Date.now()) return cached.jwk;
2432
+ try {
2433
+ const res = await fetchFn(options.registryUrl);
2434
+ if (!res.ok) return null;
2435
+ const body = await res.json();
2436
+ const keys = body.keys ?? [];
2437
+ for (const k of keys) {
2438
+ if (k.kid === kid) {
2439
+ cache.set(kid, { jwk: k, expiresAt: Date.now() + ttlSec * 1e3 });
2440
+ return k;
2441
+ }
2442
+ }
2443
+ return null;
2444
+ } catch {
2445
+ return null;
2446
+ }
2447
+ }
2448
+ };
2449
+ }
2450
+
2451
+ // src/transport/registry/web-bot-auth.ts
2452
+ var DIRECTORY_PATH = "/.well-known/http-message-signatures-directory";
2453
+ function createWebBotAuthRegistry(options = {}) {
2454
+ const cache = /* @__PURE__ */ new Map();
2455
+ const ttlSec = options.cacheTtlSec ?? 3600;
2456
+ const fetchFn = options.fetch ?? globalThis.fetch;
2457
+ return {
2458
+ name: "web-bot-auth",
2459
+ async resolve(kid, context) {
2460
+ if (!kid) return null;
2461
+ const directoryUrl = resolveDirectoryUrl(options.directoryUrl, context?.origin);
2462
+ if (!directoryUrl) return null;
2463
+ const cached = cache.get(directoryUrl);
2464
+ const now = Date.now();
2465
+ if (cached && cached.expiresAt > now) {
2466
+ return findKeyByKid(cached.keys, kid);
2467
+ }
2468
+ try {
2469
+ const res = await fetchFn(directoryUrl);
2470
+ if (!res.ok) return null;
2471
+ const body = await res.json();
2472
+ const keys = body.keys ?? [];
2473
+ cache.set(directoryUrl, { keys, expiresAt: now + ttlSec * 1e3 });
2474
+ return findKeyByKid(keys, kid);
2475
+ } catch {
2476
+ return null;
2477
+ }
2478
+ }
2479
+ };
2480
+ }
2481
+ function resolveDirectoryUrl(explicit, origin) {
2482
+ if (explicit) return explicit;
2483
+ if (!origin) return null;
2484
+ try {
2485
+ const url = new URL(origin);
2486
+ return `${url.origin}${DIRECTORY_PATH}`;
2487
+ } catch {
2488
+ return null;
2489
+ }
2490
+ }
2491
+ function findKeyByKid(keys, kid) {
2492
+ for (const k of keys) {
2493
+ if (k.kid === kid) return k;
2494
+ }
2495
+ return null;
2496
+ }
2497
+
165
2498
  // src/transport/index.ts
166
2499
  function detectProtocol(context) {
167
2500
  if (context.metadata && typeof context.metadata === "object") {
@@ -198,14 +2531,63 @@ function extractCredentialsFromProtocol(protocol, context) {
198
2531
  }
199
2532
  // Annotate the CommonJS export names for ESM import in node:
200
2533
  0 && (module.exports = {
2534
+ STRIPE_WEBHOOK_INFORMATIONAL_EVENTS,
201
2535
  applyCredentials,
2536
+ bindIdentity,
2537
+ claim,
2538
+ clearTransportExtractors,
2539
+ createMastercardRegistry,
2540
+ createVisaRegistry,
2541
+ createWebBotAuthRegistry,
202
2542
  detectProtocol,
2543
+ evaluatePaymentMethodAllowlist,
2544
+ evaluateSpendingLimit,
2545
+ evaluateVIConstraints,
203
2546
  extractA2ACredentials,
2547
+ extractACPContext,
2548
+ extractACPTransactionValue,
2549
+ extractAP2Mandate,
2550
+ extractAP2Mandates,
2551
+ extractAP2TransactionValue,
204
2552
  extractCredentialsFromProtocol,
205
2553
  extractHttpCredentials,
2554
+ extractMPPContext,
2555
+ extractMPPFromRequest,
2556
+ extractMPPFromResponse,
2557
+ extractMPPTransactionValue,
206
2558
  extractMcpCredentials,
2559
+ extractUCPContext,
2560
+ extractUCPTransactionValue,
2561
+ extractVIClaims,
2562
+ extractVITransactionValue,
2563
+ extractX402Context,
2564
+ extractX402FromRequest,
2565
+ extractX402FromResponse,
2566
+ extractX402TransactionValue,
2567
+ fetchUCPManifest,
2568
+ getTransportExtractor,
2569
+ getTransportExtractors,
2570
+ isStripeWebhookInformational,
2571
+ mapACPRequestToPurpose,
2572
+ mapAP2MandateToPurpose,
2573
+ mapMPPRequestToPurpose,
2574
+ mapRFC9421TagToPurpose,
2575
+ mapUCPRequestToPurpose,
2576
+ mapVIMandateToPurpose,
2577
+ mapX402RequestToPurpose,
2578
+ parseRFC9421,
2579
+ registerTransportExtractor,
2580
+ runCommercePipeline,
2581
+ runMatchingExtractors,
207
2582
  setA2AMetadata,
208
2583
  setHttpHeaders,
209
- setMcpMeta
2584
+ setMcpMeta,
2585
+ validateUCPManifest,
2586
+ verifyACPSignature,
2587
+ verifyAP2Chain,
2588
+ verifyMPP,
2589
+ verifyRFC9421,
2590
+ verifyStripeWebhook,
2591
+ verifyVIChain
210
2592
  });
211
2593
  //# sourceMappingURL=index.js.map