@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
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/payments/x402/networks.ts","../src/core/execution/settlement-order.ts","../src/payments/x402/addresses.ts","../src/payments/x402/local-chain/accounts.ts","../src/payments/x402/dev-key-guard.ts","../src/payments/x402/guardrails.ts","../src/payments/x402/options.ts","../src/payments/x402/payment-flow.ts"],"names":["invalid"],"mappings":";;;AAiBO,IAAM,cAAA,GAAiB;AA0D9B,IAAM,IAAA,GAAO,CAAC,OAAA,EAAiB,IAAA,MAC5B,EAAE,MAAA,EAAQ,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAM,OAAA,EAAS,GAAA,EAAK,QAAA,EAAU,CAAA,EAAE,CAAA;AAE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BAAA,GAA6C","file":"chunk-QPV3EGJO.js","sourcesContent":["/**\n * Network profiles: family, display name, environment, EVM chain ID and\n * default stablecoin. Config load rejects unknown IDs; parsing an EVM chain\n * ID cannot establish whether it is mainnet. Merchants must declare custom\n * EVM networks under `payments.x402.networks`; built-ins cannot be redeclared.\n *\n * Profiles copy SDK asset defaults to keep config load and the CLI SDK-free.\n * Tests compare each profile with the pinned SDK tables.\n *\n * The local Anvil chain has a profile of its own, `eip155:31337` (Anvil's\n * default chain id), so the network alone tells a local deployment from a\n * public one. Local health checks still require an Anvil response, because an\n * RPC endpoint can report any chain id.\n */\nimport { CommerceError } from '../../core';\n\n/** Chain id of the local Anvil dev chain, Anvil's default */\nexport const LOCAL_CHAIN_ID = 31337;\n\nexport type X402NetworkFamily = 'evm' | 'svm' | 'near';\n\nexport type NetworkKind = 'testnet' | 'mainnet';\n\n/** An EVM network the x402 provider can settle on */\nexport interface NetworkProfile {\n /** CAIP-2 identifier, e.g. `eip155:84532` */\n readonly id: string;\n /** Signed into the buyer's EIP-712 domain */\n readonly chainId: number;\n readonly displayName: string;\n readonly kind: NetworkKind;\n /** The local Anvil dev chain, where the in-process facilitator runs */\n readonly local?: boolean;\n /**\n * Default USDC deployment and EIP-712 domain. EVM offers may name another\n * token; the local chain has no default and requires explicit token metadata.\n *\n * `name` is the signed EIP-712 domain name, not the symbol, and deployments\n * differ: `\"USDC\"` on Base Sepolia, `\"USD Coin\"` on Base.\n */\n readonly canonicalAsset?: {\n readonly symbol: string;\n readonly address: string;\n readonly name: string;\n readonly version: string;\n readonly decimals: number;\n };\n}\n\ninterface NonEvmNetwork<F extends X402NetworkFamily> {\n readonly family: F;\n readonly id: string;\n readonly displayName: string;\n readonly kind: NetworkKind;\n /** Solana mint or NEAR NEP-141 contract account, with no EIP-712 domain */\n readonly canonicalAsset: {\n readonly symbol: string;\n readonly address: string;\n readonly decimals: number;\n };\n}\n\nexport type X402Network =\n | (NetworkProfile & { readonly family: 'evm' })\n | NonEvmNetwork<'svm'>\n | NonEvmNetwork<'near'>;\n\n/** A merchant-declared EVM network, from `payments.x402.networks` */\nexport interface CustomNetworkDeclaration {\n readonly kind: NetworkKind;\n readonly displayName: string;\n}\n\nexport type CustomNetworks = Readonly<Record<string, CustomNetworkDeclaration>>;\n\nconst usdc = (address: string, name: string) =>\n ({ symbol: 'USDC', address, name, version: '2', decimals: 6 }) as const;\n\nconst PROFILES: readonly X402Network[] = [\n {\n family: 'evm',\n id: `eip155:${LOCAL_CHAIN_ID}`,\n chainId: LOCAL_CHAIN_ID,\n displayName: 'Local Anvil',\n kind: 'testnet',\n local: true,\n },\n {\n family: 'evm',\n id: 'eip155:84532',\n chainId: 84532,\n displayName: 'Base Sepolia',\n kind: 'testnet',\n canonicalAsset: usdc('0x036CbD53842c5426634e7929541eC2318f3dCF7e', 'USDC'),\n },\n {\n family: 'evm',\n id: 'eip155:8453',\n chainId: 8453,\n displayName: 'Base',\n kind: 'mainnet',\n canonicalAsset: usdc('0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:1',\n chainId: 1,\n displayName: 'Ethereum',\n kind: 'mainnet',\n canonicalAsset: usdc('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:137',\n chainId: 137,\n displayName: 'Polygon',\n kind: 'mainnet',\n canonicalAsset: usdc('0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:42161',\n chainId: 42161,\n displayName: 'Arbitrum One',\n kind: 'mainnet',\n canonicalAsset: usdc('0xaf88d065e77c8cC2239327C5EDb3A432268e5831', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:421614',\n chainId: 421614,\n displayName: 'Arbitrum Sepolia',\n kind: 'testnet',\n canonicalAsset: usdc('0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:43114',\n chainId: 43114,\n displayName: 'Avalanche C-Chain',\n kind: 'mainnet',\n canonicalAsset: usdc('0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', 'USD Coin'),\n },\n {\n family: 'svm',\n id: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',\n displayName: 'Solana',\n kind: 'mainnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',\n decimals: 6,\n },\n },\n {\n family: 'svm',\n id: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',\n displayName: 'Solana Devnet',\n kind: 'testnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',\n decimals: 6,\n },\n },\n // NEAR's USDC contracts are implicit accounts: 64 lowercase hex characters\n {\n family: 'near',\n id: 'near:mainnet',\n displayName: 'NEAR',\n kind: 'mainnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1',\n decimals: 6,\n },\n },\n {\n family: 'near',\n id: 'near:testnet',\n displayName: 'NEAR Testnet',\n kind: 'testnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '3e2210e1184b45b64c8a434c0a7e7b23cc04ea7eb7a6c3c32520d03d4afcb8af',\n decimals: 6,\n },\n },\n];\n\nconst BY_ID = new Map(PROFILES.map((profile) => [profile.id, profile]));\n\n/** Built-in networks of every family, for tests and diagnostics */\nexport const BUILT_IN_NETWORKS: readonly X402Network[] = PROFILES;\n\n/** The built-in EVM networks the x402 provider settles on without a declaration */\nexport const SUPPORTED_NETWORK_IDS: readonly string[] = PROFILES.filter(\n (p) => p.family === 'evm',\n).map((p) => p.id);\n\n// A chain id viem and EIP-712 can carry as a JS number\nconst EVM_NETWORK_ID = /^eip155:([1-9]\\d{0,15})$/;\n\nfunction invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\n/** Built-in EVM profile for callers using the original network interface */\nexport function findNetworkProfile(id: string): NetworkProfile | undefined {\n const profile = BY_ID.get(id);\n return profile?.family === 'evm' ? profile : undefined;\n}\n\n/** A built-in network of any family, or a declared custom EVM network */\nexport function findX402Network(id: string, custom?: CustomNetworks): X402Network | undefined {\n const builtIn = BY_ID.get(id);\n if (builtIn) return builtIn;\n const declared = custom?.[id];\n const chainId = Number(EVM_NETWORK_ID.exec(id)?.[1]);\n if (!declared || !Number.isSafeInteger(chainId)) return undefined;\n return {\n family: 'evm',\n id,\n chainId,\n displayName: declared.displayName,\n kind: declared.kind,\n };\n}\n\nexport function requireX402Network(id: string, path: string, custom?: CustomNetworks): X402Network {\n const network = findX402Network(id, custom);\n if (!network) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `${path}: \"${id}\" is not a known network. Built-in CAIP-2 identifiers: ${PROFILES.map((p) => p.id).join(', ')}. Declare another EVM network under payments.x402.networks with its kind and displayName.`,\n { details: { path, network: id } },\n );\n }\n return network;\n}\n\n/**\n * Allows only new `eip155` networks in `payments.x402.networks`. Redeclaring\n * built-ins could relabel mainnet as testnet; Solana and NEAR IDs are SDK-fixed.\n */\nexport function validateCustomNetworks(custom: CustomNetworks, path: string): void {\n for (const id of Object.keys(custom)) {\n const at = `${path}.${id}`;\n if (BY_ID.has(id)) {\n throw invalid(\n `${at}: \"${id}\" is a built-in network and cannot be redeclared; remove this entry`,\n at,\n );\n }\n if (!findX402Network(id, custom)) {\n throw invalid(\n `${at}: \"${id}\" is not an EVM CAIP-2 identifier (\"eip155:\" followed by a positive chain id below 2^53). Only EVM networks can be declared.`,\n at,\n );\n }\n }\n}\n\n/** What a deployment is: the local dev chain, or a public testnet or mainnet */\nexport type DeploymentMode = 'local' | 'testnet' | 'mainnet';\n\nexport function resolveDeploymentMode(profile: {\n readonly kind: NetworkKind;\n readonly local?: boolean;\n}): DeploymentMode {\n return profile.local ? 'local' : profile.kind;\n}\n\n// The banner an operator must not miss. Printed for mainnet only\nconst LIVE_MAINNET_BANNER = 'LIVE MAINNET MODE - REAL FUNDS';\n\nexport function describeDeploymentMode(mode: DeploymentMode): string {\n return mode === 'mainnet' ? LIVE_MAINNET_BANNER : mode.toUpperCase();\n}\n","/**\n * Set on a payment requirement to run the backend before settlement.\n * The pipeline settles first unless this metadata value is `true`.\n */\nexport const SETTLE_AFTER_BACKEND_METADATA_KEY = 'settleAfterBackend';\n\n/**\n * Set to `true` when the rail permits presenting an authorization again after\n * its attempt was rejected, which settled nothing; the chain still spends each\n * nonce once. The pipeline lets retries reclaim the rejected attempt;\n * otherwise, it refuses them as replays.\n */\nexport const REUSE_REJECTED_AUTHORIZATION_METADATA_KEY = 'reuseRejectedAuthorization';\n","/**\n * SDK-free address checks for config load and the CLI. EVM addresses compare\n * without case; Solana keys and NEAR account IDs compare exactly.\n */\nimport type { X402Network } from './networks';\n\n// `0x` + 40 hex characters. Config load cannot check the EIP-55 checksum,\n// which needs keccak-256; the x402 and MPP providers refuse a mixed-case\n// address whose checksum is wrong when they start.\nconst EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst EVM_ZERO = /^0x0{40}$/i;\n\n/** `0x` followed by 40 hex characters, in any case */\nexport const isEvmAddress = (value: unknown): value is `0x${string}` =>\n typeof value === 'string' && EVM_ADDRESS.test(value);\n\n/** The EVM zero address, in any case */\nexport const isEvmZeroAddress = (value: string): boolean => EVM_ZERO.test(value);\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n// A 32-byte key is 32 to 44 base58 characters\nconst SOLANA_ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n// The all-zero key, which is the System Program and owns nothing recoverable\nconst SOLANA_ZERO = '11111111111111111111111111111111';\nconst EVM_TRANSACTION_HASH = /^0x[0-9a-fA-F]{64}$/;\n// A 64-byte Ed25519 signature is at most 88 base58 characters\nconst SOLANA_SIGNATURE = /^[1-9A-HJ-NP-Za-km-z]{64,88}$/;\n\n// nearcore's account ID rule: 2 to 64 characters, lowercase alphanumeric runs\n// joined by single \"-\", \"_\" or \".\"; implicit accounts are 64 hex characters\nconst NEAR_ACCOUNT_ID = /^(([a-z\\d]+[-_])*[a-z\\d]+\\.)*([a-z\\d]+[-_])*[a-z\\d]+$/;\n// A transaction hash: 32 bytes in base58\nconst NEAR_TRANSACTION_HASH = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\n/**\n * Returns the family's wire address or `undefined`. NEAR uses named or\n * implicit account IDs; a `.near` suffix does not identify the network.\n */\nexport function normalizeAddress(network: X402Network, value: string): string | undefined {\n switch (network.family) {\n case 'evm':\n return isEvmAddress(value) ? value : undefined;\n case 'svm':\n return SOLANA_ADDRESS.test(value) && base58ByteLength(value) === 32 ? value : undefined;\n case 'near':\n return value.length >= 2 && value.length <= 64 && NEAR_ACCOUNT_ID.test(value)\n ? value\n : undefined;\n }\n}\n\n/**\n * An address funds cannot be recovered from: the zero address of its family.\n * NEAR has no zero account.\n */\nexport function isBurnAddress(network: X402Network, wireAddress: string): boolean {\n switch (network.family) {\n case 'evm':\n return isEvmZeroAddress(wireAddress);\n case 'svm':\n return wireAddress === SOLANA_ZERO;\n case 'near':\n return false;\n }\n}\n\n/** Compare EVM addresses case-insensitively, Solana keys and NEAR account IDs exactly */\nexport function sameAddress(network: X402Network, a: string, b: string): boolean {\n return network.family === 'evm' ? a.toLowerCase() === b.toLowerCase() : a === b;\n}\n\n/**\n * A settlement reference in its family's form: an EVM transaction hash, a\n * Solana transaction signature or a NEAR transaction hash\n */\nexport function isTransactionReference(network: X402Network, value: string): boolean {\n switch (network.family) {\n case 'evm':\n return EVM_TRANSACTION_HASH.test(value);\n case 'svm':\n return SOLANA_SIGNATURE.test(value) && base58ByteLength(value) === 64;\n case 'near':\n return NEAR_TRANSACTION_HASH.test(value) && base58ByteLength(value) === 32;\n }\n}\n\nfunction base58ByteLength(value: string): number {\n let n = 0n;\n for (const char of value) n = n * 58n + BigInt(BASE58_ALPHABET.indexOf(char));\n // Each leading '1' encodes one leading zero byte\n const leadingZeros = value.length - value.replace(/^1+/, '').length;\n return leadingZeros + (n === 0n ? 0 : Math.ceil(n.toString(16).length / 2));\n}\n","/**\n * Anvil's well-known development accounts.\n *\n * LOCAL DEVELOPMENT ONLY - DO NOT FUND. The keys come from Foundry's public\n * default mnemonic (\"test test ... junk\"), so value sent to these addresses on\n * a real network can be taken by anyone.\n *\n * Index layout on the local demo chain:\n * 0 - deployer and local facilitator signer (pays gas, broadcasts settlement)\n * 1 - merchant settlement destination (`payTo`)\n * 2 - buyer (signs EIP-3009 authorizations; never held by the gateway)\n */\nexport interface AnvilWellKnownAccount {\n readonly address: `0x${string}`;\n readonly privateKey: `0x${string}`;\n}\n\n/** A fixed-length tuple, so indexing by the layout above is typed */\nexport const ANVIL_WELL_KNOWN_ACCOUNTS: readonly [\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n] = [\n {\n address: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',\n privateKey: '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80',\n },\n {\n address: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8',\n privateKey: '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',\n },\n {\n address: '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC',\n privateKey: '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a',\n },\n];\n\nexport const LOCAL_FACILITATOR_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[0];\nexport const LOCAL_MERCHANT_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[1];\nexport const LOCAL_BUYER_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[2];\n\n/** Label printed wherever a dev key appears in output, logs or manifests */\nexport const DEV_KEY_LABEL = 'LOCAL DEVELOPMENT ONLY - DO NOT FUND';\n","/**\n * Rejects well-known Anvil keys and payment destinations when the RPC host\n * does not look local or private. Their private keys are published, so anyone\n * can spend what such an address receives on a public chain.\n *\n * The check uses the RPC hostname because the local chain shares Base\n * Sepolia's chain id. Both guards run at provider construction.\n */\nimport { CommerceError } from '../../core';\nimport { ANVIL_WELL_KNOWN_ACCOUNTS } from './local-chain/accounts';\n\nconst WELL_KNOWN_DEV_KEYS: ReadonlySet<string> = new Set(\n ANVIL_WELL_KNOWN_ACCOUNTS.map((a) => a.privateKey.toLowerCase()),\n);\n\nconst WELL_KNOWN_DEV_ADDRESSES: ReadonlySet<string> = new Set(\n ANVIL_WELL_KNOWN_ACCOUNTS.map((a) => a.address.toLowerCase()),\n);\n\n// `0x` plus 64 hex characters, the only shape `privateKeyToAccount` accepts\nconst PRIVATE_KEY_SHAPE = /^0x[0-9a-fA-F]{64}$/;\n\nexport function isWellKnownDevKey(privateKey: string): boolean {\n return WELL_KNOWN_DEV_KEYS.has(privateKey.toLowerCase());\n}\n\nexport function isWellKnownDevAddress(address: string): boolean {\n return WELL_KNOWN_DEV_ADDRESSES.has(address.toLowerCase());\n}\n\n/**\n * True for loopback addresses, RFC 1918 private ranges, and bare (dot-free)\n * hostnames, such as the compose service name \"anvil\".\n *\n * Bare hostnames are treated as local without resolving them. Operators must\n * point them at a private chain.\n */\nexport function isLikelyLocalOrPrivateHost(hostname: string): boolean {\n const h = hostname.toLowerCase().replace(/^\\[|\\]$/g, '');\n if (h === 'localhost' || h === '::1') return true;\n if (/^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^192\\.168\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^172\\.(1[6-9]|2\\d|3[01])\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (!h.includes('.') && !h.includes(':')) return true; // bare hostname\n return false;\n}\n\nfunction parseHostnameOrThrow(rpcUrl: string): string {\n try {\n return new URL(rpcUrl).hostname;\n } catch (cause) {\n // Never the URL itself: RPC providers commonly put an API key in the path,\n // and this message reaches startup output and CI logs\n throw new CommerceError('CONFIG_INVALID', 'x402 provider: rpcUrl is not a valid URL', {\n cause,\n });\n }\n}\n\n/** Origin only, for diagnostics: RPC URLs often carry an API key in the path or query */\nexport function describeRpc(rpcUrl: string): string {\n try {\n return new URL(rpcUrl).origin;\n } catch {\n return '[unparseable rpcUrl]';\n }\n}\n\n/**\n * Throws CONFIG_INVALID if `signerPrivateKey` is not shaped like a private key,\n * or if it is a well-known dev key and the RPC is not local.\n *\n * The shape check runs first, so a truncated key is reported as malformed\n * instead of passing as \"not a dev key\".\n */\nexport function assertDevKeyIsLocalOnly(rpcUrl: string, signerPrivateKey: string): void {\n if (!PRIVATE_KEY_SHAPE.test(signerPrivateKey)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.signerPrivateKey is not a well-formed private key ' +\n '(expected \"0x\" followed by exactly 64 hex characters).',\n );\n }\n\n if (!isWellKnownDevKey(signerPrivateKey)) return; // the operator's own key\n\n const hostname = parseHostnameOrThrow(rpcUrl);\n\n if (!isLikelyLocalOrPrivateHost(hostname)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.signerPrivateKey is a well-known Anvil development key, but rpcUrl ' +\n `${describeRpc(rpcUrl)} does not look like a local/private chain. A public dev key must never sign against ` +\n 'a public network: it is instantly drainable and can grief real settlements via nonce exhaustion. ' +\n 'Use a real facilitator key for any non-local RPC, or point rpcUrl at your local/dev chain.',\n );\n }\n}\n\n/**\n * Throws CONFIG_INVALID if `payTo` is a well-known Anvil address and `rpcUrl`\n * does not look local or private.\n *\n * Guards the receiving side, in every facilitator mode. `agent-commerce init`\n * defaults `payTo` to a well-known address for the local demo, and on a real\n * network that default sends every payment where anyone can sweep it.\n */\nexport function assertPayToIsNotDevAddress(rpcUrl: string, payTo: string): void {\n if (!isWellKnownDevAddress(payTo)) return;\n\n const hostname = parseHostnameOrThrow(rpcUrl);\n\n if (!isLikelyLocalOrPrivateHost(hostname)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"payTo\" (${payTo}) is a well-known Anvil development address, but rpcUrl ` +\n `${describeRpc(rpcUrl)} does not look like a local/private chain. The private key behind that address ` +\n 'is public knowledge, so any revenue settled to it is immediately spendable by anyone. Set ' +\n '\"payTo\" to your own merchant wallet for any non-local RPC, or point rpcUrl at your ' +\n 'local/dev chain.',\n );\n }\n}\n","/**\n * What must hold before this gateway may settle a payment on the configured\n * network. Two callers share these checks: the provider runs them at\n * construction, so a library consumer who skips our config loader still gets\n * them, and the config loader runs them, so `validate` and `doctor` report\n * them too.\n *\n * Both run before any request, because a failure found in `settle()` would\n * come after the pipeline reserved the buyer's replay key.\n *\n * Imports no peer (no viem, no `@x402/*`), so the CLI can load it.\n */\nimport { CommerceError } from '../../core';\nimport { isBurnAddress, sameAddress } from './addresses';\nimport { isLikelyLocalOrPrivateHost, isWellKnownDevAddress } from './dev-key-guard';\nimport {\n type CustomNetworks,\n type DeploymentMode,\n LOCAL_CHAIN_ID,\n requireX402Network,\n resolveDeploymentMode,\n type X402Network,\n} from './networks';\n\n/**\n * How the gateway authenticates to a remote facilitator.\n *\n * - `none`: send no credential; use it when the facilitator accepts\n * anonymous requests.\n * - `bearer`: send a static token; no extra peer package is needed.\n * - `cdp`: Coinbase Developer Platform. The optional peer `@coinbase/x402`,\n * imported only for this type, signs a fresh JWT per request.\n *\n * Any other auth type is refused at config load.\n */\nexport type FacilitatorAuth =\n | { readonly type: 'none' }\n | { readonly type: 'bearer'; readonly token: string }\n | { readonly type: 'cdp'; readonly apiKeyId: string; readonly apiKeySecret: string };\n\nexport type X402FacilitatorConfig =\n | { readonly mode: 'local'; readonly signerPrivateKey: string }\n | { readonly mode: 'remote'; readonly url: string; readonly auth: FacilitatorAuth };\n\nexport interface X402DeploymentInput {\n readonly network: string;\n readonly payTo: string;\n readonly asset: string;\n /** EIP-712 domain of the asset, as the token itself reports it */\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly facilitator: X402FacilitatorConfig;\n /** Must be `true` before anything settles on a mainnet */\n readonly allowMainnet?: boolean;\n /**\n * Must be `true` on mainnet when facilitator auth is `none`. A separate\n * decision from `allowMainnet`: it accepts settling without an account at\n * the facilitator, under its anonymous-access limits.\n */\n readonly allowUnauthenticatedFacilitator?: boolean;\n /**\n * Allow other tokens on built-in EVM networks with explicit metadata.\n * MPP config leaves this unset; Solana and NEAR still require USDC.\n */\n readonly allowOtherEvmToken?: boolean;\n /** Error-path prefix, `payments.x402` by default */\n readonly configPath?: string;\n /** Settlement-recipient field named in errors, `payTo` by default */\n readonly payToField?: string;\n /** EVM networks declared under `payments.x402.networks` */\n readonly customNetworks?: CustomNetworks;\n}\n\nexport interface X402Deployment {\n readonly profile: X402Network;\n readonly mode: DeploymentMode;\n}\n\nconst BASE_SEPOLIA = 'eip155:84532';\n\nfunction invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\n/**\n * Resolves the deployment and refuses the combinations that could move real\n * money by accident. The network must resolve first; the other checks are\n * independent.\n */\nexport function resolveX402Deployment(input: X402DeploymentInput): X402Deployment {\n const at = input.configPath ?? 'payments.x402';\n const payTo = input.payToField ?? 'payTo';\n const profile = requireX402Network(input.network, `${at}.network`, input.customNetworks);\n const mode = resolveDeploymentMode(profile);\n\n // Local mode keeps a gas-paying key in the gateway process. A compromise\n // could expose that key, so mainnet requires a remote facilitator.\n if (profile.kind === 'mainnet' && input.facilitator.mode === 'local') {\n throw invalid(\n `${at}: network \"${profile.id}\" (${profile.displayName}) is a mainnet and cannot be served by facilitator.mode \"local\". A mainnet deployment must settle through a remote facilitator.`,\n `${at}.facilitator.mode`,\n );\n }\n // The in-process facilitator signs with a client built for the Anvil chain\n // id, so on any other chain every settlement would fail\n if (input.facilitator.mode === 'local' && mode !== 'local') {\n throw invalid(\n profile.id === BASE_SEPOLIA\n ? `${at}: the local Anvil chain is eip155:${LOCAL_CHAIN_ID}, Anvil's default chain id; \"${BASE_SEPOLIA}\" is public Base Sepolia. Set ${at}.network to eip155:${LOCAL_CHAIN_ID}, start Anvil with its default chain id and redeploy the local contracts (npm run chain:start, npm run chain:deploy).`\n : `${at}: facilitator.mode \"local\" serves the local Anvil chain (eip155:${LOCAL_CHAIN_ID}) only, not \"${profile.id}\" (${profile.displayName}). Use a remote facilitator.`,\n `${at}.facilitator.mode`,\n );\n }\n\n if (mode === 'mainnet' && input.allowMainnet !== true) {\n throw invalid(\n `${at}: network \"${profile.id}\" (${profile.displayName}) settles real funds. Set ${at}.allowMainnet: true to acknowledge this explicitly - it is never the default.`,\n `${at}.allowMainnet`,\n );\n }\n\n if (input.facilitator.mode === 'remote') {\n assertFacilitatorUrlIsSafe(input.facilitator.url, mode, at);\n // `@coinbase/x402` signs each request for CDP's own host and route,\n // whatever URL is configured, so no other facilitator can accept the credential\n if (input.facilitator.auth.type === 'cdp' && !isCdpFacilitatorUrl(input.facilitator.url)) {\n throw invalid(\n `${at}: facilitator.auth.type \"cdp\" signs requests for ${CDP_FACILITATOR_URL} only, so facilitator ${describeOrigin(input.facilitator.url)} cannot accept its credential. Set facilitator.url to ${CDP_FACILITATOR_URL}, or use auth.type \"bearer\" or \"none\".`,\n `${at}.facilitator.url`,\n );\n }\n // The authorization fixes recipient, amount and chain, so a facilitator\n // cannot redirect funds. A credential adds an account: rate limits, terms\n // and support. On mainnet, going without one is an explicit choice.\n if (\n mode === 'mainnet' &&\n input.facilitator.auth.type === 'none' &&\n input.allowUnauthenticatedFacilitator !== true\n ) {\n throw invalid(\n `${at}: no credential is configured for facilitator ${describeOrigin(input.facilitator.url)} on mainnet. Set ${at}.allowUnauthenticatedFacilitator: true to accept anonymous access and the facilitator's limits, or configure facilitator.auth.`,\n `${at}.allowUnauthenticatedFacilitator`,\n );\n }\n // A blank credential reaches the facilitator as \"unauthenticated\" and fails\n // every payment after the buyer signed. `${VAR:- }` resolving to whitespace\n // is the usual cause.\n for (const [field, value] of credentialFields(input.facilitator.auth)) {\n if (value.trim() === '') {\n throw invalid(\n `${at}: facilitator.auth.type is \"${input.facilitator.auth.type}\" but ${field} is empty. An empty credential is refused rather than sent.`,\n `${at}.facilitator.auth.${field}`,\n );\n }\n }\n }\n\n // The config loader's address check refuses this too; repeated here for a\n // library consumer who calls `createX402PaymentProvider` without it\n if (isBurnAddress(profile, input.payTo)) {\n throw invalid(\n `${at}: \"${payTo}\" is the zero address. Every payment settled there is destroyed.`,\n `${at}.${payTo}`,\n );\n }\n\n // Anyone can spend from a well-known Anvil address. `dev-key-guard` refuses\n // one behind a public RPC; this refuses one on any non-local deployment,\n // whose RPC host says nothing about where a remote facilitator settles.\n if (mode !== 'local' && isWellKnownDevAddress(input.payTo)) {\n throw invalid(\n `${at}: \"${payTo}\" (${input.payTo}) is a well-known Anvil development address and this is a ${mode} deployment. Anyone can spend what settles there. Set ${payTo} to your own merchant wallet.`,\n `${at}.${payTo}`,\n );\n }\n\n // Public built-ins require USDC unless the caller allows another EVM token.\n // Local and declared networks have no default asset.\n const canonical = profile.canonicalAsset;\n if (canonical) {\n if (!sameAddress(profile, input.asset, canonical.address)) {\n if (input.allowOtherEvmToken !== true || profile.family !== 'evm') {\n const rule =\n input.allowOtherEvmToken === true\n ? `Only an EVM network accepts another token; ${profile.displayName} settles only in its ${canonical.symbol}.`\n : `A built-in network settles only in its ${canonical.symbol}.`;\n throw invalid(\n `${at}: asset ${input.asset} is not ${canonical.symbol} on ${profile.displayName} (expected ${canonical.address}). ${rule}`,\n `${at}.asset`,\n );\n }\n } else {\n // Catch USDC domain mismatches before accepting payments; a wrong name\n // can fail with `invalid_exact_evm_token_name_mismatch`\n const domain = 'name' in canonical ? canonical : undefined;\n if (domain && input.assetName !== undefined && input.assetName !== domain.name) {\n throw invalid(\n `${at}: assetName \"${input.assetName}\" is not the EIP-712 domain name ${canonical.symbol} reports on ${profile.displayName} (expected \"${domain.name}\"). Every payment would be refused after the buyer signed.`,\n `${at}.assetName`,\n );\n }\n if (domain && input.assetVersion !== undefined && input.assetVersion !== domain.version) {\n throw invalid(\n `${at}: assetVersion \"${input.assetVersion}\" is not the EIP-712 domain version ${canonical.symbol} reports on ${profile.displayName} (expected \"${domain.version}\").`,\n `${at}.assetVersion`,\n );\n }\n }\n }\n\n return { profile, mode };\n}\n\n/**\n * A facilitator sees every payment authorization this gateway handles. Plain\n * HTTP puts those on the wire in the clear and lets anyone in the path rewrite\n * a settlement result, so it is allowed only to a local or private host, and\n * never on a mainnet.\n */\nfunction assertFacilitatorUrlIsSafe(url: string, mode: DeploymentMode, at: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch (cause) {\n throw new CommerceError('CONFIG_INVALID', `${at}: facilitator.url is not a valid URL`, {\n cause,\n details: { path: `${at}.facilitator.url` },\n });\n }\n\n if (parsed.protocol === 'https:') return;\n if (parsed.protocol !== 'http:') {\n throw invalid(\n `${at}: facilitator ${describeOrigin(url)} must be reached over https (or http on a local/private host); got \"${parsed.protocol}//\"`,\n `${at}.facilitator.url`,\n );\n }\n if (mode !== 'mainnet' && isLikelyLocalOrPrivateHost(parsed.hostname)) return;\n\n // The origin, never the whole URL: the path can carry a tenant or an API\n // key, and this message reaches `validate`, `doctor`, startup output and CI logs\n throw invalid(\n `${at}: facilitator ${describeOrigin(url)} is reached over plain HTTP. Payment authorizations and settlement results would travel unencrypted. Use https, or point at a local/private host on a non-mainnet deployment.`,\n `${at}.facilitator.url`,\n );\n}\n\n/** The facilitator URL `@coinbase/x402` signs its JWTs for */\nexport const CDP_FACILITATOR_URL = 'https://api.cdp.coinbase.com/platform/v2/x402';\n\n// The SDK client strips trailing slashes before appending its route\nfunction isCdpFacilitatorUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n const expected = new URL(CDP_FACILITATOR_URL);\n return (\n parsed.origin === expected.origin &&\n parsed.pathname.replace(/\\/+$/, '') === expected.pathname &&\n parsed.search === ''\n );\n } catch {\n return false;\n }\n}\n\n// Origin only: a facilitator URL can carry a tenant path or an API key\nfunction describeOrigin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return '[unparseable facilitator.url]';\n }\n}\n\n// The secret-bearing fields of an auth block, for emptiness checks only. Never logged\nfunction credentialFields(auth: FacilitatorAuth): readonly (readonly [string, string])[] {\n switch (auth.type) {\n case 'bearer':\n return [['token', auth.token]];\n case 'cdp':\n return [\n ['apiKeyId', auth.apiKeyId],\n ['apiKeySecret', auth.apiKeySecret],\n ];\n default:\n return [];\n }\n}\n","/**\n * Resolves an x402 option into offer terms at config load, so `validate`\n * reports invalid options before startup. This module uses no SDK.\n *\n * Omitted assets use `canonicalAsset`. Overrides for the default token must\n * match its metadata; another token needs its own, including the EIP-712 domain\n * on EVM.\n */\nimport { CommerceError } from '../../core';\nimport { isBurnAddress, normalizeAddress, sameAddress } from './addresses';\nimport { type CustomNetworks, requireX402Network, type X402Network } from './networks';\n\nexport interface X402OptionInput {\n readonly scheme?: string;\n readonly network: string;\n readonly payTo: string;\n readonly asset?: string;\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly assetDecimals?: number;\n /** `eip3009` (the default) or `permit2`; EVM only */\n readonly assetTransferMethod?: string;\n}\n\nexport interface ResolvedX402Option {\n readonly scheme: 'exact';\n readonly network: X402Network;\n readonly payTo: string;\n readonly asset: string;\n /** EIP-712 domain; EVM only */\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly assetDecimals: number;\n /**\n * Default token symbol when `asset` is omitted; resource prices must use\n * this symbol or USD\n */\n readonly defaultAssetSymbol?: string;\n /** How the buyer authorizes the transfer; always `eip3009` off EVM */\n readonly assetTransferMethod: X402AssetTransferMethod;\n}\n\n/**\n * Names health components by network, asset and payee for discovery matching.\n * Lowercase EVM addresses so case variants identify the same offer.\n */\nexport function x402OfferName(offer: {\n readonly network: string;\n readonly asset: string;\n readonly payTo: string;\n}): string {\n const evm = offer.network.startsWith('eip155:');\n const address = (value: string) => (evm ? value.toLowerCase() : value);\n return `${offer.network} ${address(offer.asset)} ${address(offer.payTo)}`;\n}\n\n/** EIP-3009 `transferWithAuthorization`, or Permit2 with a prior token allowance */\nexport type X402AssetTransferMethod = 'eip3009' | 'permit2';\n\n// Incorrect EIP-712 domain values invalidate the buyer's signature\nconst FIELD_MEANINGS = {\n assetName: 'EIP-712 domain name',\n assetVersion: 'EIP-712 domain version',\n assetDecimals: 'decimals',\n} as const;\n\nconst ADDRESS_SHAPES = {\n evm: '\"0x\" followed by 40 hex characters',\n svm: 'a base58 public key of 32 bytes',\n near: 'a NEAR account ID: 2 to 64 lowercase characters, digits and single \"-\", \"_\" or \".\" separators',\n} as const;\n\nfunction invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\nexport function resolveX402Option(\n input: X402OptionInput,\n path: string,\n custom?: CustomNetworks,\n): ResolvedX402Option {\n if (input.scheme !== undefined && input.scheme !== 'exact') {\n throw invalid(\n `${path}.scheme: \"${input.scheme}\" is not supported; the only x402 scheme is \"exact\"`,\n `${path}.scheme`,\n );\n }\n const network = requireX402Network(input.network, `${path}.network`, custom);\n const address = (field: 'payTo' | 'asset', value: string): string => {\n const wire = normalizeAddress(network, value);\n if (wire === undefined) {\n throw invalid(\n // The value is not echoed: a swapped variable could put a key here\n `${path}.${field} is not a plausible address on ${network.displayName} (expected ${ADDRESS_SHAPES[network.family]})`,\n `${path}.${field}`,\n );\n }\n return wire;\n };\n\n const payTo = address('payTo', input.payTo);\n if (isBurnAddress(network, payTo)) {\n throw invalid(\n `${path}.payTo is the zero address of ${network.displayName}. Every payment settled there is destroyed.`,\n `${path}.payTo`,\n );\n }\n\n const method = input.assetTransferMethod ?? 'eip3009';\n if (method !== 'eip3009' && method !== 'permit2') {\n throw invalid(\n `${path}.assetTransferMethod: \"${method}\" is not supported; use \"eip3009\" or \"permit2\"`,\n `${path}.assetTransferMethod`,\n );\n }\n if (network.family !== 'evm' && input.assetTransferMethod !== undefined) {\n throw invalid(\n `${path}.assetTransferMethod applies to EVM networks only, not to ${network.displayName}`,\n `${path}.assetTransferMethod`,\n );\n }\n\n if (network.family !== 'evm') {\n for (const field of ['assetName', 'assetVersion'] as const) {\n if (input[field] !== undefined) {\n throw invalid(\n `${path}.${field}: an EIP-712 domain applies to EVM tokens only, not to ${network.displayName}`,\n `${path}.${field}`,\n );\n }\n }\n }\n\n const canonical = network.canonicalAsset;\n const domain = canonical && 'name' in canonical ? canonical : undefined;\n\n const asset = input.asset !== undefined ? address('asset', input.asset) : undefined;\n if (asset !== undefined && isBurnAddress(network, asset)) {\n throw invalid(`${path}.asset must not be the zero address`, `${path}.asset`);\n }\n\n // The default asset applies when the option names none or names it exactly\n if (canonical && (asset === undefined || sameAddress(network, asset, canonical.address))) {\n const expected = {\n assetName: domain?.name,\n assetVersion: domain?.version,\n assetDecimals: canonical.decimals,\n };\n for (const field of ['assetName', 'assetVersion', 'assetDecimals'] as const) {\n const given = input[field];\n if (given !== undefined && given !== expected[field]) {\n throw invalid(\n `${path}.${field} does not match ${canonical.symbol} on ${network.displayName}, which reports ${FIELD_MEANINGS[field]} ${JSON.stringify(expected[field])}. Remove ${field}, or set asset to the token it describes.`,\n `${path}.${field}`,\n );\n }\n }\n return {\n scheme: 'exact',\n network,\n payTo,\n asset: asset ?? canonical.address,\n ...(domain ? { assetName: domain.name, assetVersion: domain.version } : {}),\n assetDecimals: canonical.decimals,\n defaultAssetSymbol: canonical.symbol,\n assetTransferMethod: method,\n };\n }\n\n // Another token: nothing about it can be borrowed from the default. The\n // token's EIP-712 domain matters to EIP-3009 only: a Permit2 buyer signs\n // Permit2's own domain.\n const required =\n network.family === 'evm' && method === 'eip3009'\n ? (['asset', 'assetName', 'assetVersion', 'assetDecimals'] as const)\n : (['asset', 'assetDecimals'] as const);\n const missing = required.filter((field) => input[field] === undefined);\n if (asset === undefined || missing.length > 0) {\n throw invalid(\n canonical\n ? `${path}: a token other than ${canonical.symbol} on ${network.displayName} needs ${missing.join(', ')}`\n : `${path}: ${network.displayName} has no default asset, so the option needs ${missing.join(', ')}`,\n `${path}.${missing[0] ?? 'asset'}`,\n );\n }\n return {\n scheme: 'exact',\n network,\n payTo,\n asset,\n ...(input.assetName !== undefined ? { assetName: input.assetName } : {}),\n ...(input.assetVersion !== undefined ? { assetVersion: input.assetVersion } : {}),\n assetDecimals: input.assetDecimals as number,\n assetTransferMethod: method,\n };\n}\n","/**\n * x402 exact-scheme flows, shared by the config loader and CLI.\n * The default `authorization` flow settles after a successful backend call;\n * `upfront` settles first.\n */\nexport const X402_PAYMENT_FLOWS = ['authorization', 'upfront'] as const;\n\nexport type X402PaymentFlow = (typeof X402_PAYMENT_FLOWS)[number];\n\nexport const X402_DEFAULT_PAYMENT_FLOW: X402PaymentFlow = 'authorization';\n"]}
@@ -1 +0,0 @@
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,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,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,MAAA,CAAO,KAAA,EAAM;AAAA,IACf;AAAA,GACF;AACF","file":"ap2-GWSP4LYY.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 a local commit are not one transaction. If the process dies\n * between them the row stays `reserved` and that mandate is refused from then\n * on: a refused retry costs a round trip, the other direction costs a second\n * payment.\n */\nimport type { Database } from 'better-sqlite3';\nimport { type Logger, NOOP_LOGGER } from '../../core';\nimport { openSqliteDatabase } from '../../storage/sqlite';\n\n/**\n * `released` is \"nothing happened\" and the only state a mandate can be\n * presented from again. `uncertain` is a settlement whose outcome we never\n * learned: not reusable, but findable by an operator reconciling by hand.\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 of uncertain outcome. Never re-spendable */\n | { readonly kind: 'replayed'; readonly state: Ap2AuthorizationState };\n\nexport interface Ap2ReplayStore {\n /** Atomically claim a mandate, or report that something already holds it */\n reserve(request: Ap2ReservationRequest): Ap2ReservationResult;\n /** Settlement succeeded: spend it permanently */\n consume(reference: string): void;\n /** Nothing happened: hand it back so a corrected retry can use it */\n release(reference: string): void;\n /** Settlement outcome unknown. Not reusable, and flagged for a human */\n markUncertain(reference: string): void;\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 // Guarded on `reserved`: releasing a `consumed` row would hand back a\n // mandate whose money has already moved\n const transition = db.prepare(\n `UPDATE ap2_authorizations SET state = @state, updated_at = @at\n WHERE reference = @reference AND state = 'reserved'`,\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): void => {\n transition.run({ reference, state, at: new Date(now()).toISOString() });\n };\n\n let closed = false;\n return {\n reserve(request) {\n return reserveTx(request);\n },\n consume(reference) {\n move(reference, 'consumed');\n },\n release(reference) {\n move(reference, 'released');\n },\n markUncertain(reference) {\n move(reference, 'uncertain');\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 try {\n replay[action](reservationId);\n } catch (cause) {\n throw ap2Unavailable(`replay store could not record ${action}`, { ...context, cause });\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"]}