@devlab.group/agent-commerce 2.4.1 → 2.5.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 (108) hide show
  1. package/README.md +115 -15
  2. package/dist/ap2.d.ts +24 -12
  3. package/dist/ap2.js +31 -13
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-DTKU3Z2M.js → chunk-3OTCFFFT.js} +37 -4
  6. package/dist/chunk-3OTCFFFT.js.map +1 -0
  7. package/dist/{chunk-QPV3EGJO.js → chunk-4K7FIBJM.js} +25 -4
  8. package/dist/chunk-4K7FIBJM.js.map +1 -0
  9. package/dist/{chunk-CXWC5LWM.js → chunk-FKQK5XZA.js} +652 -68
  10. package/dist/chunk-FKQK5XZA.js.map +1 -0
  11. package/dist/chunk-GA3O2A7R.js +92 -0
  12. package/dist/chunk-GA3O2A7R.js.map +1 -0
  13. package/dist/{chunk-WZW5ORZH.js → chunk-VUCMBGUR.js} +3 -3
  14. package/dist/{chunk-WZW5ORZH.js.map → chunk-VUCMBGUR.js.map} +1 -1
  15. package/dist/cli/{ap2-GWSP4LYY.js → ap2-YAPLERSC.js} +34 -15
  16. package/dist/cli/ap2-YAPLERSC.js.map +1 -0
  17. package/dist/cli/{chunk-G2JEY7MB.js → chunk-2J2IQQ4X.js} +8 -7
  18. package/dist/cli/chunk-2J2IQQ4X.js.map +1 -0
  19. package/dist/cli/chunk-2UPPX3FJ.js +311 -0
  20. package/dist/cli/chunk-2UPPX3FJ.js.map +1 -0
  21. package/dist/cli/{chunk-WYOGIANL.js → chunk-4H2QLHQI.js} +4 -4
  22. package/dist/cli/{chunk-WYOGIANL.js.map → chunk-4H2QLHQI.js.map} +1 -1
  23. package/dist/cli/{chunk-OZ4LAWBK.js → chunk-5R7DM5LM.js} +25 -4
  24. package/dist/cli/chunk-5R7DM5LM.js.map +1 -0
  25. package/dist/cli/chunk-663ALDZA.js +92 -0
  26. package/dist/cli/chunk-663ALDZA.js.map +1 -0
  27. package/dist/cli/{chunk-QQ3WY5L3.js → chunk-IDY2735M.js} +36 -104
  28. package/dist/cli/chunk-IDY2735M.js.map +1 -0
  29. package/dist/cli/chunk-JFVRG2HH.js +107 -0
  30. package/dist/cli/chunk-JFVRG2HH.js.map +1 -0
  31. package/dist/cli/chunk-M7NXVRU5.js +8 -0
  32. package/dist/cli/{chunk-ITWNSS2B.js.map → chunk-M7NXVRU5.js.map} +1 -1
  33. package/dist/cli/chunk-NIU5EMSB.js +119 -0
  34. package/dist/cli/chunk-NIU5EMSB.js.map +1 -0
  35. package/dist/cli/{chunk-TNMLDPUO.js → chunk-QA2OPHBF.js} +655 -70
  36. package/dist/cli/chunk-QA2OPHBF.js.map +1 -0
  37. package/dist/cli/{chunk-GJIMDMYT.js → chunk-QLUCNPRT.js} +404 -161
  38. package/dist/cli/chunk-QLUCNPRT.js.map +1 -0
  39. package/dist/cli/chunk-SYQLJXIU.js +105 -0
  40. package/dist/cli/chunk-SYQLJXIU.js.map +1 -0
  41. package/dist/cli/{chunk-3MGAJ5FX.js → chunk-VJ4EO4LE.js} +3 -3
  42. package/dist/cli/{chunk-3MGAJ5FX.js.map → chunk-VJ4EO4LE.js.map} +1 -1
  43. package/dist/cli/{chunk-PIMFPCNZ.js → chunk-Z34UMZBB.js} +234 -85
  44. package/dist/cli/chunk-Z34UMZBB.js.map +1 -0
  45. package/dist/cli/config-BWFMN2ZB.js +12 -0
  46. package/dist/cli/{config-UI4EDG4L.js.map → config-BWFMN2ZB.js.map} +1 -1
  47. package/dist/cli/index.js +258 -11
  48. package/dist/cli/index.js.map +1 -1
  49. package/dist/cli/{mcp-PGBRWZVA.js → mcp-KZEMXLHR.js} +5 -4
  50. package/dist/cli/mcp-KZEMXLHR.js.map +1 -0
  51. package/dist/cli/{near-5AY3HWYF.js → near-U6365VFX.js} +15 -4
  52. package/dist/cli/near-U6365VFX.js.map +1 -0
  53. package/dist/cli/payment-providers-SZL36H3Y.js +6 -0
  54. package/dist/cli/payment-providers-SZL36H3Y.js.map +1 -0
  55. package/dist/cli/{provider-I2ESL6RS.js → provider-6TKB5ADJ.js} +26 -15
  56. package/dist/cli/provider-6TKB5ADJ.js.map +1 -0
  57. package/dist/cli/receipts-ZGLJWMQG.js +8 -0
  58. package/dist/cli/receipts-ZGLJWMQG.js.map +1 -0
  59. package/dist/cli/reconcile-IC22MJD5.js +4 -0
  60. package/dist/cli/reconcile-IC22MJD5.js.map +1 -0
  61. package/dist/cli/{run-JK4ERPJV.js → run-ZTYPQI4D.js} +151 -115
  62. package/dist/cli/run-ZTYPQI4D.js.map +1 -0
  63. package/dist/cli/svm-KDSPDFJG.js +48 -0
  64. package/dist/cli/svm-KDSPDFJG.js.map +1 -0
  65. package/dist/cli/{x402-7WBFZQXV.js → x402-WLYBLODI.js} +10 -9
  66. package/dist/cli/x402-WLYBLODI.js.map +1 -0
  67. package/dist/index.d.ts +112 -12
  68. package/dist/index.js +948 -157
  69. package/dist/index.js.map +1 -1
  70. package/dist/mcp.d.ts +1 -2
  71. package/dist/mcp.js +1 -1
  72. package/dist/mpp.js +20 -10
  73. package/dist/mpp.js.map +1 -1
  74. package/dist/{near-D6C42VPE.js → near-FH7HPZV3.js} +15 -4
  75. package/dist/near-FH7HPZV3.js.map +1 -0
  76. package/dist/{protocol-adapter-C9odYl6l.d.ts → protocol-adapter-DEXpdp8m.d.ts} +102 -48
  77. package/dist/{runtime-Cl_BLVZV.d.ts → runtime-Dz2fSO-P.d.ts} +220 -2
  78. package/dist/svm-KNC3PHMS.js +48 -0
  79. package/dist/svm-KNC3PHMS.js.map +1 -0
  80. package/dist/x402.js +5 -5
  81. package/package.json +1 -1
  82. package/dist/authorization-DjAecwuW.d.ts +0 -115
  83. package/dist/chunk-CXWC5LWM.js.map +0 -1
  84. package/dist/chunk-DTKU3Z2M.js.map +0 -1
  85. package/dist/chunk-KA2AX5FH.js +0 -44
  86. package/dist/chunk-KA2AX5FH.js.map +0 -1
  87. package/dist/chunk-QPV3EGJO.js.map +0 -1
  88. package/dist/cli/ap2-GWSP4LYY.js.map +0 -1
  89. package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
  90. package/dist/cli/chunk-GJIMDMYT.js.map +0 -1
  91. package/dist/cli/chunk-ITWNSS2B.js +0 -8
  92. package/dist/cli/chunk-OSTCU6ZK.js +0 -44
  93. package/dist/cli/chunk-OSTCU6ZK.js.map +0 -1
  94. package/dist/cli/chunk-OZ4LAWBK.js.map +0 -1
  95. package/dist/cli/chunk-PIMFPCNZ.js.map +0 -1
  96. package/dist/cli/chunk-QQ3WY5L3.js.map +0 -1
  97. package/dist/cli/chunk-TNMLDPUO.js.map +0 -1
  98. package/dist/cli/config-UI4EDG4L.js +0 -11
  99. package/dist/cli/mcp-PGBRWZVA.js.map +0 -1
  100. package/dist/cli/near-5AY3HWYF.js.map +0 -1
  101. package/dist/cli/provider-I2ESL6RS.js.map +0 -1
  102. package/dist/cli/run-JK4ERPJV.js.map +0 -1
  103. package/dist/cli/svm-3MMYFPC7.js +0 -33
  104. package/dist/cli/svm-3MMYFPC7.js.map +0 -1
  105. package/dist/cli/x402-7WBFZQXV.js.map +0 -1
  106. package/dist/near-D6C42VPE.js.map +0 -1
  107. package/dist/svm-QEUAUNPQ.js +0 -33
  108. package/dist/svm-QEUAUNPQ.js.map +0 -1
@@ -0,0 +1,92 @@
1
+ import { getAddress, encodeAbiParameters, keccak256 } from 'viem';
2
+ import { createHash } from 'crypto';
3
+ import { PERMIT2_ADDRESS } from '@x402/evm';
4
+
5
+ // src/payments/x402/locator.ts
6
+ var LOCATOR_VERSION = 1;
7
+ var SECONDS = /^\d{1,13}$/;
8
+ var MAX_DATE_MS = 864e13;
9
+ function isoFromSeconds(seconds) {
10
+ const ms = SECONDS.test(seconds) ? Number(seconds) * 1e3 : Number.NaN;
11
+ return ms <= MAX_DATE_MS ? new Date(ms).toISOString() : void 0;
12
+ }
13
+ function eip3009Locator(network, asset, authorization) {
14
+ const { from, to, value, validAfter, validBefore, nonce } = authorization;
15
+ return withExpiry(
16
+ {
17
+ v: LOCATOR_VERSION,
18
+ network,
19
+ method: "eip3009",
20
+ asset: getAddress(asset),
21
+ from: getAddress(from),
22
+ to: getAddress(to),
23
+ value,
24
+ nonce: nonce.toLowerCase(),
25
+ validAfter,
26
+ validBefore
27
+ },
28
+ validBefore
29
+ );
30
+ }
31
+ function permit2Locator(network, transfer) {
32
+ const { asset, owner, to, amount, nonce, deadline, validAfter, proxy } = transfer;
33
+ return withExpiry(
34
+ {
35
+ v: LOCATOR_VERSION,
36
+ network,
37
+ method: "permit2",
38
+ asset: getAddress(asset),
39
+ owner: getAddress(owner),
40
+ to: getAddress(to),
41
+ amount,
42
+ nonce,
43
+ deadline,
44
+ validAfter,
45
+ proxy: getAddress(proxy)
46
+ },
47
+ deadline
48
+ );
49
+ }
50
+ function withExpiry(locator, seconds) {
51
+ const expiresAt = isoFromSeconds(seconds);
52
+ return expiresAt !== void 0 ? { ...locator, expiresAt } : locator;
53
+ }
54
+ function computeReplayKey(input) {
55
+ const encoded = encodeAbiParameters(
56
+ [{ type: "uint256" }, { type: "address" }, { type: "address" }, { type: "bytes32" }],
57
+ [BigInt(input.chainId), input.asset, input.from, input.nonce]
58
+ );
59
+ return keccak256(encoded);
60
+ }
61
+ function computePermit2ReplayKey(input) {
62
+ return keccak256(
63
+ encodeAbiParameters(
64
+ [
65
+ { type: "string" },
66
+ { type: "uint256" },
67
+ { type: "address" },
68
+ { type: "address" },
69
+ { type: "uint256" }
70
+ ],
71
+ [
72
+ "x402/exact/permit2/v1",
73
+ BigInt(input.chainId),
74
+ PERMIT2_ADDRESS,
75
+ input.owner,
76
+ BigInt(input.nonce)
77
+ ]
78
+ )
79
+ );
80
+ }
81
+ function computeSvmReplayKey(input) {
82
+ const digest = createHash("sha256").update("x402/exact/svm/v1\0").update(input.network).update("\0").update(Buffer.from(input.messageHash, "base64")).digest("hex");
83
+ return `0x${digest}`;
84
+ }
85
+ function computeNearReplayKey(input) {
86
+ const digest = createHash("sha256").update("x402/exact/near/v1\0").update(`${input.network}\0${input.senderId}\0${input.publicKey}\0${input.nonce.toString(10)}`).digest("hex");
87
+ return `0x${digest}`;
88
+ }
89
+
90
+ export { LOCATOR_VERSION, computeNearReplayKey, computePermit2ReplayKey, computeReplayKey, computeSvmReplayKey, eip3009Locator, isoFromSeconds, permit2Locator };
91
+ //# sourceMappingURL=chunk-GA3O2A7R.js.map
92
+ //# sourceMappingURL=chunk-GA3O2A7R.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/payments/x402/locator.ts","../src/payments/x402/replay-key.ts"],"names":[],"mappings":";;;;;AAQO,IAAM,eAAA,GAAkB;AAG/B,IAAM,OAAA,GAAU,YAAA;AAChB,IAAM,WAAA,GAAc,MAAA;AAMb,SAAS,eAAe,OAAA,EAAqC;AAClE,EAAA,MAAM,EAAA,GAAK,QAAQ,IAAA,CAAK,OAAO,IAAI,MAAA,CAAO,OAAO,CAAA,GAAI,GAAA,GAAO,MAAA,CAAO,GAAA;AACnE,EAAA,OAAO,MAAM,WAAA,GAAc,IAAI,KAAK,EAAE,CAAA,CAAE,aAAY,GAAI,MAAA;AAC1D;AAYO,SAAS,cAAA,CACd,OAAA,EACA,KAAA,EACA,aAAA,EACmC;AACnC,EAAA,MAAM,EAAE,IAAA,EAAM,EAAA,EAAI,OAAO,UAAA,EAAY,WAAA,EAAa,OAAM,GAAI,aAAA;AAC5D,EAAA,OAAO,UAAA;AAAA,IACL;AAAA,MACE,CAAA,EAAG,eAAA;AAAA,MACH,OAAA;AAAA,MACA,MAAA,EAAQ,SAAA;AAAA,MACR,KAAA,EAAO,WAAW,KAAK,CAAA;AAAA,MACvB,IAAA,EAAM,WAAW,IAAI,CAAA;AAAA,MACrB,EAAA,EAAI,WAAW,EAAE,CAAA;AAAA,MACjB,KAAA;AAAA,MACA,KAAA,EAAO,MAAM,WAAA,EAAY;AAAA,MACzB,UAAA;AAAA,MACA;AAAA,KACF;AAAA,IACA;AAAA,GACF;AACF;A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AA,QACjB,EAAE,MAAM,SAAA,EAAU;AAAA,QAClB,EAAE,MAAM,SAAA,EAAU;AAAA,QAClB,EAAE,MAAM,SAAA,EAAU;AAAA,QAClB,EAAE,MAAM,SAAA;AAAU,OACpB;AAAA,MACA;AAAA,QACE,uBAAA;AAAA,QACA,MAAA,CAAO,MAAM,OAAO,CAAA;AAAA,QACpB,eAAA;AAAA,QACA,KAAA,CAAM,KAAA;AAAA,QACN,MAAA,CAAO,MAAM,KAAK;AAAA;AACpB;AACF,GACF;AACF;AAQO,SAAS,oBAAoB,KAAA,EAGzB;AACT,EAAA,MAAM,MAAA,GAAS,WAAW,QAAQ,CAAA,CAC/B,OAAO,qBAAqB,CAAA,CAC5B,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,CACpB,OAAO,IAAI,CAAA,CACX,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,aAAa,QAAQ,CAAC,CAAA,CAC/C,MAAA,CAAO,KAAK,CAAA;AACf,EAAA,OAAO,KAAK,MAAM,CAAA,CAAA;AACpB;AAQO,SAAS,qBAAqB,KAAA,EAK1B;AACT,EAAA,MAAM,MAAA,GAAS,UAAA,CAAW,QAAQ,CAAA,CAC/B,MAAA,CAAO,sBAAsB,CAAA,CAC7B,MAAA,CAAO,CAAA,EAAG,KAAA,CAAM,OAAO,CAAA,EAAA,EAAK,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK,KAAA,CAAM,SAAS,CAAA,EAAA,EAAK,KAAA,CAAM,KAAA,CAAM,QAAA,CAAS,EAAE,CAAC,CAAA,CAAE,CAAA,CAC7F,MAAA,CAAO,KAAK,CAAA;AACf,EAAA,OAAO,KAAK,MAAM,CAAA,CAAA;AACpB","file":"chunk-GA3O2A7R.js","sourcesContent":["/**\n * Public payment coordinates returned under `RECONCILIATION_METADATA_KEY`\n * for later reconciliation. Locators contain transfer details and derived\n * metadata, excluding signatures, payloads and transaction bytes. Field names\n * avoid \"token\" because the receipt store redacts values under such keys.\n */\nimport { getAddress } from 'viem';\n\nexport const LOCATOR_VERSION = 1;\n\n// Bound decimal input length to cover Date's range without parsing large integers\nconst SECONDS = /^\\d{1,13}$/;\nconst MAX_DATE_MS = 8.64e15;\n\n/**\n * Converts unsigned decimal Unix seconds to ISO time, or undefined for invalid\n * or out-of-range input\n */\nexport function isoFromSeconds(seconds: string): string | undefined {\n const ms = SECONDS.test(seconds) ? Number(seconds) * 1000 : Number.NaN;\n return ms <= MAX_DATE_MS ? new Date(ms).toISOString() : undefined;\n}\n\nexport interface Eip3009Authorization {\n readonly from: string;\n readonly to: string;\n readonly value: string;\n readonly validAfter: string;\n readonly validBefore: string;\n readonly nonce: string;\n}\n\n/** Builds the shared EIP-3009 locator used by x402 and MPP */\nexport function eip3009Locator(\n network: string,\n asset: string,\n authorization: Eip3009Authorization,\n): Readonly<Record<string, unknown>> {\n const { from, to, value, validAfter, validBefore, nonce } = authorization;\n return withExpiry(\n {\n v: LOCATOR_VERSION,\n network,\n method: 'eip3009',\n asset: getAddress(asset),\n from: getAddress(from),\n to: getAddress(to),\n value,\n nonce: nonce.toLowerCase(),\n validAfter,\n validBefore,\n },\n validBefore,\n );\n}\n\nexport interface Permit2Transfer {\n readonly asset: string;\n readonly owner: string;\n /** Recipient named in the signed witness for the x402 proxy transfer */\n readonly to: string;\n readonly amount: string;\n readonly nonce: string;\n readonly deadline: string;\n readonly validAfter: string;\n readonly proxy: string;\n}\n\n/** A Permit2 transfer's locator */\nexport function permit2Locator(\n network: string,\n transfer: Permit2Transfer,\n): Readonly<Record<string, unknown>> {\n const { asset, owner, to, amount, nonce, deadline, validAfter, proxy } = transfer;\n return withExpiry(\n {\n v: LOCATOR_VERSION,\n network,\n method: 'permit2',\n asset: getAddress(asset),\n owner: getAddress(owner),\n to: getAddress(to),\n amount,\n nonce,\n deadline,\n validAfter,\n proxy: getAddress(proxy),\n },\n deadline,\n );\n}\n\nfunction withExpiry(\n locator: Readonly<Record<string, unknown>>,\n seconds: string,\n): Readonly<Record<string, unknown>> {\n const expiresAt = isoFromSeconds(seconds);\n return expiresAt !== undefined ? { ...locator, expiresAt } : locator;\n}\n","/**\n * `PaymentResult.replayKey` is derived from the payment authorization alone,\n * never from the request id, so the same authorization replayed on another\n * request collides in the receipt store's reservation. The MPP provider uses\n * the EIP-3009 derivation.\n */\nimport { createHash } from 'node:crypto';\nimport { PERMIT2_ADDRESS } from '@x402/evm';\nimport { encodeAbiParameters, keccak256 } from 'viem';\n\nexport interface ReplayKeyInput {\n readonly chainId: number;\n readonly asset: `0x${string}`;\n readonly from: `0x${string}`;\n readonly nonce: `0x${string}`;\n}\n\nexport function computeReplayKey(input: ReplayKeyInput): string {\n const encoded = encodeAbiParameters(\n [{ type: 'uint256' }, { type: 'address' }, { type: 'address' }, { type: 'bytes32' }],\n [BigInt(input.chainId), input.asset, input.from, input.nonce],\n );\n return keccak256(encoded);\n}\n\n/**\n * Identifies a Permit2 authorization by chain, Permit2 contract, owner and\n * nonce. Nonces span all tokens and spenders, so asset and resource are excluded.\n * The tag separates these keys from EIP-3009 in the receipt store's unique column.\n */\nexport function computePermit2ReplayKey(input: {\n readonly chainId: number;\n readonly owner: `0x${string}`;\n readonly nonce: string;\n}): string {\n return keccak256(\n encodeAbiParameters(\n [\n { type: 'string' },\n { type: 'uint256' },\n { type: 'address' },\n { type: 'address' },\n { type: 'uint256' },\n ],\n [\n 'x402/exact/permit2/v1',\n BigInt(input.chainId),\n PERMIT2_ADDRESS,\n input.owner,\n BigInt(input.nonce),\n ],\n ),\n );\n}\n\n/**\n * Identifies a Solana `exact` payment by network and SHA-256 of the signed\n * message bytes. Excludes signatures, including the facilitator's fee payer\n * slot, so altered signatures keep the same key. `messageHash` is the SDK's\n * base64 `transactionMessageHash`.\n */\nexport function computeSvmReplayKey(input: {\n readonly network: string;\n readonly messageHash: string;\n}): string {\n const digest = createHash('sha256')\n .update('x402/exact/svm/v1\\0')\n .update(input.network)\n .update('\\0')\n .update(Buffer.from(input.messageHash, 'base64'))\n .digest('hex');\n return `0x${digest}`;\n}\n\n/**\n * Identifies a NEAR `exact` payment by network, sender, curve-prefixed public\n * key (`ed25519:...`) and delegate nonce. Nonces are scoped per access key,\n * excluding token, recipient, relayer and signature; another key of the same\n * sender has an independent nonce scope.\n */\nexport function computeNearReplayKey(input: {\n readonly network: string;\n readonly senderId: string;\n readonly publicKey: string;\n readonly nonce: bigint;\n}): string {\n const digest = createHash('sha256')\n .update('x402/exact/near/v1\\0')\n .update(`${input.network}\\0${input.senderId}\\0${input.publicKey}\\0${input.nonce.toString(10)}`)\n .digest('hex');\n return `0x${digest}`;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { CommerceError } from './chunk-DTKU3Z2M.js';
1
+ import { CommerceError } from './chunk-3OTCFFFT.js';
2
2
  import { existsSync, accessSync, constants, closeSync, openSync, mkdirSync, chmodSync } from 'fs';
3
3
  import { dirname } from 'path';
4
4
  import Database from 'better-sqlite3';
@@ -79,5 +79,5 @@ function restrictDatabasePermissions(path, label, logger) {
79
79
  }
80
80
 
81
81
  export { AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_DIGEST_ALGORITHM, AP2_JWK_COORDINATE_BYTES, AP2_JWK_CURVE, AP2_JWK_MEMBERS, AP2_KEY_TYPE, AP2_MAX_CLOCK_SKEW_SECONDS, AP2_MODES, AP2_SIGNING_ALGORITHM, AP2_SPEC_VERSION, openSqliteDatabase };
82
- //# sourceMappingURL=chunk-WZW5ORZH.js.map
83
- //# sourceMappingURL=chunk-WZW5ORZH.js.map
82
+ //# sourceMappingURL=chunk-VUCMBGUR.js.map
83
+ //# sourceMappingURL=chunk-VUCMBGUR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/authorization/ap2/constants.ts","../src/storage/sqlite.ts"],"names":["fsConstants"],"mappings":";;;;;;AAQO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,SAAA,GAAY,CAAC,QAAQ;AA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;AACvD,IAAA,IAAI;AACF,MAAA,SAAA,CAAU,MAAM,GAAK,CAAA;AAAA,IACvB,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,OAAQ,KAAA,CAAgC,IAAA;AAC9C,MAAA,IAAI,SAAS,QAAA,EAAU;AACvB,MAAA,MAAA,CAAO,IAAA;AAAA,QACL,EAAE,IAAA,EAAM,KAAA,EAAO,KAAA,EAAO,QAAQ,SAAA,EAAU;AAAA,QACxC;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"chunk-WZW5ORZH.js","sourcesContent":["/**\n * Pinned AP2 identifiers and key policy.\n *\n * AP2 v0.2.0 (2026-04-28, commit b4587ac) is the tagged release this gateway\n * verifies against; unversioned `main` is never implemented against. Config,\n * the verifier and `doctor` all read these, so a bump lands in one place.\n */\n\nexport const AP2_SPEC_VERSION = '0.2.0';\n\n/**\n * Direct only. Autonomous mode needs open mandates, cnf-bound agent keys and\n * constraint evaluation over `checkout.line_items`, none of which is\n * implemented, so it is refused rather than partly served.\n */\nexport const AP2_MODES = ['direct'] as const;\nexport type Ap2Mode = (typeof AP2_MODES)[number];\n\n/**\n * A single algorithm, so `alg=none` and the HMAC family are excluded by\n * construction rather than by a denylist\n */\nexport const AP2_SIGNING_ALGORITHM = 'ES256';\n\n/** The key type and curve ES256 implies. Any other pair is refused at load */\nexport const AP2_KEY_TYPE = 'EC';\nexport const AP2_JWK_CURVE = 'P-256';\n\n/** Byte length of a P-256 coordinate, before base64url encoding */\nexport const AP2_JWK_COORDINATE_BYTES = 32;\n\n/**\n * JWK members a verification key may carry. An allowlist, so private material\n * (`d`) and URL members (`x5u`, `jku`) are refused without the list naming\n * them. Keys are configured inline and never fetched; see docs/security.md.\n */\nexport const AP2_JWK_MEMBERS = ['kty', 'crv', 'x', 'y', 'kid', 'alg', 'use'] as const;\n\n/**\n * Compared against this literal, never as a prefix. `mandate.checkout.open.1`\n * carries spending constraints nothing here evaluates, so accepting it would\n * tell a buyer their limits were checked when nothing read them.\n */\nexport const AP2_CHECKOUT_MANDATE_VCT = 'mandate.checkout.1';\n\n/**\n * Merchant checkout JWTs declare this gateway-specific profile; AP2 leaves\n * the checkout payload out of scope. The identifier is a namespace that\n * clients do not dereference. Merchants sign it into each checkout JWT, so\n * changing the expected value would reject previously signed JWTs.\n */\nexport const AP2_CHECKOUT_PROFILE = 'agent-commerce/ap2/checkout/v1';\n\n/**\n * The only accepted SD-JWT `_sd_alg` (an absent one means sha-256). Any other\n * value is refused rather than hashed as sha-256, which would check a\n * presentation under an algorithm it never claimed.\n */\nexport const AP2_DIGEST_ALGORITHM = 'sha-256';\n\n/** Seconds of clock skew tolerated on mandate and checkout time claims */\nexport const AP2_DEFAULT_CLOCK_SKEW_SECONDS = 60;\n\n/**\n * Skew as wide as a mandate's validity window would stop `exp` rejecting\n * anything. An operator who needs more than five minutes has a clock to fix.\n */\nexport const AP2_MAX_CLOCK_SKEW_SECONDS = 300;\n","/**\n * Opens a SQLite file with owner-only permissions. Every store that keeps a\n * SQLite file opens it here, so the hardening below exists once: the file is\n * pre-created at 0600, the WAL sidecars are narrowed once WAL creates them, and\n * an existing but unwritable file fails at startup.\n *\n * Callers own their schema; this function migrates nothing.\n */\nimport {\n accessSync,\n chmodSync,\n closeSync,\n existsSync,\n constants as fsConstants,\n mkdirSync,\n openSync,\n} from 'node:fs';\nimport { dirname } from 'node:path';\nimport Database from 'better-sqlite3';\nimport { CommerceError, type Logger } from '../core';\n\nexport interface OpenSqliteOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing */\n readonly path: string;\n /** Names the database in operator-facing errors, e.g. \"Receipt database\" */\n readonly label: string;\n readonly logger: Logger;\n}\n\nexport function openSqliteDatabase(options: OpenSqliteOptions): Database.Database {\n const { path, label, logger } = options;\n const isFileBacked = path !== ':memory:';\n\n if (isFileBacked) {\n try {\n createDirectory(dirname(path));\n } catch (cause) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `${label} directory \"${dirname(path)}\" cannot be created: ${cause instanceof Error ? cause.message : String(cause)}`,\n { details: { path }, cause },\n );\n }\n }\n\n // Check write access at startup. SQLite can open a read-only database and\n // report the problem only when the first write is attempted.\n if (isFileBacked && existsSync(path)) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `${label} \"${path}\" exists but is not writable by this process (uid ${typeof process.getuid === 'function' ? process.getuid() : 'unknown'}). If this is a container that recently changed user, an existing volume may still be owned by the previous one - recreate it (docker compose down -v) or fix its ownership.`,\n { details: { path } },\n );\n }\n }\n\n // Create the file at 0600 before SQLite creates it at 0644 (less the umask).\n // A chmod afterwards is too late: a local user who opens the file in between\n // keeps a readable descriptor across the chmod. SQLite copies the main file's\n // mode onto the -wal/-shm sidecars, so this covers all three. `mode` applies\n // on creation only; an existing file is left to the chmod below.\n if (isFileBacked) {\n try {\n closeSync(openSync(path, 'a', 0o600));\n } catch {\n // Silent on purpose: `new Database` reports the same cause with a better\n // message, or the failure is harmless and the chmod below covers it\n }\n }\n\n const db = new Database(path);\n db.pragma('journal_mode = WAL');\n db.pragma('foreign_keys = ON');\n if (isFileBacked) restrictDatabasePermissions(path, label, logger);\n return db;\n}\n\n// Create missing directory levels at 0700, preserving existing modes. Explicit\n// recursion avoids the recursive mkdir hang observed on Node 24.8.0 when /proc\n// returns ENOENT for a directory it cannot create.\nfunction createDirectory(dir: string): void {\n if (existsSync(dir)) return;\n const parent = dirname(dir);\n if (parent !== dir) createDirectory(parent);\n try {\n mkdirSync(dir, { mode: 0o700 });\n } catch (error) {\n // Created by someone else in the meantime\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n}\n\n/**\n * Narrows the database and its WAL sidecars to owner-only. The receipt ledger\n * holds no key material, but it does hold payer and payee addresses, amounts,\n * settlement hashes, replay keys and the commerce event log.\n *\n * Runs after `journal_mode = WAL`, which creates the sidecars, and also\n * tightens a database that already existed with a looser mode. A failure only\n * warns: a filesystem without POSIX modes must not stop the gateway starting.\n */\nfunction restrictDatabasePermissions(path: string, label: string, logger: Logger): void {\n for (const file of [path, `${path}-wal`, `${path}-shm`]) {\n try {\n chmodSync(file, 0o600);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') continue;\n logger.warn(\n { file, label, error: code ?? 'unknown' },\n 'could not restrict database permissions to owner-only',\n );\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/authorization/ap2/constants.ts","../src/storage/sqlite.ts"],"names":["fsConstants"],"mappings":";;;;;;AAQO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,SAAA,GAAY,CAAC,QAAQ;AAO3B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,YAAA,GAAe;AACrB,IAAM,aAAA,GAAgB;AAGtB,IAAM,wBAAA,GAA2B;AAOjC,IAAM,eAAA,GAAkB,CAAC,KAAA,EAAO,KAAA,EAAO,KAAK,GAAA,EAAK,KAAA,EAAO,OAAO,KAAK;AAOpE,IAAM,wBAAA,GAA2B;AAQjC,IAAM,oBAAA,GAAuB;AAO7B,IAAM,oBAAA,GAAuB;AAG7B,IAAM,8BAAA,GAAiC;AAMvC,IAAM,0BAAA,GAA6B;ACtCnC,SAAS,mBAAmB,OAAA,EAA+C;AAChF,EAAA,MAAM,EAAE,IAAA,EAAM,KAAA,EAAO,MAAA,EAAO,GAAI,OAAA;AAChC,EAAA,MAAM,eAAe,IAAA,KAAS,UAAA;AAE9B,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,IAAI;AACF,MAAA,eAAA,CAAgB,OAAA,CAAQ,IAAI,CAAC,CAAA;AAAA,IAC/B,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,IAAI,aAAA;AAAA,QACR,eAAA;AAAA,QACA,CAAA,EAAG,KAAK,CAAA,YAAA,EAAe,OAAA,CAAQ,IAAI,CAAC,CAAA,qBAAA,EAAwB,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC,CAA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AAA,SAAA,CAAU,GAAA,EAAK,EAAE,IAAA,EAAM,GAAA,EAAO,CAAA;AAAA,EAChC,SAAS,KAAA,EAAO;AAEd,IAAA,IAAK,KAAA,CAAgC,IAAA,KAAS,QAAA,EAAU,MAAM,KAAA;AAAA,EAChE;AACF;AAWA,SAAS,2BAAA,CAA4B,IAAA,EAAc,KAAA,EAAe,MAAA,EAAsB;AACtF,EAAA,KAAA,MAAW,IAAA,IAAQ,CAAC,IAAA,EAAM,CAAA,EAAG,IAAI,CAAA,IAAA,CAAA,EAAQ,CAAA,EAAG,IAAI,CAAA,IAAA,CAAM,CAAA,EAAG;AACvD,IAAA,IAAI;AACF,MAAA,SAAA,CAAU,MAAM,GAAK,CAAA;AAAA,IACvB,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,OAAQ,KAAA,CAAgC,IAAA;AAC9C,MAAA,IAAI,SAAS,QAAA,EAAU;AACvB,MAAA,MAAA,CAAO,IAAA;AAAA,QACL,EAAE,IAAA,EAAM,KAAA,EAAO,KAAA,EAAO,QAAQ,SAAA,EAAU;AAAA,QACxC;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"chunk-VUCMBGUR.js","sourcesContent":["/**\n * Pinned AP2 identifiers and key policy.\n *\n * AP2 v0.2.0 (2026-04-28, commit b4587ac) is the tagged release this gateway\n * verifies against; unversioned `main` is never implemented against. Config,\n * the verifier and `doctor` all read these, so a bump lands in one place.\n */\n\nexport const AP2_SPEC_VERSION = '0.2.0';\n\n/**\n * Direct only. Autonomous mode needs open mandates, cnf-bound agent keys and\n * constraint evaluation over `checkout.line_items`, none of which is\n * implemented, so it is refused rather than partly served.\n */\nexport const AP2_MODES = ['direct'] as const;\nexport type Ap2Mode = (typeof AP2_MODES)[number];\n\n/**\n * A single algorithm, so `alg=none` and the HMAC family are excluded by\n * construction rather than by a denylist\n */\nexport const AP2_SIGNING_ALGORITHM = 'ES256';\n\n/** The key type and curve ES256 implies. Any other pair is refused at load */\nexport const AP2_KEY_TYPE = 'EC';\nexport const AP2_JWK_CURVE = 'P-256';\n\n/** Byte length of a P-256 coordinate, before base64url encoding */\nexport const AP2_JWK_COORDINATE_BYTES = 32;\n\n/**\n * JWK members a verification key may carry. An allowlist, so private material\n * (`d`) and URL members (`x5u`, `jku`) are refused without the list naming\n * them. Keys are configured inline and never fetched; see docs/security.md.\n */\nexport const AP2_JWK_MEMBERS = ['kty', 'crv', 'x', 'y', 'kid', 'alg', 'use'] as const;\n\n/**\n * Compared against this literal, never as a prefix. `mandate.checkout.open.1`\n * carries spending constraints nothing here evaluates, so accepting it would\n * tell a buyer their limits were checked when nothing read them.\n */\nexport const AP2_CHECKOUT_MANDATE_VCT = 'mandate.checkout.1';\n\n/**\n * Merchant checkout JWTs declare this gateway-specific profile; AP2 leaves\n * the checkout payload out of scope. The identifier is a namespace that\n * clients do not dereference. Merchants sign it into each checkout JWT, so\n * changing the expected value would reject previously signed JWTs.\n */\nexport const AP2_CHECKOUT_PROFILE = 'agent-commerce/ap2/checkout/v1';\n\n/**\n * The only accepted SD-JWT `_sd_alg` (an absent one means sha-256). Any other\n * value is refused rather than hashed as sha-256, which would check a\n * presentation under an algorithm it never claimed.\n */\nexport const AP2_DIGEST_ALGORITHM = 'sha-256';\n\n/** Seconds of clock skew tolerated on mandate and checkout time claims */\nexport const AP2_DEFAULT_CLOCK_SKEW_SECONDS = 60;\n\n/**\n * Skew as wide as a mandate's validity window would stop `exp` rejecting\n * anything. An operator who needs more than five minutes has a clock to fix.\n */\nexport const AP2_MAX_CLOCK_SKEW_SECONDS = 300;\n","/**\n * Opens a SQLite file with owner-only permissions. Every store that keeps a\n * SQLite file opens it here, so the hardening below exists once: the file is\n * pre-created at 0600, the WAL sidecars are narrowed once WAL creates them, and\n * an existing but unwritable file fails at startup.\n *\n * Callers own their schema; this function migrates nothing.\n */\nimport {\n accessSync,\n chmodSync,\n closeSync,\n existsSync,\n constants as fsConstants,\n mkdirSync,\n openSync,\n} from 'node:fs';\nimport { dirname } from 'node:path';\nimport Database from 'better-sqlite3';\nimport { CommerceError, type Logger } from '../core';\n\nexport interface OpenSqliteOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing */\n readonly path: string;\n /** Names the database in operator-facing errors, e.g. \"Receipt database\" */\n readonly label: string;\n readonly logger: Logger;\n}\n\nexport function openSqliteDatabase(options: OpenSqliteOptions): Database.Database {\n const { path, label, logger } = options;\n const isFileBacked = path !== ':memory:';\n\n if (isFileBacked) {\n try {\n createDirectory(dirname(path));\n } catch (cause) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `${label} directory \"${dirname(path)}\" cannot be created: ${cause instanceof Error ? cause.message : String(cause)}`,\n { details: { path }, cause },\n );\n }\n }\n\n // Check write access at startup. SQLite can open a read-only database and\n // report the problem only when the first write is attempted.\n if (isFileBacked && existsSync(path)) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `${label} \"${path}\" exists but is not writable by this process (uid ${typeof process.getuid === 'function' ? process.getuid() : 'unknown'}). If this is a container that recently changed user, an existing volume may still be owned by the previous one - recreate it (docker compose down -v) or fix its ownership.`,\n { details: { path } },\n );\n }\n }\n\n // Create the file at 0600 before SQLite creates it at 0644 (less the umask).\n // A chmod afterwards is too late: a local user who opens the file in between\n // keeps a readable descriptor across the chmod. SQLite copies the main file's\n // mode onto the -wal/-shm sidecars, so this covers all three. `mode` applies\n // on creation only; an existing file is left to the chmod below.\n if (isFileBacked) {\n try {\n closeSync(openSync(path, 'a', 0o600));\n } catch {\n // Silent on purpose: `new Database` reports the same cause with a better\n // message, or the failure is harmless and the chmod below covers it\n }\n }\n\n const db = new Database(path);\n db.pragma('journal_mode = WAL');\n db.pragma('foreign_keys = ON');\n if (isFileBacked) restrictDatabasePermissions(path, label, logger);\n return db;\n}\n\n// Create missing directory levels at 0700, preserving existing modes. Explicit\n// recursion avoids the recursive mkdir hang observed on Node 24.8.0 when /proc\n// returns ENOENT for a directory it cannot create.\nfunction createDirectory(dir: string): void {\n if (existsSync(dir)) return;\n const parent = dirname(dir);\n if (parent !== dir) createDirectory(parent);\n try {\n mkdirSync(dir, { mode: 0o700 });\n } catch (error) {\n // Created by someone else in the meantime\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n}\n\n/**\n * Narrows the database and its WAL sidecars to owner-only. The receipt ledger\n * holds no key material, but it does hold payer and payee addresses, amounts,\n * settlement hashes, replay keys and the commerce event log.\n *\n * Runs after `journal_mode = WAL`, which creates the sidecars, and also\n * tightens a database that already existed with a looser mode. A failure only\n * warns: a filesystem without POSIX modes must not stop the gateway starting.\n */\nfunction restrictDatabasePermissions(path: string, label: string, logger: Logger): void {\n for (const file of [path, `${path}-wal`, `${path}-shm`]) {\n try {\n chmodSync(file, 0o600);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') continue;\n logger.warn(\n { file, label, error: code ?? 'unknown' },\n 'could not restrict database permissions to owner-only',\n );\n }\n }\n}\n"]}
@@ -1,10 +1,11 @@
1
1
  import { buildAp2Descriptor } from './chunk-3EQBCFZY.js';
2
2
  export { AP2_CAPABILITIES, AP2_UNSUPPORTED, buildAp2Descriptor } from './chunk-3EQBCFZY.js';
3
- import { openSqliteDatabase } from './chunk-3MGAJ5FX.js';
3
+ import { openSqliteDatabase } from './chunk-VJ4EO4LE.js';
4
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
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 { PACKAGE_VERSION } from './chunk-ITWNSS2B.js';
7
- import { NOOP_LOGGER, systemClock, CommerceError } from './chunk-QQ3WY5L3.js';
6
+ import { PACKAGE_VERSION } from './chunk-M7NXVRU5.js';
7
+ import { NOOP_LOGGER, systemClock } from './chunk-IDY2735M.js';
8
+ import { CommerceError } from './chunk-SYQLJXIU.js';
8
9
  import { isRecord } from './chunk-3M6U7ILB.js';
9
10
  import { SignJWT, importPKCS8, importJWK, jwtVerify, decodeProtectedHeader, decodeJwt } from 'jose';
10
11
  import canonicalize from 'canonicalize';
@@ -232,7 +233,11 @@ function createAp2ReplayStore(options) {
232
233
  );
233
234
  const transition = db.prepare(
234
235
  `UPDATE ap2_authorizations SET state = @state, updated_at = @at
235
- WHERE reference = @reference AND state = 'reserved'`
236
+ WHERE reference = @reference AND state IN ('reserved', 'uncertain')
237
+ AND (@request_id IS NULL OR request_id = @request_id)`
238
+ );
239
+ const selectHolder = db.prepare(
240
+ "SELECT state, request_id FROM ap2_authorizations WHERE reference = ?"
236
241
  );
237
242
  const reserveTx = db.transaction((request) => {
238
243
  const at = new Date(now()).toISOString();
@@ -259,22 +264,32 @@ function createAp2ReplayStore(options) {
259
264
  });
260
265
  return { kind: "reserved" };
261
266
  });
262
- const move = (reference, state) => {
263
- transition.run({ reference, state, at: new Date(now()).toISOString() });
267
+ const move = (reference, state, requestId) => {
268
+ const { changes } = transition.run({
269
+ reference,
270
+ state,
271
+ request_id: requestId ?? null,
272
+ at: new Date(now()).toISOString()
273
+ });
274
+ if (changes > 0) return true;
275
+ const row = selectHolder.get(reference);
276
+ if (row === void 0) return false;
277
+ if (requestId !== void 0 && row.request_id !== requestId) return state === "released";
278
+ return row.state === state;
264
279
  };
265
280
  let closed = false;
266
281
  return {
267
282
  reserve(request) {
268
283
  return reserveTx(request);
269
284
  },
270
- consume(reference) {
271
- move(reference, "consumed");
285
+ consume(reference, requestId) {
286
+ return move(reference, "consumed", requestId);
272
287
  },
273
- release(reference) {
274
- move(reference, "released");
288
+ release(reference, requestId) {
289
+ return move(reference, "released", requestId);
275
290
  },
276
- markUncertain(reference) {
277
- move(reference, "uncertain");
291
+ markUncertain(reference, requestId) {
292
+ return move(reference, "uncertain", requestId);
278
293
  },
279
294
  stateOf(reference) {
280
295
  return selectByReference.get(reference)?.state;
@@ -626,11 +641,15 @@ function createAp2AuthorizationProvider(options) {
626
641
  };
627
642
  }
628
643
  const finalize = (action, reservationId, context) => {
644
+ let applied;
629
645
  try {
630
- replay[action](reservationId);
646
+ applied = replay[action](reservationId, context.requestId);
631
647
  } catch (cause) {
632
648
  throw ap2Unavailable(`replay store could not record ${action}`, { ...context, cause });
633
649
  }
650
+ if (applied === false) {
651
+ throw ap2Unavailable(`replay store holds no matching reservation to ${action}`, context);
652
+ }
634
653
  };
635
654
  return {
636
655
  name: "ap2",
@@ -674,5 +693,5 @@ function createAp2AuthorizationProvider(options) {
674
693
  }
675
694
 
676
695
  export { AP2_REJECTION_REASONS, createAp2AuthorizationProvider, createAp2ReplayStore, createCheckoutJwt };
677
- //# sourceMappingURL=ap2-GWSP4LYY.js.map
678
- //# sourceMappingURL=ap2-GWSP4LYY.js.map
696
+ //# sourceMappingURL=ap2-YAPLERSC.js.map
697
+ //# sourceMappingURL=ap2-YAPLERSC.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,S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,MAAM,CAAA;AAAA,OAC/F;AAAA,IACF,CAAA;AAAA,IAEA,KAAA,GAAQ;AACN,MAAA,MAAA,CAAO,KAAA,EAAM;AAAA,IACf;AAAA,GACF;AACF","file":"ap2-YAPLERSC.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 * It owns its replay store, so whoever creates it must call `close()`:\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} from '../../core';\nimport { NOOP_LOGGER, systemClock } from '../../core';\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 { type Ap2ReplayStore, createAp2ReplayStore } 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 /** Injectable so tests need not touch the filesystem */\n readonly replayStore?: Ap2ReplayStore;\n}\n\nexport interface Ap2AuthorizationProvider extends AuthorizationProvider {\n /** Closes the replay store */\n close(): void;\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 replay =\n options.replayStore ?? createAp2ReplayStore({ path: options.config.replay.path, 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: ReturnType<Ap2ReplayStore['reserve']>;\n try {\n reservation = replay.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 = (\n action: 'consume' | 'release' | 'markUncertain',\n reservationId: string,\n context: AuthorizationFinalizeContext,\n ): void => {\n let applied: ReturnType<Ap2ReplayStore[typeof action]>;\n try {\n applied = replay[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 async consume(reservationId, context) {\n finalize('consume', reservationId, context);\n },\n async release(reservationId, context) {\n finalize('release', reservationId, context);\n },\n async markUncertain(reservationId, context) {\n finalize('markUncertain', reservationId, context);\n },\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 replay.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 replay.close();\n },\n };\n}\n"]}
@@ -1,10 +1,11 @@
1
- import { ACP_WELL_KNOWN_PATH, DEFAULT_CONFIG_FILENAME, ACP_CHECKOUT_OPERATIONS, isObjectSchemaNode, extractPathParameterNames, findUnparsedBraceToken, ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS, ACP_SESSION_ID_INPUT_KEY } from './chunk-PIMFPCNZ.js';
2
- import { MPP_DEFAULT_NETWORK, isMppNetwork, MPP_NETWORKS, MPP_DEFAULT_PAYMENT_FLOW, MPP_MIN_CHALLENGE_SECRET_LENGTH, MPP_PROFILE } from './chunk-AA3FIEAR.js';
3
- import { resolveX402Deployment, resolveX402Option } from './chunk-WYOGIANL.js';
4
- import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, isEvmAddress, isEvmZeroAddress } from './chunk-OZ4LAWBK.js';
1
+ import { ACP_WELL_KNOWN_PATH, DEFAULT_CONFIG_FILENAME, ACP_CHECKOUT_OPERATIONS, isObjectSchemaNode, extractPathParameterNames, findUnparsedBraceToken, ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS, ACP_SESSION_ID_INPUT_KEY } from './chunk-Z34UMZBB.js';
5
2
  import { AP2_SPEC_VERSION, AP2_MODES, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_JWK_MEMBERS, AP2_KEY_TYPE, AP2_SIGNING_ALGORITHM, AP2_JWK_CURVE, AP2_JWK_COORDINATE_BYTES, AP2_MAX_CLOCK_SKEW_SECONDS } from './chunk-FHCFR2GS.js';
6
3
  import { MCP_TOOL_NAME_PATTERN } from './chunk-TPC4EJLT.js';
7
- import { PROTOCOL_NAMES, PAYMENT_METHOD_NAMES, CommerceError, RESERVED_INPUT_FIELDS } from './chunk-QQ3WY5L3.js';
4
+ import { MPP_DEFAULT_NETWORK, isMppNetwork, MPP_NETWORKS, MPP_DEFAULT_PAYMENT_FLOW, MPP_MIN_CHALLENGE_SECRET_LENGTH, MPP_PROFILE } from './chunk-AA3FIEAR.js';
5
+ import { resolveX402Deployment, resolveX402Option } from './chunk-4H2QLHQI.js';
6
+ import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, isEvmAddress, isEvmZeroAddress } from './chunk-5R7DM5LM.js';
7
+ import { PROTOCOL_NAMES, PAYMENT_METHOD_NAMES, RESERVED_INPUT_FIELDS } from './chunk-IDY2735M.js';
8
+ import { CommerceError } from './chunk-SYQLJXIU.js';
8
9
  import { isRecord } from './chunk-3M6U7ILB.js';
9
10
  import { promises } from 'fs';
10
11
  import * as path from 'path';
@@ -1757,5 +1758,5 @@ function resolveConfigPath(explicitPath, env, cwd) {
1757
1758
  }
1758
1759
 
1759
1760
  export { loadConfig, parseConfig, substituteEnv };
1760
- //# sourceMappingURL=chunk-G2JEY7MB.js.map
1761
- //# sourceMappingURL=chunk-G2JEY7MB.js.map
1761
+ //# sourceMappingURL=chunk-2J2IQQ4X.js.map
1762
+ //# sourceMappingURL=chunk-2J2IQQ4X.js.map