@devlab.group/agent-commerce 2.6.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -12
- package/dist/ap2.d.ts +1 -1
- package/dist/ap2.js +5 -5
- 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-G3EYYHKF.js → chunk-DJRWYDKJ.js} +3 -3
- package/dist/{chunk-G3EYYHKF.js.map → chunk-DJRWYDKJ.js.map} +1 -1
- package/dist/{chunk-M6MQ3FYS.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-M6BSXXTF.js.map → chunk-O3ACF45K.js.map} +1 -1
- package/dist/{chunk-M6WW6QIT.js → chunk-WDD2ZUR3.js} +5 -3
- package/dist/chunk-WDD2ZUR3.js.map +1 -0
- package/dist/{chunk-M52FBNJX.js → chunk-YHNTTMED.js} +6 -4
- package/dist/chunk-YHNTTMED.js.map +1 -0
- package/dist/{chunk-DRLBML7Z.js → chunk-ZSIUZPNB.js} +175 -74
- package/dist/chunk-ZSIUZPNB.js.map +1 -0
- package/dist/cli/{ap2-2YMYA2H6.js → ap2-5FFGSW6F.js} +10 -11
- 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-VJH6RYRK.js → chunk-3NVJAQRO.js} +3 -3
- package/dist/cli/{chunk-VJH6RYRK.js.map → chunk-3NVJAQRO.js.map} +1 -1
- package/dist/cli/{chunk-GET3CZGR.js → chunk-55AI6CLW.js} +6 -4
- package/dist/cli/chunk-55AI6CLW.js.map +1 -0
- package/dist/cli/{chunk-YOF7IK4V.js → chunk-5K2JDM4G.js} +177 -76
- package/dist/cli/chunk-5K2JDM4G.js.map +1 -0
- package/dist/cli/{chunk-NSYSMDQN.js → chunk-5TID36YG.js} +57 -29
- package/dist/cli/chunk-5TID36YG.js.map +1 -0
- package/dist/cli/{chunk-3NOMLMJW.js → chunk-66NTYSXI.js} +3 -3
- package/dist/cli/{chunk-3NOMLMJW.js.map → chunk-66NTYSXI.js.map} +1 -1
- 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-YWG2ZN3L.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-PTL7SNOI.js → chunk-OETKXDGA.js} +467 -122
- package/dist/cli/chunk-OETKXDGA.js.map +1 -0
- package/dist/cli/{chunk-DHFMIBPG.js → chunk-PLHPKXAT.js} +6 -6
- package/dist/cli/{chunk-DHFMIBPG.js.map → chunk-PLHPKXAT.js.map} +1 -1
- package/dist/cli/{chunk-TFV3K6YS.js → chunk-VSSSU4AU.js} +3 -3
- package/dist/cli/{chunk-TFV3K6YS.js.map → chunk-VSSSU4AU.js.map} +1 -1
- package/dist/cli/chunk-ZCW56PZ3.js +8 -0
- package/dist/cli/{chunk-4KLYFXMW.js.map → chunk-ZCW56PZ3.js.map} +1 -1
- package/dist/cli/{chunk-AZL7RPFU.js → chunk-ZFVQWOGG.js} +64 -16
- package/dist/cli/chunk-ZFVQWOGG.js.map +1 -0
- package/dist/cli/config-WT5HHDRR.js +13 -0
- package/dist/cli/{config-3K65QJ22.js.map → config-WT5HHDRR.js.map} +1 -1
- package/dist/cli/index.js +51 -37
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-6F64A7KE.js → mcp-HHGNOUKE.js} +7 -7
- package/dist/cli/{mcp-6F64A7KE.js.map → mcp-HHGNOUKE.js.map} +1 -1
- package/dist/cli/payment-providers-EWXZFBIE.js +6 -0
- package/dist/cli/{payment-providers-2ITS6KNR.js.map → payment-providers-EWXZFBIE.js.map} +1 -1
- package/dist/cli/{provider-5BGG5YKQ.js → provider-XUPLYNQ7.js} +9 -9
- package/dist/cli/{provider-5BGG5YKQ.js.map → provider-XUPLYNQ7.js.map} +1 -1
- package/dist/cli/receipts-3DSV4DIK.js +9 -0
- package/dist/cli/{receipts-I4IIE7U6.js.map → receipts-3DSV4DIK.js.map} +1 -1
- package/dist/cli/reconcile-GS25MQ42.js +4 -0
- package/dist/cli/{reconcile-55WNCSFC.js.map → reconcile-GS25MQ42.js.map} +1 -1
- package/dist/cli/{run-2P6ZGFUE.js → run-7KLKW3HE.js} +107 -35
- package/dist/cli/run-7KLKW3HE.js.map +1 -0
- package/dist/cli/{x402-4LPIIELI.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 +23 -13
- package/dist/index.js +660 -170
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +4 -4
- package/dist/mpp.js +5 -5
- package/dist/{protocol-adapter-1WbtM3xG.d.ts → protocol-adapter-DdFL5LBU.d.ts} +12 -2
- package/dist/{runtime-B-kARa2f.d.ts → runtime-BmaSp2Ce.d.ts} +31 -3
- package/dist/{store-kIIMpUA-.d.ts → store-BVvMzpuV.d.ts} +25 -8
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +156 -2
- package/dist/testing.js.map +1 -1
- package/dist/{transaction-Dv0UFGg5.d.ts → transaction-BXXJltZ-.d.ts} +1 -1
- package/dist/x402.d.ts +7 -2
- package/dist/x402.js +7 -6
- package/dist/x402.js.map +1 -1
- package/package.json +13 -29
- package/dist/chunk-5ZYXBCDX.js.map +0 -1
- package/dist/chunk-DRLBML7Z.js.map +0 -1
- package/dist/chunk-ES3V6ECS.js.map +0 -1
- package/dist/chunk-M52FBNJX.js.map +0 -1
- package/dist/chunk-M6BSXXTF.js +0 -8
- package/dist/chunk-M6MQ3FYS.js.map +0 -1
- package/dist/chunk-M6WW6QIT.js.map +0 -1
- package/dist/cli/ap2-2YMYA2H6.js.map +0 -1
- package/dist/cli/chunk-4KLYFXMW.js +0 -8
- package/dist/cli/chunk-5K4XEAZV.js.map +0 -1
- package/dist/cli/chunk-6R6WJ4FD.js +0 -18
- package/dist/cli/chunk-6R6WJ4FD.js.map +0 -1
- package/dist/cli/chunk-AZL7RPFU.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-GET3CZGR.js.map +0 -1
- package/dist/cli/chunk-NSYSMDQN.js.map +0 -1
- package/dist/cli/chunk-PTL7SNOI.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-YOF7IK4V.js.map +0 -1
- package/dist/cli/chunk-YWG2ZN3L.js.map +0 -1
- package/dist/cli/config-3K65QJ22.js +0 -12
- package/dist/cli/payment-providers-2ITS6KNR.js +0 -6
- package/dist/cli/receipts-I4IIE7U6.js +0 -8
- package/dist/cli/reconcile-55WNCSFC.js +0 -4
- package/dist/cli/run-2P6ZGFUE.js.map +0 -1
- package/dist/cli/x402-4LPIIELI.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/domain/common.ts","../src/core/domain/event.ts","../src/core/domain/payment.ts","../src/core/domain/resource.ts","../src/core/domain/transaction.ts","../src/core/errors/codes.ts","../src/core/errors/commerce-error.ts","../src/core/domain/wire.ts","../src/core/interfaces/logger.ts","../src/core/interfaces/protocol-adapter.ts","../src/core/interfaces/runtime.ts"],"names":[],"mappings":";;;AAaA,IAAM,kBAAA,GAAiD;AAAA,EACrD,IAAA,EAAM,IAAA;AAAA,EACN,GAAA,EAAK,IAAA;AAAA,EACL,GAAA,EAAK,IAAA;AAAA,EACL,GAAA,EAAK;AACP,CAAA;AAMO,IAAM,iBAA0C,MAAA,CAAO,IAAA;AAAA,EAC5D;AACF;AAaA,IAAM,wBAAA,GAA4D,EAAE,IAAA,EAAM,IAAA,EAAM,KAAK,IAAA,EAAK;AAGnF,IAAM,uBAAqD,MAAA,CAAO,IAAA;AAAA,EACvE;AACF;;;ACrCO,IAAM,oBAAA,GAAuB;AAAA,EAClC,qBAAA;AAAA,EACA,oBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA;AAAA;AAAA,EAGA,wBAAA;AAAA,EACA,wBAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA;AACF;;;ACEO,IAAM,2BAAA,GAA8B;;;ACsBpC,IAAM,0BAAA,GAA6B;;;AChCnC,IAAM,kBAAA,GAAqB;AAAA,EAChC,iBAAA;AAAA,EACA,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OAAA,EAAS,cAAa,GACjC,MAAA;AACN,EAAA,MAAM,aAAA,GAAgB,4BAAA,CAA6B,kBAAA,EAAoB,SAAS,CAAA;AAEhF,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,GAAI,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,KAAY,EAAC;AAAA,IAC3C,GAAI,aAAA,KAAkB,MAAA,GAAY,EAAE,aAAA,KAAkB;AAAC,GACzD;AACF;;;AChWO,IAAM,WAAA,GAAsB;AAAA,EACjC,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AACf;;;AC0DO,SAAS,sBAAsB,OAAA,EAA0D;AAC9F,EAAA,OAAO,OAAQ,QAAgC,UAAA,KAAe,UAAA;AAChE;;;ACnEO,IAAM,WAAA,GAAqB;AAAA,EAChC,GAAA,EAAK,sBAAM,IAAI,IAAA,EAAK;AAAA,EACpB,MAAA,EAAQ,MAAA,iBAAM,IAAI,IAAA,IAAO,WAAA,EAAY;AAAA,EACrC,WAAA,EAAa,MAAM,WAAA,CAAY,GAAA;AACjC","file":"chunk-YHNTTMED.js","sourcesContent":["// Shared primitive aliases for the canonical domain model. FROZEN CONTRACT\n\n/**\n * A JSON Schema document (in practice a draft 2020-12 subset). Deliberately\n * loose: adapters translate it to their own schema representation. Never treat\n * it as trusted input without validation.\n */\nexport type JsonSchema = Record<string, unknown>;\n\n/** Protocol surfaces a resource can be exposed through */\nexport type ProtocolName = 'http' | 'mcp' | 'a2a' | 'acp';\n\n// A Record over the union fails to compile when a name is missing or extra\nconst PROTOCOL_NAME_KEYS: Record<ProtocolName, true> = {\n http: true,\n mcp: true,\n a2a: true,\n acp: true,\n};\n\n/**\n * The same names as a value, for code that checks one at runtime: config\n * validation and the OpenAPI importer's `--expose`\n */\nexport const PROTOCOL_NAMES: readonly ProtocolName[] = Object.keys(\n PROTOCOL_NAME_KEYS,\n) as ProtocolName[];\n\n/**\n * Payment rails a resource can accept.\n *\n * A resource's list is an ordered candidate list, not a buyer-selected menu.\n * The pipeline uses the first method with an enabled provider, and a\n * rejection ends the request instead of trying another rail. Config requires at\n * least one named rail to be enabled and permits others that are not.\n */\nexport type PaymentMethodName = 'x402' | 'mpp';\n\n// Checked for completeness the same way as PROTOCOL_NAME_KEYS\nconst PAYMENT_METHOD_NAME_KEYS: Record<PaymentMethodName, true> = { x402: true, mpp: true };\n\n/** The same names as a value, for config validation */\nexport const PAYMENT_METHOD_NAMES: readonly PaymentMethodName[] = Object.keys(\n PAYMENT_METHOD_NAME_KEYS,\n) as PaymentMethodName[];\n\n/**\n * Authorization methods a resource can require. Neither a transport nor a\n * payment rail: it proves the purchase was approved, and sits beside the\n * payment rather than replacing it.\n */\nexport type AuthorizationMethodName = 'ap2';\n\n/** ISO-8601 timestamp string, always UTC with millisecond precision */\nexport type IsoTimestamp = string;\n\n/**\n * A decimal amount as a string in the currency's display unit (for example\n * \"0.01\" USDC), never a float and never base units. Payment providers convert\n * it to on-chain base units.\n */\nexport type DecimalAmount = string;\n\n/** Health of an individual adapter or subsystem */\nexport interface AdapterHealth {\n readonly status: 'pass' | 'warn' | 'fail';\n readonly detail?: string;\n readonly checkedAt: IsoTimestamp;\n readonly durationMs?: number;\n /**\n * Results per checked part, such as each x402 offer. Names and statuses\n * may be published; exclude diagnostic detail.\n */\n readonly components?: readonly AdapterHealthComponent[];\n}\n\n/** One part of an {@link AdapterHealth} result */\nexport interface AdapterHealthComponent {\n readonly name: string;\n readonly status: 'pass' | 'warn' | 'fail';\n}\n\n/** Describes an adapter's supported surface for diagnostics */\nexport interface AdapterDescriptor {\n readonly name: string;\n readonly kind: 'protocol' | 'payment' | 'storage' | 'authorization';\n /** Version of this adapter implementation, independent of the spec */\n readonly implementationVersion: string;\n /** Exact pinned specification revision this adapter targets */\n readonly supportedSpec: string;\n readonly capabilities: readonly string[];\n readonly status: 'stable' | 'experimental' | 'planned';\n /** Capabilities explicitly not implemented, printed by `doctor` */\n readonly unsupported?: readonly string[];\n}\n","/**\n * Canonical commerce events. FROZEN CONTRACT. Every event in one flow shares\n * one `requestId`, which correlates logs, payment attempts, backend calls and\n * receipts.\n */\nimport type { IsoTimestamp } from './common';\n\nexport const COMMERCE_EVENT_TYPES = [\n 'resource.discovered',\n 'resource.requested',\n 'payment.required',\n 'payment.rejected',\n 'payment.verified',\n 'payment.settled',\n // The same two types for every authorization method, so an audit-trail\n // reader never has to know what AP2 is\n 'authorization.verified',\n 'authorization.rejected',\n 'backend.called',\n 'backend.failed',\n 'resource.delivered',\n] as const;\n\nexport type CommerceEventType = (typeof COMMERCE_EVENT_TYPES)[number];\n\nexport interface CommerceEvent {\n readonly id: string;\n readonly type: CommerceEventType;\n readonly requestId: string;\n /** Links events from one execution; optional for compatibility with pre-2.5.0 rows */\n readonly transactionId?: string;\n readonly resourceId?: string;\n readonly at: IsoTimestamp;\n /** Protocol adapter that originated the request, e.g. 'mcp' or 'http' */\n readonly adapter?: string;\n readonly paymentProvider?: string;\n readonly durationMs?: number;\n readonly status?: 'ok' | 'error';\n /** Non-secret, structured detail. Must never contain keys, headers or proofs */\n readonly data?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Sink for canonical events. `emit` must not throw: a sink failure must never\n * fail an otherwise successful commerce flow.\n */\nexport interface EventSink {\n emit(event: CommerceEvent): Promise<void>;\n}\n","/**\n * Canonical payment model. FROZEN CONTRACT.\n *\n * Core decides that a payment is required and for how much. Payment providers\n * decide how the challenge is encoded, verified and settled. No x402- or\n * EVM-specific type may appear in this file.\n */\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n DecimalAmount,\n IsoTimestamp,\n PaymentMethodName,\n} from './common';\nimport type { PaymentAttempt } from './receipt';\nimport type { CommerceResource } from './resource';\n\n/**\n * `PaymentResult.metadata` key for public coordinates returned by `verify`\n * for later provider reconciliation. Core must store the value unchanged and\n * interpret only `expiresAt`. Never include signatures, payloads or\n * transaction bytes. Experimental: may change in a minor release.\n */\nexport const RECONCILIATION_METADATA_KEY = 'reconciliation';\n\n/**\n * Provider-native payment challenge, opaque to core. For x402 the `accepts`\n * entries are x402 `PaymentRequirements` objects, passed to protocol adapters\n * verbatim.\n */\nexport interface PaymentChallenge {\n readonly provider: PaymentMethodName;\n /** Provider protocol version, e.g. the x402 `x402Version` value as a string */\n readonly version: string;\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim: for x402 v2 the\n * `PaymentRequired` object a buyer's client consumes, for MPP an object\n * carrying the serialized `WWW-Authenticate` challenge. Opaque to core.\n *\n * `accepts` alone is not that document: x402 v2 carries the resource\n * description and protocol version on the envelope. Adapters with a native\n * channel for it (x402's `PAYMENT-REQUIRED` header, MPP's `WWW-Authenticate`)\n * send it there as is, so every surface offers the same challenge.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What the buyer must pay, in canonical terms, plus the provider-native\n * challenge the buyer's client needs to construct a payment\n */\nexport interface PaymentRequirement {\n readonly id: string;\n readonly requestId: string;\n readonly resourceId: string;\n readonly provider: PaymentMethodName;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * Merchant-controlled settlement destination, never a gateway-owned wallet.\n * Multi-offer challenges omit this, `network` and `asset`; selection\n * supplies the chosen offer's terms.\n */\n readonly destination?: string;\n readonly network?: string;\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n readonly challenge: PaymentChallenge;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Opaque payment proof supplied by the buyer's client. For x402 over HTTP it is\n * the base64 `PAYMENT-SIGNATURE` header value; over MCP and A2A it is the same\n * string in the reserved `_payment` input field.\n */\nexport interface PaymentSubmission {\n readonly method: PaymentMethodName;\n readonly payload: string;\n}\n\n/** Outcome of verification or settlement */\nexport interface PaymentResult {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly provider: PaymentMethodName;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly payer?: string;\n readonly payee?: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly network?: string;\n readonly asset?: string;\n /**\n * Stable, provider-computed identity of the payment authorization.\n *\n * The pipeline reserves this key before settlement and rejects a second\n * request presenting it with `PAYMENT_REPLAYED`. Providers must derive it\n * only from the authorization (payer, nonce, asset, network), so the same\n * authorization always maps to the same key. A `rejected` result may also\n * carry it so a store lookup can identify an unfinished attempt even when\n * verification rejects the proof because its transfer has landed.\n */\n readonly replayKey?: string;\n /** Machine-readable rejection reason when status is `rejected` */\n readonly rejectionReason?: string;\n readonly settledAt?: IsoTimestamp;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Input to {@link PaymentProvider.createRequirement} */\nexport interface PaymentContext {\n readonly requestId: string;\n readonly resource: CommerceResource;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly requestedAt: IsoTimestamp;\n /**\n * Validated resource input used to build the backend request. The pipeline\n * sets this field on every createRequirement call. A rail may bind its\n * challenge to the input but must not send it to a third party.\n */\n readonly input?: unknown;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Input to {@link PaymentProvider.verify} */\nexport interface PaymentVerificationContext {\n readonly requestId: string;\n readonly resource: CommerceResource;\n readonly requirement: PaymentRequirement;\n readonly submission: PaymentSubmission;\n}\n\n/** Input to {@link PaymentProvider.settle} */\nexport interface PaymentSettlementContext extends PaymentVerificationContext {\n readonly verification: PaymentResult;\n}\n\n/** Input to {@link PaymentProvider.reconcile}. Experimental: may change in a minor release */\nexport interface PaymentReconciliationContext {\n readonly attempt: PaymentAttempt;\n /** Coordinates from `verify`; optional for compatibility with pre-2.5.0 attempts */\n readonly locator?: Readonly<Record<string, unknown>>;\n readonly now: IsoTimestamp;\n}\n\n/** Chain evidence for resolving an attempt. Experimental: may change in a minor release */\nexport interface PaymentReconciliationResult {\n /**\n * Report `settled` only with a final transfer record for this authorization.\n * Report `not-settled` only when a state read proves it unused after it can\n * no longer land; missing logs or receipts are insufficient. Otherwise,\n * report `unknown`.\n */\n readonly outcome: 'settled' | 'not-settled' | 'unknown';\n /** A machine-readable token, such as `not_final` */\n readonly reason: string;\n readonly externalReference?: string;\n /** Public chain facts only */\n readonly evidence?: Readonly<Record<string, unknown>>;\n /** For `unknown`, the earliest time a different answer is possible, if known */\n readonly retryAfter?: IsoTimestamp;\n}\n\n/**\n * Contract every payment rail implements. Implementations must be\n * non-custodial: they orchestrate an external payment protocol and never hold\n * buyer or merchant production signing keys.\n */\nexport interface PaymentProvider {\n readonly name: PaymentMethodName;\n readonly descriptor: AdapterDescriptor;\n\n /**\n * Build the requirement and its challenge. The pipeline calls it for every\n * paid request, including one that already carries a proof to verify.\n */\n createRequirement(context: PaymentContext): Promise<PaymentRequirement>;\n\n /**\n * Extract a client retry key from a proof without I/O. Return `undefined`\n * if the proof has no key; throw `INPUT_INVALID` if the key is malformed.\n * Experimental: may change in a minor release.\n */\n retryKey?(context: {\n readonly resource: CommerceResource;\n readonly submission: PaymentSubmission;\n }): string | undefined;\n\n /**\n * Selects a proof's offer before verification, returning its destination,\n * network, asset and metadata while preserving `id` and the full `challenge`.\n * Verification, authorization, replay reservation and settlement use the result.\n * This hook must not verify, reserve or settle. If no unique offer matches,\n * return the original requirement for `verify` to reject.\n */\n selectRequirement?(context: PaymentVerificationContext): Promise<PaymentRequirement>;\n\n /**\n * Validate a submitted proof against the requirement. Must return `rejected`\n * or throw a `CommerceError` rather than an untyped error, and must never\n * move funds.\n */\n verify(context: PaymentVerificationContext): Promise<PaymentResult>;\n\n /**\n * Called only after `verify` returns `verified` and the replay key is reserved.\n * Return a settlement verdict, including rejection. The pipeline records a\n * throw as `settlement-uncertain`, unless a `CommerceError` has\n * `details.settlementNotSubmitted: true`; that records `rejected` and releases\n * the authorization hold.\n */\n settle(context: PaymentSettlementContext): Promise<PaymentResult>;\n\n /**\n * Read chain evidence for an attempt with an unknown outcome. Implementations\n * must not write, broadcast or call a facilitator. Providers without this\n * hook require manual resolution. Experimental: may change in a minor release.\n */\n reconcile?(context: PaymentReconciliationContext): Promise<PaymentReconciliationResult>;\n\n health(): Promise<AdapterHealth>;\n}\n","// Canonical resource model. FROZEN CONTRACT\nimport type {\n AuthorizationMethodName,\n DecimalAmount,\n JsonSchema,\n PaymentMethodName,\n ProtocolName,\n} from './common';\n\n/** HTTP methods a backend handler may use */\nexport type BackendMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * How the gateway calls the merchant's existing backend.\n *\n * Backend URLs come from operator configuration only, never from users or\n * agents (docs/security.md, SSRF). Secret header values belong in `${ENV_VAR}`\n * placeholders resolved by the config loader, not in plaintext configuration.\n */\nexport interface BackendHandler {\n readonly type: 'http';\n readonly method: BackendMethod;\n readonly url: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Hard upper bound on the backend call. Defaults to `DEFAULT_BACKEND_TIMEOUT_MS` */\n readonly timeoutMs?: number;\n /**\n * Names the top-level input properties carrying each part of the request.\n *\n * When absent, `{param}` values come from top-level input and everything left\n * over becomes the query string (GET/DELETE) or the whole JSON body\n * (POST/PUT/PATCH). That cannot express an operation with path, query and\n * body at once, such as `POST /users/{userId}/orders?notify=true`.\n *\n * When present, each group comes from its named property, and top-level input\n * that no binding names is not forwarded.\n */\n readonly inputBindings?: {\n readonly path?: string;\n readonly query?: string;\n readonly body?: string;\n };\n}\n\n/** Default backend timeout when a resource does not specify one */\nexport const DEFAULT_BACKEND_TIMEOUT_MS = 10_000;\n\n/**\n * Canonical pricing. `dynamic` exists in the type for forward compatibility;\n * config validation rejects it and the pipeline refuses it as defense in depth.\n */\nexport type Pricing =\n | { readonly type: 'free' }\n | {\n readonly type: 'fixed';\n readonly amount: DecimalAmount;\n readonly currency: string;\n }\n | {\n readonly type: 'dynamic';\n readonly resolver: string;\n };\n\n/**\n * A merchant capability exposed to agents. Protocol adapters map it outward and\n * never define their own parallel notion of a resource.\n */\nexport interface CommerceResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly handler: BackendHandler;\n readonly pricing: Pricing;\n readonly exposedVia: readonly ProtocolName[];\n readonly paymentMethods: readonly PaymentMethodName[];\n /**\n * Authorization the buyer must present in addition to payment. Opt-in per\n * resource. It sits beside `paymentMethods`, not inside it, because an\n * authorization method is not a payment rail and must never be selectable as\n * one.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationMethodName[];\n };\n /**\n * Paid retry settings, disabled when omitted. For redelivery, the x402 provider\n * extracts `payment-identifier` IDs; the HTTP invoke route reads MPP's\n * `Idempotency-Key` header.\n * Experimental: may change in a minor release.\n */\n readonly idempotency?: {\n /** Send the backend an `Idempotency-Key` identifying this paid operation */\n readonly merchantKey?: boolean;\n /** Store delivered responses for retries with the same client key */\n readonly redelivery?: {\n /** Hours from the initial retry check to the stored response's expiry */\n readonly retentionHours: number;\n /** If true, reject a missing `id` during x402 retry-key extraction with HTTP 400 */\n readonly required: boolean;\n };\n };\n}\n\n/** Read-only view of every configured resource */\nexport interface ResourceRegistry {\n get(id: string): CommerceResource | undefined;\n list(): readonly CommerceResource[];\n /** Resources exposed through a given protocol surface */\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[];\n has(id: string): boolean;\n}\n","/**\n * Canonical transaction model. FROZEN CONTRACT.\n *\n * A transaction links a paid purchase's request, payment attempt, optional\n * authorization hold, backend call and receipt by ID. PaymentAttempt owns the\n * payment status; journal readers must read it from the attempt rather than\n * maintain a separate copy.\n */\nimport type { AuthorizationRecord } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName, ProtocolName } from './common';\nimport type { PaymentAttempt } from './receipt';\n\n/** States derived by {@link transactionState} */\nexport const TRANSACTION_STATES = [\n 'payment-pending',\n 'payment-failed',\n 'payment-uncertain',\n 'settled-undelivered',\n 'delivery-started',\n 'delivery-unknown',\n 'delivered',\n] as const;\n\n/**\n * Open to state names added by later releases; consumers must handle values\n * outside {@link TRANSACTION_STATES}\n */\nexport type TransactionState = (typeof TRANSACTION_STATES)[number] | (string & {});\n\n/** Last hold state communicated to the authorization provider */\nexport type AuthorizationHoldState = 'reserved' | 'consumed' | 'released' | 'uncertain';\n\n/**\n * Store writes reported as failed during an execution. Consumers must handle\n * unlisted labels that later releases may add.\n */\nexport type PersistenceFailure = 'payment-attempt' | 'receipt' | 'journal' | (string & {});\n\n/**\n * Journal record for a paid purchase, starting with replay reservation.\n * Store only references and digests, never payment proofs, signatures, mandates\n * or input bodies.\n */\nexport interface Transaction {\n readonly id: string;\n /** The request that created it */\n readonly requestId: string;\n readonly resourceId: string;\n readonly protocol: ProtocolName;\n /** Cached derived state; readers must recompute it with {@link transactionState} */\n readonly state: TransactionState;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly attemptId: string;\n readonly replayKey: string;\n /** Read from PaymentAttempt, not maintained independently */\n readonly status: PaymentAttempt['status'];\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly network?: string;\n readonly asset?: string;\n readonly payee?: string;\n readonly externalReference?: string;\n /**\n * Public coordinates for the provider's `reconcile` hook, governed by\n * `RECONCILIATION_METADATA_KEY`\n */\n readonly locator?: Readonly<Record<string, unknown>>;\n /** When the provider's `settle` was called */\n readonly settlingAt?: IsoTimestamp;\n /** The authorization cannot land after this */\n readonly expiresAt?: IsoTimestamp;\n };\n readonly authorization?: AuthorizationRecord & {\n /** The handle the authorization provider consumes or releases */\n readonly reservationId: string;\n readonly hold: AuthorizationHoldState;\n };\n readonly backend?: {\n readonly dispatchedAt: IsoTimestamp;\n /** Dispatch time plus the backend timeout and a margin */\n readonly deadlineAt: IsoTimestamp;\n /** 0 if the call ended without a status, such as a timeout or transport failure */\n readonly status?: number;\n readonly errorCode?: string;\n };\n readonly receiptId?: string;\n /** `sha256:` followed by the canonical JSON input digest in hex; omit for non-I-JSON input */\n readonly inputDigest?: string;\n /** Digest of pricing and settlement terms, excluding credentials */\n readonly configDigest: string;\n readonly persistenceFailures?: readonly PersistenceFailure[];\n readonly createdAt: IsoTimestamp;\n readonly updatedAt: IsoTimestamp;\n /** Time of the pipeline's last journal write before returning the outcome */\n readonly completedAt?: IsoTimestamp;\n}\n\n/** What {@link transactionState} reads */\nexport type TransactionFacts = Pick<Transaction, 'backend' | 'completedAt'> & {\n readonly payment: Pick<Transaction['payment'], 'status'>;\n};\n\nconst isSuccess = (status: number): boolean => status >= 200 && status <= 299;\n\n/**\n * Derive state from payment status, backend facts and pipeline completion.\n * For a settled payment, a dispatched call with no result after `deadlineAt`\n * means `delivery-unknown`; a timeout does not prove that the backend never ran.\n */\nexport function transactionState(\n facts: TransactionFacts,\n now: IsoTimestamp,\n): (typeof TRANSACTION_STATES)[number] {\n const { payment, backend, completedAt } = facts;\n if (payment.status === 'settlement-uncertain' || payment.status === 'failed') {\n return 'payment-uncertain';\n }\n if (payment.status === 'rejected') return 'payment-failed';\n\n // Invalid timestamps make the comparison false, treating the deadline as passed\n const waiting =\n backend !== undefined &&\n completedAt === undefined &&\n Date.parse(now) < Date.parse(backend.deadlineAt);\n if (payment.status !== 'settled') {\n return waiting && backend?.status === undefined ? 'delivery-started' : 'payment-pending';\n }\n\n if (backend === undefined) return 'settled-undelivered';\n const { status } = backend;\n if (status !== undefined && status !== 0 && !isSuccess(status)) return 'settled-undelivered';\n if (status !== undefined && isSuccess(status) && completedAt !== undefined) return 'delivered';\n // Wait until the deadline for a missing result or an unfinished 2xx flow.\n // Status 0 means the call already ended without a response.\n if (status !== 0 && waiting) return 'delivery-started';\n return 'delivery-unknown';\n}\n","/**\n * 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, by default */\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 /** Override the code's default retryability for this error instance */\n readonly retryable?: boolean;\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 = options.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","/**\n * Gateway-defined wire envelopes and carriers. FROZEN CONTRACT.\n *\n * The HTTP routes and the MCP and A2A adapters build their \"payment required\"\n * and \"error\" bodies with these helpers, so those surfaces send the same\n * shapes. The ACP adapter maps errors to ACP's own error format instead.\n */\n\nimport { CommerceError, type CommerceErrorCode } from '../errors';\nimport { isRecord } from '../is-record';\nimport type { AuthorizationRequirement, AuthorizationSubmission } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName } from './common';\nimport type { PaymentSubmission } from './payment';\nimport type { DeliveredOutcome, PaymentRequiredOutcome } from './request';\nimport type { CommerceResource } from './resource';\n\n/**\n * Reserved input property carrying a payment proof on protocols with no header\n * channel (MCP tool calls, A2A message data). HTTP uses a header instead.\n */\nexport const PAYMENT_INPUT_FIELD = '_payment';\n\n/**\n * HTTP request header carrying an x402 payment proof. MPP proofs use\n * `Authorization: Payment ...` instead.\n *\n * The x402 v2 header names, lowercased as Node presents incoming headers. v1's\n * `X-PAYMENT` / `X-PAYMENT-RESPONSE` pair is not accepted: honoring both\n * versions would mean two verification paths for the same money.\n */\nexport const PAYMENT_HEADER = 'payment-signature';\n\n/** HTTP response header carrying the settlement result */\nexport const PAYMENT_RESPONSE_HEADER = 'payment-response';\n\n/**\n * Reserved input property carrying an authorization proof, the counterpart of\n * {@link PAYMENT_INPUT_FIELD}.\n *\n * `_payment` is a bare string whose method is taken from the resource's first\n * payment method. This field is a `{ method, payload }` object, because the\n * method of a security control should be stated, not inferred.\n */\nexport const AUTHORIZATION_INPUT_FIELD = '_authorization';\n\n/**\n * Every input property name the gateway claims for itself. The config loader\n * rejects a resource declaring one, protocol adapters lift them out of client\n * input, and the pipeline strips them again as defense in depth.\n */\nexport const RESERVED_INPUT_FIELDS: readonly string[] = [\n PAYMENT_INPUT_FIELD,\n AUTHORIZATION_INPUT_FIELD,\n];\n\n/**\n * HTTP request header carrying the authorization proof: base64url-encoded JSON\n * of the same `{ method, payload }` object the reserved input field carries.\n *\n * An Agent Commerce carrier, not a header from any authorization\n * specification. It is namespaced rather than reusing `Authorization`, which\n * already carries other credentials, including MPP payment proofs.\n */\nexport const AUTHORIZATION_HEADER = 'agent-authorization';\n\n/**\n * Hard cap on the encoded `Agent-Authorization` header.\n *\n * Node's default limit is 16 KiB across all request headers, and a request over\n * it is refused before the gateway sees it. Capping well below that gives an\n * oversized proof a deterministic `AUTHORIZATION_INVALID` naming the limit.\n */\nexport const MAX_AUTHORIZATION_HEADER_BYTES = 8192;\n\n/**\n * HTTP response header carrying the base64 x402 challenge on a 402.\n *\n * The body still carries the richer {@link PaymentRequiredEnvelope}, the only\n * channel MCP has, but an x402 v2 client reads the challenge from this header\n * and ignores the body, so both are sent.\n */\nexport const PAYMENT_REQUIRED_HEADER = 'payment-required';\n\n/**\n * Key under which a protocol adapter attaches a {@link DeliverySummary} to its\n * result metadata: MCP's `CallToolResult._meta` and the A2A task artifact's\n * metadata.\n *\n * Part of the frozen contract because producer and consumer must agree on it;\n * both import this constant. Follows MCP's `<namespace>/<name>` convention for\n * `_meta` keys.\n */\nexport const DELIVERY_SUMMARY_META_KEY = 'agent-commerce/delivery';\n\nexport interface PaymentRequiredEnvelope {\n readonly status: 'payment-required';\n readonly code: 'PAYMENT_REQUIRED';\n readonly requestId: string;\n readonly resourceId: string;\n readonly message: string;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly version: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `payTo`; MPP challenges use\n * `request.recipient`. Omitted for multi-offer x402 challenges.\n */\n readonly destination?: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `network`; MPP challenges use\n * the numeric `request.methodDetails.chainId`\n */\n readonly network?: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `asset`; MPP challenges use\n * `request.currency`\n */\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n /** Provider-native requirement objects, passed through verbatim */\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim (see\n * {@link PaymentChallenge.envelope}). Present for providers that have one;\n * a buyer's protocol client can hand it straight to its SDK.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n };\n /**\n * Present only when the resource also requires an authorization proof, so a\n * client learns before it spends anything that paying alone will not get the\n * resource delivered. A client that ignores the field sees the plain\n * envelope. The proof comes from the merchant's own approval flow, outside\n * the gateway.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationRequirement[];\n };\n}\n\nexport interface ErrorEnvelope {\n readonly status: 'error';\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a buyer learns about their own completed purchase: the request, whether\n * it settled, and the settlement reference they can check on-chain. The\n * merchant's ledger is not theirs to read, which is why `/api/receipts` is an\n * operator route behind `server.adminToken`.\n */\nexport interface DeliverySummary {\n readonly requestId: string;\n readonly resourceId: string;\n readonly receiptId: string;\n /** `false` marks a failed receipt write; do not treat `receiptId` as proof of persistence */\n readonly receiptCommitted?: false;\n readonly deliveredAt: IsoTimestamp;\n readonly payment?: {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly amount: DecimalAmount;\n readonly currency: string;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly network?: string;\n };\n /**\n * True when this request reuses a stored response without another charge.\n * Experimental: may change in a minor release.\n */\n readonly redelivered?: boolean;\n}\n\n/** Build the payer-facing summary of a delivered outcome */\nexport function toDeliverySummary(outcome: DeliveredOutcome): DeliverySummary {\n const p = outcome.payment;\n return {\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n receiptId: outcome.receipt.id,\n ...(outcome.persistenceFailures?.includes('receipt') ? { receiptCommitted: false } : {}),\n deliveredAt: outcome.receipt.deliveredAt,\n ...(p !== undefined\n ? {\n payment: {\n status: p.status,\n amount: p.amount,\n currency: p.currency,\n ...(p.externalReference !== undefined\n ? { externalReference: p.externalReference }\n : {}),\n ...(p.network !== undefined ? { network: p.network } : {}),\n },\n }\n : {}),\n // Omit the flag from original deliveries to preserve the existing summary shape\n ...(outcome.redelivered === true ? { redelivered: true } : {}),\n };\n}\n\nexport function toPaymentRequiredEnvelope(\n outcome: PaymentRequiredOutcome,\n): PaymentRequiredEnvelope {\n const r = outcome.requirement;\n return {\n status: 'payment-required',\n code: 'PAYMENT_REQUIRED',\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n message: `Payment of ${r.amount} ${r.currency} is required for resource \"${outcome.resourceId}\". Retry with a ${r.provider} payment proof.`,\n payment: {\n provider: r.provider,\n version: r.challenge.version,\n amount: r.amount,\n currency: r.currency,\n ...(r.destination !== undefined ? { destination: r.destination } : {}),\n ...(r.network !== undefined ? { network: r.network } : {}),\n ...(r.asset !== undefined ? { asset: r.asset } : {}),\n ...(r.expiresAt !== undefined ? { expiresAt: r.expiresAt } : {}),\n accepts: r.challenge.accepts,\n ...(r.challenge.envelope !== undefined ? { envelope: r.challenge.envelope } : {}),\n },\n ...(outcome.authorization !== undefined && outcome.authorization.length > 0\n ? { authorization: { required: outcome.authorization } }\n : {}),\n };\n}\n\nexport function toErrorEnvelope(error: CommerceError): ErrorEnvelope {\n const info = error.toInfo();\n return {\n status: 'error',\n code: info.code,\n message: info.message,\n retryable: info.retryable,\n ...(info.requestId !== undefined ? { requestId: info.requestId } : {}),\n ...(info.resourceId !== undefined ? { resourceId: info.resourceId } : {}),\n ...(info.details !== undefined ? { details: info.details } : {}),\n };\n}\n\nexport function isPaymentRequiredEnvelope(value: unknown): value is PaymentRequiredEnvelope {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as PaymentRequiredEnvelope).status === 'payment-required' &&\n typeof (value as PaymentRequiredEnvelope).payment === 'object'\n );\n}\n\n/**\n * Parses the `{ method, payload }` authorization object, whichever carrier\n * brought it. Absent returns `undefined`; malformed throws\n * `AUTHORIZATION_INVALID`.\n *\n * An unusable `_payment` is dropped, which leaves the buyer a 402 to act on. A\n * dropped authorization would instead come back as \"not authorized\", with no\n * way to tell a rejected mandate from a typo in the object around it.\n */\nexport function parseAuthorizationSubmission(\n value: unknown,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n if (value === undefined || value === null) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (!isRecord(value)) {\n return fail(`expected an object with \"method\" and \"payload\", got ${typeof value}`);\n }\n const method = value['method'];\n const payload = value['payload'];\n\n // Compared against the literal rather than a registry: a second method needs\n // a second verifier, a deliberate addition rather than a string that starts\n // working because a client sent it\n if (method !== 'ap2') {\n fail(`unsupported method ${typeof method === 'string' ? `\"${method}\"` : typeof method}`);\n }\n if (typeof payload !== 'string' || payload.length === 0) {\n fail('\"payload\" must be a non-empty string');\n }\n\n return { method: 'ap2', payload: payload as string };\n}\n\n/**\n * Decodes the base64url JSON `Agent-Authorization` header. The size check runs\n * on the encoded value, so an oversized header costs a length comparison rather\n * than a decode and a JSON parse.\n */\nexport function parseAuthorizationHeader(\n raw: string | readonly string[] | undefined,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n const value = Array.isArray(raw) ? raw[0] : (raw as string | undefined);\n if (value === undefined || value.length === 0) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (Buffer.byteLength(value, 'utf8') > MAX_AUTHORIZATION_HEADER_BYTES) {\n fail(`header exceeds the ${MAX_AUTHORIZATION_HEADER_BYTES}-byte limit`);\n }\n\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));\n } catch {\n // Nothing from the exception is repeated back: a JSON parse error quotes\n // the input it choked on, which here is whatever the caller sent\n fail('header is not base64url-encoded JSON');\n }\n return parseAuthorizationSubmission(decoded, requestId);\n}\n\n/**\n * Splits raw client input into resource input plus the reserved fields, for\n * protocols that carry them in the input object (MCP tool arguments, A2A\n * message data). HTTP carries both in headers.\n *\n * A payment proof is labeled with the resource's first payment method.\n * `createGateway` puts provider-backed methods first so the label matches the\n * pipeline's selection; a custom registry must keep that order. A resource with\n * no payment method gets no payment proof, so the request reaches the pipeline\n * unpaid.\n */\nexport function extractReservedInputFields(\n rawInput: Record<string, unknown>,\n resource: CommerceResource | undefined,\n requestId?: string,\n): {\n input: Record<string, unknown>;\n payment?: PaymentSubmission;\n authorization?: AuthorizationSubmission;\n} {\n const {\n [PAYMENT_INPUT_FIELD]: paymentValue,\n [AUTHORIZATION_INPUT_FIELD]: authorizationValue,\n ...input\n } = rawInput;\n\n const method = resource?.paymentMethods[0];\n const payment =\n typeof paymentValue === 'string' && paymentValue.length > 0 && method !== undefined\n ? ({ method, payload: paymentValue } satisfies PaymentSubmission)\n : undefined;\n const authorization = parseAuthorizationSubmission(authorizationValue, requestId);\n\n return {\n input,\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n","/**\n * Minimal structural logger. Core does not depend on pino; the gateway injects\n * a pino instance that satisfies this shape.\n *\n * Never log secrets: private keys, seed phrases, Authorization headers or\n * payment authorization payloads.\n */\nexport interface Logger {\n debug(obj: Record<string, unknown>, msg?: string): void;\n info(obj: Record<string, unknown>, msg?: string): void;\n warn(obj: Record<string, unknown>, msg?: string): void;\n error(obj: Record<string, unknown>, msg?: string): void;\n child(bindings: Record<string, unknown>): Logger;\n}\n\n/** A logger that discards everything */\nexport const NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n","/**\n * Protocol adapter boundary. FROZEN CONTRACT.\n *\n * An adapter translates a protocol's wire format into a `CanonicalRequest`,\n * hands it to the execution pipeline and maps the outcome back. It must not\n * call merchant backends, implement payment logic or hold its own copy of the\n * canonical model. A failure while starting or serving one adapter must not\n * stop the others.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AdapterDescriptor, AdapterHealth, ProtocolName } from '../domain/common';\nimport type { EventSink } from '../domain/event';\nimport type { ExecutionPipeline } from '../domain/request';\nimport type { ResourceRegistry } from '../domain/resource';\nimport type { Logger } from './logger';\nimport type { Clock, IdGenerator } from './runtime';\n\n/** Everything an adapter is given. Nothing else is available to it */\nexport interface ProtocolAdapterContext {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n /** Externally reachable base URL of the gateway, from config */\n readonly publicBaseUrl: string;\n}\n\nexport interface ProtocolAdapter {\n readonly name: ProtocolName;\n readonly descriptor: AdapterDescriptor;\n\n start(context: ProtocolAdapterContext): Promise<void>;\n health(): Promise<AdapterHealth>;\n stop(): Promise<void>;\n}\n\n/**\n * A protocol adapter served over HTTP. The gateway mounts `handleHttp` at\n * `mountPath` with raw Node request and response objects, so adapters stay\n * independent of the HTTP framework.\n *\n * Guarantee: `req` arrives with its body stream unread. The gateway suppresses\n * every body parser on the mount, so an adapter whose SDK reads the body itself\n * (MCP's Streamable HTTP transport) can do so. The adapter owns reading,\n * size-limiting beyond the gateway's own cap, and parsing.\n *\n * The guarantee can break silently. Fastify prefers its exact-match\n * `application/json` and `text/plain` parsers over a `'*'` wildcard, so a\n * wildcard no-op alone lets the JSON parser drain the body and the adapter\n * reads an empty stream. The MCP conformance suite drives `handleHttp` over a\n * bare `node:http` server and cannot catch it, so any change to adapter mounting\n * needs a test that POSTs a JSON body through the real gateway and asserts the\n * adapter received it intact.\n */\nexport interface HttpProtocolAdapter extends ProtocolAdapter {\n /** Path prefix the gateway mounts this adapter at, e.g. '/mcp' */\n readonly mountPath: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n /**\n * Fixed paths this adapter owns outside its mount, for protocols whose\n * specification pins a discovery URL (A2A's `/.well-known/agent-card.json`).\n * The gateway mounts them with the same guarantees as `mountPath`: unread\n * body, concurrency cap and failure isolation.\n */\n readonly additionalHttpRoutes?: readonly AdapterHttpRoute[];\n}\n\n/**\n * One fixed, method-scoped route owned by an adapter. Unlike `mountPath` it\n * registers no wildcard and matches exactly the path given.\n */\nexport interface AdapterHttpRoute {\n readonly method: 'GET' | 'POST';\n /** Absolute gateway path, e.g. '/.well-known/agent-card.json' */\n readonly path: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n}\n\nexport function isHttpProtocolAdapter(adapter: ProtocolAdapter): adapter is HttpProtocolAdapter {\n return typeof (adapter as HttpProtocolAdapter).handleHttp === 'function';\n}\n","// Time and ids are injected so tests can be deterministic\nimport type { IsoTimestamp } from '../domain/common';\n\nexport interface Clock {\n now(): Date;\n nowIso(): IsoTimestamp;\n /** Milliseconds since an arbitrary origin; use for durations only */\n monotonicMs(): number;\n}\n\nexport interface IdGenerator {\n /** Opaque, collision-resistant identifier */\n next(prefix?: string): string;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n nowIso: () => new Date().toISOString(),\n monotonicMs: () => performance.now(),\n};\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { isWellKnownDevKey, findX402Network, normalizeAddress, assertPayToIsNotDevAddress, resolveX402Deployment, assertDevKeyIsLocalOnly, describeRpc, canonicalJson, X402_DEFAULT_PAYMENT_FLOW, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, SETTLE_AFTER_BACKEND_METADATA_KEY, sameAddress, LOCAL_CHAIN_ID, isTransactionReference, x402OfferName, isEvmAddress, describeDeploymentMode } from './chunk-
|
|
2
|
-
import { PACKAGE_VERSION } from './chunk-
|
|
3
|
-
import { CommerceError, systemClock, NOOP_LOGGER, redactedErrorText, RECONCILIATION_METADATA_KEY, isCommerceError } from './chunk-
|
|
1
|
+
import { isWellKnownDevKey, findX402Network, normalizeAddress, assertPayToIsNotDevAddress, resolveX402Deployment, assertDevKeyIsLocalOnly, describeRpc, canonicalJson, X402_DEFAULT_PAYMENT_FLOW, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, SETTLE_AFTER_BACKEND_METADATA_KEY, sameAddress, LOCAL_CHAIN_ID, isTransactionReference, x402OfferName, CDP_FACILITATOR_URL, isEvmAddress, describeDeploymentMode } from './chunk-EMKITGVV.js';
|
|
2
|
+
import { PACKAGE_VERSION } from './chunk-O3ACF45K.js';
|
|
3
|
+
import { CommerceError, systemClock, NOOP_LOGGER, redactedErrorText, RECONCILIATION_METADATA_KEY, isCommerceError } from './chunk-YHNTTMED.js';
|
|
4
4
|
import { LOCATOR_VERSION, eip3009Locator, computeReplayKey, permit2Locator, computePermit2ReplayKey, isoFromSeconds } from './chunk-GA3O2A7R.js';
|
|
5
5
|
import { isRecord } from './chunk-2CJNA7MS.js';
|
|
6
6
|
import { x402ExactPermit2ProxyAddress, toFacilitatorEvmSigner, PERMIT2_ADDRESS, eip3009ABI, x402ExactPermit2ProxyABI } from '@x402/evm';
|
|
@@ -8,9 +8,9 @@ import { parseAbi, isAddress, keccak256, stringToBytes, isHash, getAddress, form
|
|
|
8
8
|
import { privateKeyToAccount } from 'viem/accounts';
|
|
9
9
|
import { HTTPFacilitatorClient } from '@x402/core/http';
|
|
10
10
|
import { SettleError, VerifyError } from '@x402/core/types';
|
|
11
|
+
import { randomBytes, createPrivateKey, sign } from 'crypto';
|
|
11
12
|
import { x402Facilitator } from '@x402/core/facilitator';
|
|
12
13
|
import { registerExactEvmScheme } from '@x402/evm/exact/facilitator';
|
|
13
|
-
import { randomBytes } from 'crypto';
|
|
14
14
|
import { PaymentPayloadV2Schema } from '@x402/core/schemas';
|
|
15
15
|
|
|
16
16
|
// src/payments/x402/provider/constants.ts
|
|
@@ -426,32 +426,71 @@ function createLocalFacilitatorClient(rpcUrl, signerPrivateKey, chainId) {
|
|
|
426
426
|
transport: http(rpcUrl)
|
|
427
427
|
}).extend(publicActions);
|
|
428
428
|
}
|
|
429
|
-
var
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
const
|
|
433
|
-
(mod) => mod.createCdpAuthHeaders(apiKeyId, apiKeySecret),
|
|
434
|
-
(cause) => {
|
|
435
|
-
throw new CommerceError(
|
|
436
|
-
"CONFIG_INVALID",
|
|
437
|
-
'x402 provider: facilitator.auth.type is "cdp", which needs the optional peer "@coinbase/x402". Install it (npm install @coinbase/x402), or use a facilitator that accepts a static token with auth.type "bearer".',
|
|
438
|
-
{ cause }
|
|
439
|
-
);
|
|
440
|
-
}
|
|
441
|
-
);
|
|
442
|
-
loading.catch(() => {
|
|
443
|
-
});
|
|
429
|
+
var TOKEN_LIFETIME_SECONDS = 120;
|
|
430
|
+
function createCdpAuthHeaders(apiKeyId, apiKeySecret, now = Date.now) {
|
|
431
|
+
const signingKey = readKey(apiKeySecret);
|
|
432
|
+
const { host, pathname } = new URL(CDP_FACILITATOR_URL);
|
|
444
433
|
return async () => {
|
|
445
|
-
|
|
446
|
-
if (!create) {
|
|
434
|
+
if (!signingKey) {
|
|
447
435
|
throw new CommerceError(
|
|
448
|
-
"
|
|
449
|
-
"x402 provider:
|
|
436
|
+
"CONFIG_INVALID",
|
|
437
|
+
"x402 provider: facilitator.auth.apiKeySecret is not a CDP API key secret. Use the PEM EC private key or the base64 Ed25519 key that CDP issued."
|
|
450
438
|
);
|
|
451
439
|
}
|
|
452
|
-
|
|
440
|
+
const issuedAt = Math.floor(now() / 1e3);
|
|
441
|
+
const header = (method, route) => ({
|
|
442
|
+
Authorization: `Bearer ${signJwt(signingKey, apiKeyId, `${method} ${host}${pathname}/${route}`, issuedAt)}`
|
|
443
|
+
});
|
|
444
|
+
return {
|
|
445
|
+
verify: header("POST", "verify"),
|
|
446
|
+
settle: header("POST", "settle"),
|
|
447
|
+
supported: header("GET", "supported")
|
|
448
|
+
};
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
function readKey(secret) {
|
|
452
|
+
try {
|
|
453
|
+
if (secret.includes("-----BEGIN")) {
|
|
454
|
+
const key2 = createPrivateKey(secret);
|
|
455
|
+
const p256 = key2.asymmetricKeyType === "ec" && key2.asymmetricKeyDetails?.namedCurve === "prime256v1";
|
|
456
|
+
return p256 ? { alg: "ES256", key: key2 } : void 0;
|
|
457
|
+
}
|
|
458
|
+
const raw = Buffer.from(secret, "base64");
|
|
459
|
+
if (raw.length !== 64) return void 0;
|
|
460
|
+
const key = createPrivateKey({
|
|
461
|
+
format: "jwk",
|
|
462
|
+
key: {
|
|
463
|
+
kty: "OKP",
|
|
464
|
+
crv: "Ed25519",
|
|
465
|
+
d: raw.subarray(0, 32).toString("base64url"),
|
|
466
|
+
x: raw.subarray(32).toString("base64url")
|
|
467
|
+
}
|
|
468
|
+
});
|
|
469
|
+
return { alg: "EdDSA", key };
|
|
470
|
+
} catch {
|
|
471
|
+
return void 0;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
function signJwt(signingKey, apiKeyId, uri, issuedAt) {
|
|
475
|
+
const { alg, key } = signingKey;
|
|
476
|
+
const header = { alg, kid: apiKeyId, typ: "JWT", nonce: randomBytes(16).toString("hex") };
|
|
477
|
+
const claims = {
|
|
478
|
+
sub: apiKeyId,
|
|
479
|
+
iss: "cdp",
|
|
480
|
+
uris: [uri],
|
|
481
|
+
iat: issuedAt,
|
|
482
|
+
nbf: issuedAt,
|
|
483
|
+
exp: issuedAt + TOKEN_LIFETIME_SECONDS
|
|
453
484
|
};
|
|
485
|
+
const input = `${base64url(header)}.${base64url(claims)}`;
|
|
486
|
+
const signature = alg === "ES256" ? sign("sha256", Buffer.from(input), { key, dsaEncoding: "ieee-p1363" }) : sign(null, Buffer.from(input), key);
|
|
487
|
+
return `${input}.${signature.toString("base64url")}`;
|
|
454
488
|
}
|
|
489
|
+
var base64url = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
490
|
+
|
|
491
|
+
// src/payments/x402/facilitator.ts
|
|
492
|
+
var SETTLEMENT_CONFIRMATION_TIMEOUT_MS = 6e4;
|
|
493
|
+
var SUPPORTED_TIMEOUT_MS = 1e4;
|
|
455
494
|
function verdictFromVerifyError(err) {
|
|
456
495
|
if (err instanceof VerifyError && err.statusCode === 400 && typeof err.invalidReason === "string") {
|
|
457
496
|
return {
|
|
@@ -483,7 +522,7 @@ function createRemoteFacilitatorBinding(options) {
|
|
|
483
522
|
return { verify: headers, settle: headers, supported: headers };
|
|
484
523
|
};
|
|
485
524
|
} else if (auth.type === "cdp") {
|
|
486
|
-
createAuthHeaders =
|
|
525
|
+
createAuthHeaders = createCdpAuthHeaders(auth.apiKeyId, auth.apiKeySecret);
|
|
487
526
|
}
|
|
488
527
|
const client = new HTTPFacilitatorClient({
|
|
489
528
|
url: options.url,
|
|
@@ -634,10 +673,10 @@ function resolveOffers(inputs, options) {
|
|
|
634
673
|
let remoteBinding;
|
|
635
674
|
let mode;
|
|
636
675
|
const built = /* @__PURE__ */ new Map();
|
|
637
|
-
const resolveList = (list,
|
|
676
|
+
const resolveList = (list, field2) => {
|
|
638
677
|
const seen = /* @__PURE__ */ new Set();
|
|
639
678
|
return list.map((input, index) => {
|
|
640
|
-
const at = (name) =>
|
|
679
|
+
const at = (name) => field2(index, name);
|
|
641
680
|
const known = findX402Network(input.network, options.customNetworks);
|
|
642
681
|
if (known !== void 0 && known.family !== "evm") {
|
|
643
682
|
const shape = known.family === "svm" ? "a Solana address (base58, 32 bytes)" : "a NEAR account ID";
|
|
@@ -793,6 +832,104 @@ function offerCurrency(offer, quoted) {
|
|
|
793
832
|
const canonical = offer.profile.canonicalAsset;
|
|
794
833
|
return canonical !== void 0 && sameAddress(offer.profile, offer.asset, canonical.address) ? canonical.symbol : quoted;
|
|
795
834
|
}
|
|
835
|
+
function decodePaymentSubmission(payloadBase64) {
|
|
836
|
+
const json = decodeJson(payloadBase64);
|
|
837
|
+
if (json === void 0) return void 0;
|
|
838
|
+
const result = PaymentPayloadV2Schema.safeParse(json);
|
|
839
|
+
return result.success ? result.data : void 0;
|
|
840
|
+
}
|
|
841
|
+
function declaredX402Version(payloadBase64) {
|
|
842
|
+
const json = decodeJson(payloadBase64);
|
|
843
|
+
return typeof json === "object" && json !== null ? json["x402Version"] : void 0;
|
|
844
|
+
}
|
|
845
|
+
function forFacilitator(payload) {
|
|
846
|
+
const { resource: _resource, extensions: _extensions, ...rest } = payload;
|
|
847
|
+
return rest;
|
|
848
|
+
}
|
|
849
|
+
function decodeJson(payloadBase64) {
|
|
850
|
+
try {
|
|
851
|
+
return JSON.parse(Buffer.from(payloadBase64, "base64").toString("utf8"));
|
|
852
|
+
} catch {
|
|
853
|
+
return void 0;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
function isExactEvmPayload(payload) {
|
|
857
|
+
const inner = payload.payload;
|
|
858
|
+
return payload.accepted.scheme === "exact" && isRecord(inner) && isRecord(inner["authorization"]) && !("permit2Authorization" in inner) && typeof inner["signature"] === "string";
|
|
859
|
+
}
|
|
860
|
+
var UINT256 = /^(0|[1-9]\d{0,77})$/;
|
|
861
|
+
var UINT256_MAX = 2n ** 256n - 1n;
|
|
862
|
+
var BYTES32 = /^0x[0-9a-fA-F]{64}$/;
|
|
863
|
+
var isUint256 = (value) => typeof value === "string" && UINT256.test(value) && BigInt(value) <= UINT256_MAX;
|
|
864
|
+
function hasEip3009Fields(authorization) {
|
|
865
|
+
return isEvmAddress(authorization["from"]) && isEvmAddress(authorization["to"]) && isUint256(authorization["value"]) && isUint256(authorization["validAfter"]) && isUint256(authorization["validBefore"]) && typeof authorization["nonce"] === "string" && BYTES32.test(authorization["nonce"]);
|
|
866
|
+
}
|
|
867
|
+
function isExactPermit2Payload(payload) {
|
|
868
|
+
const inner = payload.payload;
|
|
869
|
+
if (payload.accepted.scheme !== "exact" || !isRecord(inner)) return false;
|
|
870
|
+
const auth = inner["permit2Authorization"];
|
|
871
|
+
if (!isRecord(auth) || "authorization" in inner || typeof inner["signature"] !== "string") {
|
|
872
|
+
return false;
|
|
873
|
+
}
|
|
874
|
+
const { permitted, witness } = auth;
|
|
875
|
+
return isRecord(permitted) && isRecord(witness) && isEvmAddress(auth["from"]) && isEvmAddress(auth["spender"]) && isEvmAddress(permitted["token"]) && isEvmAddress(witness["to"]) && isUint256(permitted["amount"]) && isUint256(auth["nonce"]) && isUint256(auth["deadline"]) && isUint256(witness["validAfter"]);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// src/payments/x402/provider/payment-id.ts
|
|
879
|
+
var PAYMENT_IDENTIFIER = "payment-identifier";
|
|
880
|
+
var ID_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;
|
|
881
|
+
var field = (value, key) => isRecord(value) ? value[key] : void 0;
|
|
882
|
+
function paymentIdentifierExtensions(resource) {
|
|
883
|
+
const redelivery = resource.idempotency?.redelivery;
|
|
884
|
+
if (redelivery === void 0) return void 0;
|
|
885
|
+
return {
|
|
886
|
+
[PAYMENT_IDENTIFIER]: {
|
|
887
|
+
info: { required: redelivery.required },
|
|
888
|
+
schema: {
|
|
889
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
890
|
+
type: "object",
|
|
891
|
+
properties: {
|
|
892
|
+
required: { type: "boolean" },
|
|
893
|
+
id: { type: "string", minLength: 16, maxLength: 128, pattern: "^[a-zA-Z0-9_-]+$" }
|
|
894
|
+
},
|
|
895
|
+
required: ["required"]
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
function paymentRetryKey(context) {
|
|
901
|
+
const { resource, submission } = context;
|
|
902
|
+
const redelivery = resource.idempotency?.redelivery;
|
|
903
|
+
if (redelivery === void 0) return void 0;
|
|
904
|
+
const payload = decodePaymentSubmission(submission.payload);
|
|
905
|
+
if (payload === void 0) return void 0;
|
|
906
|
+
const extension = payload.extensions?.[PAYMENT_IDENTIFIER];
|
|
907
|
+
const info = field(extension, "info");
|
|
908
|
+
if (extension !== void 0 && !isRecord(info)) throw invalid(resource);
|
|
909
|
+
const id = field(info, "id");
|
|
910
|
+
if (id === void 0) {
|
|
911
|
+
if (!redelivery.required) return void 0;
|
|
912
|
+
throw new CommerceError("INPUT_INVALID", "This resource requires a payment identifier", {
|
|
913
|
+
resourceId: resource.id,
|
|
914
|
+
details: { reason: "payment_identifier_required" }
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
if (typeof id !== "string" || !ID_PATTERN.test(id)) throw invalid(resource);
|
|
918
|
+
return id;
|
|
919
|
+
}
|
|
920
|
+
function paymentIdentifierEchoed(envelope, payload) {
|
|
921
|
+
const declared = field(field(field(envelope, "extensions"), PAYMENT_IDENTIFIER), "info");
|
|
922
|
+
const echoed = payload.extensions?.[PAYMENT_IDENTIFIER];
|
|
923
|
+
if (!isRecord(declared) || echoed === void 0) return true;
|
|
924
|
+
return field(field(echoed, "info"), "required") === declared["required"];
|
|
925
|
+
}
|
|
926
|
+
function invalid(resource) {
|
|
927
|
+
return new CommerceError(
|
|
928
|
+
"INPUT_INVALID",
|
|
929
|
+
'A payment identifier must be 16 to 128 characters of A-Z, a-z, 0-9, "_" and "-"',
|
|
930
|
+
{ resourceId: resource.id, details: { reason: "payment_identifier_invalid" } }
|
|
931
|
+
);
|
|
932
|
+
}
|
|
796
933
|
var QUOTE_EXTENSION = "erc-8409";
|
|
797
934
|
var QUOTE_REQUEST_SCHEME = "agent-commerce/request/v1";
|
|
798
935
|
var QUOTE_DOMAIN = { name: "Signed Service Payment Quotes", version: "1" };
|
|
@@ -825,9 +962,9 @@ var QUOTE_INFO_SCHEMA = {
|
|
|
825
962
|
// Every field is a string in the ERC's JSON encoding
|
|
826
963
|
quote: {
|
|
827
964
|
type: "object",
|
|
828
|
-
required: QUOTE_TYPES.ServicePaymentQuote.map((
|
|
965
|
+
required: QUOTE_TYPES.ServicePaymentQuote.map((field2) => field2.name),
|
|
829
966
|
properties: Object.fromEntries(
|
|
830
|
-
QUOTE_TYPES.ServicePaymentQuote.map((
|
|
967
|
+
QUOTE_TYPES.ServicePaymentQuote.map((field2) => [field2.name, { type: "string" }])
|
|
831
968
|
)
|
|
832
969
|
},
|
|
833
970
|
signature: { type: "string" }
|
|
@@ -1511,48 +1648,6 @@ function parseCanonicalAmount(amount, decimals) {
|
|
|
1511
1648
|
const combined = `${integerPart}${paddedFraction}`;
|
|
1512
1649
|
return BigInt(combined);
|
|
1513
1650
|
}
|
|
1514
|
-
function decodePaymentSubmission(payloadBase64) {
|
|
1515
|
-
const json = decodeJson(payloadBase64);
|
|
1516
|
-
if (json === void 0) return void 0;
|
|
1517
|
-
const result = PaymentPayloadV2Schema.safeParse(json);
|
|
1518
|
-
return result.success ? result.data : void 0;
|
|
1519
|
-
}
|
|
1520
|
-
function declaredX402Version(payloadBase64) {
|
|
1521
|
-
const json = decodeJson(payloadBase64);
|
|
1522
|
-
return typeof json === "object" && json !== null ? json["x402Version"] : void 0;
|
|
1523
|
-
}
|
|
1524
|
-
function forFacilitator(payload) {
|
|
1525
|
-
const { resource: _resource, extensions: _extensions, ...rest } = payload;
|
|
1526
|
-
return rest;
|
|
1527
|
-
}
|
|
1528
|
-
function decodeJson(payloadBase64) {
|
|
1529
|
-
try {
|
|
1530
|
-
return JSON.parse(Buffer.from(payloadBase64, "base64").toString("utf8"));
|
|
1531
|
-
} catch {
|
|
1532
|
-
return void 0;
|
|
1533
|
-
}
|
|
1534
|
-
}
|
|
1535
|
-
function isExactEvmPayload(payload) {
|
|
1536
|
-
const inner = payload.payload;
|
|
1537
|
-
return payload.accepted.scheme === "exact" && isRecord(inner) && isRecord(inner["authorization"]) && !("permit2Authorization" in inner) && typeof inner["signature"] === "string";
|
|
1538
|
-
}
|
|
1539
|
-
var UINT256 = /^(0|[1-9]\d{0,77})$/;
|
|
1540
|
-
var UINT256_MAX = 2n ** 256n - 1n;
|
|
1541
|
-
var BYTES32 = /^0x[0-9a-fA-F]{64}$/;
|
|
1542
|
-
var isUint256 = (value) => typeof value === "string" && UINT256.test(value) && BigInt(value) <= UINT256_MAX;
|
|
1543
|
-
function hasEip3009Fields(authorization) {
|
|
1544
|
-
return isEvmAddress(authorization["from"]) && isEvmAddress(authorization["to"]) && isUint256(authorization["value"]) && isUint256(authorization["validAfter"]) && isUint256(authorization["validBefore"]) && typeof authorization["nonce"] === "string" && BYTES32.test(authorization["nonce"]);
|
|
1545
|
-
}
|
|
1546
|
-
function isExactPermit2Payload(payload) {
|
|
1547
|
-
const inner = payload.payload;
|
|
1548
|
-
if (payload.accepted.scheme !== "exact" || !isRecord(inner)) return false;
|
|
1549
|
-
const auth = inner["permit2Authorization"];
|
|
1550
|
-
if (!isRecord(auth) || "authorization" in inner || typeof inner["signature"] !== "string") {
|
|
1551
|
-
return false;
|
|
1552
|
-
}
|
|
1553
|
-
const { permitted, witness } = auth;
|
|
1554
|
-
return isRecord(permitted) && isRecord(witness) && isEvmAddress(auth["from"]) && isEvmAddress(auth["spender"]) && isEvmAddress(permitted["token"]) && isEvmAddress(witness["to"]) && isUint256(permitted["amount"]) && isUint256(auth["nonce"]) && isUint256(auth["deadline"]) && isUint256(witness["validAfter"]);
|
|
1555
|
-
}
|
|
1556
1651
|
|
|
1557
1652
|
// src/payments/x402/provider/requirement.ts
|
|
1558
1653
|
var SELECTED_OFFER_KEY = "x402.offer";
|
|
@@ -1597,7 +1692,7 @@ function createRequirementBuilders(ctx, svmFeePayer) {
|
|
|
1597
1692
|
}))
|
|
1598
1693
|
);
|
|
1599
1694
|
const single = offers.length === 1 ? offers[0] : void 0;
|
|
1600
|
-
const
|
|
1695
|
+
const quoteExtensions = await ctx.quotes?.extensionsFor(
|
|
1601
1696
|
context.resource.id,
|
|
1602
1697
|
context.input,
|
|
1603
1698
|
offers.flatMap((offer, index) => {
|
|
@@ -1605,6 +1700,8 @@ function createRequirementBuilders(ctx, svmFeePayer) {
|
|
|
1605
1700
|
return offer.family === "evm" && accepted ? [{ offer, amount: accepted.amount }] : [];
|
|
1606
1701
|
})
|
|
1607
1702
|
);
|
|
1703
|
+
const identifier = paymentIdentifierExtensions(context.resource);
|
|
1704
|
+
const extensions = identifier === void 0 ? quoteExtensions : { ...quoteExtensions, ...identifier };
|
|
1608
1705
|
const resourceId = encodeURIComponent(context.resource.id);
|
|
1609
1706
|
const envelope = {
|
|
1610
1707
|
x402Version: X402_VERSION,
|
|
@@ -1963,6 +2060,9 @@ function createVerify(ctx, nearRelayers) {
|
|
|
1963
2060
|
if (!acceptedMatchesOffer(requirements, payload.accepted, offer.profile) || payload.resource !== void 0 && payload.resource.url !== offeredUrl) {
|
|
1964
2061
|
return refused("invalid_payment_requirements");
|
|
1965
2062
|
}
|
|
2063
|
+
if (!paymentIdentifierEchoed(requirement.challenge.envelope, payload)) {
|
|
2064
|
+
return refused("extension_echo_mismatch");
|
|
2065
|
+
}
|
|
1966
2066
|
let required;
|
|
1967
2067
|
try {
|
|
1968
2068
|
required = BigInt(requirements.amount);
|
|
@@ -2160,6 +2260,7 @@ function createX402PaymentProvider(options) {
|
|
|
2160
2260
|
createRequirement,
|
|
2161
2261
|
// A single offer needs no selection
|
|
2162
2262
|
...severalOffers ? { selectRequirement } : {},
|
|
2263
|
+
retryKey: paymentRetryKey,
|
|
2163
2264
|
verify,
|
|
2164
2265
|
settle,
|
|
2165
2266
|
reconcile: createReconcile(ctx),
|
|
@@ -2185,5 +2286,5 @@ function loadOptionalModule(load, missing) {
|
|
|
2185
2286
|
}
|
|
2186
2287
|
|
|
2187
2288
|
export { DEFAULT_IDS, chainIdFromCaip2, createX402PaymentProvider, parseCanonicalAmount };
|
|
2188
|
-
//# sourceMappingURL=chunk-
|
|
2189
|
-
//# sourceMappingURL=chunk-
|
|
2289
|
+
//# sourceMappingURL=chunk-ZSIUZPNB.js.map
|
|
2290
|
+
//# sourceMappingURL=chunk-ZSIUZPNB.js.map
|