@devlab.group/agent-commerce 2.6.0 → 2.7.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 (123) hide show
  1. package/README.md +17 -12
  2. package/dist/ap2.d.ts +1 -1
  3. package/dist/ap2.js +5 -5
  4. package/dist/{chunk-ES3V6ECS.js → chunk-77HLISG4.js} +3 -2
  5. package/dist/chunk-77HLISG4.js.map +1 -0
  6. package/dist/{chunk-5ZYXBCDX.js → chunk-D7FPSGUQ.js} +25 -4
  7. package/dist/chunk-D7FPSGUQ.js.map +1 -0
  8. package/dist/{chunk-G3EYYHKF.js → chunk-DJRWYDKJ.js} +3 -3
  9. package/dist/{chunk-G3EYYHKF.js.map → chunk-DJRWYDKJ.js.map} +1 -1
  10. package/dist/{chunk-M6MQ3FYS.js → chunk-EMKITGVV.js} +4 -4
  11. package/dist/chunk-EMKITGVV.js.map +1 -0
  12. package/dist/chunk-IWXVQYG5.js +6 -0
  13. package/dist/chunk-IWXVQYG5.js.map +1 -0
  14. package/dist/chunk-O3ACF45K.js +8 -0
  15. package/dist/{chunk-M6BSXXTF.js.map → chunk-O3ACF45K.js.map} +1 -1
  16. package/dist/{chunk-M6WW6QIT.js → chunk-WDD2ZUR3.js} +5 -3
  17. package/dist/chunk-WDD2ZUR3.js.map +1 -0
  18. package/dist/{chunk-M52FBNJX.js → chunk-YHNTTMED.js} +6 -4
  19. package/dist/chunk-YHNTTMED.js.map +1 -0
  20. package/dist/{chunk-DRLBML7Z.js → chunk-ZSIUZPNB.js} +175 -74
  21. package/dist/chunk-ZSIUZPNB.js.map +1 -0
  22. package/dist/cli/{ap2-2YMYA2H6.js → ap2-5FFGSW6F.js} +10 -11
  23. package/dist/cli/ap2-5FFGSW6F.js.map +1 -0
  24. package/dist/cli/{chunk-5K4XEAZV.js → chunk-3IEXJ7I3.js} +25 -4
  25. package/dist/cli/chunk-3IEXJ7I3.js.map +1 -0
  26. package/dist/cli/{chunk-VJH6RYRK.js → chunk-3NVJAQRO.js} +3 -3
  27. package/dist/cli/{chunk-VJH6RYRK.js.map → chunk-3NVJAQRO.js.map} +1 -1
  28. package/dist/cli/{chunk-GET3CZGR.js → chunk-55AI6CLW.js} +6 -4
  29. package/dist/cli/chunk-55AI6CLW.js.map +1 -0
  30. package/dist/cli/{chunk-YOF7IK4V.js → chunk-5K2JDM4G.js} +177 -76
  31. package/dist/cli/chunk-5K2JDM4G.js.map +1 -0
  32. package/dist/cli/{chunk-NSYSMDQN.js → chunk-5TID36YG.js} +57 -29
  33. package/dist/cli/chunk-5TID36YG.js.map +1 -0
  34. package/dist/cli/{chunk-3NOMLMJW.js → chunk-66NTYSXI.js} +3 -3
  35. package/dist/cli/{chunk-3NOMLMJW.js.map → chunk-66NTYSXI.js.map} +1 -1
  36. package/dist/cli/{chunk-VJ4EO4LE.js → chunk-6EBDOH37.js} +3 -3
  37. package/dist/cli/{chunk-VJ4EO4LE.js.map → chunk-6EBDOH37.js.map} +1 -1
  38. package/dist/cli/{chunk-YWG2ZN3L.js → chunk-AGQ4U7IN.js} +5 -5
  39. package/dist/cli/chunk-AGQ4U7IN.js.map +1 -0
  40. package/dist/cli/chunk-APC5BTQM.js +6 -0
  41. package/dist/cli/chunk-APC5BTQM.js.map +1 -0
  42. package/dist/cli/{chunk-SYQLJXIU.js → chunk-C5YISPT6.js} +3 -3
  43. package/dist/cli/chunk-C5YISPT6.js.map +1 -0
  44. package/dist/cli/chunk-DKWO6LLX.js +34 -0
  45. package/dist/cli/chunk-DKWO6LLX.js.map +1 -0
  46. package/dist/cli/{chunk-SPAYKVUP.js → chunk-FL4HPCD4.js} +3 -2
  47. package/dist/cli/chunk-FL4HPCD4.js.map +1 -0
  48. package/dist/cli/{chunk-3EQBCFZY.js → chunk-H7EBJ4I3.js} +3 -3
  49. package/dist/cli/{chunk-3EQBCFZY.js.map → chunk-H7EBJ4I3.js.map} +1 -1
  50. package/dist/cli/{chunk-PTL7SNOI.js → chunk-OETKXDGA.js} +467 -122
  51. package/dist/cli/chunk-OETKXDGA.js.map +1 -0
  52. package/dist/cli/{chunk-DHFMIBPG.js → chunk-PLHPKXAT.js} +6 -6
  53. package/dist/cli/{chunk-DHFMIBPG.js.map → chunk-PLHPKXAT.js.map} +1 -1
  54. package/dist/cli/{chunk-TFV3K6YS.js → chunk-VSSSU4AU.js} +3 -3
  55. package/dist/cli/{chunk-TFV3K6YS.js.map → chunk-VSSSU4AU.js.map} +1 -1
  56. package/dist/cli/chunk-ZCW56PZ3.js +8 -0
  57. package/dist/cli/{chunk-4KLYFXMW.js.map → chunk-ZCW56PZ3.js.map} +1 -1
  58. package/dist/cli/{chunk-AZL7RPFU.js → chunk-ZFVQWOGG.js} +64 -16
  59. package/dist/cli/chunk-ZFVQWOGG.js.map +1 -0
  60. package/dist/cli/config-WT5HHDRR.js +13 -0
  61. package/dist/cli/{config-3K65QJ22.js.map → config-WT5HHDRR.js.map} +1 -1
  62. package/dist/cli/index.js +51 -37
  63. package/dist/cli/index.js.map +1 -1
  64. package/dist/cli/{mcp-6F64A7KE.js → mcp-HHGNOUKE.js} +7 -7
  65. package/dist/cli/{mcp-6F64A7KE.js.map → mcp-HHGNOUKE.js.map} +1 -1
  66. package/dist/cli/payment-providers-EWXZFBIE.js +6 -0
  67. package/dist/cli/{payment-providers-2ITS6KNR.js.map → payment-providers-EWXZFBIE.js.map} +1 -1
  68. package/dist/cli/{provider-5BGG5YKQ.js → provider-XUPLYNQ7.js} +9 -9
  69. package/dist/cli/{provider-5BGG5YKQ.js.map → provider-XUPLYNQ7.js.map} +1 -1
  70. package/dist/cli/receipts-3DSV4DIK.js +9 -0
  71. package/dist/cli/{receipts-I4IIE7U6.js.map → receipts-3DSV4DIK.js.map} +1 -1
  72. package/dist/cli/reconcile-GS25MQ42.js +4 -0
  73. package/dist/cli/{reconcile-55WNCSFC.js.map → reconcile-GS25MQ42.js.map} +1 -1
  74. package/dist/cli/{run-2P6ZGFUE.js → run-7KLKW3HE.js} +107 -35
  75. package/dist/cli/run-7KLKW3HE.js.map +1 -0
  76. package/dist/cli/{x402-4LPIIELI.js → x402-HP4E3QET.js} +11 -10
  77. package/dist/cli/x402-HP4E3QET.js.map +1 -0
  78. package/dist/{guardrails-CX_jYXvZ.d.ts → guardrails-CeyLS1ou.d.ts} +2 -2
  79. package/dist/index.d.ts +23 -13
  80. package/dist/index.js +660 -170
  81. package/dist/index.js.map +1 -1
  82. package/dist/mcp.d.ts +2 -2
  83. package/dist/mcp.js +4 -4
  84. package/dist/mpp.js +5 -5
  85. package/dist/{protocol-adapter-1WbtM3xG.d.ts → protocol-adapter-DdFL5LBU.d.ts} +12 -2
  86. package/dist/{runtime-B-kARa2f.d.ts → runtime-BmaSp2Ce.d.ts} +31 -3
  87. package/dist/{store-kIIMpUA-.d.ts → store-BVvMzpuV.d.ts} +25 -8
  88. package/dist/testing.d.ts +1 -1
  89. package/dist/testing.js +156 -2
  90. package/dist/testing.js.map +1 -1
  91. package/dist/{transaction-Dv0UFGg5.d.ts → transaction-BXXJltZ-.d.ts} +1 -1
  92. package/dist/x402.d.ts +7 -2
  93. package/dist/x402.js +7 -6
  94. package/dist/x402.js.map +1 -1
  95. package/package.json +13 -29
  96. package/dist/chunk-5ZYXBCDX.js.map +0 -1
  97. package/dist/chunk-DRLBML7Z.js.map +0 -1
  98. package/dist/chunk-ES3V6ECS.js.map +0 -1
  99. package/dist/chunk-M52FBNJX.js.map +0 -1
  100. package/dist/chunk-M6BSXXTF.js +0 -8
  101. package/dist/chunk-M6MQ3FYS.js.map +0 -1
  102. package/dist/chunk-M6WW6QIT.js.map +0 -1
  103. package/dist/cli/ap2-2YMYA2H6.js.map +0 -1
  104. package/dist/cli/chunk-4KLYFXMW.js +0 -8
  105. package/dist/cli/chunk-5K4XEAZV.js.map +0 -1
  106. package/dist/cli/chunk-6R6WJ4FD.js +0 -18
  107. package/dist/cli/chunk-6R6WJ4FD.js.map +0 -1
  108. package/dist/cli/chunk-AZL7RPFU.js.map +0 -1
  109. package/dist/cli/chunk-FHCFR2GS.js +0 -17
  110. package/dist/cli/chunk-FHCFR2GS.js.map +0 -1
  111. package/dist/cli/chunk-GET3CZGR.js.map +0 -1
  112. package/dist/cli/chunk-NSYSMDQN.js.map +0 -1
  113. package/dist/cli/chunk-PTL7SNOI.js.map +0 -1
  114. package/dist/cli/chunk-SPAYKVUP.js.map +0 -1
  115. package/dist/cli/chunk-SYQLJXIU.js.map +0 -1
  116. package/dist/cli/chunk-YOF7IK4V.js.map +0 -1
  117. package/dist/cli/chunk-YWG2ZN3L.js.map +0 -1
  118. package/dist/cli/config-3K65QJ22.js +0 -12
  119. package/dist/cli/payment-providers-2ITS6KNR.js +0 -6
  120. package/dist/cli/receipts-I4IIE7U6.js +0 -8
  121. package/dist/cli/reconcile-55WNCSFC.js +0 -4
  122. package/dist/cli/run-2P6ZGFUE.js.map +0 -1
  123. package/dist/cli/x402-4LPIIELI.js.map +0 -1
@@ -1,12 +1,11 @@
1
- import { hasMethodGroup } from './chunk-6R6WJ4FD.js';
2
- import { buildAp2Descriptor } from './chunk-3EQBCFZY.js';
3
- export { AP2_CAPABILITIES, AP2_UNSUPPORTED, buildAp2Descriptor } from './chunk-3EQBCFZY.js';
4
- import { AP2_CHECKOUT_PROFILE, AP2_SIGNING_ALGORITHM, AP2_SPEC_VERSION, AP2_KEY_TYPE, AP2_JWK_CURVE, AP2_DIGEST_ALGORITHM, AP2_CHECKOUT_MANDATE_VCT } from './chunk-FHCFR2GS.js';
5
- export { AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_DIGEST_ALGORITHM, AP2_MAX_CLOCK_SKEW_SECONDS, AP2_MODES, AP2_SIGNING_ALGORITHM, AP2_SPEC_VERSION } from './chunk-FHCFR2GS.js';
6
- import { openSqliteDatabase } from './chunk-VJ4EO4LE.js';
7
- import { PACKAGE_VERSION } from './chunk-4KLYFXMW.js';
8
- import { NOOP_LOGGER, systemClock } from './chunk-GET3CZGR.js';
9
- import { CommerceError } from './chunk-SYQLJXIU.js';
1
+ import { buildAp2Descriptor } from './chunk-H7EBJ4I3.js';
2
+ export { AP2_CAPABILITIES, AP2_UNSUPPORTED, buildAp2Descriptor } from './chunk-H7EBJ4I3.js';
3
+ import { AP2_CHECKOUT_PROFILE, AP2_SIGNING_ALGORITHM, AP2_SPEC_VERSION, AP2_KEY_TYPE, AP2_JWK_CURVE, hasMethodGroup, AP2_DIGEST_ALGORITHM, AP2_CHECKOUT_MANDATE_VCT } from './chunk-DKWO6LLX.js';
4
+ export { AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_DIGEST_ALGORITHM, AP2_MAX_CLOCK_SKEW_SECONDS, AP2_MODES, AP2_SIGNING_ALGORITHM, AP2_SPEC_VERSION } from './chunk-DKWO6LLX.js';
5
+ import { openSqliteDatabase } from './chunk-6EBDOH37.js';
6
+ import { PACKAGE_VERSION } from './chunk-ZCW56PZ3.js';
7
+ import { NOOP_LOGGER, systemClock } from './chunk-55AI6CLW.js';
8
+ import { CommerceError } from './chunk-C5YISPT6.js';
10
9
  import { isRecord } from './chunk-3M6U7ILB.js';
11
10
  import { SignJWT, importPKCS8, importJWK, jwtVerify, decodeProtectedHeader, decodeJwt } from 'jose';
12
11
  import canonicalize from 'canonicalize';
@@ -730,5 +729,5 @@ function createAp2AuthorizationProvider(options) {
730
729
  }
731
730
 
732
731
  export { AP2_REJECTION_REASONS, createAp2AuthorizationProvider, createAp2ReplayStore, createCheckoutJwt };
733
- //# sourceMappingURL=ap2-2YMYA2H6.js.map
734
- //# sourceMappingURL=ap2-2YMYA2H6.js.map
732
+ //# sourceMappingURL=ap2-5FFGSW6F.js.map
733
+ //# sourceMappingURL=ap2-5FFGSW6F.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/authorization/ap2/errors.ts","../../src/authorization/ap2/sha256.ts","../../src/authorization/ap2/profile.ts","../../src/authorization/ap2/checkout-signer.ts","../../src/authorization/ap2/replay-store.ts","../../src/authorization/ap2/checkout-jwt.ts","../../src/authorization/ap2/sd-jwt.ts","../../src/authorization/ap2/trust.ts","../../src/authorization/ap2/verifier.ts","../../src/authorization/ap2/provider.ts"],"names":["jwtVerify"],"mappings":";;;;;;;;;;;;;;;AAqBO,IAAM,qBAAA,GAAwB;AAAA,EACnC,wBAAA;AAAA,EACA,kBAAA;AAAA,EACA,aAAA;AAAA,EACA,mBAAA;AAAA,EACA,gBAAA;AAAA,EACA,SAAA;AAAA,EACA,gBAAA;AAAA,EACA,0BAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF;AAIA,IAAM,QAAA,GAAyD;AAAA,EAC7D,sBAAA,EAAwB,6DAAA;AAAA,EACxB,gBAAA,EAAkB,iEAAA;AAAA,EAClB,WAAA,EAAa,+DAAA;AAAA,EACb,iBAAA,EAAmB,uCAAA;AAAA,EACnB,cAAA,EAAgB,+DAAA;AAAA,EAChB,OAAA,EAAS,0CAAA;AAAA,EACT,cAAA,EAAgB,mDAAA;AAAA,EAChB,wBAAA,EAA0B,sDAAA;AAAA,EAC1B,uBAAA,EAAyB,qEAAA;AAAA,EACzB,iBAAA,EAAmB;AACrB,CAAA;AASO,SAAS,WAAA,CACd,MAAA,EACA,OAAA,GAA2B,EAAC,EACb;AACf,EAAA,OAAO,IAAI,aAAA,CAAc,uBAAA,EAAyB,QAAA,CAAS,MAAM,CAAA,EAAG;AAAA,IAClE,OAAA,EAAS,EAAE,MAAA,EAAQ,KAAA,EAAO,MAAA,EAAO;AAAA,IACjC,GAAI,QAAQ,SAAA,KAAc,MAAA,GAAY,EAAE,SAAA,EAAW,OAAA,CAAQ,SAAA,EAAU,GAAI,EAAC;AAAA,IAC1E,GAAI,QAAQ,UAAA,KAAe,MAAA,GAAY,EAAE,UAAA,EAAY,OAAA,CAAQ,UAAA,EAAW,GAAI,EAAC;AAAA,IAC7E,GAAI,QAAQ,KAA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MAAA,MAAM,SAAA,GAAY,MAAM,MAAA,EAAO;AAC/B,MAAA,IAAI,SAAA,GAAY,IAAA;AAChB,MAAA,IAAI;AAGF,QAAA,MAAM,KAAA,CAAM,QAAQ,cAAc,CAAA;AAAA,MACpC,CAAA,CAAA,MAAQ;AACN,QAAA,SAAA,GAAY,KAAA;AAAA,MACd;AACA,MAAA,MAAM,aAAa,IAAA,CAAK,KAAA,CAAM,KAAA,CAAM,WAAA,KAAgB,SAAS,CAAA;AAC7D,MAAA,IAAI,CAAC,SAAA,EAAW;AAEd,QAAA,OAAO,EAAE,MAAA,EAAQ,MAAA,EAAQ,SAAA,EAAW,UAAA,EAAY,QAAQ,0BAAA,EAA2B;AAAA,MACrF;AACA,MAAA,MAAM,OAAA,GAAU,SAAS,cAAA,EAAe;AACxC,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,MAAA;AAAA,QACR,SAAA;AAAA,QACA,UAAA;AAAA,QACA,MAAA,EAAQ,mBAAmB,OAAA,CAAQ,OAAA,CAAQ,MAAM,CAAA,kBAAA,EAAqB,OAAA,CAAQ,SAAS,MAAM,CAAA;AAAA,OAC/F;AAAA,IACF,CAAA;AAAA,IAEA,KAAA,GAAQ;AACN,MAAA,KAAA,CAAM,KAAA,EAAM;AAAA,IACd;AAAA,GACF;AACF","file":"ap2-5FFGSW6F.js","sourcesContent":["/**\n * Every failure the AP2 verifier can report.\n *\n * `CommerceError.message` reaches the client, and a mandate carries the\n * buyer's purchase and often personal data, so messages are fixed phrases from\n * the list below. The machine-readable code goes in `details.reason` and the\n * original exception on `cause`, which is never serialized.\n *\n * Three codes: AUTHORIZATION_INVALID when the buyer's mandate is bad,\n * AUTHORIZATION_REPLAYED when it is good but spent, and\n * AUTHORIZATION_PROVIDER_UNAVAILABLE when our verifier never reached a\n * verdict. Blaming the buyer for our outage refuses a good mandate.\n */\nimport { CommerceError } from '../../core';\n\n/**\n * Coarse on purpose: a client learns roughly where its mandate was refused,\n * not which check failed. Finer detail is an oracle for probing trust policy,\n * so a mandate signed with a disallowed algorithm reports `invalid_signature`\n * and one declaring a digest other than sha-256 `malformed_presentation`.\n */\nexport const AP2_REJECTION_REASONS = [\n 'malformed_presentation',\n 'untrusted_issuer',\n 'unknown_key',\n 'invalid_signature',\n 'invalid_claims',\n 'expired',\n 'wrong_audience',\n 'unsupported_mandate_type',\n 'checkout_binding_failed',\n 'purchase_mismatch',\n] as const;\n\nexport type Ap2RejectionReason = (typeof AP2_REJECTION_REASONS)[number];\n\nconst MESSAGES: Readonly<Record<Ap2RejectionReason, string>> = {\n malformed_presentation: 'The authorization is not a well-formed SD-JWT presentation.',\n untrusted_issuer: 'The mandate was issued by a party this merchant does not trust.',\n unknown_key: 'The mandate names a signing key this merchant does not trust.',\n invalid_signature: 'The mandate signature did not verify.',\n invalid_claims: 'The mandate is missing required claims or they are malformed.',\n expired: 'The mandate is expired or not yet valid.',\n wrong_audience: 'The mandate is addressed to a different audience.',\n unsupported_mandate_type: 'The mandate is not a closed Direct Checkout Mandate.',\n checkout_binding_failed: 'The merchant checkout document bound to the mandate did not verify.',\n purchase_mismatch: 'The mandate does not authorize this purchase.',\n};\n\nexport interface Ap2ErrorContext {\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly cause?: unknown;\n}\n\n/** The buyer's mandate is bad. Fail closed */\nexport function ap2Rejected(\n reason: Ap2RejectionReason,\n context: Ap2ErrorContext = {},\n): CommerceError {\n return new CommerceError('AUTHORIZATION_INVALID', MESSAGES[reason], {\n details: { method: 'ap2', reason },\n ...(context.requestId !== undefined ? { requestId: context.requestId } : {}),\n ...(context.resourceId !== undefined ? { resourceId: context.resourceId } : {}),\n ...(context.cause !== undefined ? { cause: context.cause } : {}),\n });\n}\n\n/**\n * The mandate verified but has already been presented. A separate code from\n * a bad mandate: nothing is wrong with this mandate except that it is spent.\n */\nexport function ap2Replayed(state: string, context: Ap2ErrorContext = {}): CommerceError {\n return new CommerceError(\n 'AUTHORIZATION_REPLAYED',\n 'This mandate has already been presented and cannot authorize another purchase.',\n {\n details: { method: 'ap2', reason: 'replayed', state },\n ...(context.requestId !== undefined ? { requestId: context.requestId } : {}),\n ...(context.resourceId !== undefined ? { resourceId: context.resourceId } : {}),\n },\n );\n}\n\n/**\n * The check never ran (a configured key that will not import, say). Retryable,\n * and never recorded against the payer: the mandate may be perfectly good.\n */\nexport function ap2Unavailable(detail: string, context: Ap2ErrorContext = {}): CommerceError {\n return new CommerceError(\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'Authorization could not be verified right now. This is a merchant-side fault, not a problem with the presented mandate.',\n {\n details: { method: 'ap2', reason: 'verifier_unavailable', detail },\n ...(context.requestId !== undefined ? { requestId: context.requestId } : {}),\n ...(context.resourceId !== undefined ? { resourceId: context.resourceId } : {}),\n ...(context.cause !== undefined ? { cause: context.cause } : {}),\n },\n );\n}\n","import { createHash } from 'node:crypto';\n\n/** SHA-256, the only digest AP2 verification and signing use. A string is hashed as UTF-8 */\nexport function sha256(data: string | Uint8Array): Buffer {\n return createHash('sha256').update(data).digest();\n}\n","/**\n * Binds a verified mandate to the purchase in front of us. Without this\n * comparison a mandate approved for a $0.01 report would settle a $500 one.\n *\n * Everything is compared against the ALREADY RESOLVED request. Nothing is\n * taken from the mandate to shape the purchase, which would invert the\n * control.\n */\nimport canonicalize from 'canonicalize';\nimport { type AuthorizationVerificationContext, CommerceError } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { AP2_CHECKOUT_PROFILE } from './constants';\nimport { type Ap2ErrorContext, ap2Rejected } from './errors';\nimport { sha256 } from './sha256';\nimport type { VerifiedCheckoutMandate } from './types';\n\n/**\n * All required. Absent is a mismatch, never a skipped check: a mandate that\n * will not say which resource or how much authorizes nothing in particular.\n */\nconst REQUIRED_PROFILE_CLAIMS = [\n 'profile',\n 'resource_id',\n 'input_hash',\n 'amount',\n 'currency',\n 'payment_method',\n] as const;\n\n/**\n * RFC 8785 (JCS) digest of the validated resource input.\n *\n * Binds a mandate to the exact request, not just to a resource and a price:\n * without it, one mandate for `translate` would authorize any translation.\n *\n * The merchant's signer, possibly in another language, agrees with this digest\n * only if it follows RFC 8785's number formatting and UTF-16 key ordering too;\n * sorting keys is not enough.\n *\n * The caller passes what the backend will receive: validated, reserved fields\n * stripped, no request id or transport metadata (the buyer could not have\n * known those when they approved).\n */\nexport function computeInputHash(input: unknown): string {\n const canonical = canonicalize(input ?? {});\n // undefined means JSON cannot represent the value (a function, say). On the\n // gateway path the input already passed schema validation, so this is not a\n // buyer error.\n if (canonical === undefined) {\n throw new CommerceError('INTERNAL_ERROR', 'resource input is not canonicalizable JSON');\n }\n return sha256(canonical).toString('base64url');\n}\n\nconst EVM_ADDRESS = /^0x[0-9a-f]{40}$/i;\n\n// EIP-55 encodes an address checksum through letter casing, so lowercase and\n// checksummed forms identify the same account. Other values compare exactly.\nfunction sameCoordinate(declared: unknown, expected: string | undefined): boolean {\n if (typeof declared === 'string' && expected !== undefined) {\n if (EVM_ADDRESS.test(declared) && EVM_ADDRESS.test(expected)) {\n return declared.toLowerCase() === expected.toLowerCase();\n }\n }\n return declared === expected;\n}\n\n/**\n * Throws on the first mismatch with one coarse reason. Which field disagreed\n * is not reported: a caller able to ask about one field at a time can read a\n * mandate's contents out of the gateway by elimination.\n */\nexport async function bindMandateToPurchase(\n mandate: VerifiedCheckoutMandate,\n context: AuthorizationVerificationContext,\n errorContext: Ap2ErrorContext,\n): Promise<void> {\n const profile = mandate.checkoutClaims['agent_commerce'];\n if (!isRecord(profile)) throw ap2Rejected('purchase_mismatch', errorContext);\n\n for (const claim of REQUIRED_PROFILE_CLAIMS) {\n const value = profile[claim];\n if (typeof value !== 'string' || value.length === 0) {\n throw ap2Rejected('purchase_mismatch', errorContext);\n }\n }\n\n const requirement = context.requirement;\n const expectedInputHash = computeInputHash(context.input);\n\n const mustMatch: readonly (readonly [string, unknown])[] = [\n ['profile', AP2_CHECKOUT_PROFILE],\n ['resource_id', context.resourceId],\n ['input_hash', expectedInputHash],\n // Decimal strings on both sides. Comparing numerically would make \"0.10\"\n // and \"0.1\" equal, and a mandate says what it says.\n ['amount', requirement.amount],\n ['currency', requirement.currency],\n ['payment_method', requirement.provider],\n ];\n\n for (const [claim, expected] of mustMatch) {\n if (profile[claim] !== expected) throw ap2Rejected('purchase_mismatch', errorContext);\n }\n\n // Checked whenever EITHER side names one, which is the fail-closed reading.\n // A mandate silent about the chain must not unlock a mainnet settlement, and\n // one naming a chain the requirement lacks was approved for another rail.\n for (const [claim, expected] of [\n ['destination', requirement.destination],\n ['network', requirement.network],\n ['asset', requirement.asset],\n ] as const) {\n const declared = profile[claim];\n if (declared === undefined && expected === undefined) continue;\n if (!sameCoordinate(declared, expected)) throw ap2Rejected('purchase_mismatch', errorContext);\n }\n}\n","/**\n * Merchant-side helper: mints the checkout JWT a Checkout Mandate binds.\n *\n * A merchant runs it in their own process, with their own key, to produce the\n * document the buyer approves; the gateway never calls it. It mirrors\n * `createPaymentProof`, which a buyer runs to produce a payment proof.\n *\n * It exists mainly for `input_hash`, an RFC 8785 digest. A serializer that\n * only sorts keys, as many non-JavaScript JSON libraries do, can disagree with\n * it on floats and non-ASCII keys, and the mandate is then refused with a\n * reason that does not name the field.\n */\nimport { importPKCS8, type JWK, SignJWT } from 'jose';\nimport {\n AP2_CHECKOUT_PROFILE,\n AP2_JWK_CURVE,\n AP2_KEY_TYPE,\n AP2_SIGNING_ALGORITHM,\n} from './constants';\nimport { computeInputHash } from './profile';\n\n/**\n * A private ES256 key: either a private JWK (the pair of the public one in the\n * gateway's `checkoutIssuers`) or a PKCS#8 PEM, as `openssl` emits it\n */\nexport type Ap2SigningKey = Readonly<Record<string, unknown>> | string;\n\nexport interface CreateCheckoutJwtOptions {\n readonly privateKey: Ap2SigningKey;\n /** Must match a `kid` configured under the gateway's `checkoutIssuers` */\n readonly kid: string;\n /** Must match that issuer's configured `issuer` */\n readonly issuer: string;\n /** Must match that issuer's configured `audience` */\n readonly audience: string;\n\n readonly resourceId: string;\n /**\n * The resource input this purchase is for, exactly as the buyer will send\n * it: no reserved fields, no request id, no transport metadata\n */\n readonly input: unknown;\n\n /**\n * Decimal string, never a number, and compared as a string: `0.10` and `0.1`\n * are different mandates. Take it from your own catalog rather than from\n * whatever the agent asked for.\n */\n readonly amount: string;\n readonly currency: string;\n /** The rail that will settle, e.g. `x402` */\n readonly paymentMethod: string;\n\n /**\n * Settlement coordinates. Required whenever the gateway's requirement names\n * them, which under x402 is always. A mandate silent about the chain will\n * not unlock a settlement on one.\n */\n readonly destination?: string;\n readonly network?: string;\n readonly asset?: string;\n\n /** Defaults to a random UUID. Recorded on the receipt and used for replay defense */\n readonly jwtId?: string;\n /** Defaults to 900: a human approval sits inside this window */\n readonly expiresInSeconds?: number;\n /** Injectable so a test need not move the wall clock */\n readonly now?: Date;\n}\n\nconst DEFAULT_EXPIRES_IN_SECONDS = 900;\n\nfunction requireText(value: unknown, field: string): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new TypeError(\n `createCheckoutJwt: ${field} must be a non-empty string, received ${describe(value)}`,\n );\n }\n return value;\n}\n\nfunction describe(value: unknown): string {\n return value === null ? 'null' : typeof value;\n}\n\n/**\n * Every rejection here is a mistake that would otherwise surface as an opaque\n * verification failure much later: the public half of the pair, the wrong key\n * type, or a PEM that is not PKCS#8\n */\nasync function resolveKey(\n key: Ap2SigningKey,\n): Promise<JWK | Awaited<ReturnType<typeof importPKCS8>>> {\n if (typeof key === 'string') {\n if (!key.includes('BEGIN PRIVATE KEY')) {\n throw new TypeError(\n 'createCheckoutJwt: a string privateKey must be a PKCS#8 PEM beginning \"-----BEGIN PRIVATE KEY-----\"',\n );\n }\n return importPKCS8(key, AP2_SIGNING_ALGORITHM);\n }\n if (typeof key !== 'object' || key === null) {\n throw new TypeError('createCheckoutJwt: privateKey must be a private JWK or a PKCS#8 PEM');\n }\n if (key['d'] === undefined) {\n throw new TypeError(\n 'createCheckoutJwt: privateKey is a public JWK (no \"d\"). Use the private half of the pair whose public key is configured under checkoutIssuers',\n );\n }\n if (key['kty'] !== AP2_KEY_TYPE || key['crv'] !== AP2_JWK_CURVE) {\n throw new TypeError(\n `createCheckoutJwt: privateKey must be ${AP2_KEY_TYPE}/${AP2_JWK_CURVE}, the pair ${AP2_SIGNING_ALGORITHM} implies`,\n );\n }\n return key as JWK;\n}\n\n/**\n * Returns the compact JWT to hand to the agent, which wraps it in the Checkout\n * Mandate the buyer signs\n */\nexport async function createCheckoutJwt(options: CreateCheckoutJwtOptions): Promise<string> {\n const kid = requireText(options.kid, 'kid');\n const issuer = requireText(options.issuer, 'issuer');\n const audience = requireText(options.audience, 'audience');\n const resourceId = requireText(options.resourceId, 'resourceId');\n const currency = requireText(options.currency, 'currency');\n const paymentMethod = requireText(options.paymentMethod, 'paymentMethod');\n\n if (typeof options.amount === 'number') {\n throw new TypeError(\n 'createCheckoutJwt: amount must be a decimal string, not a number. It is compared as a string, so 0.1 and \"0.10\" are different mandates',\n );\n }\n const amount = requireText(options.amount, 'amount');\n\n const key = await resolveKey(options.privateKey);\n const issuedAt = Math.floor((options.now ?? new Date()).getTime() / 1000);\n const expiresIn = options.expiresInSeconds ?? DEFAULT_EXPIRES_IN_SECONDS;\n if (!Number.isInteger(expiresIn) || expiresIn <= 0) {\n throw new TypeError('createCheckoutJwt: expiresInSeconds must be a positive whole number');\n }\n\n const agentCommerce: Record<string, string> = {\n profile: AP2_CHECKOUT_PROFILE,\n resource_id: resourceId,\n input_hash: computeInputHash(options.input),\n amount,\n currency,\n payment_method: paymentMethod,\n ...(options.destination !== undefined ? { destination: options.destination } : {}),\n ...(options.network !== undefined ? { network: options.network } : {}),\n ...(options.asset !== undefined ? { asset: options.asset } : {}),\n };\n\n return new SignJWT({ agent_commerce: agentCommerce })\n .setProtectedHeader({ alg: AP2_SIGNING_ALGORITHM, kid, typ: 'JWT' })\n .setIssuer(issuer)\n .setAudience(audience)\n .setIssuedAt(issuedAt)\n .setExpirationTime(issuedAt + expiresIn)\n .setJti(options.jwtId ?? crypto.randomUUID())\n .sign(key);\n}\n","/**\n * Durable record of which mandates have been spent.\n *\n * Its own table in its own file: a payment replay key is needed only until its\n * authorization's `validBefore`, after which it cannot settle, while a consumed\n * mandate must stay consumed for as long as the merchant can be asked what they\n * delivered. Hence no retention sweep, unlike the ACP idempotency store:\n * deleting a `consumed` row makes that mandate spendable again. If the table\n * ever needs bounding, archive `released` rows and leave the rest.\n *\n * Settlement and replay-state updates are separate transactions. A crash\n * between them leaves the mandate `reserved`, blocking retries until its\n * payment is resolved and the hold is updated. This favors a refused retry\n * over a possible second payment.\n */\nimport type { Database } from 'better-sqlite3';\nimport { type Logger, NOOP_LOGGER } from '../../core';\nimport { openSqliteDatabase } from '../../storage/sqlite';\n\n/**\n * `released` permits another reservation; other states block reuse.\n * `uncertain` records an unknown settlement outcome and stays blocked until\n * payment resolution is followed by a consume or release update.\n */\nexport type Ap2AuthorizationState = 'reserved' | 'consumed' | 'released' | 'uncertain';\n\n/**\n * A digest and a few identifiers: everything replay defense needs, and nothing\n * a leaked database would hand an attacker\n */\nexport interface Ap2ReservationRequest {\n /**\n * Digest of the ISSUER-SIGNED TOKEN, not of the presentation. Selective\n * disclosure gives one mandate many presentation strings, so keying on the\n * presentation would let it be spent once per disclosed subset.\n */\n readonly reference: string;\n /** `jti` of the merchant checkout JWT the mandate binds */\n readonly checkoutJti: string;\n readonly mandateIssuer: string;\n readonly checkoutIssuer: string;\n readonly resourceId: string;\n readonly requestId: string;\n}\n\nexport type Ap2ReservationResult =\n | { readonly kind: 'reserved' }\n /** Already reserved, consumed or uncertain; refuse this reservation */\n | { readonly kind: 'replayed'; readonly state: Ap2AuthorizationState };\n\n// A store written against 2.4 returns nothing, which counts as applied; only an\n// explicit false is a refusal\n// biome-ignore lint/suspicious/noConfusingVoidType: keeps void-returning stores assignable\ntype TransitionResult = boolean | void;\n\nexport interface Ap2ReplayStore {\n /** Atomically claim a mandate, or report that something already holds it */\n reserve(request: Ap2ReservationRequest): Ap2ReservationResult;\n /**\n * Mark the mandate permanently spent, targeting only the supplied\n * `requestId` when present. Returns true when the matching reservation is\n * consumed, including on a repeated call, and false otherwise.\n */\n consume(reference: string, requestId?: string): TransitionResult;\n /**\n * Release a reservation for reuse. Returns true if it is released or the\n * supplied `requestId` differs from the current holder; a different holder\n * is left unchanged. Returns false otherwise.\n */\n release(reference: string, requestId?: string): TransitionResult;\n /**\n * Record an unknown settlement outcome for operator review and block reuse.\n * Returns true when the matching reservation is uncertain, including on a\n * repeated call, and false otherwise.\n */\n markUncertain(reference: string, requestId?: string): TransitionResult;\n /** Current state, for tests and diagnostics */\n stateOf(reference: string): Ap2AuthorizationState | undefined;\n close(): void;\n}\n\nexport interface Ap2ReplayStoreOptions {\n /** File path, or ':memory:' for tests */\n readonly path: string;\n readonly logger?: Logger;\n /** Injectable so tests need not move the wall clock */\n readonly now?: () => number;\n}\n\ninterface StateRow {\n state: string;\n}\n\nexport function createAp2ReplayStore(options: Ap2ReplayStoreOptions): Ap2ReplayStore {\n const logger = options.logger ?? NOOP_LOGGER;\n const now = options.now ?? (() => Date.now());\n\n const db: Database = openSqliteDatabase({\n path: options.path,\n label: 'AP2 authorization database',\n logger,\n });\n migrate(db);\n\n const selectByReference = db.prepare<[string], StateRow>(\n 'SELECT state FROM ap2_authorizations WHERE reference = ?',\n );\n // Two mandates can bind one checkout document, giving two references, so\n // the reference alone would not catch the second one\n const selectLiveByJti = db.prepare<[string, string], StateRow>(\n `SELECT state FROM ap2_authorizations\n WHERE checkout_jti = ? AND reference != ? AND state != 'released'`,\n );\n const insert = db.prepare(\n `INSERT INTO ap2_authorizations\n (reference, checkout_jti, mandate_issuer, checkout_issuer, resource_id, request_id,\n state, created_at, updated_at)\n VALUES (@reference, @checkout_jti, @mandate_issuer, @checkout_issuer, @resource_id,\n @request_id, 'reserved', @at, @at)`,\n );\n const reReserve = db.prepare(\n `UPDATE ap2_authorizations\n SET state = 'reserved', request_id = @request_id, updated_at = @at\n WHERE reference = @reference AND state = 'released'`,\n );\n // These updates leave consumed and released rows unchanged; a consumed\n // mandate must not become reusable. reserve() can claim released rows again.\n // When supplied, requestId prevents a late update from changing another\n // request's reservation.\n const transition = db.prepare(\n `UPDATE ap2_authorizations SET state = @state, updated_at = @at\n WHERE reference = @reference AND state IN ('reserved', 'uncertain')\n AND (@request_id IS NULL OR request_id = @request_id)`,\n );\n const selectHolder = db.prepare<[string], StateRow & { request_id: string }>(\n 'SELECT state, request_id FROM ap2_authorizations WHERE reference = ?',\n );\n\n const reserveTx = db.transaction((request: Ap2ReservationRequest): Ap2ReservationResult => {\n const at = new Date(now()).toISOString();\n\n const existing = selectByReference.get(request.reference);\n if (existing !== undefined && existing.state !== 'released') {\n return { kind: 'replayed', state: existing.state as Ap2AuthorizationState };\n }\n\n // Checked for a released reference too: another mandate may have reserved\n // or spent the same checkout while this one was released\n const sameCheckout = selectLiveByJti.get(request.checkoutJti, request.reference);\n if (sameCheckout !== undefined) {\n return { kind: 'replayed', state: sameCheckout.state as Ap2AuthorizationState };\n }\n\n if (existing !== undefined) {\n reReserve.run({ reference: request.reference, request_id: request.requestId, at });\n return { kind: 'reserved' };\n }\n\n insert.run({\n reference: request.reference,\n checkout_jti: request.checkoutJti,\n mandate_issuer: request.mandateIssuer,\n checkout_issuer: request.checkoutIssuer,\n resource_id: request.resourceId,\n request_id: request.requestId,\n at,\n });\n return { kind: 'reserved' };\n });\n\n const move = (reference: string, state: Ap2AuthorizationState, requestId?: string): boolean => {\n const { changes } = transition.run({\n reference,\n state,\n request_id: requestId ?? null,\n at: new Date(now()).toISOString(),\n });\n if (changes > 0) return true;\n const row = selectHolder.get(reference);\n if (row === undefined) return false;\n // A different holder can follow a release and re-reservation; acknowledge\n // an old release without changing the current reservation\n if (requestId !== undefined && row.request_id !== requestId) return state === 'released';\n return row.state === state;\n };\n\n let closed = false;\n return {\n reserve(request) {\n return reserveTx(request);\n },\n consume(reference, requestId) {\n return move(reference, 'consumed', requestId);\n },\n release(reference, requestId) {\n return move(reference, 'released', requestId);\n },\n markUncertain(reference, requestId) {\n return move(reference, 'uncertain', requestId);\n },\n stateOf(reference) {\n return selectByReference.get(reference)?.state as Ap2AuthorizationState | undefined;\n },\n close() {\n if (closed) return;\n closed = true;\n db.close();\n },\n };\n}\n\n// `PRAGMA user_version`, so reopening an existing file is a no-op check\nfunction migrate(db: Database): void {\n const current = db.pragma('user_version', { simple: true }) as number;\n if (current >= 1) return;\n const apply = db.transaction(() => {\n db.exec(`\n CREATE TABLE IF NOT EXISTS ap2_authorizations (\n reference TEXT PRIMARY KEY,\n checkout_jti TEXT NOT NULL,\n mandate_issuer TEXT NOT NULL,\n checkout_issuer TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n request_id TEXT NOT NULL,\n state TEXT NOT NULL\n CHECK (state IN ('reserved', 'consumed', 'released', 'uncertain')),\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_ap2_authorizations_checkout_jti\n ON ap2_authorizations(checkout_jti);\n `);\n db.pragma('user_version = 1');\n });\n apply();\n}\n","/**\n * Stage two: the merchant checkout JWT the mandate binds.\n *\n * Two things have to hold. The hash proves the buyer approved *this* document;\n * the signature proves the merchant issued it. Hash alone accepts a document\n * the buyer wrote themselves; signature alone accepts a genuine merchant\n * document this mandate never covered.\n */\nimport { decodeJwt, decodeProtectedHeader, type JWTVerifyOptions, jwtVerify } from 'jose';\nimport type { Clock } from '../../core';\nimport { AP2_SIGNING_ALGORITHM } from './constants';\nimport { type Ap2ErrorContext, ap2Rejected } from './errors';\nimport { sha256 } from './sha256';\nimport type { TrustStore } from './trust';\n\nexport interface VerifiedCheckoutJwt {\n readonly issuer: string;\n readonly jwtId: string;\n readonly claims: Readonly<Record<string, unknown>>;\n}\n\n/**\n * `mandateClaims` must come from an already-verified mandate: `checkout_hash`\n * is worth nothing unless the issuer signed it\n */\nexport async function verifyCheckoutJwt(\n mandateClaims: Readonly<Record<string, unknown>>,\n deps: { readonly trust: TrustStore; readonly clock: Clock; readonly clockSkewSeconds: number },\n context: Ap2ErrorContext,\n): Promise<VerifiedCheckoutJwt> {\n const compact = mandateClaims['checkout_jwt'];\n const expectedHash = mandateClaims['checkout_hash'];\n if (typeof compact !== 'string' || compact.length === 0) {\n throw ap2Rejected('invalid_claims', context);\n }\n if (typeof expectedHash !== 'string' || expectedHash.length === 0) {\n throw ap2Rejected('invalid_claims', context);\n }\n\n requireMatchingHash(compact, expectedHash, context);\n\n // Unverified, and read only to pick which configured key to try\n let header: ReturnType<typeof decodeProtectedHeader>;\n let unverifiedPayload: ReturnType<typeof decodeJwt>;\n try {\n header = decodeProtectedHeader(compact);\n unverifiedPayload = decodeJwt(compact);\n } catch (cause) {\n throw ap2Rejected('checkout_binding_failed', { ...context, cause });\n }\n\n const { issuer, key } = await deps.trust.resolve(unverifiedPayload.iss, header.kid, context);\n\n const options: JWTVerifyOptions = {\n algorithms: [AP2_SIGNING_ALGORITHM],\n issuer: issuer.issuer,\n audience: issuer.audience,\n clockTolerance: deps.clockSkewSeconds,\n currentDate: deps.clock.now(),\n };\n\n let claims: Record<string, unknown>;\n try {\n const result = await jwtVerify(compact, key, options);\n claims = result.payload as Record<string, unknown>;\n } catch (cause) {\n throw ap2Rejected('checkout_binding_failed', { ...context, cause });\n }\n\n const exp = claims['exp'];\n const iat = claims['iat'];\n const jti = claims['jti'];\n // jose validates a time claim only when present, so requiring them is ours\n if (typeof exp !== 'number' || typeof iat !== 'number') {\n throw ap2Rejected('invalid_claims', context);\n }\n // `jti` is what replay defense and the receipt record, so it is required\n if (typeof jti !== 'string' || jti.length === 0) {\n throw ap2Rejected('invalid_claims', context);\n }\n const nowSeconds = Math.floor(deps.clock.now().getTime() / 1000);\n if (iat > nowSeconds + deps.clockSkewSeconds) throw ap2Rejected('expired', context);\n\n return { issuer: issuer.issuer, jwtId: jti, claims };\n}\n\n/**\n * Hashes the compact JWT as it arrived. Re-encoding the parsed claims would\n * hash a different document from the one being verified.\n */\nfunction requireMatchingHash(compact: string, expected: string, context: Ap2ErrorContext): void {\n // sha-256 only: `_sd_alg` was already pinned to it upstream\n const actual = sha256(compact).toString('base64url');\n // Plain comparison: both sides are public to anyone holding the\n // presentation, so there is no secret for timing to leak\n if (actual !== expected) throw ap2Rejected('checkout_binding_failed', context);\n}\n","/**\n * Parse the presentation, verify the issuer's signature, resolve disclosures,\n * and read the mandate from `delegate_payload`.\n *\n * `@sd-jwt/core` handles disclosures, including malformed, duplicate, and\n * unreferenced disclosures. `jose` verifies the signature. This module applies\n * the configured key, algorithm, audience, and time policy.\n */\nimport { decodeSdJwt, getClaims, splitSdJwt } from '@sd-jwt/core';\nimport { type JWTVerifyOptions, jwtVerify } from 'jose';\nimport type { Clock } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { AP2_CHECKOUT_MANDATE_VCT, AP2_DIGEST_ALGORITHM, AP2_SIGNING_ALGORITHM } from './constants';\nimport { type Ap2ErrorContext, ap2Rejected } from './errors';\nimport { sha256 } from './sha256';\nimport type { TrustStore } from './trust';\n\nexport interface VerifiedMandate {\n readonly issuer: string;\n /** The mandate element, with its nested disclosures resolved */\n readonly claims: Readonly<Record<string, unknown>>;\n /**\n * The issuer-signed token on its own, without the disclosures.\n *\n * This, not the presentation string, is the stable identity of a mandate:\n * disclosing or withholding an optional claim rewrites the presentation and\n * leaves the signed token untouched. Replay defense keys on a digest of it.\n */\n readonly signedToken: string;\n}\n\n/**\n * `@sd-jwt/core` passes the algorithm it read from `_sd_alg`, so this is also\n * where a presentation declaring anything but sha-256 is refused\n */\nfunction hasher(data: string | ArrayBuffer, algorithm: string): Uint8Array {\n if (algorithm.toLowerCase() !== AP2_DIGEST_ALGORITHM) {\n throw ap2Rejected('malformed_presentation');\n }\n return sha256(typeof data === 'string' ? data : new Uint8Array(data));\n}\n\n/**\n * Order is the security boundary here: nothing is trusted until `jwtVerify`\n * returns. `kid` and `iss` are read before that only to pick which configured\n * key to try, and picking wrong just makes the signature fail.\n */\n// Both spellings of the renamed Delegate SD-JWT hop types\nconst KEY_BOUND_TYPES: ReadonlySet<string> = new Set([\n 'kb+sd-jwt',\n 'kb-sd-jwt',\n 'kb+sd-jwt+kb',\n 'kb-sd-jwt+kb',\n]);\n\nexport async function verifyMandate(\n presentation: string,\n deps: MandatePolicy,\n context: Ap2ErrorContext,\n): Promise<VerifiedMandate> {\n // Direct mode does not verify `~~`-joined delegation chains.\n if (presentation.includes('~~')) {\n throw ap2Rejected('unsupported_mandate_type', context);\n }\n\n let decoded: Awaited<ReturnType<typeof decodeSdJwt>>;\n let encodedJws: string;\n try {\n // Covers a malformed base JWT, a disclosure that will not decode, a\n // duplicate digest, and an `_sd_alg` other than sha-256\n decoded = await decodeSdJwt(presentation, hasher);\n encodedJws = splitSdJwt(presentation).jwt;\n } catch (cause) {\n throw ap2Rejected('malformed_presentation', { ...context, cause });\n }\n\n // Direct mode issues no key-bound mandates, so one arriving here belongs to\n // a flow we do not verify. Ignoring it would mean silently not checking a\n // proof that was sent.\n if (decoded.kbJwt !== undefined) {\n throw ap2Rejected('unsupported_mandate_type', context);\n }\n\n const rawPayload = decoded.jwt.payload;\n const header = decoded.jwt.header;\n if (!isRecord(rawPayload) || !isRecord(header)) {\n throw ap2Rejected('malformed_presentation', context);\n }\n\n // Reject a delegation hop presented without its mandate. Its type or\n // preceding-token hash identifies it.\n if (\n KEY_BOUND_TYPES.has(String(header['typ'])) ||\n rawPayload['sd_hash'] !== undefined ||\n rawPayload['issuer_jwt_hash'] !== undefined\n ) {\n throw ap2Rejected('unsupported_mandate_type', context);\n }\n\n const { issuer, key } = await deps.trust.resolve(rawPayload['iss'], header['kid'], context);\n\n // AP2 permits an absent `aud`. If present, it must match the issuer's\n // configured audience. The checkout JWT has a separate audience check.\n const hasAudience = rawPayload['aud'] !== undefined;\n if (!hasAudience && deps.requireAudience === true) {\n throw ap2Rejected('invalid_claims', context);\n }\n\n const options: JWTVerifyOptions = {\n // Redundant with one resolved EC key, which already refuses `alg: none` and\n // a forged HMAC. It stops the header picking the algorithm if a key set is\n // ever resolved instead.\n algorithms: [AP2_SIGNING_ALGORITHM],\n // Also redundant, since the key was resolved *from* `iss`, and kept as a\n // backstop for a resolver that matches on something else\n ...(rawPayload['iss'] !== undefined ? { issuer: issuer.issuer } : {}),\n // Not redundant: `aud` is the presenter's claim, checked against the\n // configured value\n ...(hasAudience ? { audience: issuer.audience } : {}),\n clockTolerance: deps.clockSkewSeconds,\n // Injected clock, not jose's `Date.now()`, so expiry is testable\n currentDate: deps.clock.now(),\n };\n\n let verifiedPayload: Record<string, unknown>;\n try {\n const result = await jwtVerify(encodedJws, key, options);\n verifiedPayload = result.payload as Record<string, unknown>;\n } catch (cause) {\n throw ap2Rejected(classifyJoseFailure(cause), { ...context, cause });\n }\n\n let claims: Record<string, unknown>;\n try {\n // Against the VERIFIED payload: the decoded one would match disclosures\n // against digests nobody signed\n claims = (await getClaims(verifiedPayload, decoded.disclosures, hasher)) as Record<\n string,\n unknown\n >;\n } catch (cause) {\n // Where an appended disclosure that no digest references is refused\n throw ap2Rejected('malformed_presentation', { ...context, cause });\n }\n\n const mandate = delegatedMandate(claims, context);\n // This verifier rejects KB-JWTs, so it cannot check a `cnf` holder-key\n // binding. Reject the mandate rather than ignore the binding.\n if (claims['cnf'] !== undefined || mandate['cnf'] !== undefined) {\n throw ap2Rejected('unsupported_mandate_type', context);\n }\n requireClosedCheckoutMandate(mandate, context);\n // Closed mandates cannot carry constraints this verifier does not evaluate\n if (mandate['constraints'] !== undefined) {\n throw ap2Rejected('unsupported_mandate_type', context);\n }\n requireFreshness([verifiedPayload, mandate], deps, context);\n\n return { issuer: issuer.issuer, claims: mandate, signedToken: encodedJws };\n}\n\n/** What the verifier enforces beyond the signature */\nexport interface MandatePolicy {\n readonly trust: TrustStore;\n readonly clock: Clock;\n readonly clockSkewSeconds: number;\n /** Refuse a mandate with no `aud` */\n readonly requireAudience?: boolean;\n /** Refuse a mandate with no `exp`, at the top level or in the mandate content */\n readonly requireExpiry?: boolean;\n}\n\n/**\n * Read the single object in `delegate_payload` after disclosure resolution.\n * The reference SDK discloses this element. If none or multiple are present,\n * there is no single mandate to check.\n */\nfunction delegatedMandate(\n claims: Record<string, unknown>,\n context: Ap2ErrorContext,\n): Record<string, unknown> {\n const delegated = claims['delegate_payload'];\n // One shape only: claims at the top level are refused, not read a second way\n if (!Array.isArray(delegated)) throw ap2Rejected('unsupported_mandate_type', context);\n const disclosed = delegated.filter(isRecord);\n const [only] = disclosed;\n if (disclosed.length !== 1 || only === undefined) throw ap2Rejected('invalid_claims', context);\n return only;\n}\n\n/**\n * Matched on jose's stable error `code`, not its message. A client is owed\n * \"expired\" versus \"did not verify\"; anything finer describes our checks back\n * to whoever is probing them.\n */\nfunction classifyJoseFailure(\n cause: unknown,\n): 'expired' | 'wrong_audience' | 'invalid_claims' | 'invalid_signature' {\n const code = (cause as { code?: unknown })?.code;\n if (code === 'ERR_JWT_EXPIRED') return 'expired';\n if (code === 'ERR_JWT_CLAIM_VALIDATION_FAILED') {\n const { claim, reason } = cause as { claim?: unknown; reason?: unknown };\n if (claim === 'aud') return 'wrong_audience';\n // `invalid` is jose's reason for a time claim that is not a number\n if (claim === 'nbf' || claim === 'exp')\n return reason === 'invalid' ? 'invalid_claims' : 'expired';\n }\n return 'invalid_signature';\n}\n\n/**\n * Check `exp`, `nbf` and `iat` on the signed token and the disclosed mandate.\n * `jose` checks only the token's time claims. AP2 requires none of them;\n * policy can require `exp` in either location.\n */\nfunction requireFreshness(\n sources: readonly Record<string, unknown>[],\n deps: MandatePolicy,\n context: Ap2ErrorContext,\n): void {\n const nowSeconds = Math.floor(deps.clock.now().getTime() / 1000);\n let expires = false;\n for (const claims of sources) {\n const exp = claims['exp'];\n const iat = claims['iat'];\n if (exp !== undefined) {\n if (typeof exp !== 'number') throw ap2Rejected('invalid_claims', context);\n if (exp <= nowSeconds - deps.clockSkewSeconds) throw ap2Rejected('expired', context);\n expires = true;\n }\n const nbf = claims['nbf'];\n if (nbf !== undefined) {\n if (typeof nbf !== 'number') throw ap2Rejected('invalid_claims', context);\n if (nbf > nowSeconds + deps.clockSkewSeconds) throw ap2Rejected('expired', context);\n }\n if (iat !== undefined) {\n if (typeof iat !== 'number') throw ap2Rejected('invalid_claims', context);\n // A future `iat` is a broken signer, or a mandate minted to outlive its\n // own expiry window\n if (iat > nowSeconds + deps.clockSkewSeconds) throw ap2Rejected('expired', context);\n }\n }\n if (!expires && deps.requireExpiry === true) throw ap2Rejected('invalid_claims', context);\n}\n\n// Exactly `mandate.checkout.1`; see AP2_CHECKOUT_MANDATE_VCT for why\nfunction requireClosedCheckoutMandate(\n claims: Record<string, unknown>,\n context: Ap2ErrorContext,\n): void {\n if (claims['vct'] !== AP2_CHECKOUT_MANDATE_VCT) {\n throw ap2Rejected('unsupported_mandate_type', context);\n }\n}\n","/**\n * Static key resolution.\n *\n * Every key was written into `config.yaml` by an operator. No JWKS fetch, no\n * `jku`, no `x5u`. A mandate's `iss` and `kid`, or its `kid` alone when it\n * names no issuer, only choose *which* trusted key verifies it; anything\n * unrecognized is refused, so a mandate can never nominate its own signer.\n *\n * Not a \"try every key\" loop: that would make `kid` advisory and accept a\n * mandate that named a key it was not signed with.\n */\nimport { importJWK, type JWK } from 'jose';\nimport { AP2_SIGNING_ALGORITHM } from './constants';\nimport { type Ap2ErrorContext, ap2Rejected, ap2Unavailable } from './errors';\nimport type { Ap2TrustedIssuer } from './types';\n\n/** Named off `importJWK` because `CryptoKey` is a DOM type we do not load */\nexport type VerificationKey = Awaited<ReturnType<typeof importJWK>>;\n\nexport interface ResolvedKey {\n readonly issuer: Ap2TrustedIssuer;\n readonly key: VerificationKey;\n}\n\n/**\n * Resolves `(iss, kid)` against one configured issuer list. Caches the import\n * promise, not the key, so concurrent requests for a cold key share one import.\n */\nexport function createTrustStore(issuers: readonly Ap2TrustedIssuer[]) {\n const byIssuer = new Map(issuers.map((entry) => [entry.issuer, entry]));\n const imported = new Map<string, Promise<VerificationKey>>();\n\n function issuerByName(iss: unknown, context: Ap2ErrorContext): Ap2TrustedIssuer {\n if (typeof iss !== 'string' || iss.length === 0) {\n throw ap2Rejected('invalid_claims', context);\n }\n const issuer = byIssuer.get(iss);\n if (issuer === undefined) throw ap2Rejected('untrusted_issuer', context);\n return issuer;\n }\n\n // AP2 mandates may omit `iss`; the reference SDK mints none. The `kid` then\n // selects the issuer, and a `kid` that two issuers share selects neither.\n function issuerByKid(kid: string, context: Ap2ErrorContext): Ap2TrustedIssuer {\n const matches = issuers.filter((entry) => entry.keys.some((key) => key.kid === kid));\n const [only] = matches;\n if (matches.length !== 1 || only === undefined) throw ap2Rejected('unknown_key', context);\n return only;\n }\n\n return {\n /** Every trusted issuer id, for diagnostics. Never the keys themselves */\n issuerIds(): readonly string[] {\n return [...byIssuer.keys()];\n },\n\n async resolve(iss: unknown, kid: unknown, context: Ap2ErrorContext): Promise<ResolvedKey> {\n // Not defaulted to the issuer's only key: mid-rotation there are two,\n // and the gateway should not guess which one signed this\n if (typeof kid !== 'string' || kid.length === 0) {\n throw ap2Rejected('unknown_key', context);\n }\n const issuer = iss === undefined ? issuerByKid(kid, context) : issuerByName(iss, context);\n const trusted = issuer.keys.find((candidate) => candidate.kid === kid);\n if (trusted === undefined) throw ap2Rejected('unknown_key', context);\n\n // JSON, not a joined string: both halves are operator-chosen and could\n // contain whatever separator we picked\n const cacheKey = JSON.stringify([iss, kid]);\n let pending = imported.get(cacheKey);\n if (pending === undefined) {\n pending = importJWK(trusted.jwk as JWK, AP2_SIGNING_ALGORITHM);\n imported.set(cacheKey, pending);\n }\n\n try {\n return { issuer, key: await pending };\n } catch (cause) {\n // Config already checked this JWK member by member, so reaching here\n // means our config is broken, not the mandate. Drop the cached\n // rejection so the next request retries the import.\n imported.delete(cacheKey);\n throw ap2Unavailable('configured verification key could not be imported', {\n ...context,\n cause,\n });\n }\n },\n };\n}\n\nexport type TrustStore = ReturnType<typeof createTrustStore>;\n","/**\n * The Direct Checkout Mandate verifier: mandate signature first, then the\n * merchant checkout JWT it binds. Either stage failing is a refusal.\n *\n * Verification establishes that a trusted issuer signed the mandate, its\n * supplied time and audience claims pass policy, and it binds a checkout JWT\n * signed by a trusted merchant issuer. `bindMandateToPurchase` separately\n * checks the purchase before settlement.\n */\nimport type { Clock } from '../../core';\nimport { verifyCheckoutJwt } from './checkout-jwt';\nimport { type Ap2ErrorContext, ap2Rejected } from './errors';\nimport { verifyMandate } from './sd-jwt';\nimport { sha256 } from './sha256';\nimport { createTrustStore } from './trust';\nimport type { EnabledAp2Config, VerifiedCheckoutMandate } from './types';\n\nexport interface Ap2VerifierOptions {\n readonly config: EnabledAp2Config;\n readonly clock: Clock;\n}\n\nexport interface Ap2MandateVerifier {\n verify(presentation: string, context?: Ap2ErrorContext): Promise<VerifiedCheckoutMandate>;\n /** Trusted issuer ids, for the provider's health detail. Never keys */\n trustedIssuers(): { readonly mandate: readonly string[]; readonly checkout: readonly string[] };\n}\n\n/**\n * Algorithm-prefixed so a future digest change is visible in stored references\n * rather than silently producing unequal values for one mandate\n */\nfunction mandateReference(signedToken: string): string {\n return `sha256:${sha256(signedToken).toString('base64url')}`;\n}\n\nexport function createAp2MandateVerifier(options: Ap2VerifierOptions): Ap2MandateVerifier {\n // Two stores, not one list: signing the merchant's checkout documents must\n // not confer the power to issue mandates\n const mandateTrust = createTrustStore(options.config.trust.mandateIssuers);\n const checkoutTrust = createTrustStore(options.config.trust.checkoutIssuers);\n const deps = { clock: options.clock, clockSkewSeconds: options.config.clockSkewSeconds };\n const mandatePolicy = {\n ...deps,\n trust: mandateTrust,\n requireAudience: options.config.requireMandateAudience === true,\n requireExpiry: options.config.requireMandateExpiry === true,\n };\n\n return {\n async verify(\n presentation: string,\n context: Ap2ErrorContext = {},\n ): Promise<VerifiedCheckoutMandate> {\n if (typeof presentation !== 'string' || presentation.length === 0) {\n throw ap2Rejected('malformed_presentation', context);\n }\n\n const mandate = await verifyMandate(presentation, mandatePolicy, context);\n const checkout = await verifyCheckoutJwt(\n mandate.claims,\n { ...deps, trust: checkoutTrust },\n context,\n );\n\n return {\n reference: mandateReference(mandate.signedToken),\n mandateIssuer: mandate.issuer,\n checkoutIssuer: checkout.issuer,\n checkoutJwtId: checkout.jwtId,\n checkoutClaims: checkout.claims,\n };\n },\n\n trustedIssuers() {\n return { mandate: mandateTrust.issuerIds(), checkout: checkoutTrust.issuerIds() };\n },\n };\n}\n","/**\n * The AP2 authorization provider: the seam between core's generic contract and\n * the mandate machinery.\n *\n * Choose the first available backend: `replayStore`, a receipt store with all\n * hold methods, or the deprecated replay file. Creators must call `close()`:\n * it closes the legacy replay backend but leaves the receipt store open.\n * `createGateway` does not close authorization providers.\n */\nimport type {\n AdapterHealth,\n AuthorizationFinalizeContext,\n AuthorizationProvider,\n AuthorizationRequirement,\n AuthorizationVerification,\n AuthorizationVerificationContext,\n Clock,\n Logger,\n ReceiptStore,\n} from '../../core';\nimport { CommerceError, NOOP_LOGGER, systemClock } from '../../core';\nimport { hasMethodGroup, type StoreGroupMethods } from '../../core/store-method-groups';\nimport { PACKAGE_VERSION } from '../../version';\nimport { AP2_CHECKOUT_PROFILE, AP2_SPEC_VERSION } from './constants';\nimport { buildAp2Descriptor } from './descriptor';\nimport { type Ap2ErrorContext, ap2Replayed, ap2Unavailable } from './errors';\nimport { bindMandateToPurchase } from './profile';\nimport {\n type Ap2AuthorizationState,\n type Ap2ReplayStore,\n type Ap2ReservationRequest,\n type Ap2ReservationResult,\n createAp2ReplayStore,\n} from './replay-store';\nimport type { EnabledAp2Config } from './types';\nimport { createAp2MandateVerifier } from './verifier';\n\nexport interface Ap2AuthorizationProviderOptions {\n readonly config: EnabledAp2Config;\n readonly clock?: Clock;\n readonly logger?: Logger;\n /**\n * Holds mandates when all authorization-hold methods are present and no\n * `replayStore` is supplied. `close()` leaves this shared store open.\n */\n readonly store?: ReceiptStore;\n /**\n * Takes precedence over `store`, and `close()` closes it.\n * @deprecated Pass `store`; 3.0.0 removes this option.\n */\n readonly replayStore?: Ap2ReplayStore;\n}\n\nexport interface Ap2AuthorizationProvider extends AuthorizationProvider {\n /** Close the legacy replay store opened or supplied; leave the receipt store open */\n close(): void;\n}\n\ntype Transition = 'consume' | 'release' | 'markUncertain';\n\n// One interface for both backends. A legacy store's void result counts as\n// applied; only an explicit false means the transition was refused.\ninterface Holds {\n reserve(request: Ap2ReservationRequest): Promise<Ap2ReservationResult>;\n // biome-ignore lint/suspicious/noConfusingVoidType: keeps void-returning stores assignable\n transition(action: Transition, reference: string, requestId: string): Promise<boolean | void>;\n stateOf(reference: string): Promise<Ap2AuthorizationState | undefined>;\n close(): void;\n}\n\nconst HOLD_STATES = {\n consume: 'consumed',\n release: 'released',\n markUncertain: 'uncertain',\n} as const;\n\nfunction fileHolds(replay: Ap2ReplayStore): Holds {\n return {\n reserve: async (request) => replay.reserve(request),\n transition: async (action, reference, requestId) => replay[action](reference, requestId),\n stateOf: async (reference) => replay.stateOf(reference),\n close: () => replay.close(),\n };\n}\n\nfunction storeHolds(store: StoreGroupMethods<'authorization_holds'>): Holds {\n return {\n reserve: (request) =>\n store.reserveAuthorizationHold({\n method: 'ap2',\n reference: request.reference,\n bindingReference: request.checkoutJti,\n resourceId: request.resourceId,\n requestId: request.requestId,\n metadata: { mandateIssuer: request.mandateIssuer, checkoutIssuer: request.checkoutIssuer },\n }),\n transition: (action, reference, requestId) =>\n store.transitionAuthorizationHold(reference, HOLD_STATES[action], requestId),\n stateOf: (reference) => store.getAuthorizationHoldState(reference),\n close: () => {},\n };\n}\n\nfunction openHolds(options: Ap2AuthorizationProviderOptions, logger: Logger): Holds {\n if (options.replayStore !== undefined) return fileHolds(options.replayStore);\n if (hasMethodGroup(options.store, 'authorization_holds')) return storeHolds(options.store);\n const path = options.config.replay?.path;\n if (path === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'AP2 needs somewhere to record spent mandates: pass a receipt store with authorization holds, or set authorization.ap2.replay.path',\n { details: { path: 'authorization.ap2.replay.path' } },\n );\n }\n return fileHolds(createAp2ReplayStore({ path, logger }));\n}\n\nexport function createAp2AuthorizationProvider(\n options: Ap2AuthorizationProviderOptions,\n): Ap2AuthorizationProvider {\n const clock = options.clock ?? systemClock;\n const logger = options.logger ?? NOOP_LOGGER;\n\n const verifier = createAp2MandateVerifier({ config: options.config, clock });\n const holds = openHolds(options, logger);\n\n const requirement: AuthorizationRequirement = {\n method: 'ap2',\n version: AP2_SPEC_VERSION,\n profile: AP2_CHECKOUT_PROFILE,\n };\n\n async function verifyAndReserve(\n context: AuthorizationVerificationContext,\n ): Promise<AuthorizationVerification> {\n const errorContext: Ap2ErrorContext = {\n requestId: context.requestId,\n resourceId: context.resourceId,\n };\n\n const mandate = await verifier.verify(context.submission.payload, errorContext);\n // Before reserving, not after: a mandate that does not authorize this\n // purchase must stay spendable on the purchase it does authorize\n await bindMandateToPurchase(mandate, context, errorContext);\n\n let reservation: Ap2ReservationResult;\n try {\n reservation = await holds.reserve({\n reference: mandate.reference,\n checkoutJti: mandate.checkoutJwtId,\n mandateIssuer: mandate.mandateIssuer,\n checkoutIssuer: mandate.checkoutIssuer,\n resourceId: context.resourceId,\n requestId: context.requestId,\n });\n } catch (cause) {\n throw ap2Unavailable('replay store could not be written', { ...errorContext, cause });\n }\n\n if (reservation.kind === 'replayed') {\n throw ap2Replayed(reservation.state, errorContext);\n }\n\n return {\n status: 'verified',\n method: 'ap2',\n reference: mandate.reference,\n // The reservation handle is the reference itself, so the two can never\n // name different mandates\n reservationId: mandate.reference,\n // Opaque identifiers an operator can reconcile with. Never a claim from\n // the mandate: those carry the buyer's purchase and their personal data.\n // `checkoutId`, not `checkoutJwtId` - the receipt store redacts any key\n // that reads as secret-shaped, and \"jwt\" is on that list.\n metadata: {\n mandateIssuer: mandate.mandateIssuer,\n checkoutIssuer: mandate.checkoutIssuer,\n checkoutId: mandate.checkoutJwtId,\n },\n };\n }\n\n const finalize = async (\n action: Transition,\n reservationId: string,\n context: AuthorizationFinalizeContext,\n ): Promise<void> => {\n let applied: Awaited<ReturnType<Holds['transition']>>;\n try {\n applied = await holds.transition(action, reservationId, context.requestId);\n } catch (cause) {\n throw ap2Unavailable(`replay store could not record ${action}`, { ...context, cause });\n }\n // Reject an explicit false so callers do not record an unconfirmed hold update\n if (applied === false) {\n throw ap2Unavailable(`replay store holds no matching reservation to ${action}`, context);\n }\n };\n\n return {\n name: 'ap2',\n descriptor: buildAp2Descriptor(PACKAGE_VERSION),\n requirement,\n verifyAndReserve,\n\n consume: (reservationId, context) => finalize('consume', reservationId, context),\n release: (reservationId, context) => finalize('release', reservationId, context),\n markUncertain: (reservationId, context) => finalize('markUncertain', reservationId, context),\n\n async health(): Promise<AdapterHealth> {\n const startedAt = clock.monotonicMs();\n const checkedAt = clock.nowIso();\n let available = true;\n try {\n // A read against the real table, so a database that opened but cannot\n // be queried is caught here rather than on the first purchase\n await holds.stateOf('health-probe');\n } catch {\n available = false;\n }\n const durationMs = Math.round(clock.monotonicMs() - startedAt);\n if (!available) {\n // A fixed token, never a sentence built from the caught error\n return { status: 'fail', checkedAt, durationMs, detail: 'replay-store-unavailable' };\n }\n const trusted = verifier.trustedIssuers();\n return {\n status: 'pass',\n checkedAt,\n durationMs,\n detail: `mandate-issuers=${trusted.mandate.length} checkout-issuers=${trusted.checkout.length}`,\n };\n },\n\n close() {\n holds.close();\n },\n };\n}\n"]}
@@ -9,7 +9,8 @@ var TITLES = {
9
9
  "invalid-challenge": "Invalid Challenge",
10
10
  "payment-expired": "Payment Expired",
11
11
  "verification-failed": "Verification Failed",
12
- "internal-payment-error": "Internal Payment Error"
12
+ "internal-payment-error": "Internal Payment Error",
13
+ "bad-request": "Bad Request"
13
14
  };
14
15
  var REASON_TYPES = /* @__PURE__ */ new Map([
15
16
  ["malformed_credential", "malformed-credential"],
@@ -20,9 +21,16 @@ var REASON_TYPES = /* @__PURE__ */ new Map([
20
21
  ["wrong_resource", "invalid-challenge"],
21
22
  ["challenge_already_used", "invalid-challenge"],
22
23
  ["challenge_expired", "payment-expired"],
23
- ["authorization_expired", "payment-expired"]
24
+ ["authorization_expired", "payment-expired"],
25
+ ["payment_identifier_invalid", "bad-request"]
26
+ ]);
27
+ var RETRY_KEY_TITLES = /* @__PURE__ */ new Map([
28
+ [409, "Conflict"],
29
+ [422, "Unprocessable Content"]
24
30
  ]);
25
31
  function mppProblem(code, httpStatus, reason) {
32
+ const retryKeyTitle = reason?.startsWith("payment_identifier_") ? RETRY_KEY_TITLES.get(httpStatus) : void 0;
33
+ if (retryKeyTitle !== void 0) return { type: "about:blank", title: retryKeyTitle };
26
34
  const problem = problemType(code, httpStatus, reason);
27
35
  return { type: `${MPP_PROBLEM_BASE_URI}${problem}`, title: TITLES[problem] };
28
36
  }
@@ -60,6 +68,19 @@ var REASON_DETAILS = /* @__PURE__ */ new Map([
60
68
  [
61
69
  "invalid_exact_evm_transaction_simulation_failed",
62
70
  "The transfer failed in simulation, so it was not submitted."
71
+ ],
72
+ [
73
+ "payment_identifier_invalid",
74
+ "The Idempotency-Key header must be 1 to 255 printable ASCII characters."
75
+ ],
76
+ [
77
+ "payment_identifier_conflict",
78
+ "The Idempotency-Key belongs to a request with other input or another payer."
79
+ ],
80
+ ["payment_identifier_in_flight", "A request with this Idempotency-Key is still in progress."],
81
+ [
82
+ "payment_identifier_unresolved",
83
+ "The earlier request with this Idempotency-Key may have been charged and has no stored response."
63
84
  ]
64
85
  ]);
65
86
  function mppProblemDetail(reason, fallback) {
@@ -109,5 +130,5 @@ function receiptObject(serialized) {
109
130
  }
110
131
 
111
132
  export { CONTENT_DIGEST_METADATA_KEY, MPP_MCP_CREDENTIAL_META_KEY, MPP_MCP_PAYMENT_REQUIRED_META_KEY, MPP_MCP_RECEIPT_META_KEY, contentDigest, mcpPaymentRequired, mppProblem, mppProblemDetail, receiptObject };
112
- //# sourceMappingURL=chunk-5K4XEAZV.js.map
113
- //# sourceMappingURL=chunk-5K4XEAZV.js.map
133
+ //# sourceMappingURL=chunk-3IEXJ7I3.js.map
134
+ //# sourceMappingURL=chunk-3IEXJ7I3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"s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rC,EAAA,MAAM,aAAa,QAAA,CAAS,QAAQ,CAAA,GAAI,QAAA,CAAS,YAAY,CAAA,GAAI,MAAA;AACjE,EAAA,IAAI,CAAC,MAAM,OAAA,CAAQ,UAAU,KAAK,UAAA,CAAW,MAAA,KAAW,GAAG,OAAO,MAAA;AAClE,EAAA,MAAM,SAAS,OAAO,OAAA,EAAS,MAAA,KAAW,QAAA,GAAW,QAAQ,MAAA,GAAS,MAAA;AACtE,EAAA,OAAO;AAAA,IACL,UAAA,EAAY,GAAA;AAAA,IACZ,UAAA;AAAA,IACA,GAAI,YAAY,MAAA,GACZ;AAAA,MACE,OAAA,EAAS;AAAA,QACP,GAAG,UAAA,CAAW,OAAA,CAAQ,IAAA,EAAM,KAAK,MAAM,CAAA;AAAA,QACvC,MAAA,EAAQ,GAAA;AAAA,QACR,MAAA,EAAQ,gBAAA,CAAiB,MAAA,EAAQ,OAAA,CAAQ,MAAM,CAAA;AAAA,QAC/C,GAAI,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,KAAW;AAAC;AAC3C,QAEF;AAAC,GACP;AACF;AAGO,SAAS,cAAc,UAAA,EAA0D;AACtF,EAAA,IAAI,OAAO,UAAA,KAAe,QAAA,EAAU,OAAO,MAAA;AAC3C,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,GAAmB,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,YAAY,WAAW,CAAA,CAAE,QAAA,CAAS,MAAM,CAAC,CAAA;AACzF,IAAA,OAAO,QAAA,CAAS,OAAO,CAAA,GAAI,OAAA,GAAU,KAAA,CAAA;AAAA,EACvC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-3IEXJ7I3.js","sourcesContent":["/**\n * Map MPP payment errors to Problem Details using `draft-httpauth-payment-01`\n * types and generic retry-key conflicts. No optional peers are imported, so\n * the main HTTP route can use this module.\n */\n\nexport const MPP_PROBLEM_BASE_URI = 'https://paymentauth.org/problems/';\n\nexport type MppProblemType =\n | 'payment-required'\n | 'malformed-credential'\n | 'invalid-challenge'\n | 'payment-expired'\n | 'verification-failed'\n | 'internal-payment-error'\n | 'bad-request';\n\nconst TITLES: Readonly<Record<MppProblemType, string>> = {\n 'payment-required': 'Payment Required',\n 'malformed-credential': 'Malformed Credential',\n 'invalid-challenge': 'Invalid Challenge',\n 'payment-expired': 'Payment Expired',\n 'verification-failed': 'Verification Failed',\n 'internal-payment-error': 'Internal Payment Error',\n 'bad-request': 'Bad Request',\n};\n\n// Map known MPP refusal reasons to problem types; other reasons use\n// `verification-failed`. A Map keeps facilitator text out of Object.prototype\nconst REASON_TYPES: ReadonlyMap<string, MppProblemType> = new Map([\n ['malformed_credential', 'malformed-credential'],\n ['invalid_payload', 'malformed-credential'],\n ['invalid_challenge', 'invalid-challenge'],\n ['challenge_not_issued', 'invalid-challenge'],\n ['wrong_realm', 'invalid-challenge'],\n ['wrong_resource', 'invalid-challenge'],\n ['challenge_already_used', 'invalid-challenge'],\n ['challenge_expired', 'payment-expired'],\n ['authorization_expired', 'payment-expired'],\n ['payment_identifier_invalid', 'bad-request'],\n]);\n\n// Use about:blank so clients do not mistake retry-key refusals for invalid\n// challenges and pay again. RFC 9457 section 4.2.1 uses the HTTP status phrase as its title.\nconst RETRY_KEY_TITLES: ReadonlyMap<number, string> = new Map([\n [409, 'Conflict'],\n [422, 'Unprocessable Content'],\n]);\n\n/** The Problem Details `type` URI and `title` for an MPP payment error */\nexport function mppProblem(\n code: string,\n httpStatus: number,\n reason?: string,\n): { readonly type: string; readonly title: string } {\n const retryKeyTitle = reason?.startsWith('payment_identifier_')\n ? RETRY_KEY_TITLES.get(httpStatus)\n : undefined;\n if (retryKeyTitle !== undefined) return { type: 'about:blank', title: retryKeyTitle };\n const problem = problemType(code, httpStatus, reason);\n return { type: `${MPP_PROBLEM_BASE_URI}${problem}`, title: TITLES[problem] };\n}\n\n// Descriptions for MPP, retry-key and x402 facilitator refusal reasons\nconst REASON_DETAILS: ReadonlyMap<string, string> = new Map([\n ['wrong_provider', 'The challenge was issued for another payment method.'],\n ['missing_challenge', 'No challenge is available for this request.'],\n ['malformed_credential', 'The credential could not be decoded.'],\n ['invalid_payload', 'The credential payload does not match the expected format.'],\n ['invalid_challenge', 'The credential does not answer a valid challenge.'],\n ['challenge_not_issued', 'The challenge was not issued by this server or was altered.'],\n ['challenge_already_used', 'The challenge has already been used for a payment.'],\n ['challenge_expired', 'The challenge has expired.'],\n ['wrong_realm', 'The challenge was issued for another realm.'],\n ['wrong_resource', 'The challenge was issued for another resource.'],\n [\n 'unsupported_method',\n 'The challenge names a payment method or intent this server does not accept.',\n ],\n ['unsupported_credential', 'The credential type is not accepted for this challenge.'],\n ['body_digest_mismatch', 'The request body differs from the one the challenge was issued for.'],\n ['wrong_amount', 'The payment amount does not match the challenge.'],\n ['wrong_recipient', 'The payment recipient does not match the challenge.'],\n ['wrong_network', 'The payment uses a different network from the challenge.'],\n ['wrong_asset', 'The payment uses a different asset from the challenge.'],\n ['wrong_terms', 'The payment terms do not match the challenge.'],\n ['wrong_nonce', 'The authorization nonce is not derived from the challenge.'],\n ['invalid_signature', 'The authorization signature does not match the payer.'],\n ['source_mismatch', 'The credential source is not the account that signed the authorization.'],\n ['authorization_not_yet_valid', 'The authorization is not valid yet.'],\n ['authorization_expired', 'The authorization has expired.'],\n ['authorization_invalid', 'The authorization failed verification.'],\n ['settlement_rejected', 'The payment was refused before settlement.'],\n ['settlement_mismatch', 'The payment could not be matched to its settlement.'],\n ['invalid_exact_evm_insufficient_balance', 'The payer balance is too low for this payment.'],\n [\n 'invalid_exact_evm_transaction_simulation_failed',\n 'The transfer failed in simulation, so it was not submitted.',\n ],\n [\n 'payment_identifier_invalid',\n 'The Idempotency-Key header must be 1 to 255 printable ASCII characters.',\n ],\n [\n 'payment_identifier_conflict',\n 'The Idempotency-Key belongs to a request with other input or another payer.',\n ],\n ['payment_identifier_in_flight', 'A request with this Idempotency-Key is still in progress.'],\n [\n 'payment_identifier_unresolved',\n 'The earlier request with this Idempotency-Key may have been charged and has no stored response.',\n ],\n]);\n\n/** Return a sentence for a known reason, or quote an unknown reason */\nexport function mppProblemDetail(reason: string | undefined, fallback: string): string {\n if (reason === undefined) return fallback;\n return REASON_DETAILS.get(reason) ?? `The payment was refused: ${reason}.`;\n}\n\nfunction problemType(code: string, httpStatus: number, reason?: string): MppProblemType {\n if (code === 'PAYMENT_REQUIRED') return 'payment-required';\n if (httpStatus >= 500) return 'internal-payment-error';\n // A replayed credential reuses its challenge because the replay key\n // includes the challenge-derived nonce\n if (code === 'PAYMENT_REPLAYED') return 'invalid-challenge';\n return (reason !== undefined ? REASON_TYPES.get(reason) : undefined) ?? 'verification-failed';\n}\n","/**\n * Build MPP MCP metadata accepted by the `mppx` client. This module has no\n * optional peer imports, so the `./mcp` subpath can use it.\n */\n\nimport { createHash } from 'node:crypto';\nimport { isRecord } from '../../core/is-record';\nimport { mppProblem, mppProblemDetail } from './problems';\n\n/**\n * `CanonicalRequest.metadata` key for the digest of an HTTP request body. The\n * MPP provider binds it into the challenge when present, so a credential\n * cannot pay for a different body.\n */\nexport const CONTENT_DIGEST_METADATA_KEY = 'contentDigest';\n\n/** RFC 9530 `sha-256` digest of a request body, the form of the MPP `digest` parameter */\nexport function contentDigest(body: Uint8Array): string {\n return `sha-256=:${createHash('sha256').update(body).digest('base64')}:`;\n}\n\n/** MCP `_meta` key of a tool call's credential object */\nexport const MPP_MCP_CREDENTIAL_META_KEY = 'org.paymentauth/credential';\n\n/** MCP `_meta` key of a tool result's challenges */\nexport const MPP_MCP_PAYMENT_REQUIRED_META_KEY = 'org.paymentauth/payment-required';\n\n/** MCP `_meta` key of a paid tool result's receipt object */\nexport const MPP_MCP_RECEIPT_META_KEY = 'org.paymentauth/receipt';\n\n/**\n * Build payment-required metadata from the provider's challenge objects.\n * Return undefined if the envelope has none. The draft uses JSON-RPC error\n * -32042; this gateway puts the data in a tool result's `_meta`, which\n * `mppx` also reads. A refusal adds its Problem Details, with the provider's\n * reason token in the `reason` member.\n */\nexport function mcpPaymentRequired(\n envelope: unknown,\n refusal?: { readonly code: string; readonly reason?: unknown; readonly detail: string },\n): Record<string, unknown> | undefined {\n const challenges = isRecord(envelope) ? envelope['challenges'] : undefined;\n if (!Array.isArray(challenges) || challenges.length === 0) return undefined;\n const reason = typeof refusal?.reason === 'string' ? refusal.reason : undefined;\n return {\n httpStatus: 402,\n challenges,\n ...(refusal !== undefined\n ? {\n problem: {\n ...mppProblem(refusal.code, 402, reason),\n status: 402,\n detail: mppProblemDetail(reason, refusal.detail),\n ...(reason !== undefined ? { reason } : {}),\n },\n }\n : {}),\n };\n}\n\n/** The receipt object from a serialized `Payment-Receipt` value, base64url JSON */\nexport function receiptObject(serialized: unknown): Record<string, unknown> | undefined {\n if (typeof serialized !== 'string') return undefined;\n try {\n const decoded: unknown = JSON.parse(Buffer.from(serialized, 'base64url').toString('utf8'));\n return isRecord(decoded) ? decoded : undefined;\n } catch {\n return undefined;\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './chunk-PTL7SNOI.js';
1
+ import { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './chunk-OETKXDGA.js';
2
2
 
3
3
  // src/protocols/a2a/constants.ts
4
4
  var A2A_SPEC_VERSION = "1.0.1";
@@ -115,5 +115,5 @@ function buildDescriptor2(implementationVersion) {
115
115
  }
116
116
 
117
117
  export { A2A_AGENT_CARD_PATH, A2A_DEFAULT_AGENT_NAME, A2A_DEFAULT_MOUNT_PATH, A2A_EXTENSIONS_HEADER, A2A_JSON_MEDIA_TYPE, A2A_METHOD_SEND_MESSAGE, A2A_PROTOCOL_BINDING, A2A_PROTOCOL_VERSION, A2A_PUSH_CONFIG_METHODS, A2A_SPEC_VERSION, A2A_TASK_LOOKUP_METHODS, A2A_TASK_STATE_COMPLETED, A2A_TASK_STATE_FAILED, A2A_TASK_STATE_INPUT_REQUIRED, A2A_UNSUPPORTED, A2A_UNSUPPORTED_METHODS, A2A_VERSION_HEADER, ACP_UNSUPPORTED, buildDescriptor, buildDescriptor2 };
118
- //# sourceMappingURL=chunk-VJH6RYRK.js.map
119
- //# sourceMappingURL=chunk-VJH6RYRK.js.map
118
+ //# sourceMappingURL=chunk-3NVJAQRO.js.map
119
+ //# sourceMappingURL=chunk-3NVJAQRO.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/protocols/a2a/constants.ts","../../src/protocols/a2a/descriptor.ts","../../src/protocols/acp/descriptor.ts"],"names":["buildDescriptor"],"mappings":";;;AAUO,IAAM,gBAAA,GAAmB;AAGzB,IAAM,oBAAA,GAAuB;AAG7B,IAAM,oBAAA,GAAuB;AAO7B,IAAM,mBAAA,GAAsB;AAG5B,IAAM,sBAAA,GAAyB;AAG/B,IAAM,mBAAA,GAAsB;AAG5B,IAAM,sBAAA,GAAyB;AAM/B,IAAM,kBAAA,GAAqB;AAG3B,IAAM,uBAAA,GAA0B;AAMhC,IAAM,uBAAA,GAA6C;AAAA,EACxD,kCAAA;AAAA,EACA,+BAAA;AAAA,EACA,iCAAA;AAAA,EACA;AACF;AAQO,IAAM,uBAAA,GAA6C;AAAA,EACxD,sBAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EACA,iBAAA;AAAA,EACA,GAAG,uBAAA;AAAA,EACH;AACF;AAMO,IAAM,uBAAA,GAA6C,CAAC,SAAA,EAAW,YAAY;AAO3E,IAAM,wBAAA,GAA2B;AACjC,IAAM,qBAAA,GAAwB;AAG9B,IAAM,6BAAA,GAAgC;AAGtC,IAAM,qBAAA,GAAwB;;;AC5ErC,IAAM,gBAAA,GAAsC;AAAA,EAC1C,YAAA;AAAA,EACA,SAAA;AAAA,EACA,aAAA;AAAA;AAAA,EAEA;AACF,CAAA;AAOO,IAAM,eAAA,GAAqC;AAAA;AAAA,EAEhD,GAAG,uBAAA;AAAA;AAAA,EAEH,wBAA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ourcesContent":["/**\n * A2A pins, kept in one place so nothing infers one version from another.\n *\n * The specification revision and the negotiation version look alike but\n * differ: `1.0.1` names the document this adapter was written against, `1.0`\n * is what a client negotiates on the wire. Neither is this package's version\n * (`PACKAGE_VERSION`).\n */\n\n/** A2A specification revision this adapter targets */\nexport const A2A_SPEC_VERSION = '1.0.1';\n\n/** Protocol negotiation version carried on the wire */\nexport const A2A_PROTOCOL_VERSION = '1.0';\n\n/** The only transport binding this adapter serves */\nexport const A2A_PROTOCOL_BINDING = 'JSONRPC';\n\n/**\n * Fixed by the A2A specification: a client fetches the card from this exact\n * path, so it is not configurable. `src/config` reserves it against adapter\n * mounts for the same reason.\n */\nexport const A2A_AGENT_CARD_PATH = '/.well-known/agent-card.json';\n\n/** Mount serving the JSON-RPC endpoint, unless configuration says otherwise */\nexport const A2A_DEFAULT_MOUNT_PATH = '/a2a';\n\n/** Content type on both sides of every supported A2A exchange */\nexport const A2A_JSON_MEDIA_TYPE = 'application/json';\n\n/** Card identity when the operator names none. Matches the MCP adapter's default server name */\nexport const A2A_DEFAULT_AGENT_NAME = 'agent-commerce';\n\n/**\n * Version negotiation header. An absent or empty value means `0.3`, which\n * this adapter does not serve.\n */\nexport const A2A_VERSION_HEADER = 'a2a-version';\n\n/** The one JSON-RPC method this adapter serves, not the legacy `message/send` */\nexport const A2A_METHOD_SEND_MESSAGE = 'SendMessage';\n\n/**\n * Push notification configuration methods. The card declares no push\n * support, so these return `PushNotificationNotSupportedError`.\n */\nexport const A2A_PUSH_CONFIG_METHODS: readonly string[] = [\n 'CreateTaskPushNotificationConfig',\n 'GetTaskPushNotificationConfig',\n 'ListTaskPushNotificationConfigs',\n 'DeleteTaskPushNotificationConfig',\n];\n\n/**\n * A2A methods that exist and are not served here, kept apart from unknown\n * methods so a caller learns whether it hit a refused method or a typo. The\n * descriptor and the transport both read this one list.\n * `A2A_TASK_LOOKUP_METHODS` get a different error code on the wire.\n */\nexport const A2A_UNSUPPORTED_METHODS: readonly string[] = [\n 'SendStreamingMessage',\n 'GetTask',\n 'ListTasks',\n 'CancelTask',\n 'SubscribeToTask',\n ...A2A_PUSH_CONFIG_METHODS,\n 'GetExtendedAgentCard',\n];\n\n/**\n * Methods A2A gives an agent no capability flag to decline. No task can be\n * read back or canceled, so they answer `TaskNotFoundError`.\n */\nexport const A2A_TASK_LOOKUP_METHODS: readonly string[] = ['GetTask', 'CancelTask'];\n\n/**\n * Terminal states for completed and failed calls. An unpaid x402 extension\n * task instead waits in `TASK_STATE_INPUT_REQUIRED`. `GetTask` finds no task\n * in any state.\n */\nexport const A2A_TASK_STATE_COMPLETED = 'TASK_STATE_COMPLETED';\nexport const A2A_TASK_STATE_FAILED = 'TASK_STATE_FAILED';\n\n/** An unpaid x402 extension task waiting for a payment message */\nexport const A2A_TASK_STATE_INPUT_REQUIRED = 'TASK_STATE_INPUT_REQUIRED';\n\n/** Extension activation header, a comma-separated list of extension URIs */\nexport const A2A_EXTENSIONS_HEADER = 'a2a-extensions';\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the A2A specification revision (`1.0.1`), never the\n * negotiation version (`1.0`) and never this package's version. Status is\n * `experimental` while the adapter lacks the features in the unsupported list\n * below; an entry leaves that list only when its feature is implemented.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport { A2A_SPEC_VERSION, A2A_UNSUPPORTED_METHODS } from './constants';\n\n// What this adapter implements\nconst A2A_CAPABILITIES: readonly string[] = [\n 'agent-card',\n 'jsonrpc',\n 'SendMessage',\n // The x402 A2A transport, opt-in per request\n 'x402-extension',\n];\n\n/**\n * Major A2A features this adapter does not implement, served on\n * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes\n * full protocol support\n */\nexport const A2A_UNSUPPORTED: readonly string[] = [\n // Methods, as the protocol names them; the transport refuses the same list\n ...A2A_UNSUPPORTED_METHODS,\n // Transports other than the one binding served\n 'HTTP+JSON/REST binding',\n 'gRPC binding',\n // Behaviors\n 'SSE',\n 'long-running task persistence',\n 'task resumption other than an x402 extension payment',\n 'push notifications',\n 'multi-turn conversational continuation',\n 'authenticated extended agent cards',\n 'A2A authentication schemes',\n 'artifact types beyond Agent Commerce outcome data',\n // Instances with separate receipt stores cannot resume each other's tasks\n 'x402 extension payments across gateway instances',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'a2a',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: A2A_SPEC_VERSION,\n capabilities: A2A_CAPABILITIES,\n status: 'experimental',\n unsupported: A2A_UNSUPPORTED,\n };\n}\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the pinned ACP snapshot, never this package's version.\n * Status is `experimental` while the adapter lacks the features in the\n * unsupported list below; an entry leaves that list only when its feature is\n * implemented.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './constants';\n\n// What this adapter implements\nconst ACP_CAPABILITIES: readonly string[] = [\n 'rest transport',\n 'well-known discovery',\n 'bearer authentication',\n 'API-Version enforcement',\n // Forwarded as received: the gateway verifies neither signature header\n 'request header forwarding to the merchant',\n 'checkout service',\n ...ACP_CHECKOUT_OPERATIONS,\n];\n\n/**\n * Major ACP features this adapter does not implement, served on\n * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes\n * full protocol support\n */\nexport const ACP_UNSUPPORTED: readonly string[] = [\n // Services this seller does not implement, named as ACP names them. The\n // discovery document advertises `checkout` alone, and these are the reason.\n 'carts service',\n 'feed service',\n 'standalone orders service',\n 'delegate_payment',\n 'delegate_authentication',\n // Bindings and delivery directions\n 'ACP MCP transport binding',\n 'webhooks',\n 'outbound merchant-to-agent delivery',\n 'ACP client role',\n // Request authentication beyond the bearer token\n 'Signature header verification',\n 'Timestamp replay-window verification',\n // Extensions, versioning and payment handlers\n 'discount extension',\n 'general ACP extension framework',\n 'multiple ACP API versions',\n 'seller-backed payment handler integration',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'acp',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: ACP_SPEC_VERSION,\n capabilities: ACP_CAPABILITIES,\n status: 'experimental',\n unsupported: ACP_UNSUPPORTED,\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/protocols/a2a/constants.ts","../../src/protocols/a2a/descriptor.ts","../../src/protocols/acp/descriptor.ts"],"names":["buildDescriptor"],"mappings":";;;AAUO,IAAM,gBAAA,GAAmB;AAGzB,IAAM,oBAAA,GAAuB;AAG7B,IAAM,oBAAA,GAAuB;AAO7B,IAAM,mBAAA,GAAsB;AAG5B,IAAM,sBAAA,GAAyB;AAG/B,IAAM,mBAAA,GAAsB;AAG5B,IAAM,sBAAA,GAAyB;AAM/B,IAAM,kBAAA,GAAqB;AAG3B,IAAM,uBAAA,GAA0B;AAMhC,IAAM,uBAAA,GAA6C;AAAA,EACxD,kCAAA;AAAA,EACA,+BAAA;AAAA,EACA,iCAAA;AAAA,EACA;AACF;AAQO,IAAM,uBAAA,GAA6C;AAAA,EACxD,sBAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EACA,iBAAA;AAAA,EACA,GAAG,uBAAA;AAAA,EACH;AACF;AAMO,IAAM,uBAAA,GAA6C,CAAC,SAAA,EAAW,YAAY;AAO3E,IAAM,wBAAA,GAA2B;AACjC,IAAM,qBAAA,GAAwB;AAG9B,IAAM,6BAAA,GAAgC;AAGtC,IAAM,qBAAA,GAAwB;;;AC5ErC,IAAM,gBAAA,GAAsC;AAAA,EAC1C,YAAA;AAAA,EACA,SAAA;AAAA,EACA,aAAA;AAAA;AAAA,EAEA;AACF,CAAA;AAOO,IAAM,eAAA,GAAqC;AAAA;AAAA,EAEhD,GAAG,uBAAA;AAAA;AAAA,EAEH,wBAAA;AAAA,EACA,cAAA;AAAA;AAAA,EAEA,KAAA;AAAA,EACA,+BAAA;AAAA,EACA,sDAAA;AAAA,EACA,oBAAA;AAAA,EACA,wCAAA;AAAA,EACA,oCAAA;AAAA,EACA,4BAAA;AAAA,EACA,mDAAA;AAAA;AAAA,EAEA;AACF;AAEO,SAAS,gBAAgB,qBAAA,EAAkD;AAChF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,KAAA;AAAA,IACN,IAAA,EAAM,UAAA;AAAA,IACN,qBAAA;AAAA,IACA,aAAA,EAAe,gBAAA;AAAA,IACf,YAAA,EAAc,gBAAA;AAAA,IACd,MAAA,EAAQ,cAAA;AAAA,IACR,WAAA,EAAa;AAAA,GACf;AACF;;;AC1CA,IAAM,gBAAA,GAAsC;AAAA,EAC1C,gBAAA;AAAA,EACA,sBAAA;AAAA,EACA,uBAAA;AAAA,EACA,yBAAA;AAAA;AAAA,EAEA,2CAAA;AAAA,EACA,kBAAA;AAAA,EACA,GAAG;AACL,CAAA;AAOO,IAAM,eAAA,GAAqC;AAAA;AAAA;AAAA,EAGhD,eAAA;AAAA,EACA,cAAA;AAAA,EACA,2BAAA;AAAA,EACA,kBAAA;AAAA,EACA,yBAAA;AAAA;AAAA,EAEA,2BAAA;AAAA,EACA,UAAA;AAAA,EACA,qCAAA;AAAA,EACA,iBAAA;AAAA;AAAA,EAEA,+BAAA;AAAA,EACA,sCAAA;AAAA;AAAA,EAEA,oBAAA;AAAA,EACA,iCAAA;AAAA,EACA,2BAAA;AAAA,EACA;AACF;AAEO,SAASA,iBAAgB,qBAAA,EAAkD;AAChF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,KAAA;AAAA,IACN,IAAA,EAAM,UAAA;AAAA,IACN,qBAAA;AAAA,IACA,aAAA,EAAe,gBAAA;AAAA,IACf,YAAA,EAAc,gBAAA;AAAA,IACd,MAAA,EAAQ,cAAA;AAAA,IACR,WAAA,EAAa;AAAA,GACf;AACF","file":"chunk-3NVJAQRO.js","sourcesContent":["/**\n * A2A pins, kept in one place so nothing infers one version from another.\n *\n * The specification revision and the negotiation version look alike but\n * differ: `1.0.1` names the document this adapter was written against, `1.0`\n * is what a client negotiates on the wire. Neither is this package's version\n * (`PACKAGE_VERSION`).\n */\n\n/** A2A specification revision this adapter targets */\nexport const A2A_SPEC_VERSION = '1.0.1';\n\n/** Protocol negotiation version carried on the wire */\nexport const A2A_PROTOCOL_VERSION = '1.0';\n\n/** The only transport binding this adapter serves */\nexport const A2A_PROTOCOL_BINDING = 'JSONRPC';\n\n/**\n * Fixed by the A2A specification: a client fetches the card from this exact\n * path, so it is not configurable. `src/config` reserves it against adapter\n * mounts for the same reason.\n */\nexport const A2A_AGENT_CARD_PATH = '/.well-known/agent-card.json';\n\n/** Mount serving the JSON-RPC endpoint, unless configuration says otherwise */\nexport const A2A_DEFAULT_MOUNT_PATH = '/a2a';\n\n/** Content type on both sides of every supported A2A exchange */\nexport const A2A_JSON_MEDIA_TYPE = 'application/json';\n\n/** Card identity when the operator names none. Matches the MCP adapter's default server name */\nexport const A2A_DEFAULT_AGENT_NAME = 'agent-commerce';\n\n/**\n * Version negotiation header. An absent or empty value means `0.3`, which\n * this adapter does not serve.\n */\nexport const A2A_VERSION_HEADER = 'a2a-version';\n\n/** The one JSON-RPC method this adapter serves, not the legacy `message/send` */\nexport const A2A_METHOD_SEND_MESSAGE = 'SendMessage';\n\n/**\n * Push notification configuration methods. The card declares no push\n * support, so these return `PushNotificationNotSupportedError`.\n */\nexport const A2A_PUSH_CONFIG_METHODS: readonly string[] = [\n 'CreateTaskPushNotificationConfig',\n 'GetTaskPushNotificationConfig',\n 'ListTaskPushNotificationConfigs',\n 'DeleteTaskPushNotificationConfig',\n];\n\n/**\n * A2A methods that exist and are not served here, kept apart from unknown\n * methods so a caller learns whether it hit a refused method or a typo. The\n * descriptor and the transport both read this one list.\n * `A2A_TASK_LOOKUP_METHODS` get a different error code on the wire.\n */\nexport const A2A_UNSUPPORTED_METHODS: readonly string[] = [\n 'SendStreamingMessage',\n 'GetTask',\n 'ListTasks',\n 'CancelTask',\n 'SubscribeToTask',\n ...A2A_PUSH_CONFIG_METHODS,\n 'GetExtendedAgentCard',\n];\n\n/**\n * Methods A2A gives an agent no capability flag to decline. No task can be\n * read back or canceled, so they answer `TaskNotFoundError`.\n */\nexport const A2A_TASK_LOOKUP_METHODS: readonly string[] = ['GetTask', 'CancelTask'];\n\n/**\n * Terminal states for completed and failed calls. An unpaid x402 extension\n * task instead waits in `TASK_STATE_INPUT_REQUIRED`. `GetTask` finds no task\n * in any state.\n */\nexport const A2A_TASK_STATE_COMPLETED = 'TASK_STATE_COMPLETED';\nexport const A2A_TASK_STATE_FAILED = 'TASK_STATE_FAILED';\n\n/** An unpaid x402 extension task waiting for a payment message */\nexport const A2A_TASK_STATE_INPUT_REQUIRED = 'TASK_STATE_INPUT_REQUIRED';\n\n/** Extension activation header, a comma-separated list of extension URIs */\nexport const A2A_EXTENSIONS_HEADER = 'a2a-extensions';\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the A2A specification revision (`1.0.1`), never the\n * negotiation version (`1.0`) and never this package's version. Status is\n * `experimental` while the adapter lacks the features in the unsupported list\n * below; an entry leaves that list only when its feature is implemented.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport { A2A_SPEC_VERSION, A2A_UNSUPPORTED_METHODS } from './constants';\n\n// What this adapter implements\nconst A2A_CAPABILITIES: readonly string[] = [\n 'agent-card',\n 'jsonrpc',\n 'SendMessage',\n // The x402 A2A transport, opt-in per request\n 'x402-extension',\n];\n\n/**\n * Major A2A features this adapter does not implement, served on\n * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes\n * full protocol support\n */\nexport const A2A_UNSUPPORTED: readonly string[] = [\n // Methods, as the protocol names them; the transport refuses the same list\n ...A2A_UNSUPPORTED_METHODS,\n // Transports other than the one binding served\n 'HTTP+JSON/REST binding',\n 'gRPC binding',\n // Behaviors\n 'SSE',\n 'long-running task persistence',\n 'task resumption other than an x402 extension payment',\n 'push notifications',\n 'multi-turn conversational continuation',\n 'authenticated extended agent cards',\n 'A2A authentication schemes',\n 'artifact types beyond Agent Commerce outcome data',\n // Instances with separate receipt stores cannot resume each other's tasks\n 'x402 extension payments across gateway instances',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'a2a',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: A2A_SPEC_VERSION,\n capabilities: A2A_CAPABILITIES,\n status: 'experimental',\n unsupported: A2A_UNSUPPORTED,\n };\n}\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the pinned ACP snapshot, never this package's version.\n * Status is `experimental` while the adapter lacks the features in the\n * unsupported list below; an entry leaves that list only when its feature is\n * implemented.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './constants';\n\n// What this adapter implements\nconst ACP_CAPABILITIES: readonly string[] = [\n 'rest transport',\n 'well-known discovery',\n 'bearer authentication',\n 'API-Version enforcement',\n // Forwarded as received: the gateway verifies neither signature header\n 'request header forwarding to the merchant',\n 'checkout service',\n ...ACP_CHECKOUT_OPERATIONS,\n];\n\n/**\n * Major ACP features this adapter does not implement, served on\n * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes\n * full protocol support\n */\nexport const ACP_UNSUPPORTED: readonly string[] = [\n // Services this seller does not implement, named as ACP names them. The\n // discovery document advertises `checkout` alone, and these are the reason.\n 'carts service',\n 'feed service',\n 'standalone orders service',\n 'delegate_payment',\n 'delegate_authentication',\n // Bindings and delivery directions\n 'ACP MCP transport binding',\n 'webhooks',\n 'outbound merchant-to-agent delivery',\n 'ACP client role',\n // Request authentication beyond the bearer token\n 'Signature header verification',\n 'Timestamp replay-window verification',\n // Extensions, versioning and payment handlers\n 'discount extension',\n 'general ACP extension framework',\n 'multiple ACP API versions',\n 'seller-backed payment handler integration',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'acp',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: ACP_SPEC_VERSION,\n capabilities: ACP_CAPABILITIES,\n status: 'experimental',\n unsupported: ACP_UNSUPPORTED,\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { CommerceError } from './chunk-SYQLJXIU.js';
1
+ import { CommerceError } from './chunk-C5YISPT6.js';
2
2
  import { isRecord } from './chunk-3M6U7ILB.js';
3
3
 
4
4
  // src/core/domain/payment.ts
@@ -87,7 +87,9 @@ function toDeliverySummary(outcome) {
87
87
  ...p.externalReference !== void 0 ? { externalReference: p.externalReference } : {},
88
88
  ...p.network !== void 0 ? { network: p.network } : {}
89
89
  }
90
- } : {}
90
+ } : {},
91
+ // Omit the flag from original deliveries to preserve the existing summary shape
92
+ ...outcome.redelivered === true ? { redelivered: true } : {}
91
93
  };
92
94
  }
93
95
  function toPaymentRequiredEnvelope(outcome) {
@@ -199,5 +201,5 @@ function isHttpProtocolAdapter(adapter) {
199
201
  }
200
202
 
201
203
  export { AUTHORIZATION_HEADER, AUTHORIZATION_INPUT_FIELD, DEFAULT_BACKEND_TIMEOUT_MS, DELIVERY_SUMMARY_META_KEY, NOOP_LOGGER, PAYMENT_HEADER, PAYMENT_INPUT_FIELD, PAYMENT_METHOD_NAMES, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PROTOCOL_NAMES, RECONCILIATION_METADATA_KEY, RESERVED_INPUT_FIELDS, TRANSACTION_STATES, extractReservedInputFields, isHttpProtocolAdapter, parseAuthorizationHeader, parseAuthorizationSubmission, systemClock, toDeliverySummary, toErrorEnvelope, toPaymentRequiredEnvelope, transactionState };
202
- //# sourceMappingURL=chunk-GET3CZGR.js.map
203
- //# sourceMappingURL=chunk-GET3CZGR.js.map
204
+ //# sourceMappingURL=chunk-55AI6CLW.js.map
205
+ //# sourceMappingURL=chunk-55AI6CLW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/domain/payment.ts","../../src/core/interfaces/runtime.ts","../../src/core/domain/common.ts","../../src/core/domain/resource.ts","../../src/core/domain/transaction.ts","../../src/core/domain/wire.ts","../../src/core/interfaces/logger.ts","../../src/core/interfaces/protocol-adapter.ts"],"names":[],"m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AA,EAAoB,SAAS,CAAA;AAEhF,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,GAAI,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,KAAY,EAAC;AAAA,IAC3C,GAAI,aAAA,KAAkB,MAAA,GAAY,EAAE,aAAA,KAAkB;AAAC,GACzD;AACF;;;AChWO,IAAM,WAAA,GAAsB;AAAA,EACjC,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AACf;;;AC0DO,SAAS,sBAAsB,OAAA,EAA0D;AAC9F,EAAA,OAAO,OAAQ,QAAgC,UAAA,KAAe,UAAA;AAChE","file":"chunk-55AI6CLW.js","sourcesContent":["/**\n * Canonical payment model. FROZEN CONTRACT.\n *\n * Core decides that a payment is required and for how much. Payment providers\n * decide how the challenge is encoded, verified and settled. No x402- or\n * EVM-specific type may appear in this file.\n */\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n DecimalAmount,\n IsoTimestamp,\n PaymentMethodName,\n} from './common';\nimport type { PaymentAttempt } from './receipt';\nimport type { CommerceResource } from './resource';\n\n/**\n * `PaymentResult.metadata` key for public coordinates returned by `verify`\n * for later provider reconciliation. Core must store the value unchanged and\n * interpret only `expiresAt`. Never include signatures, payloads or\n * transaction bytes. Experimental: may change in a minor release.\n */\nexport const RECONCILIATION_METADATA_KEY = 'reconciliation';\n\n/**\n * Provider-native payment challenge, opaque to core. For x402 the `accepts`\n * entries are x402 `PaymentRequirements` objects, passed to protocol adapters\n * verbatim.\n */\nexport interface PaymentChallenge {\n readonly provider: PaymentMethodName;\n /** Provider protocol version, e.g. the x402 `x402Version` value as a string */\n readonly version: string;\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim: for x402 v2 the\n * `PaymentRequired` object a buyer's client consumes, for MPP an object\n * carrying the serialized `WWW-Authenticate` challenge. Opaque to core.\n *\n * `accepts` alone is not that document: x402 v2 carries the resource\n * description and protocol version on the envelope. Adapters with a native\n * channel for it (x402's `PAYMENT-REQUIRED` header, MPP's `WWW-Authenticate`)\n * send it there as is, so every surface offers the same challenge.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What the buyer must pay, in canonical terms, plus the provider-native\n * challenge the buyer's client needs to construct a payment\n */\nexport interface PaymentRequirement {\n readonly id: string;\n readonly requestId: string;\n readonly resourceId: string;\n readonly provider: PaymentMethodName;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * Merchant-controlled settlement destination, never a gateway-owned wallet.\n * Multi-offer challenges omit this, `network` and `asset`; selection\n * supplies the chosen offer's terms.\n */\n readonly destination?: string;\n readonly network?: string;\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n readonly challenge: PaymentChallenge;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Opaque payment proof supplied by the buyer's client. For x402 over HTTP it is\n * the base64 `PAYMENT-SIGNATURE` header value; over MCP and A2A it is the same\n * string in the reserved `_payment` input field.\n */\nexport interface PaymentSubmission {\n readonly method: PaymentMethodName;\n readonly payload: string;\n}\n\n/** Outcome of verification or settlement */\nexport interface PaymentResult {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly provider: PaymentMethodName;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly payer?: string;\n readonly payee?: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly network?: string;\n readonly asset?: string;\n /**\n * Stable, provider-computed identity of the payment authorization.\n *\n * The pipeline reserves this key before settlement and rejects a second\n * request presenting it with `PAYMENT_REPLAYED`. Providers must derive it\n * only from the authorization (payer, nonce, asset, network), so the same\n * authorization always maps to the same key. A `rejected` result may also\n * carry it so a store lookup can identify an unfinished attempt even when\n * verification rejects the proof because its transfer has landed.\n */\n readonly replayKey?: string;\n /** Machine-readable rejection reason when status is `rejected` */\n readonly rejectionReason?: string;\n readonly settledAt?: IsoTimestamp;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Input to {@link PaymentProvider.createRequirement} */\nexport interface PaymentContext {\n readonly requestId: string;\n readonly resource: CommerceResource;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly requestedAt: IsoTimestamp;\n /**\n * Validated resource input used to build the backend request. The pipeline\n * sets this field on every createRequirement call. A rail may bind its\n * challenge to the input but must not send it to a third party.\n */\n readonly input?: unknown;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Input to {@link PaymentProvider.verify} */\nexport interface PaymentVerificationContext {\n readonly requestId: string;\n readonly resource: CommerceResource;\n readonly requirement: PaymentRequirement;\n readonly submission: PaymentSubmission;\n}\n\n/** Input to {@link PaymentProvider.settle} */\nexport interface PaymentSettlementContext extends PaymentVerificationContext {\n readonly verification: PaymentResult;\n}\n\n/** Input to {@link PaymentProvider.reconcile}. Experimental: may change in a minor release */\nexport interface PaymentReconciliationContext {\n readonly attempt: PaymentAttempt;\n /** Coordinates from `verify`; optional for compatibility with pre-2.5.0 attempts */\n readonly locator?: Readonly<Record<string, unknown>>;\n readonly now: IsoTimestamp;\n}\n\n/** Chain evidence for resolving an attempt. Experimental: may change in a minor release */\nexport interface PaymentReconciliationResult {\n /**\n * Report `settled` only with a final transfer record for this authorization.\n * Report `not-settled` only when a state read proves it unused after it can\n * no longer land; missing logs or receipts are insufficient. Otherwise,\n * report `unknown`.\n */\n readonly outcome: 'settled' | 'not-settled' | 'unknown';\n /** A machine-readable token, such as `not_final` */\n readonly reason: string;\n readonly externalReference?: string;\n /** Public chain facts only */\n readonly evidence?: Readonly<Record<string, unknown>>;\n /** For `unknown`, the earliest time a different answer is possible, if known */\n readonly retryAfter?: IsoTimestamp;\n}\n\n/**\n * Contract every payment rail implements. Implementations must be\n * non-custodial: they orchestrate an external payment protocol and never hold\n * buyer or merchant production signing keys.\n */\nexport interface PaymentProvider {\n readonly name: PaymentMethodName;\n readonly descriptor: AdapterDescriptor;\n\n /**\n * Build the requirement and its challenge. The pipeline calls it for every\n * paid request, including one that already carries a proof to verify.\n */\n createRequirement(context: PaymentContext): Promise<PaymentRequirement>;\n\n /**\n * Extract a client retry key from a proof without I/O. Return `undefined`\n * if the proof has no key; throw `INPUT_INVALID` if the key is malformed.\n * Experimental: may change in a minor release.\n */\n retryKey?(context: {\n readonly resource: CommerceResource;\n readonly submission: PaymentSubmission;\n }): string | undefined;\n\n /**\n * Selects a proof's offer before verification, returning its destination,\n * network, asset and metadata while preserving `id` and the full `challenge`.\n * Verification, authorization, replay reservation and settlement use the result.\n * This hook must not verify, reserve or settle. If no unique offer matches,\n * return the original requirement for `verify` to reject.\n */\n selectRequirement?(context: PaymentVerificationContext): Promise<PaymentRequirement>;\n\n /**\n * Validate a submitted proof against the requirement. Must return `rejected`\n * or throw a `CommerceError` rather than an untyped error, and must never\n * move funds.\n */\n verify(context: PaymentVerificationContext): Promise<PaymentResult>;\n\n /**\n * Called only after `verify` returns `verified` and the replay key is reserved.\n * Return a settlement verdict, including rejection. The pipeline records a\n * throw as `settlement-uncertain`, unless a `CommerceError` has\n * `details.settlementNotSubmitted: true`; that records `rejected` and releases\n * the authorization hold.\n */\n settle(context: PaymentSettlementContext): Promise<PaymentResult>;\n\n /**\n * Read chain evidence for an attempt with an unknown outcome. Implementations\n * must not write, broadcast or call a facilitator. Providers without this\n * hook require manual resolution. Experimental: may change in a minor release.\n */\n reconcile?(context: PaymentReconciliationContext): Promise<PaymentReconciliationResult>;\n\n health(): Promise<AdapterHealth>;\n}\n","// Time and ids are injected so tests can be deterministic\nimport type { IsoTimestamp } from '../domain/common';\n\nexport interface Clock {\n now(): Date;\n nowIso(): IsoTimestamp;\n /** Milliseconds since an arbitrary origin; use for durations only */\n monotonicMs(): number;\n}\n\nexport interface IdGenerator {\n /** Opaque, collision-resistant identifier */\n next(prefix?: string): string;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n nowIso: () => new Date().toISOString(),\n monotonicMs: () => performance.now(),\n};\n","// Shared primitive aliases for the canonical domain model. FROZEN CONTRACT\n\n/**\n * A JSON Schema document (in practice a draft 2020-12 subset). Deliberately\n * loose: adapters translate it to their own schema representation. Never treat\n * it as trusted input without validation.\n */\nexport type JsonSchema = Record<string, unknown>;\n\n/** Protocol surfaces a resource can be exposed through */\nexport type ProtocolName = 'http' | 'mcp' | 'a2a' | 'acp';\n\n// A Record over the union fails to compile when a name is missing or extra\nconst PROTOCOL_NAME_KEYS: Record<ProtocolName, true> = {\n http: true,\n mcp: true,\n a2a: true,\n acp: true,\n};\n\n/**\n * The same names as a value, for code that checks one at runtime: config\n * validation and the OpenAPI importer's `--expose`\n */\nexport const PROTOCOL_NAMES: readonly ProtocolName[] = Object.keys(\n PROTOCOL_NAME_KEYS,\n) as ProtocolName[];\n\n/**\n * Payment rails a resource can accept.\n *\n * A resource's list is an ordered candidate list, not a buyer-selected menu.\n * The pipeline uses the first method with an enabled provider, and a\n * rejection ends the request instead of trying another rail. Config requires at\n * least one named rail to be enabled and permits others that are not.\n */\nexport type PaymentMethodName = 'x402' | 'mpp';\n\n// Checked for completeness the same way as PROTOCOL_NAME_KEYS\nconst PAYMENT_METHOD_NAME_KEYS: Record<PaymentMethodName, true> = { x402: true, mpp: true };\n\n/** The same names as a value, for config validation */\nexport const PAYMENT_METHOD_NAMES: readonly PaymentMethodName[] = Object.keys(\n PAYMENT_METHOD_NAME_KEYS,\n) as PaymentMethodName[];\n\n/**\n * Authorization methods a resource can require. Neither a transport nor a\n * payment rail: it proves the purchase was approved, and sits beside the\n * payment rather than replacing it.\n */\nexport type AuthorizationMethodName = 'ap2';\n\n/** ISO-8601 timestamp string, always UTC with millisecond precision */\nexport type IsoTimestamp = string;\n\n/**\n * A decimal amount as a string in the currency's display unit (for example\n * \"0.01\" USDC), never a float and never base units. Payment providers convert\n * it to on-chain base units.\n */\nexport type DecimalAmount = string;\n\n/** Health of an individual adapter or subsystem */\nexport interface AdapterHealth {\n readonly status: 'pass' | 'warn' | 'fail';\n readonly detail?: string;\n readonly checkedAt: IsoTimestamp;\n readonly durationMs?: number;\n /**\n * Results per checked part, such as each x402 offer. Names and statuses\n * may be published; exclude diagnostic detail.\n */\n readonly components?: readonly AdapterHealthComponent[];\n}\n\n/** One part of an {@link AdapterHealth} result */\nexport interface AdapterHealthComponent {\n readonly name: string;\n readonly status: 'pass' | 'warn' | 'fail';\n}\n\n/** Describes an adapter's supported surface for diagnostics */\nexport interface AdapterDescriptor {\n readonly name: string;\n readonly kind: 'protocol' | 'payment' | 'storage' | 'authorization';\n /** Version of this adapter implementation, independent of the spec */\n readonly implementationVersion: string;\n /** Exact pinned specification revision this adapter targets */\n readonly supportedSpec: string;\n readonly capabilities: readonly string[];\n readonly status: 'stable' | 'experimental' | 'planned';\n /** Capabilities explicitly not implemented, printed by `doctor` */\n readonly unsupported?: readonly string[];\n}\n","// Canonical resource model. FROZEN CONTRACT\nimport type {\n AuthorizationMethodName,\n DecimalAmount,\n JsonSchema,\n PaymentMethodName,\n ProtocolName,\n} from './common';\n\n/** HTTP methods a backend handler may use */\nexport type BackendMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * How the gateway calls the merchant's existing backend.\n *\n * Backend URLs come from operator configuration only, never from users or\n * agents (docs/security.md, SSRF). Secret header values belong in `${ENV_VAR}`\n * placeholders resolved by the config loader, not in plaintext configuration.\n */\nexport interface BackendHandler {\n readonly type: 'http';\n readonly method: BackendMethod;\n readonly url: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Hard upper bound on the backend call. Defaults to `DEFAULT_BACKEND_TIMEOUT_MS` */\n readonly timeoutMs?: number;\n /**\n * Names the top-level input properties carrying each part of the request.\n *\n * When absent, `{param}` values come from top-level input and everything left\n * over becomes the query string (GET/DELETE) or the whole JSON body\n * (POST/PUT/PATCH). That cannot express an operation with path, query and\n * body at once, such as `POST /users/{userId}/orders?notify=true`.\n *\n * When present, each group comes from its named property, and top-level input\n * that no binding names is not forwarded.\n */\n readonly inputBindings?: {\n readonly path?: string;\n readonly query?: string;\n readonly body?: string;\n };\n}\n\n/** Default backend timeout when a resource does not specify one */\nexport const DEFAULT_BACKEND_TIMEOUT_MS = 10_000;\n\n/**\n * Canonical pricing. `dynamic` exists in the type for forward compatibility;\n * config validation rejects it and the pipeline refuses it as defense in depth.\n */\nexport type Pricing =\n | { readonly type: 'free' }\n | {\n readonly type: 'fixed';\n readonly amount: DecimalAmount;\n readonly currency: string;\n }\n | {\n readonly type: 'dynamic';\n readonly resolver: string;\n };\n\n/**\n * A merchant capability exposed to agents. Protocol adapters map it outward and\n * never define their own parallel notion of a resource.\n */\nexport interface CommerceResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly handler: BackendHandler;\n readonly pricing: Pricing;\n readonly exposedVia: readonly ProtocolName[];\n readonly paymentMethods: readonly PaymentMethodName[];\n /**\n * Authorization the buyer must present in addition to payment. Opt-in per\n * resource. It sits beside `paymentMethods`, not inside it, because an\n * authorization method is not a payment rail and must never be selectable as\n * one.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationMethodName[];\n };\n /**\n * Paid retry settings, disabled when omitted. For redelivery, the x402 provider\n * extracts `payment-identifier` IDs; the HTTP invoke route reads MPP's\n * `Idempotency-Key` header.\n * Experimental: may change in a minor release.\n */\n readonly idempotency?: {\n /** Send the backend an `Idempotency-Key` identifying this paid operation */\n readonly merchantKey?: boolean;\n /** Store delivered responses for retries with the same client key */\n readonly redelivery?: {\n /** Hours from the initial retry check to the stored response's expiry */\n readonly retentionHours: number;\n /** If true, reject a missing `id` during x402 retry-key extraction with HTTP 400 */\n readonly required: boolean;\n };\n };\n}\n\n/** Read-only view of every configured resource */\nexport interface ResourceRegistry {\n get(id: string): CommerceResource | undefined;\n list(): readonly CommerceResource[];\n /** Resources exposed through a given protocol surface */\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[];\n has(id: string): boolean;\n}\n","/**\n * Canonical transaction model. FROZEN CONTRACT.\n *\n * A transaction links a paid purchase's request, payment attempt, optional\n * authorization hold, backend call and receipt by ID. PaymentAttempt owns the\n * payment status; journal readers must read it from the attempt rather than\n * maintain a separate copy.\n */\nimport type { AuthorizationRecord } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName, ProtocolName } from './common';\nimport type { PaymentAttempt } from './receipt';\n\n/** States derived by {@link transactionState} */\nexport const TRANSACTION_STATES = [\n 'payment-pending',\n 'payment-failed',\n 'payment-uncertain',\n 'settled-undelivered',\n 'delivery-started',\n 'delivery-unknown',\n 'delivered',\n] as const;\n\n/**\n * Open to state names added by later releases; consumers must handle values\n * outside {@link TRANSACTION_STATES}\n */\nexport type TransactionState = (typeof TRANSACTION_STATES)[number] | (string & {});\n\n/** Last hold state communicated to the authorization provider */\nexport type AuthorizationHoldState = 'reserved' | 'consumed' | 'released' | 'uncertain';\n\n/**\n * Store writes reported as failed during an execution. Consumers must handle\n * unlisted labels that later releases may add.\n */\nexport type PersistenceFailure = 'payment-attempt' | 'receipt' | 'journal' | (string & {});\n\n/**\n * Journal record for a paid purchase, starting with replay reservation.\n * Store only references and digests, never payment proofs, signatures, mandates\n * or input bodies.\n */\nexport interface Transaction {\n readonly id: string;\n /** The request that created it */\n readonly requestId: string;\n readonly resourceId: string;\n readonly protocol: ProtocolName;\n /** Cached derived state; readers must recompute it with {@link transactionState} */\n readonly state: TransactionState;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly attemptId: string;\n readonly replayKey: string;\n /** Read from PaymentAttempt, not maintained independently */\n readonly status: PaymentAttempt['status'];\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly network?: string;\n readonly asset?: string;\n readonly payee?: string;\n readonly externalReference?: string;\n /**\n * Public coordinates for the provider's `reconcile` hook, governed by\n * `RECONCILIATION_METADATA_KEY`\n */\n readonly locator?: Readonly<Record<string, unknown>>;\n /** When the provider's `settle` was called */\n readonly settlingAt?: IsoTimestamp;\n /** The authorization cannot land after this */\n readonly expiresAt?: IsoTimestamp;\n };\n readonly authorization?: AuthorizationRecord & {\n /** The handle the authorization provider consumes or releases */\n readonly reservationId: string;\n readonly hold: AuthorizationHoldState;\n };\n readonly backend?: {\n readonly dispatchedAt: IsoTimestamp;\n /** Dispatch time plus the backend timeout and a margin */\n readonly deadlineAt: IsoTimestamp;\n /** 0 if the call ended without a status, such as a timeout or transport failure */\n readonly status?: number;\n readonly errorCode?: string;\n };\n readonly receiptId?: string;\n /** `sha256:` followed by the canonical JSON input digest in hex; omit for non-I-JSON input */\n readonly inputDigest?: string;\n /** Digest of pricing and settlement terms, excluding credentials */\n readonly configDigest: string;\n readonly persistenceFailures?: readonly PersistenceFailure[];\n readonly createdAt: IsoTimestamp;\n readonly updatedAt: IsoTimestamp;\n /** Time of the pipeline's last journal write before returning the outcome */\n readonly completedAt?: IsoTimestamp;\n}\n\n/** What {@link transactionState} reads */\nexport type TransactionFacts = Pick<Transaction, 'backend' | 'completedAt'> & {\n readonly payment: Pick<Transaction['payment'], 'status'>;\n};\n\nconst isSuccess = (status: number): boolean => status >= 200 && status <= 299;\n\n/**\n * Derive state from payment status, backend facts and pipeline completion.\n * For a settled payment, a dispatched call with no result after `deadlineAt`\n * means `delivery-unknown`; a timeout does not prove that the backend never ran.\n */\nexport function transactionState(\n facts: TransactionFacts,\n now: IsoTimestamp,\n): (typeof TRANSACTION_STATES)[number] {\n const { payment, backend, completedAt } = facts;\n if (payment.status === 'settlement-uncertain' || payment.status === 'failed') {\n return 'payment-uncertain';\n }\n if (payment.status === 'rejected') return 'payment-failed';\n\n // Invalid timestamps make the comparison false, treating the deadline as passed\n const waiting =\n backend !== undefined &&\n completedAt === undefined &&\n Date.parse(now) < Date.parse(backend.deadlineAt);\n if (payment.status !== 'settled') {\n return waiting && backend?.status === undefined ? 'delivery-started' : 'payment-pending';\n }\n\n if (backend === undefined) return 'settled-undelivered';\n const { status } = backend;\n if (status !== undefined && status !== 0 && !isSuccess(status)) return 'settled-undelivered';\n if (status !== undefined && isSuccess(status) && completedAt !== undefined) return 'delivered';\n // Wait until the deadline for a missing result or an unfinished 2xx flow.\n // Status 0 means the call already ended without a response.\n if (status !== 0 && waiting) return 'delivery-started';\n return 'delivery-unknown';\n}\n","/**\n * Gateway-defined wire envelopes and carriers. FROZEN CONTRACT.\n *\n * The HTTP routes and the MCP and A2A adapters build their \"payment required\"\n * and \"error\" bodies with these helpers, so those surfaces send the same\n * shapes. The ACP adapter maps errors to ACP's own error format instead.\n */\n\nimport { CommerceError, type CommerceErrorCode } from '../errors';\nimport { isRecord } from '../is-record';\nimport type { AuthorizationRequirement, AuthorizationSubmission } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName } from './common';\nimport type { PaymentSubmission } from './payment';\nimport type { DeliveredOutcome, PaymentRequiredOutcome } from './request';\nimport type { CommerceResource } from './resource';\n\n/**\n * Reserved input property carrying a payment proof on protocols with no header\n * channel (MCP tool calls, A2A message data). HTTP uses a header instead.\n */\nexport const PAYMENT_INPUT_FIELD = '_payment';\n\n/**\n * HTTP request header carrying an x402 payment proof. MPP proofs use\n * `Authorization: Payment ...` instead.\n *\n * The x402 v2 header names, lowercased as Node presents incoming headers. v1's\n * `X-PAYMENT` / `X-PAYMENT-RESPONSE` pair is not accepted: honoring both\n * versions would mean two verification paths for the same money.\n */\nexport const PAYMENT_HEADER = 'payment-signature';\n\n/** HTTP response header carrying the settlement result */\nexport const PAYMENT_RESPONSE_HEADER = 'payment-response';\n\n/**\n * Reserved input property carrying an authorization proof, the counterpart of\n * {@link PAYMENT_INPUT_FIELD}.\n *\n * `_payment` is a bare string whose method is taken from the resource's first\n * payment method. This field is a `{ method, payload }` object, because the\n * method of a security control should be stated, not inferred.\n */\nexport const AUTHORIZATION_INPUT_FIELD = '_authorization';\n\n/**\n * Every input property name the gateway claims for itself. The config loader\n * rejects a resource declaring one, protocol adapters lift them out of client\n * input, and the pipeline strips them again as defense in depth.\n */\nexport const RESERVED_INPUT_FIELDS: readonly string[] = [\n PAYMENT_INPUT_FIELD,\n AUTHORIZATION_INPUT_FIELD,\n];\n\n/**\n * HTTP request header carrying the authorization proof: base64url-encoded JSON\n * of the same `{ method, payload }` object the reserved input field carries.\n *\n * An Agent Commerce carrier, not a header from any authorization\n * specification. It is namespaced rather than reusing `Authorization`, which\n * already carries other credentials, including MPP payment proofs.\n */\nexport const AUTHORIZATION_HEADER = 'agent-authorization';\n\n/**\n * Hard cap on the encoded `Agent-Authorization` header.\n *\n * Node's default limit is 16 KiB across all request headers, and a request over\n * it is refused before the gateway sees it. Capping well below that gives an\n * oversized proof a deterministic `AUTHORIZATION_INVALID` naming the limit.\n */\nexport const MAX_AUTHORIZATION_HEADER_BYTES = 8192;\n\n/**\n * HTTP response header carrying the base64 x402 challenge on a 402.\n *\n * The body still carries the richer {@link PaymentRequiredEnvelope}, the only\n * channel MCP has, but an x402 v2 client reads the challenge from this header\n * and ignores the body, so both are sent.\n */\nexport const PAYMENT_REQUIRED_HEADER = 'payment-required';\n\n/**\n * Key under which a protocol adapter attaches a {@link DeliverySummary} to its\n * result metadata: MCP's `CallToolResult._meta` and the A2A task artifact's\n * metadata.\n *\n * Part of the frozen contract because producer and consumer must agree on it;\n * both import this constant. Follows MCP's `<namespace>/<name>` convention for\n * `_meta` keys.\n */\nexport const DELIVERY_SUMMARY_META_KEY = 'agent-commerce/delivery';\n\nexport interface PaymentRequiredEnvelope {\n readonly status: 'payment-required';\n readonly code: 'PAYMENT_REQUIRED';\n readonly requestId: string;\n readonly resourceId: string;\n readonly message: string;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly version: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `payTo`; MPP challenges use\n * `request.recipient`. Omitted for multi-offer x402 challenges.\n */\n readonly destination?: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `network`; MPP challenges use\n * the numeric `request.methodDetails.chainId`\n */\n readonly network?: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `asset`; MPP challenges use\n * `request.currency`\n */\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n /** Provider-native requirement objects, passed through verbatim */\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim (see\n * {@link PaymentChallenge.envelope}). Present for providers that have one;\n * a buyer's protocol client can hand it straight to its SDK.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n };\n /**\n * Present only when the resource also requires an authorization proof, so a\n * client learns before it spends anything that paying alone will not get the\n * resource delivered. A client that ignores the field sees the plain\n * envelope. The proof comes from the merchant's own approval flow, outside\n * the gateway.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationRequirement[];\n };\n}\n\nexport interface ErrorEnvelope {\n readonly status: 'error';\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a buyer learns about their own completed purchase: the request, whether\n * it settled, and the settlement reference they can check on-chain. The\n * merchant's ledger is not theirs to read, which is why `/api/receipts` is an\n * operator route behind `server.adminToken`.\n */\nexport interface DeliverySummary {\n readonly requestId: string;\n readonly resourceId: string;\n readonly receiptId: string;\n /** `false` marks a failed receipt write; do not treat `receiptId` as proof of persistence */\n readonly receiptCommitted?: false;\n readonly deliveredAt: IsoTimestamp;\n readonly payment?: {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly amount: DecimalAmount;\n readonly currency: string;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly network?: string;\n };\n /**\n * True when this request reuses a stored response without another charge.\n * Experimental: may change in a minor release.\n */\n readonly redelivered?: boolean;\n}\n\n/** Build the payer-facing summary of a delivered outcome */\nexport function toDeliverySummary(outcome: DeliveredOutcome): DeliverySummary {\n const p = outcome.payment;\n return {\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n receiptId: outcome.receipt.id,\n ...(outcome.persistenceFailures?.includes('receipt') ? { receiptCommitted: false } : {}),\n deliveredAt: outcome.receipt.deliveredAt,\n ...(p !== undefined\n ? {\n payment: {\n status: p.status,\n amount: p.amount,\n currency: p.currency,\n ...(p.externalReference !== undefined\n ? { externalReference: p.externalReference }\n : {}),\n ...(p.network !== undefined ? { network: p.network } : {}),\n },\n }\n : {}),\n // Omit the flag from original deliveries to preserve the existing summary shape\n ...(outcome.redelivered === true ? { redelivered: true } : {}),\n };\n}\n\nexport function toPaymentRequiredEnvelope(\n outcome: PaymentRequiredOutcome,\n): PaymentRequiredEnvelope {\n const r = outcome.requirement;\n return {\n status: 'payment-required',\n code: 'PAYMENT_REQUIRED',\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n message: `Payment of ${r.amount} ${r.currency} is required for resource \"${outcome.resourceId}\". Retry with a ${r.provider} payment proof.`,\n payment: {\n provider: r.provider,\n version: r.challenge.version,\n amount: r.amount,\n currency: r.currency,\n ...(r.destination !== undefined ? { destination: r.destination } : {}),\n ...(r.network !== undefined ? { network: r.network } : {}),\n ...(r.asset !== undefined ? { asset: r.asset } : {}),\n ...(r.expiresAt !== undefined ? { expiresAt: r.expiresAt } : {}),\n accepts: r.challenge.accepts,\n ...(r.challenge.envelope !== undefined ? { envelope: r.challenge.envelope } : {}),\n },\n ...(outcome.authorization !== undefined && outcome.authorization.length > 0\n ? { authorization: { required: outcome.authorization } }\n : {}),\n };\n}\n\nexport function toErrorEnvelope(error: CommerceError): ErrorEnvelope {\n const info = error.toInfo();\n return {\n status: 'error',\n code: info.code,\n message: info.message,\n retryable: info.retryable,\n ...(info.requestId !== undefined ? { requestId: info.requestId } : {}),\n ...(info.resourceId !== undefined ? { resourceId: info.resourceId } : {}),\n ...(info.details !== undefined ? { details: info.details } : {}),\n };\n}\n\nexport function isPaymentRequiredEnvelope(value: unknown): value is PaymentRequiredEnvelope {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as PaymentRequiredEnvelope).status === 'payment-required' &&\n typeof (value as PaymentRequiredEnvelope).payment === 'object'\n );\n}\n\n/**\n * Parses the `{ method, payload }` authorization object, whichever carrier\n * brought it. Absent returns `undefined`; malformed throws\n * `AUTHORIZATION_INVALID`.\n *\n * An unusable `_payment` is dropped, which leaves the buyer a 402 to act on. A\n * dropped authorization would instead come back as \"not authorized\", with no\n * way to tell a rejected mandate from a typo in the object around it.\n */\nexport function parseAuthorizationSubmission(\n value: unknown,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n if (value === undefined || value === null) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (!isRecord(value)) {\n return fail(`expected an object with \"method\" and \"payload\", got ${typeof value}`);\n }\n const method = value['method'];\n const payload = value['payload'];\n\n // Compared against the literal rather than a registry: a second method needs\n // a second verifier, a deliberate addition rather than a string that starts\n // working because a client sent it\n if (method !== 'ap2') {\n fail(`unsupported method ${typeof method === 'string' ? `\"${method}\"` : typeof method}`);\n }\n if (typeof payload !== 'string' || payload.length === 0) {\n fail('\"payload\" must be a non-empty string');\n }\n\n return { method: 'ap2', payload: payload as string };\n}\n\n/**\n * Decodes the base64url JSON `Agent-Authorization` header. The size check runs\n * on the encoded value, so an oversized header costs a length comparison rather\n * than a decode and a JSON parse.\n */\nexport function parseAuthorizationHeader(\n raw: string | readonly string[] | undefined,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n const value = Array.isArray(raw) ? raw[0] : (raw as string | undefined);\n if (value === undefined || value.length === 0) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (Buffer.byteLength(value, 'utf8') > MAX_AUTHORIZATION_HEADER_BYTES) {\n fail(`header exceeds the ${MAX_AUTHORIZATION_HEADER_BYTES}-byte limit`);\n }\n\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));\n } catch {\n // Nothing from the exception is repeated back: a JSON parse error quotes\n // the input it choked on, which here is whatever the caller sent\n fail('header is not base64url-encoded JSON');\n }\n return parseAuthorizationSubmission(decoded, requestId);\n}\n\n/**\n * Splits raw client input into resource input plus the reserved fields, for\n * protocols that carry them in the input object (MCP tool arguments, A2A\n * message data). HTTP carries both in headers.\n *\n * A payment proof is labeled with the resource's first payment method.\n * `createGateway` puts provider-backed methods first so the label matches the\n * pipeline's selection; a custom registry must keep that order. A resource with\n * no payment method gets no payment proof, so the request reaches the pipeline\n * unpaid.\n */\nexport function extractReservedInputFields(\n rawInput: Record<string, unknown>,\n resource: CommerceResource | undefined,\n requestId?: string,\n): {\n input: Record<string, unknown>;\n payment?: PaymentSubmission;\n authorization?: AuthorizationSubmission;\n} {\n const {\n [PAYMENT_INPUT_FIELD]: paymentValue,\n [AUTHORIZATION_INPUT_FIELD]: authorizationValue,\n ...input\n } = rawInput;\n\n const method = resource?.paymentMethods[0];\n const payment =\n typeof paymentValue === 'string' && paymentValue.length > 0 && method !== undefined\n ? ({ method, payload: paymentValue } satisfies PaymentSubmission)\n : undefined;\n const authorization = parseAuthorizationSubmission(authorizationValue, requestId);\n\n return {\n input,\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n","/**\n * Minimal structural logger. Core does not depend on pino; the gateway injects\n * a pino instance that satisfies this shape.\n *\n * Never log secrets: private keys, seed phrases, Authorization headers or\n * payment authorization payloads.\n */\nexport interface Logger {\n debug(obj: Record<string, unknown>, msg?: string): void;\n info(obj: Record<string, unknown>, msg?: string): void;\n warn(obj: Record<string, unknown>, msg?: string): void;\n error(obj: Record<string, unknown>, msg?: string): void;\n child(bindings: Record<string, unknown>): Logger;\n}\n\n/** A logger that discards everything */\nexport const NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n","/**\n * Protocol adapter boundary. FROZEN CONTRACT.\n *\n * An adapter translates a protocol's wire format into a `CanonicalRequest`,\n * hands it to the execution pipeline and maps the outcome back. It must not\n * call merchant backends, implement payment logic or hold its own copy of the\n * canonical model. A failure while starting or serving one adapter must not\n * stop the others.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AdapterDescriptor, AdapterHealth, ProtocolName } from '../domain/common';\nimport type { EventSink } from '../domain/event';\nimport type { ExecutionPipeline } from '../domain/request';\nimport type { ResourceRegistry } from '../domain/resource';\nimport type { Logger } from './logger';\nimport type { Clock, IdGenerator } from './runtime';\n\n/** Everything an adapter is given. Nothing else is available to it */\nexport interface ProtocolAdapterContext {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n /** Externally reachable base URL of the gateway, from config */\n readonly publicBaseUrl: string;\n}\n\nexport interface ProtocolAdapter {\n readonly name: ProtocolName;\n readonly descriptor: AdapterDescriptor;\n\n start(context: ProtocolAdapterContext): Promise<void>;\n health(): Promise<AdapterHealth>;\n stop(): Promise<void>;\n}\n\n/**\n * A protocol adapter served over HTTP. The gateway mounts `handleHttp` at\n * `mountPath` with raw Node request and response objects, so adapters stay\n * independent of the HTTP framework.\n *\n * Guarantee: `req` arrives with its body stream unread. The gateway suppresses\n * every body parser on the mount, so an adapter whose SDK reads the body itself\n * (MCP's Streamable HTTP transport) can do so. The adapter owns reading,\n * size-limiting beyond the gateway's own cap, and parsing.\n *\n * The guarantee can break silently. Fastify prefers its exact-match\n * `application/json` and `text/plain` parsers over a `'*'` wildcard, so a\n * wildcard no-op alone lets the JSON parser drain the body and the adapter\n * reads an empty stream. The MCP conformance suite drives `handleHttp` over a\n * bare `node:http` server and cannot catch it, so any change to adapter mounting\n * needs a test that POSTs a JSON body through the real gateway and asserts the\n * adapter received it intact.\n */\nexport interface HttpProtocolAdapter extends ProtocolAdapter {\n /** Path prefix the gateway mounts this adapter at, e.g. '/mcp' */\n readonly mountPath: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n /**\n * Fixed paths this adapter owns outside its mount, for protocols whose\n * specification pins a discovery URL (A2A's `/.well-known/agent-card.json`).\n * The gateway mounts them with the same guarantees as `mountPath`: unread\n * body, concurrency cap and failure isolation.\n */\n readonly additionalHttpRoutes?: readonly AdapterHttpRoute[];\n}\n\n/**\n * One fixed, method-scoped route owned by an adapter. Unlike `mountPath` it\n * registers no wildcard and matches exactly the path given.\n */\nexport interface AdapterHttpRoute {\n readonly method: 'GET' | 'POST';\n /** Absolute gateway path, e.g. '/.well-known/agent-card.json' */\n readonly path: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n}\n\nexport function isHttpProtocolAdapter(adapter: ProtocolAdapter): adapter is HttpProtocolAdapter {\n return typeof (adapter as HttpProtocolAdapter).handleHttp === 'function';\n}\n"]}