@devlab.group/agent-commerce 2.5.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -21
- package/dist/ap2.d.ts +19 -6
- package/dist/ap2.js +56 -18
- package/dist/ap2.js.map +1 -1
- package/dist/{chunk-ES3V6ECS.js → chunk-77HLISG4.js} +3 -2
- package/dist/chunk-77HLISG4.js.map +1 -0
- package/dist/{chunk-5ZYXBCDX.js → chunk-D7FPSGUQ.js} +25 -4
- package/dist/chunk-D7FPSGUQ.js.map +1 -0
- package/dist/{chunk-VUCMBGUR.js → chunk-DJRWYDKJ.js} +3 -3
- package/dist/{chunk-VUCMBGUR.js.map → chunk-DJRWYDKJ.js.map} +1 -1
- package/dist/{chunk-4K7FIBJM.js → chunk-EMKITGVV.js} +4 -4
- package/dist/chunk-EMKITGVV.js.map +1 -0
- package/dist/chunk-IWXVQYG5.js +6 -0
- package/dist/chunk-IWXVQYG5.js.map +1 -0
- package/dist/chunk-O3ACF45K.js +8 -0
- package/dist/chunk-O3ACF45K.js.map +1 -0
- package/dist/chunk-WDD2ZUR3.js +20 -0
- package/dist/chunk-WDD2ZUR3.js.map +1 -0
- package/dist/{chunk-3OTCFFFT.js → chunk-YHNTTMED.js} +7 -7
- package/dist/chunk-YHNTTMED.js.map +1 -0
- package/dist/{chunk-FKQK5XZA.js → chunk-ZSIUZPNB.js} +183 -80
- package/dist/chunk-ZSIUZPNB.js.map +1 -0
- package/dist/cli/{ap2-YAPLERSC.js → ap2-5FFGSW6F.js} +61 -25
- package/dist/cli/ap2-5FFGSW6F.js.map +1 -0
- package/dist/cli/{chunk-5K4XEAZV.js → chunk-3IEXJ7I3.js} +25 -4
- package/dist/cli/chunk-3IEXJ7I3.js.map +1 -0
- package/dist/cli/{chunk-NIU5EMSB.js → chunk-3NVJAQRO.js} +5 -5
- package/dist/cli/{chunk-NIU5EMSB.js.map → chunk-3NVJAQRO.js.map} +1 -1
- package/dist/cli/{chunk-IDY2735M.js → chunk-55AI6CLW.js} +6 -4
- package/dist/cli/chunk-55AI6CLW.js.map +1 -0
- package/dist/cli/{chunk-QA2OPHBF.js → chunk-5K2JDM4G.js} +185 -83
- package/dist/cli/chunk-5K2JDM4G.js.map +1 -0
- package/dist/cli/{chunk-QLUCNPRT.js → chunk-5TID36YG.js} +860 -170
- package/dist/cli/chunk-5TID36YG.js.map +1 -0
- package/dist/cli/{chunk-5R7DM5LM.js → chunk-66NTYSXI.js} +27 -27
- package/dist/cli/chunk-66NTYSXI.js.map +1 -0
- package/dist/cli/{chunk-VJ4EO4LE.js → chunk-6EBDOH37.js} +3 -3
- package/dist/cli/{chunk-VJ4EO4LE.js.map → chunk-6EBDOH37.js.map} +1 -1
- package/dist/cli/{chunk-4H2QLHQI.js → chunk-AGQ4U7IN.js} +5 -5
- package/dist/cli/chunk-AGQ4U7IN.js.map +1 -0
- package/dist/cli/chunk-APC5BTQM.js +6 -0
- package/dist/cli/chunk-APC5BTQM.js.map +1 -0
- package/dist/cli/{chunk-SYQLJXIU.js → chunk-C5YISPT6.js} +3 -3
- package/dist/cli/chunk-C5YISPT6.js.map +1 -0
- package/dist/cli/chunk-DKWO6LLX.js +34 -0
- package/dist/cli/chunk-DKWO6LLX.js.map +1 -0
- package/dist/cli/{chunk-SPAYKVUP.js → chunk-FL4HPCD4.js} +3 -2
- package/dist/cli/chunk-FL4HPCD4.js.map +1 -0
- package/dist/cli/{chunk-3EQBCFZY.js → chunk-H7EBJ4I3.js} +3 -3
- package/dist/cli/{chunk-3EQBCFZY.js.map → chunk-H7EBJ4I3.js.map} +1 -1
- package/dist/cli/{chunk-Z34UMZBB.js → chunk-OETKXDGA.js} +546 -175
- package/dist/cli/chunk-OETKXDGA.js.map +1 -0
- package/dist/cli/{chunk-JFVRG2HH.js → chunk-PLHPKXAT.js} +8 -8
- package/dist/cli/chunk-PLHPKXAT.js.map +1 -0
- package/dist/cli/{chunk-2UPPX3FJ.js → chunk-VSSSU4AU.js} +76 -14
- package/dist/cli/chunk-VSSSU4AU.js.map +1 -0
- package/dist/cli/chunk-ZCW56PZ3.js +8 -0
- package/dist/cli/{chunk-M7NXVRU5.js.map → chunk-ZCW56PZ3.js.map} +1 -1
- package/dist/cli/{chunk-2J2IQQ4X.js → chunk-ZFVQWOGG.js} +95 -42
- package/dist/cli/chunk-ZFVQWOGG.js.map +1 -0
- package/dist/cli/config-WT5HHDRR.js +13 -0
- package/dist/cli/{config-BWFMN2ZB.js.map → config-WT5HHDRR.js.map} +1 -1
- package/dist/cli/index.js +560 -252
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-KZEMXLHR.js → mcp-HHGNOUKE.js} +7 -7
- package/dist/cli/{mcp-KZEMXLHR.js.map → mcp-HHGNOUKE.js.map} +1 -1
- package/dist/cli/payment-providers-EWXZFBIE.js +6 -0
- package/dist/cli/{payment-providers-SZL36H3Y.js.map → payment-providers-EWXZFBIE.js.map} +1 -1
- package/dist/cli/{provider-6TKB5ADJ.js → provider-XUPLYNQ7.js} +36 -18
- package/dist/cli/provider-XUPLYNQ7.js.map +1 -0
- package/dist/cli/receipts-3DSV4DIK.js +9 -0
- package/dist/cli/{receipts-ZGLJWMQG.js.map → receipts-3DSV4DIK.js.map} +1 -1
- package/dist/cli/reconcile-GS25MQ42.js +4 -0
- package/dist/cli/{reconcile-IC22MJD5.js.map → reconcile-GS25MQ42.js.map} +1 -1
- package/dist/cli/{run-ZTYPQI4D.js → run-7KLKW3HE.js} +310 -91
- package/dist/cli/run-7KLKW3HE.js.map +1 -0
- package/dist/cli/{x402-WLYBLODI.js → x402-HP4E3QET.js} +11 -10
- package/dist/cli/x402-HP4E3QET.js.map +1 -0
- package/dist/{guardrails-CX_jYXvZ.d.ts → guardrails-CeyLS1ou.d.ts} +2 -2
- package/dist/index.d.ts +119 -206
- package/dist/index.js +1703 -427
- package/dist/index.js.map +1 -1
- package/dist/logger-CllGwQ8i.d.ts +19 -0
- package/dist/mcp.d.ts +3 -1
- package/dist/mcp.js +4 -3
- package/dist/mcp.js.map +1 -1
- package/dist/mpp.d.ts +2 -1
- package/dist/mpp.js +32 -13
- package/dist/mpp.js.map +1 -1
- package/dist/{protocol-adapter-DEXpdp8m.d.ts → protocol-adapter-DdFL5LBU.d.ts} +15 -132
- package/dist/{runtime-Dz2fSO-P.d.ts → runtime-BmaSp2Ce.d.ts} +36 -23
- package/dist/store-BVvMzpuV.d.ts +389 -0
- package/dist/testing.d.ts +51 -0
- package/dist/testing.js +2050 -0
- package/dist/testing.js.map +1 -0
- package/dist/transaction-BXXJltZ-.d.ts +129 -0
- package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
- package/dist/x402.d.ts +9 -3
- package/dist/x402.js +7 -5
- package/dist/x402.js.map +1 -1
- package/package.json +17 -29
- package/dist/chunk-3OTCFFFT.js.map +0 -1
- package/dist/chunk-4K7FIBJM.js.map +0 -1
- package/dist/chunk-5ZYXBCDX.js.map +0 -1
- package/dist/chunk-ES3V6ECS.js.map +0 -1
- package/dist/chunk-FKQK5XZA.js.map +0 -1
- package/dist/cli/ap2-YAPLERSC.js.map +0 -1
- package/dist/cli/chunk-2J2IQQ4X.js.map +0 -1
- package/dist/cli/chunk-2UPPX3FJ.js.map +0 -1
- package/dist/cli/chunk-4H2QLHQI.js.map +0 -1
- package/dist/cli/chunk-5K4XEAZV.js.map +0 -1
- package/dist/cli/chunk-5R7DM5LM.js.map +0 -1
- package/dist/cli/chunk-FHCFR2GS.js +0 -17
- package/dist/cli/chunk-FHCFR2GS.js.map +0 -1
- package/dist/cli/chunk-IDY2735M.js.map +0 -1
- package/dist/cli/chunk-JFVRG2HH.js.map +0 -1
- package/dist/cli/chunk-M7NXVRU5.js +0 -8
- package/dist/cli/chunk-QA2OPHBF.js.map +0 -1
- package/dist/cli/chunk-QLUCNPRT.js.map +0 -1
- package/dist/cli/chunk-SPAYKVUP.js.map +0 -1
- package/dist/cli/chunk-SYQLJXIU.js.map +0 -1
- package/dist/cli/chunk-Z34UMZBB.js.map +0 -1
- package/dist/cli/config-BWFMN2ZB.js +0 -12
- package/dist/cli/payment-providers-SZL36H3Y.js +0 -6
- package/dist/cli/provider-6TKB5ADJ.js.map +0 -1
- package/dist/cli/receipts-ZGLJWMQG.js +0 -8
- package/dist/cli/reconcile-IC22MJD5.js +0 -4
- package/dist/cli/run-ZTYPQI4D.js.map +0 -1
- package/dist/cli/x402-WLYBLODI.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/storage/receipts/redact.ts","../../src/storage/receipts/rows.ts","../../src/storage/receipts/schema.ts","../../src/storage/receipts/store.ts"],"names":["fsConstants"],"mappings":";;;;;;;;AAWA,IAAM,kBAAA,GACJ,iOAAA;AAEF,IAAM,QAAA,GAAW,YAAA;AAGV,SAAS,YAAY,GAAA,EAAsB;AAChD,EAAA,OAAO,kBAAA,CAAmB,KAAK,GAAG,CAAA;AACpC;AAMO,SAAS,OAAU,KAAA,EAAa;AACrC,EAAA,OAAO,YAAY,KAAK,CAAA;AAC1B;AAEA,SAAS,YAAY,KAAA,EAAyB;AAC5C,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACxB,IAAA,OAAO,KAAA,CAAM,IAAI,WAAW,CAAA;AAAA,EAC9B;AACA,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,EAAU;AAC/C,IAAA,MAAM,MAA+B,EAAC;AACtC,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAgC,CAAA,EAAG;AAC3E,MAAA,GAAA,CAAI,GAAG,CAAA,GAAI,WAAA,CAAY,GAAG,CAAA,GAAI,QAAA,GAAW,YAAY,KAAK,CAAA;AAAA,IAC5D;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT;;;AC2DO,SAAS,aAAa,OAA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,QAAA,IAAI,YAAY,cAAA,EAAgB;AAC9B,UAAA,MAAA,CAAO,IAAA;AAAA,YACL,EAAE,KAAA,EAAO,OAAA,EAAS,QAAA,EAAU,cAAA,EAAe;AAAA,YAC3C;AAAA,WACF;AACA,UAAA,OAAO;AAAA,YACL,MAAA,EAAQ,MAAA;AAAA,YACR,MAAA,EAAQ,uBAAA;AAAA,YACR,SAAA,EAAW,MAAM,MAAA,EAAO;AAAA,YACxB,UAAA,EAAY,KAAA,CAAM,WAAA,EAAY,GAAI;AAAA,WACpC;AAAA,QACF;AACA,QAAA,OAAO;AAAA,UACL,MAAA,EAAQ,MAAA;AAAA,UACR,MAAA,EAAQ,kBAAkB,cAAc,CAAA,SAAA,CAAA;AAAA,UACxC,SAAA,EAAW,MAAM,MAAA,EAAO;AAAA,UACxB,UAAA,EAAY,KAAA,CAAM,WAAA,EAAY,GAAI;AAAA,SACpC;AAAA,MACF,SAAS,GAAA,EAAK;AACZ,QAAA,MAAA,CAAO,IAAA;AAAA,UACL,EAAE,KAAK,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAA,EAAE;AAAA,UACxD;AAAA,SACF;AACA,QAAA,OAAO;AAAA,UACL,MAAA,EAAQ,MAAA;AAAA,UACR,MAAA,EAAQ,mBAAA;AAAA,UACR,SAAA,EAAW,MAAM,MAAA,EAAO;AAAA,UACxB,UAAA,EAAY,KAAA,CAAM,WAAA,EAAY,GAAI;AAAA,SACpC;AAAA,MACF;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,KAAA,GAAuB;AAC3B,MAAA,IAAI,CAAC,MAAA,EAAQ;AACX,QAAA,MAAA,GAAS,IAAA;AACT,QAAA,EAAA,CAAG,KAAA,EAAM;AAAA,MACX;AAAA,IACF;AAAA,GACF;AAEA,EAAA,OAAO,KAAA;AACT","file":"chunk-QLUCNPRT.js","sourcesContent":["/**\n * Defense in depth against persisting secrets. Receipt, event and payment\n * metadata must not carry secrets (docs/contracts.md, \"Store no secrets\"); at\n * the persistence boundary this module replaces secret-shaped values rather\n * than rejecting the write, because event persistence must not break a\n * commerce flow.\n */\n\n// Matches anywhere in the key (only `auth` and `proof` must be the whole key),\n// so an audit field whose name contains \"token\", \"session\", \"jwt\" or similar\n// persists as [REDACTED]\nconst SECRET_KEY_PATTERN =\n /private[-_ ]?key|secret|password|mnemonic|seed[-_ ]?phrase|api[-_ ]?key|authoriz(e|ation)|^auth$|auth[-_]?header|payment[-_ ]?proof|^proof$|x-payment|signature|signed[-_ ]?message|token|bearer|credential|cookie|session|jwt/i;\n\nconst REDACTED = '[REDACTED]';\n\n/** True if `key` looks like it names a secret value */\nexport function isSecretKey(key: string): boolean {\n return SECRET_KEY_PATTERN.test(key);\n}\n\n/**\n * Returns a copy with every value under a secret-shaped key replaced, at any\n * depth. Clean input comes back equal to itself.\n */\nexport function redact<T>(value: T): T {\n return redactValue(value) as T;\n}\n\nfunction redactValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {\n out[key] = isSecretKey(key) ? REDACTED : redactValue(inner);\n }\n return out;\n }\n return value;\n}\n","/**\n * SQLite row shapes and their mapping to and from the canonical model. Under\n * `exactOptionalPropertyTypes`, an optional field is set only when present.\n */\nimport {\n type AuthorizationRecord,\n type CommerceEvent,\n type CommerceEventType,\n type CommerceReceipt,\n type IsoTimestamp,\n type PaymentAttempt,\n type PaymentAttemptResolution,\n type PaymentResult,\n type Transaction,\n transactionState,\n} from '../../core';\nimport { redact } from './redact';\n\nexport interface ReceiptRow {\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly payment_json: string | null;\n readonly delivered_at: string;\n readonly backend_status: number;\n readonly duration_ms: number | null;\n readonly protocol: string | null;\n readonly metadata_json: string | null;\n readonly authorization_json: string | null;\n readonly transaction_id: string | null;\n}\n\nexport interface EventRow {\n readonly id: string;\n readonly type: string;\n readonly request_id: string;\n readonly resource_id: string | null;\n readonly at: string;\n readonly adapter: string | null;\n readonly payment_provider: string | null;\n readonly duration_ms: number | null;\n readonly status: string | null;\n readonly data_json: string | null;\n readonly transaction_id: string | null;\n}\n\nexport interface PaymentAttemptRow {\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly provider: string;\n readonly replay_key: string;\n readonly status: string;\n readonly amount: string;\n readonly currency: string;\n readonly payer: string | null;\n readonly payee: string | null;\n readonly external_reference: string | null;\n readonly rejection_reason: string | null;\n readonly created_at: string;\n readonly updated_at: string;\n readonly transaction_id: string | null;\n readonly resolution_json: string | null;\n}\n\n/** A `transactions` row joined with the columns of its payment attempt */\nexport interface TransactionRow {\n readonly seq: number;\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly protocol: string;\n readonly provider: string;\n readonly attempt_id: string;\n readonly replay_key: string;\n readonly network: string | null;\n readonly asset: string | null;\n readonly authorization_json: string | null;\n readonly reservation_id: string | null;\n readonly locator_json: string | null;\n readonly expires_at: string | null;\n readonly input_digest: string | null;\n readonly config_digest: string;\n readonly settling_at: string | null;\n readonly backend_dispatched_at: string | null;\n readonly backend_deadline_at: string | null;\n readonly backend_status: number | null;\n readonly backend_error_code: string | null;\n readonly receipt_id: string | null;\n readonly persistence_failures_json: string | null;\n readonly completed_at: string | null;\n readonly created_at: string;\n readonly updated_at: string;\n readonly payment_status: string;\n readonly payment_amount: string;\n readonly payment_currency: string;\n readonly payment_payee: string | null;\n readonly payment_external_reference: string | null;\n}\n\nexport function receiptToRow(receipt: CommerceReceipt): {\n id: string;\n request_id: string;\n resource_id: string;\n payment_json: string | null;\n delivered_at: string;\n backend_status: number;\n duration_ms: number | null;\n protocol: string | null;\n metadata_json: string | null;\n authorization_json: string | null;\n transaction_id: string | null;\n} {\n return {\n id: receipt.id,\n request_id: receipt.requestId,\n resource_id: receipt.resourceId,\n payment_json: receipt.payment !== undefined ? JSON.stringify(redact(receipt.payment)) : null,\n delivered_at: receipt.deliveredAt,\n backend_status: receipt.backendStatus,\n duration_ms: receipt.durationMs ?? null,\n protocol: receipt.protocol ?? null,\n metadata_json: receipt.metadata !== undefined ? JSON.stringify(redact(receipt.metadata)) : null,\n authorization_json:\n receipt.authorization !== undefined ? JSON.stringify(redact(receipt.authorization)) : null,\n transaction_id: receipt.transactionId ?? null,\n };\n}\n\nexport function rowToReceipt(row: ReceiptRow): CommerceReceipt {\n const payment =\n row.payment_json !== null ? (JSON.parse(row.payment_json) as PaymentResult) : undefined;\n const metadata =\n row.metadata_json !== null\n ? (JSON.parse(row.metadata_json) as Record<string, unknown>)\n : undefined;\n // Null for a receipt written before this column existed and for a resource\n // that requires no authorization\n const authorization =\n row.authorization_json !== null\n ? (JSON.parse(row.authorization_json) as AuthorizationRecord)\n : undefined;\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n deliveredAt: row.delivered_at,\n backendStatus: row.backend_status,\n ...(payment !== undefined ? { payment } : {}),\n ...(row.duration_ms !== null ? { durationMs: row.duration_ms } : {}),\n ...(row.protocol !== null ? { protocol: row.protocol } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n ...(row.transaction_id !== null ? { transactionId: row.transaction_id } : {}),\n };\n}\n\nexport function eventToRow(event: CommerceEvent): {\n id: string;\n type: string;\n request_id: string;\n resource_id: string | null;\n at: string;\n adapter: string | null;\n payment_provider: string | null;\n duration_ms: number | null;\n status: string | null;\n data_json: string | null;\n transaction_id: string | null;\n} {\n return {\n id: event.id,\n type: event.type,\n request_id: event.requestId,\n resource_id: event.resourceId ?? null,\n at: event.at,\n adapter: event.adapter ?? null,\n payment_provider: event.paymentProvider ?? null,\n duration_ms: event.durationMs ?? null,\n status: event.status ?? null,\n data_json: event.data !== undefined ? JSON.stringify(redact(event.data)) : null,\n transaction_id: event.transactionId ?? null,\n };\n}\n\nexport function rowToEvent(row: EventRow): CommerceEvent {\n const data =\n row.data_json !== null ? (JSON.parse(row.data_json) as Record<string, unknown>) : undefined;\n return {\n id: row.id,\n type: row.type as CommerceEventType,\n requestId: row.request_id,\n at: row.at,\n ...(row.resource_id !== null ? { resourceId: row.resource_id } : {}),\n ...(row.adapter !== null ? { adapter: row.adapter } : {}),\n ...(row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {}),\n ...(row.duration_ms !== null ? { durationMs: row.duration_ms } : {}),\n ...(row.status !== null ? { status: row.status as 'ok' | 'error' } : {}),\n ...(data !== undefined ? { data } : {}),\n ...(row.transaction_id !== null ? { transactionId: row.transaction_id } : {}),\n };\n}\n\nexport function rowToPaymentAttempt(row: PaymentAttemptRow): PaymentAttempt {\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n provider: row.provider,\n replayKey: row.replay_key,\n status: row.status as PaymentAttempt['status'],\n amount: row.amount,\n currency: row.currency,\n ...(row.payer !== null ? { payer: row.payer } : {}),\n ...(row.payee !== null ? { payee: row.payee } : {}),\n ...(row.external_reference !== null ? { externalReference: row.external_reference } : {}),\n ...(row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {}),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n ...(row.transaction_id !== null ? { transactionId: row.transaction_id } : {}),\n ...(row.resolution_json !== null\n ? { resolution: JSON.parse(row.resolution_json) as PaymentAttemptResolution }\n : {}),\n };\n}\n\n/**\n * Recompute state using `now` so reads reflect backend deadlines that have\n * passed since the last write\n */\nexport function rowToTransaction(row: TransactionRow, now: IsoTimestamp): Transaction {\n const status = row.payment_status as PaymentAttempt['status'];\n const backend =\n row.backend_dispatched_at !== null && row.backend_deadline_at !== null\n ? {\n dispatchedAt: row.backend_dispatched_at,\n deadlineAt: row.backend_deadline_at,\n ...(row.backend_status !== null ? { status: row.backend_status } : {}),\n ...(row.backend_error_code !== null ? { errorCode: row.backend_error_code } : {}),\n }\n : undefined;\n const completedAt = row.completed_at ?? undefined;\n const authorization =\n row.authorization_json !== null && row.reservation_id !== null\n ? {\n ...(JSON.parse(row.authorization_json) as NonNullable<Transaction['authorization']>),\n reservationId: row.reservation_id,\n }\n : undefined;\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n protocol: row.protocol as Transaction['protocol'],\n state: transactionState(\n {\n payment: { status },\n ...(backend !== undefined ? { backend } : {}),\n ...(completedAt !== undefined ? { completedAt } : {}),\n },\n now,\n ),\n payment: {\n provider: row.provider as Transaction['payment']['provider'],\n attemptId: row.attempt_id,\n replayKey: row.replay_key,\n status,\n amount: row.payment_amount,\n currency: row.payment_currency,\n ...(row.network !== null ? { network: row.network } : {}),\n ...(row.asset !== null ? { asset: row.asset } : {}),\n ...(row.payment_payee !== null ? { payee: row.payment_payee } : {}),\n ...(row.payment_external_reference !== null\n ? { externalReference: row.payment_external_reference }\n : {}),\n ...(row.locator_json !== null\n ? { locator: JSON.parse(row.locator_json) as Record<string, unknown> }\n : {}),\n ...(row.settling_at !== null ? { settlingAt: row.settling_at } : {}),\n ...(row.expires_at !== null ? { expiresAt: row.expires_at } : {}),\n },\n ...(authorization !== undefined ? { authorization } : {}),\n ...(backend !== undefined ? { backend } : {}),\n ...(row.receipt_id !== null ? { receiptId: row.receipt_id } : {}),\n ...(row.input_digest !== null ? { inputDigest: row.input_digest } : {}),\n configDigest: row.config_digest,\n ...(row.persistence_failures_json !== null\n ? { persistenceFailures: JSON.parse(row.persistence_failures_json) as string[] }\n : {}),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n ...(completedAt !== undefined ? { completedAt } : {}),\n };\n}\n","/**\n * Receipt-store schema migrations. `PRAGMA user_version` records the applied\n * version, so a restart against an existing file keeps its data.\n */\nimport type Database from 'better-sqlite3';\n\ninterface Migration {\n readonly version: number;\n up(db: Database.Database): void;\n}\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS receipts (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n payment_json TEXT,\n delivered_at TEXT NOT NULL,\n backend_status INTEGER NOT NULL,\n duration_ms INTEGER,\n protocol TEXT,\n metadata_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_receipts_request_id ON receipts(request_id);\n CREATE INDEX IF NOT EXISTS idx_receipts_delivered_at ON receipts(delivered_at);\n\n CREATE TABLE IF NOT EXISTS events (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n type TEXT NOT NULL,\n request_id TEXT NOT NULL,\n resource_id TEXT,\n at TEXT NOT NULL,\n adapter TEXT,\n payment_provider TEXT,\n duration_ms INTEGER,\n status TEXT,\n data_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_events_request_id ON events(request_id);\n CREATE INDEX IF NOT EXISTS idx_events_at ON events(at);\n\n CREATE TABLE IF NOT EXISTS payment_attempts (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n provider TEXT NOT NULL,\n replay_key TEXT NOT NULL UNIQUE,\n status TEXT NOT NULL,\n amount TEXT NOT NULL,\n currency TEXT NOT NULL,\n payer TEXT,\n payee TEXT,\n external_reference TEXT,\n rejection_reason TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_payment_attempts_request_id ON payment_attempts(request_id);\n CREATE INDEX IF NOT EXISTS idx_payment_attempts_created_at ON payment_attempts(created_at);\n `);\n },\n },\n {\n version: 2,\n up(db) {\n // Not folded into v1: an existing database keeps its rows, and a receipt\n // written before this column has no authorization to record\n db.exec(`ALTER TABLE receipts ADD COLUMN authorization_json TEXT;`);\n },\n },\n {\n version: 3,\n up(db) {\n // Archive rejected attempts before reclaim overwrites them. replay_key\n // is not unique here: one authorization can be rejected and reclaimed\n // repeatedly.\n db.exec(`\n CREATE TABLE IF NOT EXISTS payment_attempt_history (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n provider TEXT NOT NULL,\n replay_key TEXT NOT NULL,\n status TEXT NOT NULL,\n amount TEXT NOT NULL,\n currency TEXT NOT NULL,\n payer TEXT,\n payee TEXT,\n external_reference TEXT,\n rejection_reason TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n superseded_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_replay_key ON payment_attempt_history(replay_key);\n CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_request_id ON payment_attempt_history(request_id);\n `);\n },\n },\n {\n version: 4,\n up(db) {\n // Join payment status from the attempt through attempt_id; cache only\n // the derived transaction state for filtering. New columns on existing\n // rows remain NULL, and no journal entries are backfilled.\n db.exec(`\n CREATE TABLE IF NOT EXISTS transactions (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n protocol TEXT NOT NULL,\n state TEXT NOT NULL,\n provider TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n replay_key TEXT NOT NULL,\n network TEXT,\n asset TEXT,\n authorization_json TEXT,\n reservation_id TEXT,\n locator_json TEXT,\n expires_at TEXT,\n input_digest TEXT,\n config_digest TEXT NOT NULL,\n settling_at TEXT,\n backend_dispatched_at TEXT,\n backend_deadline_at TEXT,\n backend_status INTEGER,\n backend_error_code TEXT,\n receipt_id TEXT,\n persistence_failures_json TEXT,\n completed_at TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_transactions_state_seq ON transactions(state, seq);\n CREATE INDEX IF NOT EXISTS idx_transactions_request_id ON transactions(request_id);\n CREATE INDEX IF NOT EXISTS idx_transactions_replay_key ON transactions(replay_key);\n\n ALTER TABLE receipts ADD COLUMN transaction_id TEXT;\n ALTER TABLE events ADD COLUMN transaction_id TEXT;\n ALTER TABLE payment_attempts ADD COLUMN transaction_id TEXT;\n ALTER TABLE payment_attempts ADD COLUMN resolution_json TEXT;\n ALTER TABLE payment_attempt_history ADD COLUMN transaction_id TEXT;\n ALTER TABLE payment_attempt_history ADD COLUMN resolution_json TEXT;\n CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_id ON payment_attempt_history(id);\n `);\n },\n },\n];\n\n/** Target schema version: the version of the last migration */\nexport const SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;\n\n/**\n * Apply pending migrations through `target`, defaulting to {@link SCHEMA_VERSION},\n * with one transaction per migration. At or above the target version, read\n * `PRAGMA user_version` without changing the database.\n */\nexport function migrate(db: Database.Database, target = SCHEMA_VERSION): void {\n const current = db.pragma('user_version', { simple: true }) as number;\n for (const migration of MIGRATIONS) {\n if (migration.version <= current || migration.version > target) continue;\n const apply = db.transaction(() => {\n migration.up(db);\n db.pragma(`user_version = ${migration.version}`);\n });\n apply();\n }\n}\n","/**\n * SQLite implementation of the frozen ReceiptStore interface: a thin layer\n * over statements prepared once at open, with no ORM\n */\nimport { randomUUID } from 'node:crypto';\nimport { accessSync, constants as fsConstants } from 'node:fs';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type Clock,\n CommerceError,\n type CommerceEvent,\n type CommerceReceipt,\n type IdGenerator,\n type IsoTimestamp,\n type ListOptions,\n type Logger,\n NOOP_LOGGER,\n type PaymentAttempt,\n type PaymentAttemptListOptions,\n type PaymentAttemptReservation,\n type PaymentAttemptResolveRequest,\n type PaymentAttemptUpdate,\n type ReceiptListOptions,\n type ReceiptStore,\n systemClock,\n type Transaction,\n type TransactionListOptions,\n type TransactionPage,\n type TransactionStep,\n toCommerceError,\n transactionState,\n} from '../../core';\nimport { PACKAGE_VERSION } from '../../version';\nimport { openSqliteDatabase } from '../sqlite';\nimport { redact } from './redact';\nimport {\n type EventRow,\n eventToRow,\n type PaymentAttemptRow,\n type ReceiptRow,\n receiptToRow,\n rowToEvent,\n rowToPaymentAttempt,\n rowToReceipt,\n rowToTransaction,\n type TransactionRow,\n} from './rows';\nimport { migrate, SCHEMA_VERSION } from './schema';\n\nconst DEFAULT_LIST_LIMIT = 50;\n/**\n * Ceiling on every list query, enforced in the store so every caller is\n * covered, not only the HTTP route. SQLite reads a negative `LIMIT` as no\n * limit, so `{ limit: -1 }` would otherwise return the whole table.\n */\nconst MAX_LIST_LIMIT = 500;\n\n// Clamps to a whole number in [1, MAX_LIST_LIMIT]. An absent or non-finite\n// limit (NaN, Infinity) takes the default, whether or not the caller filtered\n// it first.\nfunction clampListLimit(limit: number | undefined): number {\n const base = limit !== undefined && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;\n return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);\n}\n\n// Non-2xx statuses, including 0 (unknown), are undelivered, matching\n// deliveryResult() in ReceiptList.tsx. NOT NULL prevents NULL comparisons from\n// hiding rows.\nconst UNDELIVERED = 'backend_status NOT BETWEEN 200 AND 299';\n\n// Statuses needing reconciliation; see ReceiptStore.countUncertainPaymentAttempts\nconst UNCERTAIN = \"status IN ('settlement-uncertain', 'failed')\";\n\n// Join each transaction with its payment attempt. Reclaim replaces the live\n// attempt's ID and archives the old row, so earlier transactions read their\n// attempt from payment_attempt_history.\nconst TRANSACTION_SELECT = `\n SELECT t.*,\n COALESCE(a.status, h.status) AS payment_status,\n COALESCE(a.amount, h.amount) AS payment_amount,\n COALESCE(a.currency, h.currency) AS payment_currency,\n COALESCE(a.payee, h.payee) AS payment_payee,\n COALESCE(a.external_reference, h.external_reference) AS payment_external_reference\n FROM transactions t\n LEFT JOIN payment_attempts a ON a.id = t.attempt_id\n LEFT JOIN payment_attempt_history h ON a.id IS NULL AND h.seq = (\n SELECT MAX(seq) FROM payment_attempt_history\n WHERE replay_key = t.replay_key AND id = t.attempt_id\n )`;\n\n// Rows without completedAt can change state when backend.deadlineAt passes.\n// Include them as filter candidates; transactionState recomputes their state\n// on read without a database write.\nconst TIME_DEPENDENT = 't.backend_deadline_at IS NOT NULL AND t.completed_at IS NULL';\nconst RESOLVED_STATES = ['delivered', 'payment-failed'] as const;\n\nconst CURSOR_PATTERN = /^[1-9][0-9]{0,15}$/;\n\nexport interface SqliteReceiptStoreOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing */\n readonly path: string;\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n}\n\nconst defaultIds: IdGenerator = {\n next: (prefix) => (prefix !== undefined ? `${prefix}_${randomUUID()}` : randomUUID()),\n};\n\nfunction isUniqueConstraintOn(err: unknown, column: string): boolean {\n return (\n err instanceof Error &&\n 'code' in err &&\n (err as { code?: unknown }).code === 'SQLITE_CONSTRAINT_UNIQUE' &&\n err.message.includes(column)\n );\n}\n\nexport function createSqliteReceiptStore(options: SqliteReceiptStoreOptions): ReceiptStore {\n const logger = options.logger ?? NOOP_LOGGER;\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? defaultIds;\n const path = options.path;\n const isFileBacked = path !== ':memory:';\n\n // Shared with the ACP idempotency and AP2 replay stores, so the permission\n // hardening has one definition\n const db = openSqliteDatabase({ path, label: 'Receipt database', logger });\n migrate(db);\n\n const insertReceiptStmt = db.prepare(\n `INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json, authorization_json, transaction_id)\n VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json, @authorization_json, @transaction_id)`,\n );\n const getReceiptStmt = db.prepare<[string], ReceiptRow>('SELECT * FROM receipts WHERE id = ?');\n const listReceiptsStmt = db.prepare<[number], ReceiptRow>(\n 'SELECT * FROM receipts ORDER BY delivered_at DESC, seq DESC LIMIT ?',\n );\n const listReceiptsByRequestStmt = db.prepare<[string, number], ReceiptRow>(\n 'SELECT * FROM receipts WHERE request_id = ? ORDER BY delivered_at DESC, seq DESC LIMIT ?',\n );\n const listUndeliveredReceiptsStmt = db.prepare<[number], ReceiptRow>(\n `SELECT * FROM receipts WHERE ${UNDELIVERED} ORDER BY delivered_at DESC, seq DESC LIMIT ?`,\n );\n const listUndeliveredReceiptsByRequestStmt = db.prepare<[string, number], ReceiptRow>(\n `SELECT * FROM receipts WHERE request_id = ? AND ${UNDELIVERED} ORDER BY delivered_at DESC, seq DESC LIMIT ?`,\n );\n const countReceiptsStmt = db.prepare<[], { count: number }>(\n 'SELECT COUNT(*) AS count FROM receipts',\n );\n const countUndeliveredReceiptsStmt = db.prepare<[], { count: number }>(\n `SELECT COUNT(*) AS count FROM receipts WHERE ${UNDELIVERED}`,\n );\n\n const insertEventStmt = db.prepare(\n `INSERT INTO events (id, type, request_id, resource_id, at, adapter, payment_provider, duration_ms, status, data_json, transaction_id)\n VALUES (@id, @type, @request_id, @resource_id, @at, @adapter, @payment_provider, @duration_ms, @status, @data_json, @transaction_id)`,\n );\n const listEventsStmt = db.prepare<[number], EventRow>(\n 'SELECT * FROM events ORDER BY at DESC, seq DESC LIMIT ?',\n );\n const listEventsByRequestStmt = db.prepare<[string, number], EventRow>(\n 'SELECT * FROM events WHERE request_id = ? ORDER BY at DESC, seq DESC LIMIT ?',\n );\n\n const insertPaymentAttemptStmt = db.prepare<Record<string, unknown>, PaymentAttemptRow>(\n `INSERT INTO payment_attempts (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, transaction_id)\n VALUES (@id, @request_id, @resource_id, @provider, @replay_key, @status, @amount, @currency, @payer, @payee, @external_reference, @rejection_reason, @created_at, @updated_at, @transaction_id)\n RETURNING *`,\n );\n // Keeps the rejected row a reclaim is about to overwrite\n const archiveRejectedAttemptStmt = db.prepare(\n `INSERT INTO payment_attempt_history (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, superseded_at, transaction_id, resolution_json)\n SELECT id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, @created_at, transaction_id, resolution_json\n FROM payment_attempts\n WHERE replay_key = @replay_key AND provider = @provider AND status = 'rejected'`,\n );\n const reclaimPaymentAttemptStmt = db.prepare<Record<string, unknown>, PaymentAttemptRow>(\n `UPDATE payment_attempts SET id = @id, request_id = @request_id, resource_id = @resource_id,\n status = 'reserved', amount = @amount, currency = @currency,\n payer = @payer, payee = @payee, external_reference = NULL, rejection_reason = NULL,\n created_at = @created_at, updated_at = @updated_at,\n transaction_id = @transaction_id, resolution_json = NULL\n WHERE replay_key = @replay_key AND provider = @provider AND status = 'rejected'\n RETURNING *`,\n );\n // Omitted fields bind as NULL, so COALESCE preserves stored values. A\n // status-only update must retain external_reference: it may identify funds\n // that already moved. Clearing a field would need an explicit sentinel\n // rather than undefined. Rows with recorded resolutions reject later\n // pipeline updates.\n const updatePaymentAttemptStmt = db.prepare(\n `UPDATE payment_attempts SET status = @status,\n external_reference = COALESCE(@external_reference, external_reference),\n rejection_reason = COALESCE(@rejection_reason, rejection_reason),\n updated_at = @updated_at\n WHERE replay_key = @replay_key AND resolution_json IS NULL`,\n );\n const listPaymentAttemptsStmt = db.prepare<[number], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts ORDER BY created_at DESC, seq DESC LIMIT ?',\n );\n const listPaymentAttemptsByRequestStmt = db.prepare<[string, number], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts WHERE request_id = ? ORDER BY created_at DESC, seq DESC LIMIT ?',\n );\n const listUncertainPaymentAttemptsStmt = db.prepare<[number], PaymentAttemptRow>(\n `SELECT * FROM payment_attempts WHERE ${UNCERTAIN} ORDER BY created_at DESC, seq DESC LIMIT ?`,\n );\n const listUncertainPaymentAttemptsByRequestStmt = db.prepare<[string, number], PaymentAttemptRow>(\n `SELECT * FROM payment_attempts WHERE request_id = ? AND ${UNCERTAIN} ORDER BY created_at DESC, seq DESC LIMIT ?`,\n );\n const countUncertainPaymentAttemptsStmt = db.prepare<[], { count: number }>(\n `SELECT COUNT(*) AS count FROM payment_attempts WHERE ${UNCERTAIN}`,\n );\n const paymentAttemptStatusStmt = db.prepare<\n [string],\n Pick<PaymentAttemptRow, 'id' | 'status' | 'resolution_json'>\n >('SELECT id, status, resolution_json FROM payment_attempts WHERE replay_key = ?');\n const insertTransactionStmt = db.prepare(\n `INSERT INTO transactions (id, request_id, resource_id, protocol, state, provider, attempt_id, replay_key, network, asset, authorization_json, reservation_id, locator_json, expires_at, input_digest, config_digest, created_at, updated_at)\n VALUES (@id, @request_id, @resource_id, @protocol, @state, @provider, @attempt_id, @replay_key, @network, @asset, @authorization_json, @reservation_id, @locator_json, @expires_at, @input_digest, @config_digest, @created_at, @created_at)`,\n );\n const getTransactionStmt = db.prepare<[string], TransactionRow>(\n `${TRANSACTION_SELECT} WHERE t.id = ?`,\n );\n // After reclaim, purchases can share a replay key but refer to different\n // attempts. Match attempt_id to refresh only the current attempt's transactions;\n // the replay_key condition also permits an indexed lookup.\n const transactionsOfAttemptStmt = db.prepare<[string], { id: string }>(\n `SELECT t.id FROM payment_attempts a\n JOIN transactions t ON t.replay_key = a.replay_key AND t.attempt_id = a.id\n WHERE a.replay_key = ?`,\n );\n const transactionsOfAttemptIdStmt = db.prepare<[string], { id: string }>(\n `SELECT t.id FROM payment_attempts a\n JOIN transactions t ON t.replay_key = a.replay_key AND t.attempt_id = a.id\n WHERE a.id = ?`,\n );\n const setTransactionStateStmt = db.prepare('UPDATE transactions SET state = ? WHERE id = ?');\n const stepStmts = {\n settling: db.prepare(\n 'UPDATE transactions SET settling_at = @at, updated_at = @at WHERE id = @id',\n ),\n // A transaction without an authorization has no hold to record\n hold: db.prepare(\n `UPDATE transactions SET authorization_json = json_set(authorization_json, '$.hold', @hold), updated_at = @at\n WHERE id = @id AND authorization_json IS NOT NULL`,\n ),\n 'backend-dispatched': db.prepare(\n `UPDATE transactions SET backend_dispatched_at = @at, backend_deadline_at = @deadline_at, updated_at = @at\n WHERE id = @id`,\n ),\n // Preserve a backend result even when the dispatch step was not saved:\n // use the result time for missing dispatch and deadline timestamps\n 'backend-result': db.prepare(\n `UPDATE transactions SET backend_status = @status, backend_error_code = @error_code,\n backend_dispatched_at = COALESCE(backend_dispatched_at, @at),\n backend_deadline_at = COALESCE(backend_deadline_at, @at), updated_at = @at\n WHERE id = @id`,\n ),\n receipt: db.prepare(\n 'UPDATE transactions SET receipt_id = @receipt_id, updated_at = @at WHERE id = @id',\n ),\n completed: db.prepare(\n `UPDATE transactions SET completed_at = @at, persistence_failures_json = @persistence_failures_json, updated_at = @at\n WHERE id = @id`,\n ),\n } satisfies Record<TransactionStep['kind'], unknown>;\n const getPaymentAttemptStmt = db.prepare<[string], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts WHERE id = ?',\n );\n const getArchivedPaymentAttemptStmt = db.prepare<[string], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempt_history WHERE id = ? ORDER BY seq DESC LIMIT 1',\n );\n // Check status and missing resolution in the UPDATE so only one resolver\n // succeeds. Only reconciliation may replace the attempt's reference; manual\n // references belong in resolution_json.\n const resolvePaymentAttemptStmt = db.prepare(\n `UPDATE payment_attempts SET status = @status,\n rejection_reason = COALESCE(@rejection_reason, rejection_reason),\n external_reference = COALESCE(@external_reference, external_reference),\n resolution_json = @resolution_json, updated_at = @updated_at\n WHERE id = @id AND status = @expected_status AND resolution_json IS NULL`,\n );\n\n // Refresh the cached state inside the transaction that updated its inputs\n function refreshTransactionState(id: string, now: IsoTimestamp): void {\n const row = getTransactionStmt.get(id);\n if (row !== undefined) setTransactionStateStmt.run(rowToTransaction(row, now).state, id);\n }\n\n // IMMEDIATE locks before checking the replay key. Once a rejected attempt is\n // reserved again, a competing claim hits the unique replay-key constraint.\n // Journal creation shares the transaction, so a failure also rolls back the\n // attempt insert or reclaim.\n const reserve = db.transaction(\n (\n reservation: PaymentAttemptReservation,\n params: Record<string, unknown>,\n ): PaymentAttemptRow => {\n let row: PaymentAttemptRow | undefined;\n // Reclaim only if the rail permits reusing an authorization whose\n // attempt was rejected. NEAR client retries reuse the access key's\n // next nonce and therefore the replay key.\n if (reservation.reclaimRejected === true) {\n archiveRejectedAttemptStmt.run(params);\n row = reclaimPaymentAttemptStmt.get(params);\n }\n // RETURNING on a successful insert always yields the inserted row\n row ??= insertPaymentAttemptStmt.get({\n ...params,\n status: 'reserved' satisfies PaymentAttempt['status'],\n external_reference: null,\n rejection_reason: null,\n }) as PaymentAttemptRow;\n const txn = reservation.transaction;\n if (txn !== undefined) {\n const { reservationId, ...authorization } = txn.authorization ?? {};\n insertTransactionStmt.run({\n id: txn.id,\n request_id: reservation.requestId,\n resource_id: reservation.resourceId,\n protocol: txn.protocol,\n state: transactionState({ payment: { status: 'reserved' } }, row.created_at),\n provider: reservation.provider,\n attempt_id: row.id,\n replay_key: reservation.replayKey,\n network: txn.network ?? null,\n asset: txn.asset ?? null,\n authorization_json:\n reservationId !== undefined\n ? JSON.stringify(redact({ ...authorization, hold: 'reserved' }))\n : null,\n reservation_id: reservationId ?? null,\n locator_json: txn.locator !== undefined ? JSON.stringify(redact(txn.locator)) : null,\n expires_at: txn.expiresAt ?? null,\n input_digest: txn.inputDigest ?? null,\n config_digest: txn.configDigest,\n created_at: row.created_at,\n });\n }\n return row;\n },\n );\n const updateAttempt = db.transaction((update: PaymentAttemptUpdate, now: IsoTimestamp) => {\n const { changes } = updatePaymentAttemptStmt.run({\n replay_key: update.replayKey,\n status: update.status,\n external_reference: update.externalReference ?? null,\n rejection_reason: update.rejectionReason ?? null,\n updated_at: now,\n });\n for (const { id } of transactionsOfAttemptStmt.all(update.replayKey)) {\n refreshTransactionState(id, now);\n }\n return changes;\n });\n const recordStep = db.transaction((step: TransactionStep): number => {\n const base = { id: step.transactionId, at: step.at };\n let changes: number;\n switch (step.kind) {\n case 'settling':\n changes = stepStmts.settling.run(base).changes;\n break;\n case 'hold':\n changes = stepStmts.hold.run({ ...base, hold: step.hold }).changes;\n break;\n case 'backend-dispatched':\n changes = stepStmts['backend-dispatched'].run({\n ...base,\n deadline_at: step.deadlineAt,\n }).changes;\n break;\n case 'backend-result':\n changes = stepStmts['backend-result'].run({\n ...base,\n status: step.status,\n error_code: step.errorCode ?? null,\n }).changes;\n break;\n case 'receipt':\n changes = stepStmts.receipt.run({ ...base, receipt_id: step.receiptId }).changes;\n break;\n case 'completed':\n changes = stepStmts.completed.run({\n ...base,\n persistence_failures_json:\n step.persistenceFailures !== undefined && step.persistenceFailures.length > 0\n ? JSON.stringify(step.persistenceFailures)\n : null,\n }).changes;\n break;\n }\n if (changes > 0) refreshTransactionState(step.transactionId, step.at);\n return changes;\n });\n const resolveAttempt = db.transaction(\n (request: PaymentAttemptResolveRequest, now: IsoTimestamp): boolean => {\n const { changes } = resolvePaymentAttemptStmt.run({\n id: request.attemptId,\n expected_status: request.expectedStatus,\n status: request.status,\n rejection_reason: request.rejectionReason ?? null,\n // An operator's reference is unverified; it stays in resolution_json only\n external_reference:\n request.resolution.method === 'reconcile'\n ? (request.resolution.externalReference ?? null)\n : null,\n resolution_json: JSON.stringify(redact(request.resolution)),\n updated_at: now,\n });\n if (changes === 0) return false;\n for (const { id } of transactionsOfAttemptIdStmt.all(request.attemptId)) {\n refreshTransactionState(id, now);\n }\n return true;\n },\n );\n\n let closed = false;\n\n const descriptor: AdapterDescriptor = {\n name: 'sqlite-receipt-store',\n kind: 'storage',\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: `sqlite-schema-v${SCHEMA_VERSION}`,\n capabilities: ['receipts', 'events', 'payment-attempts', 'transactions'],\n status: 'stable',\n };\n\n const store: ReceiptStore = {\n async init(): Promise<void> {\n // Migration already ran synchronously at construction. This check keeps\n // init() a real, idempotent gate for callers that await it first.\n const version = db.pragma('user_version', { simple: true }) as number;\n if (version !== SCHEMA_VERSION) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION})`,\n );\n }\n },\n\n async appendEvent(event: CommerceEvent): Promise<void> {\n try {\n insertEventStmt.run(eventToRow(event));\n } catch (err) {\n logger.warn(\n {\n err: err instanceof Error ? err.message : String(err),\n eventId: event.id,\n requestId: event.requestId,\n },\n 'receipt-store: failed to persist commerce event',\n );\n }\n },\n\n async reservePaymentAttempt(reservation: PaymentAttemptReservation): Promise<PaymentAttempt> {\n const now = clock.nowIso();\n const params = {\n id: ids.next('attempt'),\n request_id: reservation.requestId,\n resource_id: reservation.resourceId,\n provider: reservation.provider,\n replay_key: reservation.replayKey,\n amount: reservation.amount,\n currency: reservation.currency,\n payer: reservation.payer ?? null,\n payee: reservation.payee ?? null,\n created_at: now,\n updated_at: now,\n transaction_id: reservation.transaction?.id ?? null,\n };\n let row: PaymentAttemptRow;\n try {\n row = reserve.immediate(reservation, params);\n } catch (err) {\n if (isUniqueConstraintOn(err, 'payment_attempts.replay_key')) {\n // Report the existing status so the pipeline can choose a replay response\n const existing = paymentAttemptStatusStmt.get(reservation.replayKey);\n throw new CommerceError(\n 'PAYMENT_REPLAYED',\n `Payment authorization has already been used (replayKey=${reservation.replayKey})`,\n {\n requestId: reservation.requestId,\n resourceId: reservation.resourceId,\n ...(existing !== undefined ? { details: { attemptStatus: existing.status } } : {}),\n },\n );\n }\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to reserve payment attempt');\n }\n return rowToPaymentAttempt(row);\n },\n\n async updatePaymentAttempt(update: PaymentAttemptUpdate): Promise<void> {\n try {\n if (updateAttempt(update, clock.nowIso()) === 0) {\n const existing = paymentAttemptStatusStmt.get(update.replayKey);\n if (existing?.resolution_json != null) {\n // Log the rejected update at warn level while preserving the resolution\n logger.warn(\n {\n attemptId: existing.id,\n resolvedStatus: existing.status,\n status: update.status,\n ...(update.externalReference !== undefined\n ? { externalReference: update.externalReference }\n : {}),\n },\n 'receipt-store: payment attempt already resolved; update not applied',\n );\n throw new CommerceError(\n 'STORAGE_ERROR',\n `Payment attempt ${existing.id} is already resolved; the update was not applied`,\n );\n }\n throw new CommerceError(\n 'STORAGE_ERROR',\n `No payment attempt found for replayKey=${update.replayKey}`,\n );\n }\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to update payment attempt');\n }\n },\n\n async saveReceipt(receipt: CommerceReceipt): Promise<void> {\n try {\n insertReceiptStmt.run(receiptToRow(receipt));\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to save receipt');\n }\n },\n\n async getReceipt(id: string): Promise<CommerceReceipt | undefined> {\n const row = getReceiptStmt.get(id);\n return row !== undefined ? rowToReceipt(row) : undefined;\n },\n\n async listReceipts(listOptions: ReceiptListOptions = {}): Promise<readonly CommerceReceipt[]> {\n const limit = clampListLimit(listOptions.limit);\n const undelivered = listOptions.undelivered === true;\n const rows =\n listOptions.requestId !== undefined\n ? (undelivered ? listUndeliveredReceiptsByRequestStmt : listReceiptsByRequestStmt).all(\n listOptions.requestId,\n limit,\n )\n : (undelivered ? listUndeliveredReceiptsStmt : listReceiptsStmt).all(limit);\n return rows.map(rowToReceipt);\n },\n\n // Exact total, not bounded by the listReceipts clamp (see ReceiptStore.countReceipts)\n async countReceipts(): Promise<number> {\n return countReceiptsStmt.get()?.count ?? 0;\n },\n\n // Exact count of non-2xx receipts (see ReceiptStore.countUndeliveredReceipts)\n async countUndeliveredReceipts(): Promise<number> {\n return countUndeliveredReceiptsStmt.get()?.count ?? 0;\n },\n\n async countUncertainPaymentAttempts(): Promise<number> {\n return countUncertainPaymentAttemptsStmt.get()?.count ?? 0;\n },\n\n async listEvents(listOptions: ListOptions = {}): Promise<readonly CommerceEvent[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listEventsByRequestStmt.all(listOptions.requestId, limit)\n : listEventsStmt.all(limit);\n return rows.map(rowToEvent);\n },\n\n async listPaymentAttempts(\n listOptions: PaymentAttemptListOptions = {},\n ): Promise<readonly PaymentAttempt[]> {\n const limit = clampListLimit(listOptions.limit);\n const uncertain = listOptions.uncertain === true;\n const rows =\n listOptions.requestId !== undefined\n ? (uncertain\n ? listUncertainPaymentAttemptsByRequestStmt\n : listPaymentAttemptsByRequestStmt\n ).all(listOptions.requestId, limit)\n : (uncertain ? listUncertainPaymentAttemptsStmt : listPaymentAttemptsStmt).all(limit);\n return rows.map(rowToPaymentAttempt);\n },\n\n async recordTransactionStep(step: TransactionStep): Promise<void> {\n try {\n if (recordStep(step) === 0) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n step.kind === 'hold'\n ? `No transaction with an authorization hold found for transactionId=${step.transactionId}`\n : `No transaction found for transactionId=${step.transactionId}`,\n );\n }\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to record transaction step');\n }\n },\n\n async getTransaction(id: string): Promise<Transaction | undefined> {\n const row = getTransactionStmt.get(id);\n return row !== undefined ? rowToTransaction(row, clock.nowIso()) : undefined;\n },\n\n async listTransactions(listOptions: TransactionListOptions = {}): Promise<TransactionPage> {\n const { cursor, state, unresolved, pendingHold, requestId } = listOptions;\n if (cursor !== undefined && !CURSOR_PATTERN.test(cursor)) {\n throw new CommerceError('INPUT_INVALID', 'Malformed transaction list cursor');\n }\n const limit = clampListLimit(listOptions.limit);\n const where: string[] = [];\n const params: unknown[] = [];\n if (cursor !== undefined) {\n where.push('t.seq < ?');\n params.push(Number(cursor));\n }\n if (requestId !== undefined) {\n where.push('t.request_id = ?');\n params.push(requestId);\n }\n if (state !== undefined) {\n where.push(`(t.state = ? OR (${TIME_DEPENDENT}))`);\n params.push(state);\n }\n if (pendingHold === true) {\n where.push(\"json_extract(t.authorization_json, '$.hold') IN ('reserved', 'uncertain')\");\n }\n if (unresolved === true) {\n where.push(`t.state NOT IN (${RESOLVED_STATES.map(() => '?').join(', ')})`);\n params.push(...RESOLVED_STATES);\n }\n const rows = db\n .prepare<unknown[], TransactionRow>(\n `${TRANSACTION_SELECT}${where.length > 0 ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY t.seq DESC LIMIT ?`,\n )\n .all(...params, limit);\n const now = clock.nowIso();\n const resolved: readonly string[] = RESOLVED_STATES;\n const transactions = rows\n .map((row) => rowToTransaction(row, now))\n .filter(\n (t) =>\n (state === undefined || t.state === state) &&\n (unresolved !== true || !resolved.includes(t.state)),\n );\n // Base the cursor on candidate rows, including any removed by the filter\n const last = rows.at(-1);\n return {\n transactions,\n ...(rows.length === limit && last !== undefined ? { nextCursor: String(last.seq) } : {}),\n };\n },\n\n async getPaymentAttempt(id: string): Promise<PaymentAttempt | undefined> {\n const row = getPaymentAttemptStmt.get(id) ?? getArchivedPaymentAttemptStmt.get(id);\n return row !== undefined ? rowToPaymentAttempt(row) : undefined;\n },\n\n async resolvePaymentAttempt(request: PaymentAttemptResolveRequest): Promise<boolean> {\n try {\n return resolveAttempt(request, clock.nowIso());\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to resolve payment attempt');\n }\n },\n\n descriptor,\n\n async health(): Promise<AdapterHealth> {\n // `detail` comes from a fixed vocabulary, never from a caught error: an\n // accessSync error carries an absolute host path, e.g. \"EACCES:\n // permission denied, access '/workspace/data/receipts.sqlite'\". The raw\n // message goes to the logger at warn.\n const startedAt = clock.monotonicMs();\n if (closed) {\n return { status: 'fail', detail: 'store-unavailable', checkedAt: clock.nowIso() };\n }\n if (isFileBacked) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch (err) {\n logger.warn(\n { err: err instanceof Error ? err.message : String(err) },\n 'receipt-store: health check failed (store not writable)',\n );\n return {\n status: 'fail',\n detail: 'store-unwritable',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n }\n try {\n const version = db.pragma('user_version', { simple: true }) as number;\n if (version !== SCHEMA_VERSION) {\n logger.warn(\n { found: version, expected: SCHEMA_VERSION },\n 'receipt-store: health check failed (schema version mismatch)',\n );\n return {\n status: 'fail',\n detail: 'store-schema-mismatch',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n return {\n status: 'pass',\n detail: `sqlite schema v${SCHEMA_VERSION} writable`,\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n } catch (err) {\n logger.warn(\n { err: err instanceof Error ? err.message : String(err) },\n 'receipt-store: health check failed (store unavailable)',\n );\n return {\n status: 'fail',\n detail: 'store-unavailable',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n },\n\n async close(): Promise<void> {\n if (!closed) {\n closed = true;\n db.close();\n }\n },\n };\n\n return store;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/protocols/http.ts","../../src/payments/x402/transport.ts"],"names":[],"mappings":";;;AAIA,IAAM,aAAA,GAAgB,YAAA;AAQf,SAAS,kBAAkB,aAAA,EAAgE;AAChG,EAAA,MAAM,QAAA,GAAW,OAAO,aAAa,CAAA;AACrC,EAAA,OAAO,CAAC,MAAA,KAAW;AACjB,IAAA,IAAI,WAAW,MAAA,IAAa,CAAC,cAAc,IAAA,CAAK,MAAM,GAAG,OAAO,KAAA;AAChE,IAAA,MAAM,SAAA,GAAY,MAAA,CAAO,OAAA,CAAQ,aAAA,EAAe,EAAE,CAAA;AAClD,IAAA,OAAO,UAAU,MAAA,GAAS,CAAA,IAAK,gBAAgB,MAAA,CAAO,SAAS,GAAG,QAAQ,CAAA;AAAA,EAC5E,CAAA;AACF;AAEA,SAAS,OAAO,KAAA,EAAuB;AACrC,EAAA,OAAO,WAAW,QAAQ,CAAA,CAAE,OAAO,KAAA,EAAO,MAAM,EAAE,MAAA,EAAO;AAC3D;AAYA,eAAsB,cAAA,CAAe,KAAsB,QAAA,EAAqC;AAC9F,EAAA,MAAM,SAAmB,EAAC;AAC1B,EAAA,IAAI,KAAA,GAAQ,CAAA;AACZ,EAAA,IAAI;AACF,IAAA,WAAA,MAAiB,SAAS,GAAA,EAAK;AAC7B,MAAA,MAA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AA,GAAc,IAAA,CAAK,QAAQ,CAAA,IAAK,yBAAA;AACpC,EAAA,IAAI,OAAA,GAAU,qBAAqB,CAAA,KAAM,IAAA,EAAM;AAC7C,IAAA,WAAA,GAAc,WAAA,KAAgB,SAAY,oBAAA,GAAuB,yBAAA;AAAA,EACnE;AACA,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT,WAAA;AAAA,IACA,aAAa,WAAA,IAAe,EAAA;AAAA,IAC5B,OAAA,EAAS,IAAA,CAAK,SAAS,CAAA,IAAK,EAAA;AAAA,IAC5B,GAAI,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,KAAU;AAAC,GACzC;AACF","file":"chunk-SPAYKVUP.js","sourcesContent":["// HTTP helpers shared by the A2A and ACP adapters and the gateway's admin-token gate\nimport { createHash, timingSafeEqual } from 'node:crypto';\nimport type { IncomingMessage } from 'node:http';\n\nconst BEARER_PREFIX = /^Bearer +/i;\n\n/**\n * Builds a check of an `Authorization: Bearer <token>` header against a fixed\n * token. The scheme is case-insensitive (RFC 9110). Both sides are compared as\n * SHA-256 digests, because `timingSafeEqual` throws on a length mismatch and\n * would reveal the token's length; the expected digest is computed once here.\n */\nexport function createBearerCheck(expectedToken: string): (header: string | undefined) => boolean {\n const expected = sha256(expectedToken);\n return (header) => {\n if (header === undefined || !BEARER_PREFIX.test(header)) return false;\n const presented = header.replace(BEARER_PREFIX, '');\n return presented.length > 0 && timingSafeEqual(sha256(presented), expected);\n };\n}\n\nfunction sha256(value: string): Buffer {\n return createHash('sha256').update(value, 'utf8').digest();\n}\n\n/** A tagged result, so no body text can be mistaken for a failure */\nexport type BodyRead =\n | { readonly kind: 'ok'; readonly text: string }\n | { readonly kind: 'too-large' }\n | { readonly kind: 'unreadable' };\n\n/**\n * Reads the unconsumed request stream the gateway hands an adapter, stopping\n * at the cap rather than buffering whatever arrives\n */\nexport async function readCappedBody(req: IncomingMessage, maxBytes: number): Promise<BodyRead> {\n const chunks: Buffer[] = [];\n let total = 0;\n try {\n for await (const chunk of req) {\n const buffer = chunk as Buffer;\n total += buffer.length;\n if (total > maxBytes) return { kind: 'too-large' };\n chunks.push(buffer);\n }\n } catch {\n return { kind: 'unreadable' };\n }\n return { kind: 'ok', text: Buffer.concat(chunks).toString('utf8') };\n}\n\n/**\n * Joins a base URL and a mount path with exactly one slash between them and\n * none at the end. Plain concatenation can yield `https://host//a2a`, which a\n * router may treat as a different path.\n */\nexport function joinUrl(baseUrl: string, mountPath: string): string {\n return `${baseUrl.replace(/\\/+$/, '')}/${mountPath.replace(/^\\/+|\\/+$/g, '')}`;\n}\n","/**\n * Build x402 v2 responses for the HTTP route and MCP adapter. This module\n * has no optional peer imports, so both entries can use it.\n */\n\nimport type { PaymentResult } from '../../core';\nimport { isRecord } from '../../core/is-record';\n\n/** MCP `_meta` key of a tool call's `PaymentPayload` (x402 MCP transport) */\nexport const X402_MCP_PAYMENT_META_KEY = 'x402/payment';\n\n/** Challenge key read by the `cloudflare/agents` x402 MCP client */\nexport const X402_MCP_ERROR_META_KEY = 'x402/error';\n\n/**\n * Accept an object or base64 string from `x402/payment` and return the string\n * the provider decodes. An absent value returns undefined; other JSON\n * values are encoded for provider validation.\n */\nexport function x402McpPaymentSubmission(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === 'string') return value;\n return Buffer.from(JSON.stringify(value), 'utf8').toString('base64');\n}\n\n/** MCP `_meta` key of a tool result's settlement response (x402 MCP transport) */\nexport const X402_MCP_PAYMENT_RESPONSE_META_KEY = 'x402/payment-response';\n\n// The code an SDK facilitator gives a spent authorization, by CAIP-2 namespace.\n// The Solana scheme has none; its specification refuses a payload being\n// settled again as `duplicate_settlement`.\nconst REPLAY_CODES: Readonly<Record<string, string>> = {\n near: 'invalid_exact_near_payload_delegate_action_nonce_already_used',\n solana: 'duplicate_settlement',\n};\n\n/**\n * Returns the provider's refusal reason, or the paid network family's replay\n * code. Unknown networks use EVM's replay code.\n */\nexport function x402ErrorCode(code: string, reason: unknown, network?: unknown): string {\n if (code === 'PAYMENT_REPLAYED') {\n const namespace = typeof network === 'string' ? network.split(':')[0] : undefined;\n return (\n (namespace !== undefined ? REPLAY_CODES[namespace] : undefined) ??\n 'invalid_exact_evm_nonce_already_used'\n );\n }\n return typeof reason === 'string' ? reason : 'unexpected_verify_error';\n}\n\n/**\n * Returns 412 Precondition Failed for a missing Permit2 allowance: the buyer\n * must approve Permit2 before retrying. Other refusals keep their status.\n */\nexport function x402RefusalStatus(code: string, httpStatus: number, reason: unknown): number {\n return code === 'PAYMENT_INVALID' && reason === 'permit2_allowance_required' ? 412 : httpStatus;\n}\n\ninterface SettledPayment {\n readonly status: string;\n readonly provider: string;\n readonly currency: string;\n readonly network?: string | undefined;\n readonly externalReference?: string | undefined;\n readonly payer?: string | undefined;\n readonly amountBaseUnits?: string | undefined;\n}\n\n// The `SettleResponse` shape. When present, `amount` uses base units.\n// `status`, `provider`, `currency`, and `externalReference` are gateway\n// extensions; an x402 v2 client ignores fields it does not know.\nfunction settlementDocument(payment: SettledPayment): Record<string, unknown> {\n return {\n success: payment.status === 'settled',\n transaction: payment.externalReference ?? '',\n network: payment.network ?? '',\n ...(payment.payer !== undefined ? { payer: payment.payer } : {}),\n ...(payment.amountBaseUnits !== undefined ? { amount: payment.amountBaseUnits } : {}),\n status: payment.status,\n provider: payment.provider,\n currency: payment.currency,\n ...(payment.externalReference !== undefined\n ? { externalReference: payment.externalReference }\n : {}),\n };\n}\n\n/** A delivered payment's settlement response */\nexport function settlementResponse(payment: PaymentResult): Record<string, unknown> {\n const amountBaseUnits = payment.metadata?.['amountBaseUnits'];\n return settlementDocument({\n ...payment,\n ...(typeof amountBaseUnits === 'string' ? { amountBaseUnits } : {}),\n });\n}\n\n/**\n * The settlement response for a backend failure after settlement, from the\n * error's `details.payment`; undefined when the error carries none\n */\nexport function settlementResponseFromDetails(\n details: Readonly<Record<string, unknown>> | undefined,\n): Record<string, unknown> | undefined {\n const payment = details?.['payment'];\n if (!isRecord(payment)) return undefined;\n const text = (key: string): string | undefined =>\n typeof payment[key] === 'string' ? payment[key] : undefined;\n const status = text('status');\n const provider = text('provider');\n const currency = text('currency');\n if (status === undefined || provider === undefined || currency === undefined) return undefined;\n return settlementDocument({\n status,\n provider,\n currency,\n network: text('network'),\n externalReference: text('externalReference'),\n payer: text('payer'),\n amountBaseUnits: text('amountBaseUnits'),\n });\n}\n\n/**\n * A refused or unconfirmed settlement as a failed `SettleResponse`. An\n * unconfirmed transfer with a hash uses x402's `settlement_pending` reason.\n */\nexport function settlementFailure(\n details: Readonly<Record<string, unknown>> | undefined,\n): Record<string, unknown> {\n const text = (key: string): string | undefined => {\n const value = details?.[key];\n return typeof value === 'string' ? value : undefined;\n };\n const transaction = text('transactionHash');\n const payer = text('payer');\n let errorReason = text('reason') ?? 'unexpected_settle_error';\n if (details?.['settlementUncertain'] === true) {\n errorReason = transaction !== undefined ? 'settlement_pending' : 'unexpected_settle_error';\n }\n return {\n success: false,\n errorReason,\n transaction: transaction ?? '',\n network: text('network') ?? '',\n ...(payer !== undefined ? { payer } : {}),\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/errors/codes.ts","../../src/core/errors/commerce-error.ts"],"names":[],"mappings":";AAgCO,IAAM,0BAAA,GAA0E;AAAA,EACrF,cAAA,EAAgB,GAAA;AAAA,EAChB,kBAAA,EAAoB,GAAA;AAAA,EACpB,aAAA,EAAe,GAAA;AAAA,EACf,gBAAA,EAAkB,GAAA;AAAA,EAClB,eAAA,EAAiB,GAAA;AAAA,EACjB,gBAAA,EAAkB,GAAA;AAAA,EAClB,4BAAA,EAA8B,GAAA;AAAA,EAC9B,yBAAA,EAA2B,GAAA;AAAA;AAAA;AAAA;AAAA,EAI3B,sBAAA,EAAwB,GAAA;AAAA,EACxB,qBAAA,EAAuB,GAAA;AAAA,EACvB,sBAAA,EAAwB,GAAA;AAAA,EACxB,kCAAA,EAAoC,GAAA;AAAA,EAC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AM,IAAI,CAAA,EAAA,EAAK,KAAA,CAAM,OAAO,CAAA,CAAA,GAAK,MAAA,CAAO,KAAK,CAAA;AACtF,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,qCAAA,EAAuC,CAAC,KAAA,KAAU;AACpE,IAAA,IAAI;AACF,MAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,KAAK,CAAA;AACzB,MAAA,OAAO,CAAA,EAAG,GAAA,CAAI,QAAQ,CAAA,EAAA,EAAK,IAAI,IAAI,CAAA,CAAA;AAAA,IACrC,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,mBAAA;AAAA,IACT;AAAA,EACF,CAAC,CAAA;AACH;AAGA,IAAM,iBAAA,GAAoB,CAAA;AAMnB,SAAS,UACd,KAAA,EAC4D;AAC5D,EAAA,MAAM,KAAA,GAAQ,gBAAgB,KAAK,CAAA;AACnC,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,IAAI,UAAU,KAAA,CAAM,KAAA;AACpB,EAAA,OAAO,OAAA,KAAY,MAAA,IAAa,KAAA,CAAM,MAAA,GAAS,iBAAA,EAAmB;AAChE,IAAA,KAAA,CAAM,IAAA,CAAK,iBAAA,CAAkB,OAAO,CAAC,CAAA;AACrC,IAAA,OAAA,GAAU,OAAA,YAAmB,KAAA,GAAQ,OAAA,CAAQ,KAAA,GAAQ,MAAA;AAAA,EACvD;AACA,EAAA,OAAO,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,EAAE,GAAG,KAAA,CAAM,MAAA,EAAO,EAAG,KAAA,EAAM,GAAI,KAAA,CAAM,MAAA,EAAO;AACxE","file":"chunk-SYQLJXIU.js","sourcesContent":["/**\n * Typed domain error codes. FROZEN CONTRACT. Protocol adapters map them into\n * their own response format. Never throw a bare string or untyped Error across\n * an area boundary.\n */\nexport const COMMERCE_ERROR_CODES = [\n 'CONFIG_INVALID',\n 'RESOURCE_NOT_FOUND',\n 'INPUT_INVALID',\n 'PAYMENT_REQUIRED',\n 'PAYMENT_INVALID',\n 'PAYMENT_REPLAYED',\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'PAYMENT_SETTLEMENT_FAILED',\n 'AUTHORIZATION_REQUIRED',\n 'AUTHORIZATION_INVALID',\n 'AUTHORIZATION_REPLAYED',\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n 'BACKEND_ERROR',\n 'PROTOCOL_UNSUPPORTED',\n 'GATEWAY_BUSY',\n 'STORAGE_ERROR',\n 'INTERNAL_ERROR',\n] as const;\n\nexport type CommerceErrorCode = (typeof COMMERCE_ERROR_CODES)[number];\n\n/**\n * Canonical HTTP status for each error code. Every payment failure maps to a\n * 4xx or 5xx status, never to a delivery.\n */\nexport const COMMERCE_ERROR_HTTP_STATUS: Readonly<Record<CommerceErrorCode, number>> = {\n CONFIG_INVALID: 500,\n RESOURCE_NOT_FOUND: 404,\n INPUT_INVALID: 400,\n PAYMENT_REQUIRED: 402,\n PAYMENT_INVALID: 402,\n PAYMENT_REPLAYED: 409,\n PAYMENT_PROVIDER_UNAVAILABLE: 503,\n PAYMENT_SETTLEMENT_FAILED: 502,\n // 403, not 402: a 402 tells a client to pay and retry, which cannot fix a\n // missing or rejected mandate, and a client that auto-pays on 402 would be\n // charged for a request that was never going to be delivered\n AUTHORIZATION_REQUIRED: 403,\n AUTHORIZATION_INVALID: 403,\n AUTHORIZATION_REPLAYED: 409,\n AUTHORIZATION_PROVIDER_UNAVAILABLE: 503,\n BACKEND_TIMEOUT: 504,\n BACKEND_ERROR: 502,\n PROTOCOL_UNSUPPORTED: 501,\n GATEWAY_BUSY: 503,\n STORAGE_ERROR: 500,\n INTERNAL_ERROR: 500,\n};\n\n/** Codes for which a client may reasonably retry the same request */\nexport const RETRYABLE_ERROR_CODES: ReadonlySet<CommerceErrorCode> = new Set([\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n // The verifier or replay store was unreachable, so the mandate got no\n // verdict. The same proof can verify once the outage clears.\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n // Load shedding is transient: the caller should back off and try again.\n // Clients act on this flag, and leaving it out would make a momentary\n // throttle look like a permanent failure.\n 'GATEWAY_BUSY',\n]);\n","// The single error type crossing area boundaries. FROZEN CONTRACT\nimport { COMMERCE_ERROR_HTTP_STATUS, type CommerceErrorCode, RETRYABLE_ERROR_CODES } from './codes';\n\nexport interface CommerceErrorOptions {\n /** Structured, non-secret detail safe to return to a client */\n readonly details?: Readonly<Record<string, unknown>>;\n readonly cause?: unknown;\n readonly requestId?: string;\n readonly resourceId?: string;\n /** Override the default HTTP status for this code */\n readonly httpStatus?: number;\n}\n\n/** Serializable wire form of a CommerceError */\nexport interface CommerceErrorInfo {\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport class CommerceError extends Error {\n readonly code: CommerceErrorCode;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n readonly requestId?: string;\n readonly resourceId?: string;\n\n constructor(code: CommerceErrorCode, message: string, options: CommerceErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = 'CommerceError';\n this.code = code;\n this.httpStatus = options.httpStatus ?? COMMERCE_ERROR_HTTP_STATUS[code];\n this.retryable = RETRYABLE_ERROR_CODES.has(code);\n if (options.details !== undefined) this.details = options.details;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.resourceId !== undefined) this.resourceId = options.resourceId;\n Error.captureStackTrace?.(this, CommerceError);\n }\n\n /** Non-secret, client-safe representation. `cause` is never included */\n toInfo(): CommerceErrorInfo {\n return {\n code: this.code,\n message: this.message,\n httpStatus: this.httpStatus,\n retryable: this.retryable,\n ...(this.requestId !== undefined ? { requestId: this.requestId } : {}),\n ...(this.resourceId !== undefined ? { resourceId: this.resourceId } : {}),\n ...(this.details !== undefined ? { details: this.details } : {}),\n };\n }\n}\n\nexport function isCommerceError(value: unknown): value is CommerceError {\n return value instanceof CommerceError;\n}\n\n/**\n * Passes an existing CommerceError through. Other thrown values become a\n * CommerceError with a caller-chosen message, for example\n * `toCommerceError(err, 'BACKEND_ERROR', 'Backend call failed')`.\n *\n * Arbitrary Error messages may contain internal URLs, hostnames or file paths.\n * The original value remains on `cause` for internal logging; `toInfo()` and\n * `toErrorEnvelope()` do not serialize it.\n */\nexport function toCommerceError(\n value: unknown,\n fallbackCode: CommerceErrorCode = 'INTERNAL_ERROR',\n fallbackMessage = 'Unexpected internal error',\n): CommerceError {\n if (isCommerceError(value)) return value;\n return new CommerceError(fallbackCode, fallbackMessage, { cause: value });\n}\n\n/** A thrown value reduced to its message and name, for a log line */\nexport function describeError(error: unknown): { message: string; name?: string } {\n if (error instanceof Error) return { message: error.message, name: error.name };\n return { message: String(error) };\n}\n\n/**\n * `Name: message` for a log line, with every URL cut to its scheme and host,\n * because a backend or RPC URL can carry a credential in its userinfo, path or\n * query\n */\nexport function redactedErrorText(value: unknown): string {\n const text = value instanceof Error ? `${value.name}: ${value.message}` : String(value);\n return text.replace(/\\b[a-z][a-z\\d+.-]*:\\/\\/[^\\s\"'<>]+/gi, (match) => {\n try {\n const url = new URL(match);\n return `${url.protocol}//${url.host}`;\n } catch {\n return '[unparseable URL]';\n }\n });\n}\n\n// Deepest `cause` level toLogInfo() follows, which also ends a cyclic chain\nconst MAX_LOGGED_CAUSES = 5;\n\n/**\n * An error for an operator log line: the `toInfo()` fields plus the `cause`\n * chain that `toInfo()` leaves out, each level as `redactedErrorText()` gives it\n */\nexport function toLogInfo(\n value: unknown,\n): CommerceErrorInfo & { readonly cause?: readonly string[] } {\n const error = toCommerceError(value);\n const cause: string[] = [];\n let current = error.cause;\n while (current !== undefined && cause.length < MAX_LOGGED_CAUSES) {\n cause.push(redactedErrorText(current));\n current = current instanceof Error ? current.cause : undefined;\n }\n return cause.length > 0 ? { ...error.toInfo(), cause } : error.toInfo();\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/filename.ts","../../src/core/execution/backend-request.ts","../../src/core/execution/backend-http.ts","../../src/core/execution/journal.ts","../../src/core/execution/validation.ts","../../src/core/execution/pipeline/authorization.ts","../../src/core/execution/pipeline/challenge.ts","../../src/core/execution/pipeline/admission.ts","../../src/core/execution/pipeline/context.ts","../../src/core/execution/pipeline/settlement.ts","../../src/core/execution/pipeline/index.ts","../../src/core/execution/registry.ts","../../src/core/execution/store-event-sink.ts","../../src/protocols/acp/constants.ts"],"names":["url","durationMs"],"mappings":";;;;;;;;AASO,IAAM,uBAAA,GAA0B;;;ACCvC,IAAM,sBAAA,GACJ,0JAAA;AAMF,IAAM,kBAAA,GAAqB,wBAAA;AAOpB,SAAS,0BAA0B,GAAA,EAAuB;AAC/D,EAAA,OAAO,CAAC,GAAG,GAAA,CAAI,QAAA,CAAS,kBAAkB,CAAC,CAAA,CAAE,GAAA,CAAI,CAAC,KAAA,KAAU,KAAA,CAAM,CAAC,CAAW,CAAA;AAChF;AAUO,SAAS,uBAAuB,GAAA,EAAiC;AACtE,EAAA,MAAM,OAAA,GAAU,GAAA,CAAI,OAAA,CAAQ,kBAAA,EAAoB,EAAE,CAAA;AAClD,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,MAAA,CAAO,MAAM,CAAA;AACnC,EAAA,IAAI,KAAA,KAAU,IAAI,OAAO,MAAA;AAEzB,EAAA,MAAM,QAAQ,gBAAA,CAAiB,IAAA,CAAK,OAAA,CAAQ,KAAA,CAAM,KAAK,CAAC,CAAA;AACxD,EAAA,OAAO,KAAA,GAAQ,CAAC,CAAA,IAAK,OAAA,CAAQ,KAAK,CAAA;AACpC;AAQO,SAAS,2BAAA,CACd,OAAA,EACA,KAAA,EACA,OAAA,EACA,cAAA,EACM;AACN,EAAA,MAAM,WAAA,GAAc,QAAA,CAAS,KAAK,CAAA,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,IAAM,gBAAA,GAAmB;AACzB,IAAM,eAAA,GAAkB;AAGxB,IAAM,mBAAA,GAAsB;AAO5B,IAAM,uBAAA,GAA0B;AAAA,EACrC,uBAAA;AAAA,EACA,uBAAA;AAAA,EACA,oBAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF;AASO,IAAM,wBAAA,GAET;AAAA,EACF,qBAAA,EAAuB,CAAC,MAAM,CAAA;AAAA,EAC9B,qBAAA,EAAuB,CAAC,MAAA,EAAQ,MAAM,CAAA;AAAA,EACtC,kBAAA,EAAoB,CAAC,MAAM,CAAA;AAAA,EAC3B,uBAAA,EAAyB,CAAC,MAAA,EAAQ,MAAM,CAAA;AAAA,EACxC,qBAAA,EAAuB,CAAC,MAAM;AAChC;AAOO,IAAM,iCAAA,GAET;AAAA,EACF,qBAAA,EAAuB,CAAC,MAAM;AAChC;AAGO,IAAM,wBAAA,GAA2B;AAGjC,IAAM,mBAAA,GAAsB;AAS5B,IAAM,sBAAA,GAAyB;AAC/B,IAAM,qBAAA,GAAwB;AAC9B,IAAM,0BAAA,GAA6B;AACnC,IAAM,8BAAA,GAAiC;AAMvC,IAAM,iCAAA,GAAoC;AAM1C,IAAM,yBAAA,GAA4B;AAGlC,IAAM,qBAAA,GAAwB;AAAA,EACnC,iBAAA;AAAA,EACA,YAAA;AAAA,EACA,qBAAA;AAAA,EACA,sBAAA;AAAA,EACA,WAAA;AAAA,EACA;AACF;AAGO,IAAM,+BAAA,GAAkC;AAGxC,IAAM,wCAAA,GAA2C;AACjD,IAAM,oCAAA,GAAuC","file":"chunk-Z34UMZBB.js","sourcesContent":["/**\n * The default configuration filename, shared by the loader, `init`'s default\n * output path and the `--config` help text.\n *\n * Its own module with no imports: `src/cli` loads the rest of `src/config`\n * only through a dynamic import (`src/cli/lib/config-client.ts`), so a broken\n * config module cannot take down commands that never read configuration. A\n * leaf with no module graph can be imported statically without undoing that.\n */\nexport const DEFAULT_CONFIG_FILENAME = 'config.yaml';\n","/**\n * Shapes a backend request from validated input: the path template, query,\n * body and forwarded headers. The pipeline checks the shape before pricing, so\n * a request the backend cannot receive fails before any payment.\n */\nimport type { BackendHandler, BackendMethod } from '../domain/resource';\nimport { CommerceError } from '../errors';\nimport { isRecord } from '../is-record';\n\n// Never forward credentials, transport headers or fields set by the executor\nconst NEVER_FORWARDED_HEADER =\n /^(authorization|cookie|set-cookie|host|content-length|content-type|connection|keep-alive|te|trailer|transfer-encoding|upgrade|idempotency-key|proxy-.*)$/;\n\n// The one `{param}` grammar, shared by substitution, config, `doctor` and the\n// OpenAPI importer. It admits `-` and `.` because\n// `/report/{report-id}` is ordinary REST. Config refuses any other brace\n// (findUnparsedBraceToken).\nconst PATH_PARAM_PATTERN = /\\{([a-zA-Z0-9_.-]+)\\}/g;\n\n/**\n * `{param}` names in a `backend.url` template, in declaration order. Config,\n * `doctor` and the OpenAPI importer use it so they read the same grammar as\n * substitution.\n */\nexport function extractPathParameterNames(url: string): string[] {\n return [...url.matchAll(PATH_PARAM_PATTERN)].map((match) => match[1] as string);\n}\n\n/**\n * A brace left over after every legal `{param}` is removed, or `undefined`.\n *\n * `{report id}`, `{a/b}`, `{}` and an unbalanced `{` match no parameter and\n * would reach the backend as literals, which on a paid resource means payment\n * without delivery. Config refuses any such residue, and the OpenAPI importer\n * skips the operation.\n */\nexport function findUnparsedBraceToken(url: string): string | undefined {\n const residue = url.replace(PATH_PARAM_PATTERN, '');\n const index = residue.search(/[{}]/);\n if (index === -1) return undefined;\n // Report the offending run, not just the character, so the error is fixable\n const token = /\\{[^{}]*\\}?|\\}/.exec(residue.slice(index));\n return token?.[0] ?? residue[index];\n}\n\n/**\n * Check path values, query collisions and headers before pricing. `call()`\n * repeats these checks. Invalid input or forwarded headers raise\n * `INPUT_INVALID`; invalid configured headers raise `BACKEND_ERROR`.\n * An unparseable URL remains a call-time error. Does no I/O.\n */\nexport function validateBackendRequestShape(\n handler: BackendHandler,\n input: unknown,\n context: ShapeContext,\n backendHeaders?: Readonly<Record<string, string>>,\n): void {\n const inputRecord = isRecord(input) ? input : {};\n\n // Every shape error (missing or invalid path parameter, a bound group that is\n // not an object) throws INPUT_INVALID here\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n // Config refuses a bad header at load; this covers a hand-built resource\n buildHeaders(handler, context, backendHeaders);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch {\n return; // call() raises BACKEND_ERROR for an unparseable URL\n }\n checkQueryCollision(target, parts.query, context);\n}\n\ntype ShapeContext = { readonly requestId: string; readonly resourceId: string };\n\n// The path-templated URL plus the query and body values a request carries\ninterface BackendRequestParts {\n readonly url: string;\n readonly query: Record<string, unknown>;\n // Present when a JSON body should be sent; `value` is what gets encoded\n readonly body?: { readonly value: unknown };\n}\n\nfunction acceptsBody(method: BackendMethod): boolean {\n return method !== 'GET' && method !== 'DELETE';\n}\n\n/**\n * Split validated input into URL, query and body according to\n * `handler.inputBindings`. `call()` and `validateBackendRequestShape()` both\n * use it, so they cannot disagree about the request an input describes. Throws\n * only `CommerceError('INPUT_INVALID')`.\n */\nexport function buildBackendRequestParts(\n handler: BackendHandler,\n input: Record<string, unknown>,\n context: ShapeContext,\n): BackendRequestParts {\n const bindings = handler.inputBindings;\n if (bindings === undefined) {\n const { url, remaining } = applyPathTemplate(handler.url, input, context);\n return acceptsBody(handler.method)\n ? { url, query: {}, body: { value: remaining } }\n : { url, query: remaining };\n }\n\n const pathValues =\n bindings.path === undefined ? {} : resolveBoundGroup(input, bindings.path, 'path', context);\n const { url } = applyPathTemplate(handler.url, pathValues, context);\n const query =\n bindings.query === undefined ? {} : resolveBoundGroup(input, bindings.query, 'query', context);\n\n // An absent body value sends no body rather than `null`. A required body is\n // enforced earlier, by `required` in the resource's input schema.\n const bodyValue = bindings.body === undefined ? undefined : input[bindings.body];\n if (bodyValue === undefined || !acceptsBody(handler.method)) return { url, query };\n return { url, query, body: { value: bodyValue } };\n}\n\nfunction resolveBoundGroup(\n input: Record<string, unknown>,\n key: string,\n kind: 'path' | 'query',\n context: ShapeContext,\n): Record<string, unknown> {\n const value = input[key];\n if (value === undefined) return {};\n if (!isRecord(value)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input \"${key}\" must be an object of ${kind} parameters`,\n { ...context, details: { field: key } },\n );\n }\n return value;\n}\n\nexport function checkQueryCollision(\n target: URL,\n remaining: Record<string, unknown>,\n context: { readonly requestId: string; readonly resourceId: string },\n): void {\n const templateKeys = new Set(target.searchParams.keys());\n for (const key of Object.keys(remaining)) {\n if (templateKeys.has(key)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input key \"${key}\" collides with a query parameter already set on backend.url`,\n { requestId: context.requestId, resourceId: context.resourceId, details: { field: key } },\n );\n }\n }\n}\n\n// encodeURIComponent leaves \".\" alone, and new URL() then resolves a \".\" or\n// \"..\" segment, stepping outside the template's directory. Slashes are\n// escaped, so only these exact values (and \"\", an empty segment) need refusing.\nconst TRAVERSAL_PATH_VALUES = new Set(['', '.', '..']);\n\nfunction applyPathTemplate(\n template: string,\n input: Record<string, unknown>,\n context: ShapeContext,\n): { url: string; remaining: Record<string, unknown> } {\n const remaining: Record<string, unknown> = { ...input };\n let missing: string | undefined;\n let invalid: string | undefined;\n const url = template.replace(PATH_PARAM_PATTERN, (_match, key: string) => {\n // Object.hasOwn, not `in`: a parameter named \"constructor\" or \"toString\"\n // would otherwise resolve to the inherited Object.prototype member\n if (!Object.hasOwn(remaining, key)) {\n missing = key;\n return '';\n }\n const value = remaining[key];\n delete remaining[key];\n const raw = stringifyPrimitive(value);\n if (TRAVERSAL_PATH_VALUES.has(raw)) {\n invalid = key;\n return '';\n }\n return encodeURIComponent(raw);\n });\n if (missing !== undefined) {\n // Config refuses a template parameter the input schema cannot supply.\n // This covers a hand-built `CommerceResource` that skipped config: through\n // validateBackendRequestShape it fails before payment, instead of calling\n // the backend with an empty path segment.\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${missing}\" was not supplied`, {\n ...context,\n details: { field: missing },\n });\n }\n if (invalid !== undefined) {\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${invalid}\" is not a valid value`, {\n ...context,\n details: { field: invalid },\n });\n }\n return { url, remaining };\n}\n\nexport function stringifyPrimitive(value: unknown): string {\n if (value === undefined || value === null) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n// `Headers` throws a TypeError on an illegal name or value. The error is\n// rethrown typed and without `cause`: the TypeError quotes the value, which may\n// be a credential.\nexport function buildHeaders(\n handler: BackendHandler,\n context: ShapeContext,\n forwarded: Readonly<Record<string, string>> = {},\n): Headers {\n let headers: Headers;\n try {\n headers = new Headers(handler.headers);\n } catch {\n throw invalidHeaderError(context);\n }\n // Caller headers cannot replace operator-configured backend credentials\n for (const [name, value] of Object.entries(forwarded)) {\n if (NEVER_FORWARDED_HEADER.test(name.toLowerCase())) continue;\n try {\n if (!headers.has(name)) headers.set(name, value);\n } catch {\n throw new CommerceError('INPUT_INVALID', 'A forwarded request header is invalid', {\n ...context,\n details: { reason: 'invalid-forwarded-header' },\n });\n }\n }\n return headers;\n}\n\nexport function setHeader(\n headers: Headers,\n name: string,\n value: string,\n context: ShapeContext,\n): void {\n try {\n headers.set(name, value);\n } catch {\n throw invalidHeaderError(context);\n }\n}\n\nfunction invalidHeaderError(context: ShapeContext): CommerceError {\n return new CommerceError('BACKEND_ERROR', 'Backend request headers are invalid', {\n ...context,\n details: { reason: 'invalid-header' },\n });\n}\n","/**\n * The built-in outbound HTTP path to a merchant backend.\n *\n * - Global `fetch`, always bounded by `AbortSignal.timeout`.\n * - `redirect: 'manual'`: a 3xx response is a `BACKEND_ERROR`, never followed\n * (SSRF hardening).\n * - `{param}` segments in `handler.url` are filled from validated input and\n * URL-encoded; the rest is mapped as `BackendHandler.inputBindings`\n * describes (see `backend-request.ts`).\n */\nimport { type BackendHandler, DEFAULT_BACKEND_TIMEOUT_MS } from '../domain/resource';\nimport { CommerceError, isCommerceError } from '../errors';\nimport type { BackendExecutor, BackendRequest, BackendResponse } from '../interfaces/backend';\nimport { type Logger, NOOP_LOGGER } from '../interfaces/logger';\nimport { isRecord } from '../is-record';\nimport {\n buildBackendRequestParts,\n buildHeaders,\n checkQueryCollision,\n setHeader,\n stringifyPrimitive,\n} from './backend-request';\n\nconst MAX_BODY_SNIPPET_LENGTH = 512;\n\n// How a merchant recognizes a repeat of an operation. The de facto standard\n// name, and the one ACP requires inbound.\nconst IDEMPOTENCY_KEY_HEADER = 'idempotency-key';\n\n// The timeout bounds a response by time, not bytes; this stops a hostile or\n// broken backend from filling memory\nconst MAX_RESPONSE_BODY_BYTES = 1024 * 1024;\n\nexport interface HttpBackendExecutorOptions {\n /** Override for `fetch`, used in tests. Defaults to the global implementation */\n readonly fetchImpl?: typeof fetch;\n /** Receives a non-2xx backend body at debug level; it never reaches the client */\n readonly logger?: Logger;\n}\n\n/**\n * Merchant non-2xx response attached as the `BACKEND_ERROR` cause. Adapters\n * can inspect its body and headers; client errors omit the cause.\n */\nexport class BackendErrorResponse {\n constructor(\n readonly status: number,\n readonly body: unknown,\n /** Lowercase names, as `Headers` yields them */\n readonly headers: Readonly<Record<string, string>> = {},\n ) {}\n}\n\nexport class HttpBackendExecutor implements BackendExecutor {\n private readonly fetchImpl: typeof fetch;\n private readonly logger: Logger;\n\n constructor(options: HttpBackendExecutorOptions = {}) {\n this.fetchImpl = options.fetchImpl ?? fetch;\n this.logger = options.logger ?? NOOP_LOGGER;\n }\n\n async call(handler: BackendHandler, request: BackendRequest): Promise<BackendResponse> {\n const timeoutMs = handler.timeoutMs ?? DEFAULT_BACKEND_TIMEOUT_MS;\n const inputRecord = isRecord(request.input) ? request.input : {};\n\n const context = { requestId: request.requestId, resourceId: request.resourceId };\n // Throws INPUT_INVALID for every shape problem. The pipeline already ran it\n // before payment through validateBackendRequestShape(); this copy covers a\n // caller that bypasses the pipeline.\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch (error) {\n throw new CommerceError('BACKEND_ERROR', 'Backend URL could not be constructed from input', {\n ...context,\n details: { reason: 'invalid-url' },\n cause: error,\n });\n }\n\n // Beyond the per-parameter check: the resolved path must stay under the\n // template's literal prefix (everything before the first `{`)\n const prefixPathname = literalPrefixPathname(handler);\n if (prefixPathname !== undefined && !target.pathname.startsWith(prefixPathname)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n 'Path parameters resolved outside the configured backend path',\n context,\n );\n }\n\n const headers = buildHeaders(handler, context, request.backendHeaders);\n // Replaces a configured header of the same name, unlike content-type below:\n // a static key would make every request look like a retry of the first\n if (request.idempotencyKey !== undefined) {\n setHeader(headers, IDEMPOTENCY_KEY_HEADER, request.idempotencyKey, context);\n }\n let body: string | undefined;\n\n // searchParams.set() replaces an existing param, so a caller key named\n // like an operator's query param (`?apikey=SECRET` in handler.url) would\n // overwrite it. validateBackendRequestShape() runs the same check before\n // payment.\n checkQueryCollision(target, parts.query, context);\n for (const [key, value] of Object.entries(parts.query)) {\n target.searchParams.set(key, stringifyPrimitive(value));\n }\n if (parts.body !== undefined) {\n body = JSON.stringify(parts.body.value);\n // A configured Content-Type, such as `application/vnd.x+json`, wins\n if (!headers.has('content-type')) headers.set('content-type', 'application/json');\n }\n\n const started = performance.now();\n let response: Response;\n try {\n response = await this.fetchImpl(target, {\n method: handler.method,\n headers,\n ...(body !== undefined ? { body } : {}),\n redirect: 'manual',\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n const durationMs = Math.round(performance.now() - started);\n if (isAbortError(error)) {\n throw new CommerceError(\n 'BACKEND_TIMEOUT',\n `Backend request timed out after ${timeoutMs}ms`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { timeoutMs, durationMs },\n cause: error,\n },\n );\n }\n throw new CommerceError('BACKEND_ERROR', 'Backend request failed (transport error)', {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { durationMs },\n cause: error,\n });\n }\n const durationMs = Math.round(performance.now() - started);\n\n const isRedirect =\n response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400);\n if (isRedirect) {\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Backend responded with a redirect, which is not followed',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status, reason: 'redirect-not-followed' },\n },\n );\n }\n\n const responseHeaders = Object.fromEntries(response.headers);\n const contentType = response.headers.get('content-type') ?? '';\n let parsedBody: unknown;\n try {\n parsedBody = await parseBody(response, contentType);\n } catch (error) {\n const tooLarge = isCommerceError(error);\n throw new CommerceError(\n 'BACKEND_ERROR',\n tooLarge\n ? 'Backend response exceeded the maximum allowed size'\n : 'Backend response could not be read',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: tooLarge\n ? { reason: 'response-too-large', maxBytes: MAX_RESPONSE_BODY_BYTES }\n : { reason: 'read-error' },\n cause: error,\n },\n );\n }\n\n if (response.status < 200 || response.status >= 300) {\n // The status may reach the client, but the body is logged at debug level\n // only: a backend in verbose error mode emits stack traces, hostnames or\n // SQL fragments, and the caller may be anonymous\n this.logger.debug(\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n status: response.status,\n bodySnippet: truncateSnippet(parsedBody),\n },\n 'Backend responded with a non-2xx status',\n );\n throw new CommerceError('BACKEND_ERROR', `Backend responded with status ${response.status}`, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status },\n cause: new BackendErrorResponse(response.status, parsedBody, responseHeaders),\n });\n }\n\n return {\n status: response.status,\n headers: responseHeaders,\n body: parsedBody,\n durationMs,\n };\n }\n}\n\n// `handler.url` never changes, so its literal prefix is parsed once per handler.\n// `null` records a prefix that is not a URL, as when a parameter sits in the\n// host (which config refuses); the containment check is then skipped.\nconst prefixPathnames = new WeakMap<BackendHandler, string | null>();\n\nfunction literalPrefixPathname(handler: BackendHandler): string | undefined {\n let cached = prefixPathnames.get(handler);\n if (cached === undefined) {\n try {\n cached = new URL(handler.url.split('{')[0] ?? handler.url).pathname;\n } catch {\n cached = null;\n }\n prefixPathnames.set(handler, cached);\n }\n return cached ?? undefined;\n}\n\nasync function readBodyCapped(response: Response, maxBytes: number): Promise<string> {\n if (!response.body) return '';\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n // The only CommerceError parseBody can throw, which is how its caller\n // tells an oversized body from a read failure\n throw new CommerceError('BACKEND_ERROR', `response body exceeded ${maxBytes} bytes`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nasync function parseBody(response: Response, contentType: string): Promise<unknown> {\n const text = await readBodyCapped(response, MAX_RESPONSE_BODY_BYTES);\n if (text.length === 0) return text;\n if (contentType.includes('json')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction truncateSnippet(body: unknown): string {\n const text = typeof body === 'string' ? body : safeStringify(body);\n return text.length > MAX_BODY_SNIPPET_LENGTH\n ? `${text.slice(0, MAX_BODY_SNIPPET_LENGTH)}…`\n : text;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');\n}\n","// Execution identity and digests for the transaction journal\nimport { createHash } from 'node:crypto';\nimport { canonicalJson } from '../canonical-json';\nimport type { PaymentRequirement, PaymentResult } from '../domain/payment';\nimport { RECONCILIATION_METADATA_KEY } from '../domain/payment';\nimport type { CanonicalRequest } from '../domain/request';\nimport type { CommerceResource } from '../domain/resource';\nimport type { PersistenceFailure } from '../domain/transaction';\nimport type { NewTransaction } from '../interfaces/store';\nimport { isRecord } from '../is-record';\nimport { SETTLE_AFTER_BACKEND_METADATA_KEY } from './settlement-order';\n\n/** One execute() call */\nexport interface Flow {\n readonly request: CanonicalRequest;\n readonly transactionId: string;\n /** Labels for failed writes, deduplicated in order of first failure */\n readonly persistenceFailures: PersistenceFailure[];\n /** True when the reserved attempt matches this ID and the store provides recordTransactionStep */\n journaled: boolean;\n}\n\nexport function createFlow(request: CanonicalRequest, transactionId: string): Flow {\n return { request, transactionId, persistenceFailures: [], journaled: false };\n}\n\n/** Snapshot failure labels for events and outcomes, omitting the field when empty */\nexport function failuresOf(flow: Flow): { persistenceFailures?: readonly PersistenceFailure[] } {\n return flow.persistenceFailures.length > 0\n ? { persistenceFailures: [...flow.persistenceFailures] }\n : {};\n}\n\nfunction sha256(text: string): string {\n return `sha256:${createHash('sha256').update(text, 'utf8').digest('hex')}`;\n}\n\n/** Hash canonical JSON input, or return undefined when canonicalJson does */\nexport function inputDigest(input: unknown): string | undefined {\n const json = canonicalJson(input);\n return json !== undefined ? sha256(json) : undefined;\n}\n\n/**\n * Hash the resource's pricing, payment methods, authorization requirements and\n * selected payment terms. Exclude handler URLs and headers because they may\n * contain credentials.\n */\nexport function configDigest(resource: CommerceResource, requirement: PaymentRequirement): string {\n const terms = {\n resourceId: resource.id,\n pricing: resource.pricing,\n paymentMethods: resource.paymentMethods,\n authorization: resource.authorization?.required ?? [],\n requirement: {\n provider: requirement.provider,\n amount: requirement.amount,\n currency: requirement.currency,\n destination: requirement.destination ?? null,\n network: requirement.network ?? null,\n asset: requirement.asset ?? null,\n settleAfterBackend: requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true,\n },\n };\n // Fall back to JSON.stringify when terms cannot be canonicalized, such as\n // a configuration string containing a lone surrogate\n return sha256(canonicalJson(terms) ?? JSON.stringify(terms));\n}\n\n/** Build journal data for a verified payment's replay reservation */\nexport function newTransaction(\n flow: Flow,\n resource: CommerceResource,\n requirement: PaymentRequirement,\n verification: PaymentResult,\n validInput: unknown,\n authorization: NewTransaction['authorization'],\n): NewTransaction {\n const raw = verification.metadata?.[RECONCILIATION_METADATA_KEY];\n const locator = isRecord(raw) ? raw : undefined;\n const expiresAt = typeof locator?.['expiresAt'] === 'string' ? locator['expiresAt'] : undefined;\n const network = verification.network ?? requirement.network;\n const asset = verification.asset ?? requirement.asset;\n const digest = inputDigest(validInput);\n return {\n id: flow.transactionId,\n protocol: flow.request.protocol,\n ...(network !== undefined ? { network } : {}),\n ...(asset !== undefined ? { asset } : {}),\n ...(locator !== undefined ? { locator } : {}),\n ...(expiresAt !== undefined ? { expiresAt } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n ...(digest !== undefined ? { inputDigest: digest } : {}),\n configDigest: configDigest(resource, requirement),\n };\n}\n","/**\n * A small JSON Schema validator for resource input.\n *\n * Supported subset (draft 2020-12 vocabulary, structural only):\n * - `type`: \"object\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\" |\n * \"null\", or an array of those (e.g. `[\"object\", \"null\"]`)\n * - `properties` (validated recursively)\n * - `required` (string[])\n * - `additionalProperties` (boolean, or a schema applied to extra properties)\n * - `enum` (allowed values; objects and arrays compared structurally, in any key\n * order)\n * - `items` (one schema applied to every array element, no tuple form)\n *\n * Not enforced: `minLength`, `maxLength`, `pattern`, `format`, `minimum`,\n * `maximum`, `exclusiveMinimum/Maximum`, `multipleOf`, `oneOf`, `anyOf`,\n * `allOf`, `not`, `$ref`, `const`, `patternProperties`, `minItems`,\n * `maxItems`, `uniqueItems`, tuple-form `items`, and a `type` naming anything\n * outside the list above. Config warns at load when a schema uses one of these\n * keywords or a tuple `items`.\n */\nimport { isDeepStrictEqual } from 'node:util';\nimport type { JsonSchema } from '../domain/common';\nimport { isRecord } from '../is-record';\n\nexport interface FieldError {\n readonly path: string;\n readonly message: string;\n}\n\nexport type ValidationResult =\n | { readonly valid: true; readonly value: unknown }\n | { readonly valid: false; readonly errors: readonly FieldError[] };\n\nexport type Validator = (input: unknown) => ValidationResult;\n\nconst SUPPORTED_TYPES = new Set([\n 'object',\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'array',\n 'null',\n]);\n\n/** Wrap a resource `inputSchema` in a reusable validator function */\nexport function compileJsonSchema(schema: JsonSchema | undefined): Validator {\n return (input: unknown): ValidationResult => {\n if (schema === undefined) return { valid: true, value: input };\n const errors = validateNode(schema, input, '$');\n return errors.length === 0 ? { valid: true, value: input } : { valid: false, errors };\n };\n}\n\nfunction matchesType(type: string, value: unknown): boolean {\n switch (type) {\n case 'object':\n return isRecord(value);\n case 'array':\n return Array.isArray(value);\n case 'string':\n return typeof value === 'string';\n case 'boolean':\n return typeof value === 'boolean';\n case 'number':\n return typeof value === 'number' && Number.isFinite(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'null':\n return value === null;\n default:\n return true;\n }\n}\n\nfunction describeType(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n return typeof value;\n}\n\n// `===` first keeps a top-level -0 equal to 0; isDeepStrictEqual alone would not\nfunction deepEqual(a: unknown, b: unknown): boolean {\n return a === b || isDeepStrictEqual(a, b);\n}\n\nfunction own(obj: Record<string, unknown>, key: string): unknown {\n return Object.hasOwn(obj, key) ? obj[key] : undefined;\n}\n\n// `type` may be a string or an array of strings, e.g. `[\"object\", \"null\"]`. An\n// array with a non-string entry is ignored rather than guessed at.\nfunction typeList(raw: unknown): string[] | undefined {\n if (typeof raw === 'string') return [raw];\n if (Array.isArray(raw) && raw.every((entry): entry is string => typeof entry === 'string')) {\n return raw;\n }\n return undefined;\n}\n\n/**\n * Whether a schema node is an object schema: its `type` includes \"object\"\n * (`[\"object\", \"null\"]` counts), or it has no `type` and declares `properties`\n * or `required`.\n *\n * Config's `defaultClosedObjectSchema` uses it to close schemas and this\n * validator uses it to enforce them. With two definitions, a node could stay\n * open while config believes it closed.\n */\nexport function isObjectSchemaNode(schema: Record<string, unknown>): boolean {\n const types = typeList(schema['type']);\n if (types !== undefined) return types.includes('object');\n return Object.hasOwn(schema, 'properties') || Object.hasOwn(schema, 'required');\n}\n\nfunction validateNode(schema: JsonSchema, value: unknown, path: string): FieldError[] {\n const errors: FieldError[] = [];\n const types = typeList(own(schema, 'type'));\n const recognizedTypes = types?.filter((entry) => SUPPORTED_TYPES.has(entry));\n\n if (\n types !== undefined &&\n recognizedTypes !== undefined &&\n recognizedTypes.length === types.length &&\n types.length > 0\n ) {\n if (!types.some((entry) => matchesType(entry, value))) {\n errors.push({\n path,\n message: `expected type \"${types.join(' | ')}\" but got ${describeType(value)}`,\n });\n return errors;\n }\n }\n\n const enumRaw = own(schema, 'enum');\n if (Array.isArray(enumRaw)) {\n const allowed = enumRaw as unknown[];\n if (!allowed.some((candidate) => deepEqual(candidate, value))) {\n errors.push({ path, message: `must be one of ${JSON.stringify(allowed)}` });\n }\n }\n\n if (isObjectSchemaNode(schema) && isRecord(value)) {\n errors.push(...validateObject(schema, value, path));\n } else if ((types?.includes('array') ?? false) && Array.isArray(value)) {\n errors.push(...validateArray(schema, value, path));\n }\n\n return errors;\n}\n\nfunction validateObject(\n schema: JsonSchema,\n value: Record<string, unknown>,\n path: string,\n): FieldError[] {\n const errors: FieldError[] = [];\n const propsRaw = own(schema, 'properties');\n const properties = isRecord(propsRaw) ? propsRaw : {};\n const requiredRaw = own(schema, 'required');\n const required = Array.isArray(requiredRaw)\n ? requiredRaw.filter((entry): entry is string => typeof entry === 'string')\n : [];\n\n for (const key of required) {\n // Object.hasOwn, not `in`: `in` walks the prototype chain, so a required\n // \"toString\" or \"__proto__\" would always look present\n if (!Object.hasOwn(value, key)) {\n errors.push({ path: `${path}.${key}`, message: 'is required' });\n }\n }\n\n const additional = own(schema, 'additionalProperties');\n\n for (const key of Object.keys(value)) {\n // Own-property lookup: `properties[\"toString\"]` would find the inherited\n // member and skip the additionalProperties check below\n const propSchemaRaw = own(properties, key);\n if (propSchemaRaw !== undefined) {\n if (isRecord(propSchemaRaw)) {\n errors.push(...validateNode(propSchemaRaw, value[key], `${path}.${key}`));\n }\n continue;\n }\n if (additional === false) {\n errors.push({ path: `${path}.${key}`, message: 'additional property not allowed' });\n } else if (isRecord(additional)) {\n errors.push(...validateNode(additional, value[key], `${path}.${key}`));\n }\n }\n\n return errors;\n}\n\nfunction validateArray(schema: JsonSchema, value: unknown[], path: string): FieldError[] {\n const errors: FieldError[] = [];\n const itemsRaw = own(schema, 'items');\n if (isRecord(itemsRaw)) {\n value.forEach((item, index) => {\n errors.push(...validateNode(itemsRaw, item, `${path}[${index}]`));\n });\n }\n return errors;\n}\n","// Verifies and reserves the authorization a resource requires, before its payment is reserved\nimport type { AuthorizationProvider, AuthorizationVerification } from '../../domain/authorization';\nimport type { AuthorizationMethodName } from '../../domain/common';\nimport type { PaymentRequirement } from '../../domain/payment';\nimport type { CanonicalRequest } from '../../domain/request';\nimport type { CommerceResource } from '../../domain/resource';\nimport { CommerceError, describeError, isCommerceError } from '../../errors';\nimport type { Flow } from '../journal';\nimport type { AuthorizationHold, PipelineContext } from './context';\n\n// The provider for each method a resource requires, in the resource's order.\n// Config refuses a method that is not enabled at load; it is checked again\n// because missing it here would serve the resource with no authorization.\nexport function resolveAuthorizationProviders(\n providers: readonly AuthorizationProvider[],\n resource: CommerceResource,\n requestId: string,\n): readonly AuthorizationProvider[] {\n const required = resource.authorization?.required ?? [];\n return required.map((method: AuthorizationMethodName) => {\n const found = providers.find((provider) => provider.name === method);\n if (!found) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" requires authorization method \"${method}\", which is not enabled`,\n { requestId, resourceId: resource.id },\n );\n }\n return found;\n });\n}\n\nexport type AuthorizeAndReserve = (\n flow: Flow,\n request: CanonicalRequest,\n resource: CommerceResource,\n providers: readonly AuthorizationProvider[],\n requirement: PaymentRequirement,\n input: unknown,\n) => Promise<AuthorizationHold | undefined>;\n\nexport function createAuthorizeAndReserve(ctx: PipelineContext): AuthorizeAndReserve {\n const { options, safeEmit, buildEvent } = ctx;\n\n // Verify and reserve what the resource requires, or undefined if it requires\n // none. Runs after payment verification, which has no side effect, so a bad\n // payment proof cannot burn a reservation.\n async function authorizeAndReserve(\n flow: Flow,\n request: CanonicalRequest,\n resource: CommerceResource,\n providers: readonly AuthorizationProvider[],\n requirement: PaymentRequirement,\n input: unknown,\n ): Promise<AuthorizationHold | undefined> {\n if (providers.length === 0) return undefined;\n\n const submission = request.authorization;\n const provider = providers.find((candidate) => candidate.name === submission?.method);\n // A request carries one proof, so a resource requiring two methods is\n // refused here rather than half-checked\n const unmet = providers.filter((candidate) => candidate !== provider).map((c) => c.name);\n\n if (submission === undefined || provider === undefined || unmet.length > 0) {\n await safeEmit(\n buildEvent(flow, {\n type: 'authorization.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n data: { reason: 'AUTHORIZATION_REQUIRED', methods: unmet },\n }),\n );\n throw new CommerceError(\n 'AUTHORIZATION_REQUIRED',\n `Resource \"${resource.id}\" requires authorization: ${unmet.join(', ')}`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { required: providers.map((candidate) => candidate.name), missing: unmet },\n },\n );\n }\n\n let verification: AuthorizationVerification;\n try {\n verification = await provider.verifyAndReserve({\n requestId: request.requestId,\n resourceId: resource.id,\n input,\n submission,\n requirement,\n });\n } catch (error) {\n // An untyped throw says nothing about whose fault it was. Unavailable is\n // honest and retryable; invalid would blame the buyer for our outage.\n const mapped = isCommerceError(error)\n ? error\n : new CommerceError(\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'Authorization provider is unavailable',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n },\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'authorization.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n data: { reason: mapped.code, method: provider.name },\n }),\n );\n throw mapped;\n }\n\n await safeEmit(\n buildEvent(flow, {\n type: 'authorization.verified',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n data: { method: verification.method, reference: verification.reference },\n }),\n );\n\n const context = { requestId: request.requestId, resourceId: resource.id };\n return {\n record: {\n method: verification.method,\n reference: verification.reference,\n ...(verification.metadata !== undefined ? { metadata: verification.metadata } : {}),\n },\n reservationId: verification.reservationId,\n async finalize(action) {\n try {\n await provider[action](verification.reservationId, context);\n return true;\n } catch (error) {\n // A failure leaves the reservation reserved, which is still\n // unspendable, so the caller's outcome stands\n options.logger.error(\n { err: describeError(error), requestId: request.requestId, action },\n 'Authorization finalization failed; the reservation stays reserved',\n );\n return false;\n }\n },\n };\n }\n\n return authorizeAndReserve;\n}\n","// What a refused or replayed payment answers with: the unused challenge, when one may be retried\nimport type { PaymentRequirement } from '../../domain/payment';\nimport { CommerceError } from '../../errors';\n\n// A refusal leaves this request's challenge unused. Return it with the\n// provider's reason so the client can retry without fetching another challenge\nexport function retryChallenge(\n requirement: PaymentRequirement,\n reason?: string,\n): { details?: Record<string, unknown> } {\n const envelope = requirement.challenge.envelope;\n if (envelope === undefined && reason === undefined) return {};\n return {\n details: {\n ...(envelope !== undefined ? { challenge: envelope } : {}),\n ...(reason !== undefined ? { reason } : {}),\n },\n };\n}\n\n// Attempt statuses the pipeline treats as finished when handling a replay. The\n// legacy `failed` is not one: it recorded any throw from settle(), so it may\n// hide a transfer, like `settlement-uncertain`.\nconst FINISHED_ATTEMPT_STATUSES: ReadonlySet<string> = new Set(['settled', 'rejected']);\n\n// Include the paid offer's network for the rail's replay code. Finished\n// attempts get 402 with a fresh challenge; unfinished or unreadable attempts\n// keep 409 to avoid prompting a second payment.\nexport function replayError(error: CommerceError, requirement: PaymentRequirement): CommerceError {\n if (error.code !== 'PAYMENT_REPLAYED') return error;\n const status = error.details?.['attemptStatus'];\n const finished = typeof status === 'string' && FINISHED_ATTEMPT_STATUSES.has(status);\n const network = requirement.network;\n if (!finished && network === undefined) return error;\n return new CommerceError('PAYMENT_REPLAYED', error.message, {\n ...(error.requestId !== undefined ? { requestId: error.requestId } : {}),\n ...(error.resourceId !== undefined ? { resourceId: error.resourceId } : {}),\n ...(finished ? { httpStatus: 402 } : {}),\n details: {\n ...error.details,\n ...(network !== undefined ? { network } : {}),\n ...(finished ? retryChallenge(requirement).details : {}),\n },\n });\n}\n","// The payment phase: challenge, offer selection, verification, and the authorization and replay reservations\n\nimport type { PaymentMethodName } from '../../domain/common';\nimport type { PaymentProvider, PaymentRequirement, PaymentResult } from '../../domain/payment';\nimport type { CanonicalRequest, PaymentRequiredOutcome } from '../../domain/request';\nimport type { CommerceResource, Pricing } from '../../domain/resource';\nimport { CommerceError, isCommerceError, toCommerceError } from '../../errors';\nimport { type Flow, newTransaction } from '../journal';\nimport { REUSE_REJECTED_AUTHORIZATION_METADATA_KEY } from '../settlement-order';\nimport { type AuthorizeAndReserve, resolveAuthorizationProviders } from './authorization';\nimport { replayError, retryChallenge } from './challenge';\nimport type { PipelineContext, SettleArgs } from './context';\n\n/** A verified payment whose authorization and replay identity are reserved */\nexport interface AdmittedPayment {\n readonly kind: 'admitted';\n readonly settleArgs: SettleArgs;\n}\n\nexport type AdmitPayment = (\n flow: Flow,\n request: CanonicalRequest,\n resource: CommerceResource,\n pricing: Extract<Pricing, { type: 'fixed' }>,\n validInput: unknown,\n) => Promise<PaymentRequiredOutcome | AdmittedPayment>;\n\n/**\n * Builds the payment phase. It returns the challenge when the request carries\n * no proof, and otherwise verifies the proof and reserves the authorization\n * and replay identity, or throws.\n */\nexport function createPaymentAdmission(\n ctx: PipelineContext,\n authorizeAndReserve: AuthorizeAndReserve,\n): AdmitPayment {\n const { options, safeEmit, buildEvent } = ctx;\n\n return async function admitPayment(flow, request, resource, pricing, validInput) {\n const provider = pickProvider(options.paymentProviders, resource.paymentMethods);\n if (!provider) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `No enabled payment provider for resource \"${resource.id}\"`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { paymentMethods: resource.paymentMethods },\n },\n );\n }\n\n // Resolved before the challenge so the 402 can name what the retry must\n // also carry, and so an uncheckable method fails before payment starts\n const authProviders = resolveAuthorizationProviders(\n options.authorizationProviders ?? [],\n resource,\n request.requestId,\n );\n\n let requirement: PaymentRequirement;\n try {\n requirement = await provider.createRequirement({\n requestId: request.requestId,\n resource,\n amount: pricing.amount,\n currency: pricing.currency,\n requestedAt: options.clock.nowIso(),\n input: validInput,\n // Transport facts a rail may bind into its challenge, such as a body digest\n ...(request.metadata !== undefined ? { metadata: request.metadata } : {}),\n });\n } catch (error) {\n throw isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', 'Payment provider is unavailable', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n });\n }\n\n if (!request.payment) {\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.required',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n }),\n );\n return {\n kind: 'payment-required',\n requestId: request.requestId,\n transactionId: flow.transactionId,\n resourceId: resource.id,\n requirement,\n ...(authProviders.length > 0\n ? { authorization: authProviders.map((p) => p.requirement) }\n : {}),\n };\n }\n\n const payment = request.payment;\n\n let verification: PaymentResult;\n try {\n // Later steps, including authorization and settlement order, use the\n // selected requirement with its full retry challenge\n if (provider.selectRequirement) {\n requirement = await provider.selectRequirement({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n }\n verification = await provider.verify({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n } catch (error) {\n // A typed CommerceError is rethrown as is, keeping its code and its\n // possibly retryable status. Only an untyped throw is mapped, with a\n // fixed client-facing message.\n const mapped = isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_INVALID', 'Payment verification failed', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n ...retryChallenge(requirement),\n });\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw mapped;\n }\n\n if (verification.status !== 'verified') {\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: verification.rejectionReason ? { reason: verification.rejectionReason } : {},\n }),\n );\n throw new CommerceError(\n 'PAYMENT_INVALID',\n verification.rejectionReason ?? 'Payment was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n ...retryChallenge(requirement, verification.rejectionReason),\n },\n );\n }\n\n if (!verification.replayKey) {\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'missing-replay-key' },\n }),\n );\n throw new CommerceError('PAYMENT_INVALID', 'Payment provider did not return a replay key', {\n requestId: request.requestId,\n resourceId: resource.id,\n });\n }\n const replayKey = verification.replayKey;\n\n const hold = await authorizeAndReserve(\n flow,\n request,\n resource,\n authProviders,\n requirement,\n validInput,\n );\n\n try {\n const attempt = await options.store.reservePaymentAttempt({\n requestId: request.requestId,\n resourceId: resource.id,\n provider: provider.name,\n replayKey,\n amount: verification.amount,\n currency: verification.currency,\n ...(verification.payer !== undefined ? { payer: verification.payer } : {}),\n ...(verification.payee !== undefined ? { payee: verification.payee } : {}),\n ...(requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true\n ? { reclaimRejected: true }\n : {}),\n transaction: newTransaction(\n flow,\n resource,\n requirement,\n verification,\n validInput,\n hold !== undefined ? { ...hold.record, reservationId: hold.reservationId } : undefined,\n ),\n });\n // Require a matching transaction ID and recordTransactionStep before enabling\n // journaling, so legacy stores can ignore the transaction data\n flow.journaled =\n attempt.transactionId === flow.transactionId &&\n options.store.recordTransactionStep !== undefined;\n } catch (error) {\n // A duplicate replayKey arrives as PAYMENT_REPLAYED and is kept. Any\n // other failure (a full disk, a dropped connection) is STORAGE_ERROR,\n // never a replay.\n const mapped = toCommerceError(\n error,\n 'STORAGE_ERROR',\n 'Payment attempt could not be recorded',\n );\n await hold?.finalize('release');\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw replayError(mapped, requirement);\n }\n\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.verified',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n return {\n kind: 'admitted',\n settleArgs: {\n flow,\n request,\n resource,\n provider,\n requirement,\n payment,\n verification,\n replayKey,\n hold,\n },\n };\n };\n}\n\nfunction pickProvider(\n providers: readonly PaymentProvider[],\n methods: readonly PaymentMethodName[],\n): PaymentProvider | undefined {\n for (const method of methods) {\n const found = providers.find((provider) => provider.name === method);\n if (found) return found;\n }\n return undefined;\n}\n","// What the pipeline's stages share: its options, and event and persistence writes that never fail a flow\nimport type { AuthorizationProvider, AuthorizationRecord } from '../../domain/authorization';\nimport type { CommerceEvent, EventSink } from '../../domain/event';\nimport type {\n PaymentProvider,\n PaymentRequirement,\n PaymentResult,\n PaymentSubmission,\n} from '../../domain/payment';\nimport type { CanonicalRequest } from '../../domain/request';\nimport type { CommerceResource, ResourceRegistry } from '../../domain/resource';\nimport type { AuthorizationHoldState, PersistenceFailure } from '../../domain/transaction';\nimport { describeError } from '../../errors';\nimport type { BackendExecutor } from '../../interfaces/backend';\nimport type { Logger } from '../../interfaces/logger';\nimport type { Clock, IdGenerator } from '../../interfaces/runtime';\nimport type { ReceiptStore, TransactionStep } from '../../interfaces/store';\nimport type { Flow } from '../journal';\n\nexport interface CreateExecutionPipelineOptions {\n readonly resources: ResourceRegistry;\n readonly paymentProviders: readonly PaymentProvider[];\n /** Defaults to none */\n readonly authorizationProviders?: readonly AuthorizationProvider[];\n readonly store: ReceiptStore;\n readonly backend: BackendExecutor;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n}\n\nexport type HoldAction = 'consume' | 'release' | 'markUncertain';\n\n/**\n * An authorization reservation and its receipt summary. `finalize` returns\n * false on provider errors; journal state changes only after it returns true.\n */\nexport interface AuthorizationHold {\n readonly record: AuthorizationRecord;\n /** Handle used to consume, release or mark the reservation uncertain */\n readonly reservationId: string;\n finalize(action: HoldAction): Promise<boolean>;\n}\n\n/** Journal step data before the pipeline adds its transaction ID and timestamp */\nexport type StepBody = TransactionStep extends infer S\n ? S extends TransactionStep\n ? Omit<S, 'transactionId' | 'at'>\n : never\n : never;\n\nconst HOLD_STATES: Readonly<Record<HoldAction, AuthorizationHoldState>> = {\n consume: 'consumed',\n release: 'released',\n markUncertain: 'uncertain',\n};\n\n/** A verified, reserved payment and everything its settlement needs */\nexport interface SettleArgs {\n readonly flow: Flow;\n readonly request: CanonicalRequest;\n readonly resource: CommerceResource;\n readonly provider: PaymentProvider;\n readonly requirement: PaymentRequirement;\n readonly payment: PaymentSubmission;\n readonly verification: PaymentResult;\n readonly replayKey: string;\n readonly hold: AuthorizationHold | undefined;\n}\n\nexport interface PipelineContext {\n readonly options: CreateExecutionPipelineOptions;\n /** Emits an event; a failing sink is logged, never thrown */\n readonly safeEmit: (event: CommerceEvent) => Promise<void>;\n /**\n * Run a store write, returning true on success and false on failure.\n * Write errors are logged at error level; a supplied `failure` label is\n * recorded once in `flow.persistenceFailures`.\n */\n readonly safePersist: (\n flow: Flow,\n op: () => Promise<void>,\n label: string,\n failure?: PersistenceFailure,\n ) => Promise<boolean>;\n /** Record a journal step when enabled, logging store errors instead of aborting */\n readonly recordStep: (flow: Flow, step: StepBody) => Promise<void>;\n /** Apply a hold action and attempt its journal step only after provider success */\n readonly finalizeHold: (\n flow: Flow,\n hold: AuthorizationHold | undefined,\n action: HoldAction,\n ) => Promise<void>;\n readonly buildEvent: (\n flow: Flow,\n partial: Omit<CommerceEvent, 'id' | 'at' | 'requestId' | 'transactionId'>,\n ) => CommerceEvent;\n}\n\nexport function createPipelineContext(options: CreateExecutionPipelineOptions): PipelineContext {\n async function safeEmit(event: CommerceEvent): Promise<void> {\n try {\n await options.events.emit(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Event sink failed; commerce flow continues',\n );\n }\n }\n\n async function safePersist(\n flow: Flow,\n op: () => Promise<void>,\n label: string,\n failure?: PersistenceFailure,\n ): Promise<boolean> {\n try {\n await op();\n return true;\n } catch (error) {\n options.logger.error(\n {\n err: describeError(error),\n requestId: flow.request.requestId,\n transactionId: flow.transactionId,\n },\n `Persistence failed: ${label}`,\n );\n if (failure !== undefined && !flow.persistenceFailures.includes(failure)) {\n flow.persistenceFailures.push(failure);\n }\n return false;\n }\n }\n\n async function recordStep(flow: Flow, step: StepBody): Promise<void> {\n const record = options.store.recordTransactionStep;\n if (!flow.journaled || record === undefined) return;\n const full = {\n ...step,\n transactionId: flow.transactionId,\n at: options.clock.nowIso(),\n } as TransactionStep;\n await safePersist(\n flow,\n () => record.call(options.store, full),\n `recordTransactionStep(${step.kind})`,\n 'journal',\n );\n }\n\n async function finalizeHold(\n flow: Flow,\n hold: AuthorizationHold | undefined,\n action: HoldAction,\n ): Promise<void> {\n if (hold !== undefined && (await hold.finalize(action))) {\n await recordStep(flow, { kind: 'hold', hold: HOLD_STATES[action] });\n }\n }\n\n function buildEvent(\n flow: Flow,\n partial: Omit<CommerceEvent, 'id' | 'at' | 'requestId' | 'transactionId'>,\n ): CommerceEvent {\n return {\n id: options.ids.next('evt'),\n at: options.clock.nowIso(),\n requestId: flow.request.requestId,\n transactionId: flow.transactionId,\n ...partial,\n };\n }\n\n return { options, safeEmit, safePersist, recordStep, finalizeHold, buildEvent };\n}\n","// Settles a verified, reserved payment, or records that the backend failed before it could\nimport type { PaymentRequirement, PaymentResult } from '../../domain/payment';\nimport { CommerceError, isCommerceError } from '../../errors';\nimport { failuresOf } from '../journal';\nimport { retryChallenge } from './challenge';\nimport type { PipelineContext, SettleArgs } from './context';\n\nexport interface Settlement {\n /** Settles and finalizes the authorization; a refusal or unknown outcome throws */\n readonly settle: (args: SettleArgs) => Promise<PaymentResult>;\n /** Records a backend failure before settlement and releases the authorization */\n readonly abandonSettlement: (args: SettleArgs, backendErrorCode: string) => Promise<void>;\n}\n\nexport function createSettlement(ctx: PipelineContext): Settlement {\n const { options, safeEmit, safePersist, recordStep, finalizeHold, buildEvent } = ctx;\n\n // Settle a verified, reserved payment and finalize its authorization.\n // Rejected or uncertain settlement throws before any response is delivered.\n async function settle(args: SettleArgs): Promise<PaymentResult> {\n const {\n flow,\n request,\n resource,\n provider,\n requirement,\n payment,\n verification,\n replayKey,\n hold,\n } = args;\n await recordStep(flow, { kind: 'settling' });\n let settlement: PaymentResult;\n try {\n settlement = await provider.settle({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n verification,\n });\n } catch (error) {\n // Confirmed non-submission leaves the authorization spendable. Release\n // it for retry and report the provider failure.\n const notSubmitted = notSubmittedReason(error);\n if (notSubmitted !== undefined) {\n await finalizeHold(flow, hold, 'release');\n await safePersist(\n flow,\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n rejectionReason: notSubmitted,\n }),\n 'updatePaymentAttempt(not-submitted)',\n 'payment-attempt',\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: {\n reason: 'settlement-not-submitted',\n providerReason: notSubmitted,\n ...failuresOf(flow),\n },\n }),\n );\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'The payment provider could not settle the payment; nothing was charged',\n { requestId: request.requestId, resourceId: resource.id, cause: error },\n );\n }\n // A throw gives no settlement verdict. The facilitator may have\n // broadcast before losing its response, even without a transaction\n // hash. Keep the authorization uncertain so it cannot be spent again.\n const txHash = settlementTxHash(error);\n await finalizeHold(flow, hold, 'markUncertain');\n await safePersist(\n flow,\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'settlement-uncertain',\n ...(txHash !== undefined ? { externalReference: txHash } : {}),\n ...(error instanceof Error ? { rejectionReason: error.message } : {}),\n }),\n 'updatePaymentAttempt(settlement-uncertain)',\n 'payment-attempt',\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: {\n reason: 'settlement-uncertain',\n ...(txHash !== undefined ? { transactionHash: txHash } : {}),\n ...failuresOf(flow),\n },\n }),\n );\n // The replay key remains reserved, so report an uncertain, non-retryable\n // outcome. Expose only the transaction hash from the underlying error.\n throw new CommerceError('PAYMENT_SETTLEMENT_FAILED', 'Settlement could not be confirmed', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n details: {\n settlementUncertain: true,\n ...(txHash !== undefined ? { transactionHash: txHash } : {}),\n ...settlementParties(requirement, verification),\n },\n });\n }\n\n if (settlement.status !== 'settled') {\n await finalizeHold(flow, hold, 'release');\n await safePersist(\n flow,\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n ...(settlement.rejectionReason !== undefined\n ? { rejectionReason: settlement.rejectionReason }\n : {}),\n ...(settlement.externalReference !== undefined\n ? { externalReference: settlement.externalReference }\n : {}),\n }),\n 'updatePaymentAttempt(rejected)',\n 'payment-attempt',\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: {\n ...(settlement.rejectionReason ? { reason: settlement.rejectionReason } : {}),\n ...failuresOf(flow),\n },\n }),\n );\n // A returned rejection confirms no settlement. Both rails return 402.\n const rejectionDetails = retryChallenge(requirement, settlement.rejectionReason).details;\n throw new CommerceError(\n 'PAYMENT_SETTLEMENT_FAILED',\n settlement.rejectionReason ?? 'Settlement was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n httpStatus: 402,\n details: {\n ...rejectionDetails,\n ...settlementParties(requirement, settlement, verification),\n },\n },\n );\n }\n\n await finalizeHold(flow, hold, 'consume');\n await safePersist(\n flow,\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'settled',\n ...(settlement.externalReference !== undefined\n ? { externalReference: settlement.externalReference }\n : {}),\n }),\n 'updatePaymentAttempt(settled)',\n 'payment-attempt',\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.settled',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n return settlement;\n }\n\n // Record the pre-settlement backend failure and release the authorization\n // hold. Rails with reuse metadata can reserve the unspent replay key again,\n // as after any rejection.\n async function abandonSettlement(args: SettleArgs, backendErrorCode: string): Promise<void> {\n const { flow, request, resource, provider, replayKey, hold } = args;\n await finalizeHold(flow, hold, 'release');\n await safePersist(\n flow,\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n rejectionReason: 'backend_failed',\n }),\n 'updatePaymentAttempt(backend-failed)',\n 'payment-attempt',\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'backend-failed', backendErrorCode, ...failuresOf(flow) },\n }),\n );\n }\n\n return { settle, abandonSettlement };\n}\n\n// The reason a provider gave when it threw before submitting anything\nfunction notSubmittedReason(error: unknown): string | undefined {\n if (!isCommerceError(error) || error.details?.['settlementNotSubmitted'] !== true) {\n return undefined;\n }\n const reason = error.details['reason'];\n return typeof reason === 'string' ? reason : 'settlement_not_submitted';\n}\n\n// The broadcast transaction hash a provider attached to a settlement throw,\n// when it knows one\nfunction settlementTxHash(error: unknown): string | undefined {\n const hash = isCommerceError(error) ? error.details?.['transactionHash'] : undefined;\n return typeof hash === 'string' ? hash : undefined;\n}\n\n// Prefer the network and payer reported by settlement or verification, then\n// fall back to the requirement's network\nfunction settlementParties(\n requirement: PaymentRequirement,\n ...results: readonly PaymentResult[]\n): { network?: string; payer?: string } {\n const network = results.find((r) => r.network !== undefined)?.network ?? requirement.network;\n const payer = results.find((r) => r.payer !== undefined)?.payer;\n return {\n ...(network !== undefined ? { network } : {}),\n ...(payer !== undefined ? { payer } : {}),\n };\n}\n","/**\n * The single execution path every protocol adapter converges on. The order is a\n * security boundary; do not reorder:\n *\n * 1. resolve resource (RESOURCE_NOT_FOUND)\n * 2. strip reserved input fields, validate input and the backend request shape\n * (INPUT_INVALID, or BACKEND_ERROR for an illegal configured header)\n * 3. resolve price\n * 4. free: straight to the backend\n * 5. paid: pick provider and createRequirement, then return a challenge, or\n * select the offer the proof pays, verify it, and reserve authorization and\n * replay identities\n * 6. settle before calling the backend, or call the backend first and settle\n * only if it succeeds. Finalize authorization according to the outcome\n * (BACKEND_TIMEOUT / BACKEND_ERROR)\n * 7. persist receipt, emit events, return outcome\n */\n\nimport type { AuthorizationRecord } from '../../domain/authorization';\nimport type { PaymentResult } from '../../domain/payment';\nimport type { CommerceReceipt } from '../../domain/receipt';\nimport type { CanonicalRequest, ExecutionOutcome, ExecutionPipeline } from '../../domain/request';\nimport { type CommerceResource, DEFAULT_BACKEND_TIMEOUT_MS } from '../../domain/resource';\nimport { RESERVED_INPUT_FIELDS } from '../../domain/wire';\nimport { CommerceError, toCommerceError } from '../../errors';\nimport type { BackendResponse } from '../../interfaces/backend';\nimport { isRecord } from '../../is-record';\nimport { validateBackendRequestShape } from '../backend-request';\nimport { createFlow, type Flow, failuresOf } from '../journal';\nimport { SETTLE_AFTER_BACKEND_METADATA_KEY } from '../settlement-order';\nimport { compileJsonSchema, type Validator } from '../validation';\nimport { createPaymentAdmission } from './admission';\nimport { createAuthorizeAndReserve } from './authorization';\nimport {\n type CreateExecutionPipelineOptions,\n createPipelineContext,\n type SettleArgs,\n} from './context';\nimport { createSettlement } from './settlement';\n\nexport type { CreateExecutionPipelineOptions } from './context';\n\nexport function createExecutionPipeline(\n options: CreateExecutionPipelineOptions,\n): ExecutionPipeline {\n const validators = new Map<string, Validator>();\n\n function getValidator(resource: CommerceResource): Validator {\n const cached = validators.get(resource.id);\n if (cached) return cached;\n const compiled = compileJsonSchema(resource.inputSchema);\n validators.set(resource.id, compiled);\n return compiled;\n }\n\n const ctx = createPipelineContext(options);\n const { safeEmit, safePersist, recordStep, buildEvent } = ctx;\n const { settle, abandonSettlement } = createSettlement(ctx);\n const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx));\n\n async function execute(request: CanonicalRequest): Promise<ExecutionOutcome> {\n const pipelineStart = options.clock.monotonicMs();\n\n // 1. resolve resource\n const resource = options.resources.get(request.resourceId);\n // Same code and message as an unknown id: a caller on a protocol the\n // resource is not exposed via must not learn that it exists\n if (!resource?.exposedVia.includes(request.protocol)) {\n throw new CommerceError(\n 'RESOURCE_NOT_FOUND',\n `Resource \"${request.resourceId}\" was not found`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n },\n );\n }\n\n // Allocate one ID per resolved execution for events, returned outcomes and\n // receipts. Only paid executions that reach replay reservation can open a\n // journal row.\n const flow = createFlow(request, options.ids.next('txn'));\n\n await safeEmit(\n buildEvent(flow, {\n type: 'resource.requested',\n resourceId: resource.id,\n adapter: request.protocol,\n }),\n );\n\n // 2. strip reserved gateway fields, then validate input\n const strippedInput = stripReservedFields(request.input);\n const validation = getValidator(resource)(strippedInput);\n if (!validation.valid) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input for resource \"${resource.id}\" failed validation`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { errors: validation.errors },\n },\n );\n }\n const validInput = validation.value;\n\n // Before pricing, so a request the backend cannot receive fails before\n // payment (see validateBackendRequestShape)\n validateBackendRequestShape(\n resource.handler,\n validInput,\n { requestId: request.requestId, resourceId: resource.id },\n request.backendHeaders,\n );\n\n // 3. resolve price\n if (resource.pricing.type === 'dynamic') {\n // Config validation rejects this at load; this is defense in depth\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" uses unsupported dynamic pricing`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n // Authorization gates settlement, so on a free resource nothing would read\n // the proof. Config refuses this at load; this is defense in depth.\n if (resource.pricing.type !== 'fixed' && (resource.authorization?.required.length ?? 0) > 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" requires authorization but is not a paid resource`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n let settleArgs: SettleArgs | undefined;\n if (resource.pricing.type === 'fixed') {\n const admission = await admitPayment(flow, request, resource, resource.pricing, validInput);\n if (admission.kind === 'payment-required') return admission;\n settleArgs = admission.settleArgs;\n }\n\n try {\n return await settleAndDeliver(flow, resource, validInput, settleArgs, pipelineStart);\n } finally {\n // Attempt the final journal step after settleAndDeliver returns or throws.\n // A failure is logged after the outcome and event snapshots are built, so\n // it cannot appear in those snapshots.\n await recordStep(flow, { kind: 'completed', ...failuresOf(flow) });\n }\n }\n\n async function settleAndDeliver(\n flow: Flow,\n resource: CommerceResource,\n validInput: unknown,\n settleArgs: SettleArgs | undefined,\n pipelineStart: number,\n ): Promise<ExecutionOutcome> {\n const { request } = flow;\n const authorization: AuthorizationRecord | undefined = settleArgs?.hold?.record;\n let paymentResult: PaymentResult | undefined;\n let deferredSettlement: SettleArgs | undefined;\n if (settleArgs !== undefined) {\n if (settleArgs.requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true) {\n deferredSettlement = settleArgs;\n } else {\n paymentResult = await settle(settleArgs);\n }\n }\n\n // 6. call backend\n await recordStep(flow, {\n kind: 'backend-dispatched',\n deadlineAt: backendDeadline(options.clock.now(), resource),\n });\n const backendStart = options.clock.monotonicMs();\n let backendResponse: BackendResponse;\n try {\n backendResponse = await options.backend.call(resource.handler, {\n requestId: request.requestId,\n resourceId: resource.id,\n input: validInput,\n ...(request.idempotencyKey !== undefined ? { idempotencyKey: request.idempotencyKey } : {}),\n ...(request.backendHeaders !== undefined ? { backendHeaders: request.backendHeaders } : {}),\n });\n } catch (error) {\n const commerceError = toCommerceError(error, 'BACKEND_ERROR', 'Backend call failed');\n await recordStep(flow, {\n kind: 'backend-result',\n status: backendErrorStatus(commerceError),\n errorCode: commerceError.code,\n });\n const backendFailed = (data: Record<string, unknown> = {}) =>\n safeEmit(\n buildEvent(flow, {\n type: 'backend.failed',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n durationMs: Math.round(options.clock.monotonicMs() - backendStart),\n data: { code: commerceError.code, ...data },\n }),\n );\n\n if (deferredSettlement !== undefined) {\n await backendFailed();\n await abandonSettlement(deferredSettlement, commerceError.code);\n throw commerceError;\n }\n\n if (paymentResult !== undefined) {\n // Payment settled before the backend failed. Include its details and\n // any settlement reference in the buyer's error. Attempt to save the\n // merchant's undelivered receipt before backend.failed so that event\n // can report a failed save.\n const failedReceipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendErrorStatus(commerceError),\n protocol: request.protocol,\n payment: paymentResult,\n ...(authorization !== undefined ? { authorization } : {}),\n metadata: { delivered: false, backendErrorCode: commerceError.code },\n transactionId: flow.transactionId,\n };\n await saveReceipt(flow, failedReceipt, 'saveReceipt(backend-failed-after-settlement)');\n await backendFailed(failuresOf(flow));\n\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Payment settled but the backend call failed; the payment was not refunded automatically',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: commerceError,\n details: {\n payment: {\n status: paymentResult.status,\n provider: paymentResult.provider,\n amount: paymentResult.amount,\n currency: paymentResult.currency,\n ...(paymentResult.network !== undefined ? { network: paymentResult.network } : {}),\n ...(paymentResult.externalReference !== undefined\n ? { externalReference: paymentResult.externalReference }\n : {}),\n ...(paymentResult.payer !== undefined ? { payer: paymentResult.payer } : {}),\n ...(typeof paymentResult.metadata?.['amountBaseUnits'] === 'string'\n ? { amountBaseUnits: paymentResult.metadata['amountBaseUnits'] }\n : {}),\n ...(typeof paymentResult.metadata?.['receipt'] === 'string'\n ? { receipt: paymentResult.metadata['receipt'] }\n : {}),\n },\n },\n },\n );\n }\n\n await backendFailed();\n throw commerceError;\n }\n await recordStep(flow, { kind: 'backend-result', status: backendResponse.status });\n\n await safeEmit(\n buildEvent(flow, {\n type: 'backend.called',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: backendResponse.durationMs,\n data: { status: backendResponse.status },\n }),\n );\n\n // Hold the backend response until settlement succeeds. A refusal or\n // uncertain outcome throws before delivery.\n if (deferredSettlement !== undefined) {\n paymentResult = await settle(deferredSettlement);\n }\n\n // 7. persist receipt, emit final event, return outcome\n const receipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendResponse.status,\n durationMs: backendResponse.durationMs,\n protocol: request.protocol,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n transactionId: flow.transactionId,\n };\n\n await saveReceipt(flow, receipt, 'saveReceipt');\n\n const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);\n const failures = failuresOf(flow);\n\n await safeEmit(\n buildEvent(flow, {\n type: 'resource.delivered',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: totalDurationMs,\n ...(failures.persistenceFailures !== undefined ? { data: failures } : {}),\n }),\n );\n\n return {\n kind: 'delivered',\n requestId: request.requestId,\n transactionId: flow.transactionId,\n resourceId: resource.id,\n backendStatus: backendResponse.status,\n body: backendResponse.body,\n headers: backendResponse.headers,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n receipt,\n durationMs: totalDurationMs,\n ...failures,\n };\n }\n\n async function saveReceipt(flow: Flow, receipt: CommerceReceipt, label: string): Promise<void> {\n if (await safePersist(flow, () => options.store.saveReceipt(receipt), label, 'receipt')) {\n await recordStep(flow, { kind: 'receipt', receiptId: receipt.id });\n }\n }\n\n return { execute };\n}\n\n// Add a scheduling margin to the backend timeout when setting the journal's\n// waiting deadline; a missing result before then may still be in progress\nconst BACKEND_DEADLINE_MARGIN_MS = 5_000;\n\nfunction backendDeadline(dispatchedAt: Date, resource: CommerceResource): string {\n const timeoutMs = resource.handler.timeoutMs ?? DEFAULT_BACKEND_TIMEOUT_MS;\n return new Date(dispatchedAt.getTime() + timeoutMs + BACKEND_DEADLINE_MARGIN_MS).toISOString();\n}\n\n// The status the backend returned, which backend-http.ts puts on\n// `details.status` for a non-2xx or redirect response. 0 means no status is\n// known, as after a timeout, a transport failure or an unreadable or oversized\n// body.\nfunction backendErrorStatus(error: CommerceError): number {\n const status = error.details?.['status'];\n return typeof status === 'number' ? status : 0;\n}\n\nconst RESERVED_INPUT_KEYS: readonly string[] = [...RESERVED_INPUT_FIELDS, '__proto__'];\n\nfunction stripReservedFields(input: unknown): unknown {\n if (!isRecord(input)) return input;\n // Object.hasOwn, not `in`, which also matches inherited names\n if (!RESERVED_INPUT_KEYS.some((key) => Object.hasOwn(input, key))) return input;\n const rest: Record<string, unknown> = {};\n for (const key of Object.keys(input)) {\n // \"__proto__\" is dropped too: assigning it would call the inherited setter\n // and replace `rest`'s prototype instead of creating a data property.\n // validation.ts's own-property lookups are the primary control.\n if (!RESERVED_INPUT_KEYS.includes(key)) rest[key] = input[key];\n }\n return rest;\n}\n","// In-memory implementation of the frozen `ResourceRegistry` interface\nimport type { ProtocolName } from '../domain/common';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource';\nimport { CommerceError } from '../errors';\n\nclass ResourceRegistryImpl implements ResourceRegistry {\n private readonly byId = new Map<string, CommerceResource>();\n private readonly ordered: readonly CommerceResource[];\n\n constructor(resources: readonly CommerceResource[]) {\n for (const resource of resources) {\n if (this.byId.has(resource.id)) {\n throw new CommerceError('CONFIG_INVALID', `Duplicate resource id \"${resource.id}\"`, {\n details: { resourceId: resource.id },\n });\n }\n this.byId.set(resource.id, resource);\n }\n this.ordered = [...resources];\n }\n\n get(id: string): CommerceResource | undefined {\n return this.byId.get(id);\n }\n\n list(): readonly CommerceResource[] {\n return this.ordered;\n }\n\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[] {\n return this.ordered.filter((resource) => resource.exposedVia.includes(protocol));\n }\n\n has(id: string): boolean {\n return this.byId.has(id);\n }\n}\n\n/** Build a `ResourceRegistry` from a validated list of canonical resources */\nexport function createResourceRegistry(resources: readonly CommerceResource[]): ResourceRegistry {\n return new ResourceRegistryImpl(resources);\n}\n","/**\n * `EventSink` that persists every event to the receipt store. A store failure\n * is logged, never thrown to the caller.\n */\nimport type { CommerceEvent, EventSink } from '../domain/event';\nimport { describeError } from '../errors';\nimport type { Logger } from '../interfaces/logger';\nimport type { ReceiptStore } from '../interfaces/store';\n\nexport interface CreateStoreEventSinkOptions {\n readonly store: ReceiptStore;\n readonly logger: Logger;\n}\n\nexport function createStoreEventSink(options: CreateStoreEventSinkOptions): EventSink {\n return {\n async emit(event: CommerceEvent): Promise<void> {\n try {\n await options.store.appendEvent(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Failed to persist commerce event',\n );\n }\n },\n };\n}\n","/**\n * ACP protocol constants shared by the config layer and the adapter.\n *\n * Kept dependency-free: `src/config` reads the operation set at load time, so\n * anything imported here would become a config-load dependency too.\n */\n\n/**\n * The ACP stable snapshot this adapter implements, and the only value accepted\n * in the `API-Version` request header. Both name the same released snapshot;\n * they are separate constants because ACP versions the wire contract and the\n * header independently, and a future snapshot may accept more than one.\n *\n * Changing either means vendoring a new schema directory beside\n * `spec/2026-04-17/` - never editing the vendored one in place.\n */\nexport const ACP_SPEC_VERSION = '2026-04-17';\nexport const ACP_API_VERSION = '2026-04-17';\n\n/** Discovery path fixed by the ACP specification, never a configurable mount */\nexport const ACP_WELL_KNOWN_PATH = '/.well-known/acp.json';\n\n/**\n * The stable checkout operations, by ACP operation id. All five are required\n * when ACP is enabled: a partially configured checkout lifecycle would be\n * advertised as a whole service the seller cannot actually serve.\n */\nexport const ACP_CHECKOUT_OPERATIONS = [\n 'createCheckoutSession',\n 'updateCheckoutSession',\n 'getCheckoutSession',\n 'completeCheckoutSession',\n 'cancelCheckoutSession',\n] as const;\n\nexport type AcpCheckoutOperation = (typeof ACP_CHECKOUT_OPERATIONS)[number];\n\n/**\n * Top-level canonical-input properties each operation always supplies.\n *\n * `path` carries `{ checkout_session_id }`, `body` the ACP request document.\n */\nexport const ACP_OPERATION_INPUT_KEYS: Readonly<\n Record<AcpCheckoutOperation, readonly ('path' | 'body')[]>\n> = {\n createCheckoutSession: ['body'],\n updateCheckoutSession: ['path', 'body'],\n getCheckoutSession: ['path'],\n completeCheckoutSession: ['path', 'body'],\n cancelCheckoutSession: ['path'],\n};\n\n/**\n * Canonical-input properties an operation supplies only when the caller sends\n * them. The pinned schema lets a cancel omit its body, so a bare cancel has no\n * `body`, but one carrying `intent_trace` passes it on.\n */\nexport const ACP_OPERATION_OPTIONAL_INPUT_KEYS: Readonly<\n Partial<Record<AcpCheckoutOperation, readonly 'body'[]>>\n> = {\n cancelCheckoutSession: ['body'],\n};\n\n/** The key inside `path` that carries the checkout session id from the route */\nexport const ACP_SESSION_ID_INPUT_KEY = 'checkout_session_id';\n\n/** Media type for every ACP request and response body */\nexport const ACP_JSON_MEDIA_TYPE = 'application/json';\n\n/**\n * Protocol headers, lowercased as Node delivers them.\n *\n * `API-Version` is mandatory on checkout requests and is never defaulted:\n * answering an unversioned request as if it named the pinned snapshot would be\n * guessing on the caller's behalf about a contract that changes.\n */\nexport const ACP_API_VERSION_HEADER = 'api-version';\nexport const ACP_REQUEST_ID_HEADER = 'request-id';\nexport const ACP_IDEMPOTENCY_KEY_HEADER = 'idempotency-key';\nexport const ACP_IDEMPOTENT_REPLAYED_HEADER = 'idempotent-replayed';\n\n/**\n * Seconds a client is told to wait before retrying a key whose first request is\n * still running. Short: the original is a live HTTP call, not a queue.\n */\nexport const ACP_IN_FLIGHT_RETRY_AFTER_SECONDS = 1;\n\n/**\n * Longest `Request-Id` echoed back. The value is the caller's, so it is\n * bounded and filtered before it is ever written into a response header.\n */\nexport const ACP_MAX_REQUEST_ID_LENGTH = 128;\n\n/** Caller headers forwarded to the merchant; the bearer token stays at the gateway */\nexport const ACP_FORWARDED_HEADERS = [\n 'accept-language',\n 'user-agent',\n ACP_REQUEST_ID_HEADER,\n ACP_API_VERSION_HEADER,\n 'signature',\n 'timestamp',\n] as const;\n\n/** Maximum forwarded header value length; longer values are dropped */\nexport const ACP_MAX_FORWARDED_HEADER_LENGTH = 2048;\n\n/** Fallback and maximum `Retry-After` seconds for merchant 429 or 503 */\nexport const ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS = 5;\nexport const ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS = 300;\n"]}
|