@devlab.group/agent-commerce 2.7.1 → 2.8.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 +72 -24
- package/dist/ap2.d.ts +3 -11
- package/dist/ap2.js +96 -27
- package/dist/ap2.js.map +1 -1
- package/dist/{chunk-77HLISG4.js → chunk-2PVRHMVT.js} +14 -10
- package/dist/chunk-2PVRHMVT.js.map +1 -0
- package/dist/chunk-ENK63GKR.js +22 -0
- package/dist/chunk-ENK63GKR.js.map +1 -0
- package/dist/{chunk-YHNTTMED.js → chunk-MDOGXTZD.js} +2 -2
- package/dist/chunk-MDOGXTZD.js.map +1 -0
- package/dist/chunk-MNI6APE6.js +64 -0
- package/dist/chunk-MNI6APE6.js.map +1 -0
- package/dist/{chunk-5VW32JPV.js → chunk-QZW5YL3G.js} +160 -41
- package/dist/chunk-QZW5YL3G.js.map +1 -0
- package/dist/{chunk-DJRWYDKJ.js → chunk-RXYGC7A3.js} +3 -3
- package/dist/{chunk-DJRWYDKJ.js.map → chunk-RXYGC7A3.js.map} +1 -1
- package/dist/{chunk-5AO5N2XY.js → chunk-VHS6MGXJ.js} +621 -4
- package/dist/chunk-VHS6MGXJ.js.map +1 -0
- package/dist/cli/{ap2-NTYL7H4I.js → ap2-GYKFGE66.js} +35 -8
- package/dist/cli/ap2-GYKFGE66.js.map +1 -0
- package/dist/cli/chunk-2PO65227.js +619 -0
- package/dist/cli/chunk-2PO65227.js.map +1 -0
- package/dist/cli/{chunk-GBBG66O6.js → chunk-3PGFOEVJ.js} +132 -103
- package/dist/cli/chunk-3PGFOEVJ.js.map +1 -0
- package/dist/cli/chunk-4YZULHX2.js +64 -0
- package/dist/cli/chunk-4YZULHX2.js.map +1 -0
- package/dist/cli/chunk-526C4KZA.js +93 -0
- package/dist/cli/chunk-526C4KZA.js.map +1 -0
- package/dist/cli/{chunk-FETTSOMT.js → chunk-5CH5VFC6.js} +139 -4
- package/dist/cli/chunk-5CH5VFC6.js.map +1 -0
- package/dist/cli/chunk-6BWEHQPJ.js +215 -0
- package/dist/cli/chunk-6BWEHQPJ.js.map +1 -0
- package/dist/cli/chunk-GISJ73ML.js +20 -0
- package/dist/cli/chunk-GISJ73ML.js.map +1 -0
- package/dist/cli/chunk-MASLG557.js +26 -0
- package/dist/cli/chunk-MASLG557.js.map +1 -0
- package/dist/cli/chunk-RQ7W3NA5.js +143 -0
- package/dist/cli/chunk-RQ7W3NA5.js.map +1 -0
- package/dist/cli/chunk-RWBUHDU7.js +48 -0
- package/dist/cli/chunk-RWBUHDU7.js.map +1 -0
- package/dist/cli/chunk-SAAT2XFX.js +8 -0
- package/dist/cli/{chunk-2M2RF3CT.js.map → chunk-SAAT2XFX.js.map} +1 -1
- package/dist/cli/{chunk-MBPOKPQM.js → chunk-SYXLQ5BS.js} +7 -5
- package/dist/cli/chunk-SYXLQ5BS.js.map +1 -0
- package/dist/cli/{chunk-FL4HPCD4.js → chunk-THH7Y3OO.js} +3 -35
- package/dist/cli/chunk-THH7Y3OO.js.map +1 -0
- package/dist/cli/{chunk-55AI6CLW.js → chunk-USIXWAXZ.js} +2 -2
- package/dist/cli/chunk-USIXWAXZ.js.map +1 -0
- package/dist/cli/{chunk-EVCIEKHN.js → chunk-VWQMSWDF.js} +141 -42
- package/dist/cli/chunk-VWQMSWDF.js.map +1 -0
- package/dist/cli/{chunk-OETKXDGA.js → chunk-WFIR374D.js} +89 -272
- package/dist/cli/chunk-WFIR374D.js.map +1 -0
- package/dist/cli/{chunk-A42BCWZ2.js → chunk-YXXPZFWC.js} +4 -4
- package/dist/cli/{chunk-A42BCWZ2.js.map → chunk-YXXPZFWC.js.map} +1 -1
- package/dist/cli/config-JWMHWVRT.js +14 -0
- package/dist/cli/{config-ODN4IEMZ.js.map → config-JWMHWVRT.js.map} +1 -1
- package/dist/cli/index.js +363 -84
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-V27OKTOV.js → mcp-OW5GY7TT.js} +84 -45
- package/dist/cli/mcp-OW5GY7TT.js.map +1 -0
- package/dist/cli/payment-providers-QL2BJYMD.js +6 -0
- package/dist/cli/{payment-providers-SUATT75K.js.map → payment-providers-QL2BJYMD.js.map} +1 -1
- package/dist/cli/{provider-C3QDAXMR.js → provider-3A2LVEQS.js} +145 -23
- package/dist/cli/provider-3A2LVEQS.js.map +1 -0
- package/dist/cli/receipts-FQUFGEQD.js +9 -0
- package/dist/cli/{receipts-ZS3VZ2D4.js.map → receipts-FQUFGEQD.js.map} +1 -1
- package/dist/cli/{run-WYFZUO5D.js → run-KF5OQYPL.js} +97 -66
- package/dist/cli/run-KF5OQYPL.js.map +1 -0
- package/dist/cli/{x402-UGLZ3LA7.js → x402-5A7CVCIJ.js} +12 -8
- package/dist/cli/x402-5A7CVCIJ.js.map +1 -0
- package/dist/index.d.ts +36 -12
- package/dist/index.js +345 -397
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +80 -42
- package/dist/mcp.js.map +1 -1
- package/dist/mpp.d.ts +3 -2
- package/dist/mpp.js +139 -20
- package/dist/mpp.js.map +1 -1
- package/dist/{protocol-adapter-DdFL5LBU.d.ts → protocol-adapter-D6JH_kk-.d.ts} +2 -2
- package/dist/{runtime-BmaSp2Ce.d.ts → runtime-D8u6lYfx.d.ts} +10 -0
- package/dist/{store-DQwbKhnc.d.ts → store-BzgwHOPu.d.ts} +2 -2
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/dist/{transaction-BXXJltZ-.d.ts → transaction-F9ZvhokH.d.ts} +1 -1
- package/dist/types-Dl27vhEc.d.ts +167 -0
- package/dist/x402.d.ts +7 -110
- package/dist/x402.js +6 -5
- package/dist/x402.js.map +1 -1
- package/package.json +3 -1
- package/dist/chunk-5AO5N2XY.js.map +0 -1
- package/dist/chunk-5VW32JPV.js.map +0 -1
- package/dist/chunk-77HLISG4.js.map +0 -1
- package/dist/chunk-IGXQMAKM.js +0 -8
- package/dist/chunk-IGXQMAKM.js.map +0 -1
- package/dist/chunk-YHNTTMED.js.map +0 -1
- package/dist/cli/ap2-NTYL7H4I.js.map +0 -1
- package/dist/cli/chunk-2M2RF3CT.js +0 -8
- package/dist/cli/chunk-3NVJAQRO.js +0 -119
- package/dist/cli/chunk-3NVJAQRO.js.map +0 -1
- package/dist/cli/chunk-55AI6CLW.js.map +0 -1
- package/dist/cli/chunk-66NTYSXI.js +0 -277
- package/dist/cli/chunk-66NTYSXI.js.map +0 -1
- package/dist/cli/chunk-EVCIEKHN.js.map +0 -1
- package/dist/cli/chunk-FETTSOMT.js.map +0 -1
- package/dist/cli/chunk-FL4HPCD4.js.map +0 -1
- package/dist/cli/chunk-GBBG66O6.js.map +0 -1
- package/dist/cli/chunk-H7EBJ4I3.js +0 -53
- package/dist/cli/chunk-H7EBJ4I3.js.map +0 -1
- package/dist/cli/chunk-MBPOKPQM.js.map +0 -1
- package/dist/cli/chunk-OETKXDGA.js.map +0 -1
- package/dist/cli/chunk-TPC4EJLT.js +0 -11
- package/dist/cli/chunk-TPC4EJLT.js.map +0 -1
- package/dist/cli/config-ODN4IEMZ.js +0 -13
- package/dist/cli/mcp-V27OKTOV.js.map +0 -1
- package/dist/cli/payment-providers-SUATT75K.js +0 -6
- package/dist/cli/provider-C3QDAXMR.js.map +0 -1
- package/dist/cli/receipts-ZS3VZ2D4.js +0 -9
- package/dist/cli/run-WYFZUO5D.js.map +0 -1
- package/dist/cli/x402-UGLZ3LA7.js.map +0 -1
- package/dist/networks-DDHYJLcg.d.ts +0 -39
|
@@ -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,IAA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F,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-MDOGXTZD.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 * Marks a probe that received no response; `status` does not describe the\n * target's health in this case. Experimental: may change in a minor release.\n */\n readonly undetermined?: 'unreachable';\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 ProtocolName,\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 /**\n * The request's protocol, set by the pipeline on each createRequirement call.\n * Experimental: may change in a minor release.\n */\n readonly protocol?: ProtocolName;\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"]}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { PAYMENT_INPUT_FIELD, AUTHORIZATION_INPUT_FIELD } from './chunk-MDOGXTZD.js';
|
|
2
|
+
import { isRecord } from './chunk-2CJNA7MS.js';
|
|
3
|
+
|
|
4
|
+
// src/core/execution/schema-example.ts
|
|
5
|
+
function exampleValue(schema, name) {
|
|
6
|
+
if (!isRecord(schema)) return `<${name}>`;
|
|
7
|
+
const examples = schema["examples"];
|
|
8
|
+
if (Array.isArray(examples) && examples.length > 0) return examples[0];
|
|
9
|
+
if (schema["default"] !== void 0) return schema["default"];
|
|
10
|
+
const allowed = schema["enum"];
|
|
11
|
+
if (Array.isArray(allowed) && allowed.length > 0) return allowed[0];
|
|
12
|
+
const declared = schema["type"];
|
|
13
|
+
const type = Array.isArray(declared) ? declared[0] : declared;
|
|
14
|
+
switch (type) {
|
|
15
|
+
case "object":
|
|
16
|
+
return exampleObject(schema);
|
|
17
|
+
case "array":
|
|
18
|
+
return schema["items"] !== void 0 ? [exampleValue(schema["items"], name)] : [];
|
|
19
|
+
case "number":
|
|
20
|
+
case "integer":
|
|
21
|
+
return 0;
|
|
22
|
+
case "boolean":
|
|
23
|
+
return false;
|
|
24
|
+
case "null":
|
|
25
|
+
return null;
|
|
26
|
+
default:
|
|
27
|
+
return `<${name}>`;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function exampleObject(schema) {
|
|
31
|
+
const properties = isRecord(schema["properties"]) ? schema["properties"] : {};
|
|
32
|
+
const required = Array.isArray(schema["required"]) ? schema["required"] : [];
|
|
33
|
+
const example = {};
|
|
34
|
+
for (const key of required) {
|
|
35
|
+
if (typeof key !== "string" || key === PAYMENT_INPUT_FIELD || key === AUTHORIZATION_INPUT_FIELD)
|
|
36
|
+
continue;
|
|
37
|
+
example[key] = exampleValue(properties[key], key);
|
|
38
|
+
}
|
|
39
|
+
return example;
|
|
40
|
+
}
|
|
41
|
+
function publishedInputSchema(schema) {
|
|
42
|
+
const base = isRecord(schema) ? schema : {};
|
|
43
|
+
const properties = isRecord(base["properties"]) ? Object.fromEntries(
|
|
44
|
+
Object.entries(base["properties"]).filter(
|
|
45
|
+
(entry) => isRecord(entry[1])
|
|
46
|
+
)
|
|
47
|
+
) : {};
|
|
48
|
+
const required = Array.isArray(base["required"]) ? base["required"].filter((v) => typeof v === "string") : [];
|
|
49
|
+
const extra = Object.fromEntries(
|
|
50
|
+
Object.entries(base).filter(
|
|
51
|
+
([key]) => key !== "type" && key !== "properties" && key !== "required"
|
|
52
|
+
)
|
|
53
|
+
);
|
|
54
|
+
return {
|
|
55
|
+
...extra,
|
|
56
|
+
type: "object",
|
|
57
|
+
properties,
|
|
58
|
+
...required.length > 0 ? { required } : {}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export { exampleObject, exampleValue, publishedInputSchema };
|
|
63
|
+
//# sourceMappingURL=chunk-MNI6APE6.js.map
|
|
64
|
+
//# sourceMappingURL=chunk-MNI6APE6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/execution/schema-example.ts"],"names":[],"mappings":";;;;AAYO,SAAS,YAAA,CAAa,QAAiB,IAAA,EAAuB;AACnE,EAAA,IAAI,CA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OAAO;AAAA,IACL,GAAG,KAAA;AAAA,IACH,IAAA,EAAM,QAAA;AAAA,IACN,UAAA;AAAA,IACA,GAAI,QAAA,CAAS,MAAA,GAAS,IAAI,EAAE,QAAA,KAAa;AAAC,GAC5C;AACF","file":"chunk-MNI6APE6.js","sourcesContent":["// Example values and the published object form of a resource's input schema,\n// shared by the adapters and payment metadata that describe a resource\nimport type { JsonSchema } from '../domain/common';\nimport { AUTHORIZATION_INPUT_FIELD, PAYMENT_INPUT_FIELD } from '../domain/wire';\nimport { isRecord } from '../is-record';\n\n/**\n * Build a sample using the first schema example, then its default or first\n * enum value, otherwise a value for the declared type. Generated objects use\n * required properties only; explicit examples, defaults and enum values are\n * returned unchanged. Other constraints may require different input.\n */\nexport function exampleValue(schema: unknown, name: string): unknown {\n if (!isRecord(schema)) return `<${name}>`;\n const examples = schema['examples'];\n if (Array.isArray(examples) && examples.length > 0) return examples[0];\n if (schema['default'] !== undefined) return schema['default'];\n const allowed = schema['enum'];\n if (Array.isArray(allowed) && allowed.length > 0) return allowed[0];\n const declared = schema['type'];\n const type: unknown = Array.isArray(declared) ? declared[0] : declared;\n switch (type) {\n case 'object':\n return exampleObject(schema);\n case 'array':\n return schema['items'] !== undefined ? [exampleValue(schema['items'], name)] : [];\n case 'number':\n case 'integer':\n return 0;\n case 'boolean':\n return false;\n case 'null':\n return null;\n default:\n return `<${name}>`;\n }\n}\n\n/** An object holding an example of each required property, without the reserved fields */\nexport function exampleObject(schema: Record<string, unknown>): Record<string, unknown> {\n const properties = isRecord(schema['properties']) ? schema['properties'] : {};\n const required = Array.isArray(schema['required']) ? schema['required'] : [];\n const example: Record<string, unknown> = {};\n for (const key of required) {\n // The reserved fields carry proofs, which no example can hold\n if (typeof key !== 'string' || key === PAYMENT_INPUT_FIELD || key === AUTHORIZATION_INPUT_FIELD)\n continue;\n example[key] = exampleValue(properties[key], key);\n }\n return example;\n}\n\n/** A resource input schema in object form, before discovery surfaces add reserved fields */\nexport interface PublishedInputSchema {\n readonly [keyword: string]: unknown;\n readonly type: 'object';\n readonly properties: Readonly<Record<string, Record<string, unknown>>>;\n readonly required?: readonly string[];\n}\n\n/**\n * Normalize a resource input schema for publication before a surface adds\n * reserved fields. Set `type` to `'object'`, keep object-valued `properties`\n * and string entries in `required`, and preserve other keywords.\n */\nexport function publishedInputSchema(schema: JsonSchema | undefined): PublishedInputSchema {\n const base = isRecord(schema) ? schema : {};\n const properties = isRecord(base['properties'])\n ? Object.fromEntries(\n Object.entries(base['properties']).filter(\n (entry): entry is [string, Record<string, unknown>] => isRecord(entry[1]),\n ),\n )\n : {};\n const required = Array.isArray(base['required'])\n ? base['required'].filter((v): v is string => typeof v === 'string')\n : [];\n const extra = Object.fromEntries(\n Object.entries(base).filter(\n ([key]) => key !== 'type' && key !== 'properties' && key !== 'required',\n ),\n );\n return {\n ...extra,\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\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, CDP_FACILITATOR_URL, 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 { x402_default, 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, BAZAAR_EXTENSION_KEY, isTransactionReference, x402OfferName, CDP_FACILITATOR_URL, isEvmAddress, describeDeploymentMode } from './chunk-VHS6MGXJ.js';
|
|
2
|
+
import { exclusionNames, descriptorStatus, PACKAGE_VERSION } from './chunk-ENK63GKR.js';
|
|
3
|
+
import { CommerceError, systemClock, NOOP_LOGGER, redactedErrorText, RECONCILIATION_METADATA_KEY, isCommerceError } from './chunk-MDOGXTZD.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';
|
|
@@ -13,6 +13,54 @@ import { x402Facilitator } from '@x402/core/facilitator';
|
|
|
13
13
|
import { registerExactEvmScheme } from '@x402/evm/exact/facilitator';
|
|
14
14
|
import { PaymentPayloadV2Schema } from '@x402/core/schemas';
|
|
15
15
|
|
|
16
|
+
// src/payments/x402/provider/bazaar-forwarding.ts
|
|
17
|
+
var SUPPORTED_GRACE_MS = 1e3;
|
|
18
|
+
var MAX_LOGGED_REASON_LENGTH = 200;
|
|
19
|
+
function createBazaarForwarding(ctx, currentSupported) {
|
|
20
|
+
const { remoteBinding, logger } = ctx;
|
|
21
|
+
let unlistedLogged = false;
|
|
22
|
+
const rejectedLogged = /* @__PURE__ */ new Set();
|
|
23
|
+
async function listed() {
|
|
24
|
+
if (remoteBinding?.kind !== "remote") return false;
|
|
25
|
+
let timer;
|
|
26
|
+
const late = new Promise((resolve) => {
|
|
27
|
+
timer = setTimeout(() => resolve(void 0), SUPPORTED_GRACE_MS);
|
|
28
|
+
timer.unref();
|
|
29
|
+
});
|
|
30
|
+
const supported = await Promise.race([currentSupported(), late]).catch(() => void 0).finally(() => clearTimeout(timer));
|
|
31
|
+
if (supported === void 0) return false;
|
|
32
|
+
const lists = Array.isArray(supported.extensions) && supported.extensions.includes(BAZAAR_EXTENSION_KEY);
|
|
33
|
+
if (!lists && !unlistedLogged) {
|
|
34
|
+
unlistedLogged = true;
|
|
35
|
+
logger.warn(
|
|
36
|
+
{ facilitator: remoteBinding.describe },
|
|
37
|
+
"x402: the facilitator does not list the bazaar extension in /supported; Bazaar metadata stays in challenges but is not sent to it"
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
return lists;
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
async issuedFor(issued) {
|
|
44
|
+
if (issued?.extensions?.[BAZAAR_EXTENSION_KEY] === void 0) return void 0;
|
|
45
|
+
return await listed() ? issued : void 0;
|
|
46
|
+
},
|
|
47
|
+
report(resourceId, extensionResponses) {
|
|
48
|
+
const outcome = extensionResponses?.[BAZAAR_EXTENSION_KEY];
|
|
49
|
+
if (!isRecord(outcome) || outcome["status"] !== "rejected") return;
|
|
50
|
+
if (rejectedLogged.has(resourceId)) return;
|
|
51
|
+
rejectedLogged.add(resourceId);
|
|
52
|
+
const reason = outcome["rejectedReason"];
|
|
53
|
+
logger.warn(
|
|
54
|
+
{
|
|
55
|
+
resourceId,
|
|
56
|
+
...typeof reason === "string" ? { reportedReason: redactedErrorText(reason).slice(0, MAX_LOGGED_REASON_LENGTH) } : {}
|
|
57
|
+
},
|
|
58
|
+
"x402: the facilitator rejected the Bazaar metadata of a resource and will not catalog it. Payment is unaffected"
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
16
64
|
// src/payments/x402/provider/constants.ts
|
|
17
65
|
var X402_VERSION = 2;
|
|
18
66
|
var X402_PROTOCOL_VERSION = String(X402_VERSION);
|
|
@@ -91,6 +139,29 @@ function createNearRelayerSource(currentSupported, logger) {
|
|
|
91
139
|
};
|
|
92
140
|
}
|
|
93
141
|
|
|
142
|
+
// src/core/no-answer.ts
|
|
143
|
+
var NO_ANSWER_CODES = /* @__PURE__ */ new Set([
|
|
144
|
+
"ECONNREFUSED",
|
|
145
|
+
"ECONNRESET",
|
|
146
|
+
"ETIMEDOUT",
|
|
147
|
+
"EHOSTUNREACH",
|
|
148
|
+
"ENETUNREACH",
|
|
149
|
+
"EAI_AGAIN",
|
|
150
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
151
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
152
|
+
"UND_ERR_BODY_TIMEOUT"
|
|
153
|
+
]);
|
|
154
|
+
function gotNoAnswer(err, timeoutNames = []) {
|
|
155
|
+
let cause = err;
|
|
156
|
+
for (let depth = 0; depth < 10 && cause instanceof Error; depth++) {
|
|
157
|
+
if (cause.name === "TimeoutError" || timeoutNames.includes(cause.name)) return true;
|
|
158
|
+
const { code } = cause;
|
|
159
|
+
if (typeof code === "string" && NO_ANSWER_CODES.has(code)) return true;
|
|
160
|
+
cause = cause.cause;
|
|
161
|
+
}
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
|
|
94
165
|
// src/payments/x402/json-rpc.ts
|
|
95
166
|
async function jsonRpc(rpcUrl, method, params, timeoutMs) {
|
|
96
167
|
const response = await fetch(rpcUrl, {
|
|
@@ -306,10 +377,14 @@ function createHealthCheck(ctx) {
|
|
|
306
377
|
};
|
|
307
378
|
const results = await Promise.all(
|
|
308
379
|
offers.map(
|
|
309
|
-
(offer) => offerHealth(offer, kinds).catch(
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
380
|
+
(offer) => offerHealth(offer, kinds).catch(
|
|
381
|
+
(err) => ({
|
|
382
|
+
status: "fail",
|
|
383
|
+
detail: `x402 health check failed: ${redactedErrorText(err)}`,
|
|
384
|
+
// The SDK throws its own timeout error from `/supported`
|
|
385
|
+
...gotNoAnswer(err, ["FacilitatorTimeoutError"]) ? { undetermined: "unreachable" } : {}
|
|
386
|
+
})
|
|
387
|
+
)
|
|
313
388
|
)
|
|
314
389
|
);
|
|
315
390
|
const failed = results.some((result) => result.status === "fail");
|
|
@@ -321,10 +396,14 @@ function createHealthCheck(ctx) {
|
|
|
321
396
|
return {
|
|
322
397
|
status: failed ? "fail" : "pass",
|
|
323
398
|
detail: details.join("; "),
|
|
324
|
-
components: offers.map((offer, index) =>
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
399
|
+
components: offers.map((offer, index) => {
|
|
400
|
+
const { status, undetermined } = results[index];
|
|
401
|
+
return {
|
|
402
|
+
name: x402OfferName(offer),
|
|
403
|
+
status,
|
|
404
|
+
...undetermined !== void 0 ? { undetermined } : {}
|
|
405
|
+
};
|
|
406
|
+
}),
|
|
328
407
|
checkedAt,
|
|
329
408
|
durationMs: clock.monotonicMs() - startedAt
|
|
330
409
|
};
|
|
@@ -573,15 +652,14 @@ function createRemoteFacilitatorBinding(options) {
|
|
|
573
652
|
function withDeadline(call, ms) {
|
|
574
653
|
let timer;
|
|
575
654
|
const deadline = new Promise((_, reject) => {
|
|
576
|
-
timer = setTimeout(
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
)
|
|
582
|
-
)
|
|
583
|
-
|
|
584
|
-
);
|
|
655
|
+
timer = setTimeout(() => {
|
|
656
|
+
const message = `x402 provider: facilitator /supported did not answer within ${ms / 1e3} s`;
|
|
657
|
+
reject(
|
|
658
|
+
new CommerceError("PAYMENT_PROVIDER_UNAVAILABLE", message, {
|
|
659
|
+
cause: new DOMException(message, "TimeoutError")
|
|
660
|
+
})
|
|
661
|
+
);
|
|
662
|
+
}, ms);
|
|
585
663
|
timer.unref();
|
|
586
664
|
});
|
|
587
665
|
return Promise.race([call, deadline]).finally(() => clearTimeout(timer));
|
|
@@ -854,9 +932,10 @@ function declaredX402Version(payloadBase64) {
|
|
|
854
932
|
const json = decodeJson(payloadBase64);
|
|
855
933
|
return typeof json === "object" && json !== null ? json["x402Version"] : void 0;
|
|
856
934
|
}
|
|
857
|
-
function forFacilitator(payload) {
|
|
935
|
+
function forFacilitator(payload, issued) {
|
|
858
936
|
const { resource: _resource, extensions: _extensions, ...rest } = payload;
|
|
859
|
-
|
|
937
|
+
const bazaar = issued?.extensions?.[BAZAAR_EXTENSION_KEY];
|
|
938
|
+
return issued !== void 0 && bazaar !== void 0 ? { ...rest, resource: issued.resource, extensions: { [BAZAAR_EXTENSION_KEY]: bazaar } } : rest;
|
|
860
939
|
}
|
|
861
940
|
function decodeJson(payloadBase64) {
|
|
862
941
|
try {
|
|
@@ -1662,6 +1741,12 @@ function parseCanonicalAmount(amount, decimals) {
|
|
|
1662
1741
|
}
|
|
1663
1742
|
|
|
1664
1743
|
// src/payments/x402/provider/requirement.ts
|
|
1744
|
+
var MAX_HTTP_HEADER_BYTES = 8192;
|
|
1745
|
+
var PROOF_RESERVE_BYTES = {
|
|
1746
|
+
evm: 1024,
|
|
1747
|
+
svm: 2304,
|
|
1748
|
+
near: 1280
|
|
1749
|
+
};
|
|
1665
1750
|
var SELECTED_OFFER_KEY = "x402.offer";
|
|
1666
1751
|
function offerIndexOf(requirement) {
|
|
1667
1752
|
const selected = requirement.metadata?.[SELECTED_OFFER_KEY];
|
|
@@ -1677,7 +1762,8 @@ function acceptedMatchesOffer(offered, accepted, network) {
|
|
|
1677
1762
|
return accepted.scheme === offered.scheme && accepted.network === offered.network && accepted.amount === offered.amount && same(accepted.asset, offered.asset) && same(accepted.payTo, offered.payTo) && Object.entries(offeredExtra).every(([key, value]) => acceptedExtra[key] === value) && flow(acceptedExtra) === flow(offeredExtra);
|
|
1678
1763
|
}
|
|
1679
1764
|
function createRequirementBuilders(ctx, svmFeePayer) {
|
|
1680
|
-
const { options, offersFor, clock, ids, maxTimeoutSeconds } = ctx;
|
|
1765
|
+
const { options, offersFor, clock, ids, maxTimeoutSeconds, logger } = ctx;
|
|
1766
|
+
const oversizedLogged = /* @__PURE__ */ new Set();
|
|
1681
1767
|
async function createRequirement(context) {
|
|
1682
1768
|
const offers = offersFor(context.resource.id);
|
|
1683
1769
|
const paymentFlow = options.resourcePaymentFlows?.[context.resource.id] ?? options.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW;
|
|
@@ -1714,11 +1800,14 @@ function createRequirementBuilders(ctx, svmFeePayer) {
|
|
|
1714
1800
|
);
|
|
1715
1801
|
const identifier = paymentIdentifierExtensions(context.resource);
|
|
1716
1802
|
const extensions = identifier === void 0 ? quoteExtensions : { ...quoteExtensions, ...identifier };
|
|
1803
|
+
const bazaar = context.protocol === "http" || context.protocol === "mcp" ? options.resourceBazaar?.[context.resource.id]?.[context.protocol] : void 0;
|
|
1717
1804
|
const resourceId = encodeURIComponent(context.resource.id);
|
|
1805
|
+
const surface = context.protocol === "acp" ? void 0 : context.protocol;
|
|
1806
|
+
const publicUrl = surface !== void 0 ? options.resourceUrls?.[context.resource.id]?.[surface] : void 0;
|
|
1718
1807
|
const envelope = {
|
|
1719
1808
|
x402Version: X402_VERSION,
|
|
1720
1809
|
resource: {
|
|
1721
|
-
url: single ? `resource://agent-commerce/${encodeURIComponent(single.network)}/${single.payTo}/resources/${resourceId}` : `resource://agent-commerce/resources/${resourceId}
|
|
1810
|
+
url: publicUrl ?? (single ? `resource://agent-commerce/${encodeURIComponent(single.network)}/${single.payTo}/resources/${resourceId}` : `resource://agent-commerce/resources/${resourceId}`),
|
|
1722
1811
|
description: context.resource.description ?? context.resource.name,
|
|
1723
1812
|
// The media type the merchant declares, else `application/json`; an HTTP
|
|
1724
1813
|
// delivery carries the backend's own type when it is text and fits the body
|
|
@@ -1727,6 +1816,13 @@ function createRequirementBuilders(ctx, svmFeePayer) {
|
|
|
1727
1816
|
accepts,
|
|
1728
1817
|
...extensions !== void 0 ? { extensions } : {}
|
|
1729
1818
|
};
|
|
1819
|
+
const challenge = bazaar === void 0 ? envelope : withBazaar(
|
|
1820
|
+
envelope,
|
|
1821
|
+
bazaar,
|
|
1822
|
+
// MCP carries the challenge in the result body, not a header
|
|
1823
|
+
context.protocol === "http" ? Math.max(...offers.map((offer) => PROOF_RESERVE_BYTES[offer.family])) : void 0,
|
|
1824
|
+
context.resource.id
|
|
1825
|
+
);
|
|
1730
1826
|
const expiresAt = new Date(clock.now().getTime() + maxTimeoutSeconds * 1e3).toISOString();
|
|
1731
1827
|
return {
|
|
1732
1828
|
id: ids.next("payreq"),
|
|
@@ -1742,7 +1838,7 @@ function createRequirementBuilders(ctx, svmFeePayer) {
|
|
|
1742
1838
|
provider: "x402",
|
|
1743
1839
|
version: X402_PROTOCOL_VERSION,
|
|
1744
1840
|
accepts,
|
|
1745
|
-
envelope
|
|
1841
|
+
envelope: challenge
|
|
1746
1842
|
},
|
|
1747
1843
|
metadata: {
|
|
1748
1844
|
[SETTLE_AFTER_BACKEND_METADATA_KEY]: paymentFlow === "authorization",
|
|
@@ -1752,6 +1848,23 @@ function createRequirementBuilders(ctx, svmFeePayer) {
|
|
|
1752
1848
|
}
|
|
1753
1849
|
};
|
|
1754
1850
|
}
|
|
1851
|
+
function withBazaar(envelope, bazaar, headerReserve, resourceId) {
|
|
1852
|
+
const extended = {
|
|
1853
|
+
...envelope,
|
|
1854
|
+
extensions: { ...envelope.extensions, [BAZAAR_EXTENSION_KEY]: bazaar }
|
|
1855
|
+
};
|
|
1856
|
+
if (headerReserve === void 0) return extended;
|
|
1857
|
+
const encoded = 4 * Math.ceil(Buffer.byteLength(JSON.stringify(extended)) / 3);
|
|
1858
|
+
if (encoded + headerReserve <= MAX_HTTP_HEADER_BYTES) return extended;
|
|
1859
|
+
if (!oversizedLogged.has(resourceId)) {
|
|
1860
|
+
oversizedLogged.add(resourceId);
|
|
1861
|
+
logger.warn(
|
|
1862
|
+
{ resourceId, bytes: encoded, reservedBytes: headerReserve },
|
|
1863
|
+
"x402: Bazaar metadata left out of an HTTP challenge too large to leave room for the signed proof in an 8 KiB header"
|
|
1864
|
+
);
|
|
1865
|
+
}
|
|
1866
|
+
return envelope;
|
|
1867
|
+
}
|
|
1755
1868
|
async function selectRequirement(context) {
|
|
1756
1869
|
const { requirement, submission } = context;
|
|
1757
1870
|
const offered = requirement.challenge.accepts;
|
|
@@ -1826,7 +1939,7 @@ function readTransfer(payload, offer) {
|
|
|
1826
1939
|
}
|
|
1827
1940
|
|
|
1828
1941
|
// src/payments/x402/provider/settle.ts
|
|
1829
|
-
function createSettle(ctx) {
|
|
1942
|
+
function createSettle(ctx, bazaar) {
|
|
1830
1943
|
const { offersFor, clock, logger } = ctx;
|
|
1831
1944
|
async function settle(context) {
|
|
1832
1945
|
const { requirement, submission, verification } = context;
|
|
@@ -1864,10 +1977,13 @@ function createSettle(ctx) {
|
|
|
1864
1977
|
...verification.replayKey !== void 0 ? { replayKey: verification.replayKey } : {},
|
|
1865
1978
|
rejectionReason
|
|
1866
1979
|
});
|
|
1980
|
+
const issued = await bazaar.issuedFor(
|
|
1981
|
+
requirement.challenge.envelope
|
|
1982
|
+
);
|
|
1867
1983
|
const scope = offer.binding.open();
|
|
1868
1984
|
let sdkResult;
|
|
1869
1985
|
try {
|
|
1870
|
-
sdkResult = await scope.settle(forFacilitator(payload), requirements);
|
|
1986
|
+
sdkResult = await scope.settle(forFacilitator(payload, issued), requirements);
|
|
1871
1987
|
} catch (err) {
|
|
1872
1988
|
if (isProviderUnavailableError(err) || scope.transportFailed()) {
|
|
1873
1989
|
throw new CommerceError(
|
|
@@ -1893,6 +2009,7 @@ function createSettle(ctx) {
|
|
|
1893
2009
|
);
|
|
1894
2010
|
return rejectedSettlement("transaction_reverted");
|
|
1895
2011
|
}
|
|
2012
|
+
bazaar.report(requirement.resourceId, sdkResult.extensionResponses);
|
|
1896
2013
|
const payer = verification.payer ?? sdkResult.payer;
|
|
1897
2014
|
if (!sdkResult.success) {
|
|
1898
2015
|
if (isTransactionFailedReason(sdkResult.errorReason) && !reference(sdkResult.transaction)) {
|
|
@@ -1995,7 +2112,7 @@ function createSettle(ctx) {
|
|
|
1995
2112
|
return settle;
|
|
1996
2113
|
}
|
|
1997
2114
|
var RELAYER_GRACE_MS = 1e3;
|
|
1998
|
-
function createVerify(ctx, nearRelayers) {
|
|
2115
|
+
function createVerify(ctx, nearRelayers, bazaar) {
|
|
1999
2116
|
const { offersFor, clock, logger, svm, near } = ctx;
|
|
2000
2117
|
async function verify(context) {
|
|
2001
2118
|
const { requirement, submission } = context;
|
|
@@ -2096,10 +2213,13 @@ function createVerify(ctx, nearRelayers) {
|
|
|
2096
2213
|
}
|
|
2097
2214
|
}
|
|
2098
2215
|
const relayers = offer.family === "near" ? nearRelayers(offer) : void 0;
|
|
2216
|
+
const issued = await bazaar.issuedFor(
|
|
2217
|
+
requirement.challenge.envelope
|
|
2218
|
+
);
|
|
2099
2219
|
const scope = offer.binding.open();
|
|
2100
2220
|
let sdkResult;
|
|
2101
2221
|
try {
|
|
2102
|
-
sdkResult = await scope.verify(forFacilitator(payload), requirements);
|
|
2222
|
+
sdkResult = await scope.verify(forFacilitator(payload, issued), requirements);
|
|
2103
2223
|
} catch (err) {
|
|
2104
2224
|
if (!isProviderUnavailableError(err) && !scope.transportFailed()) {
|
|
2105
2225
|
logger.warn({ err: redactedErrorText(err) }, "x402 verify(): unexpected SDK error");
|
|
@@ -2110,6 +2230,7 @@ function createVerify(ctx, nearRelayers) {
|
|
|
2110
2230
|
{ cause: err }
|
|
2111
2231
|
);
|
|
2112
2232
|
}
|
|
2233
|
+
bazaar.report(requirement.resourceId, sdkResult.extensionResponses);
|
|
2113
2234
|
if (!sdkResult.isValid) {
|
|
2114
2235
|
if (scope.transportFailed() || NO_VERDICT_REASONS.has(sdkResult.invalidReason ?? "")) {
|
|
2115
2236
|
if (sdkResult.invalidReason !== void 0) {
|
|
@@ -2222,15 +2343,12 @@ function createX402PaymentProvider(options) {
|
|
|
2222
2343
|
"authorization-flow",
|
|
2223
2344
|
"upfront-flow",
|
|
2224
2345
|
...severalOffers ? ["multiple-offers"] : [],
|
|
2225
|
-
...quotes ? ["erc-8409-quotes"] : []
|
|
2346
|
+
...quotes ? ["erc-8409-quotes"] : [],
|
|
2347
|
+
...options.resourceUrls !== void 0 ? ["public-resource-url"] : [],
|
|
2348
|
+
...options.resourceBazaar !== void 0 ? ["bazaar"] : []
|
|
2226
2349
|
],
|
|
2227
|
-
status:
|
|
2228
|
-
unsupported:
|
|
2229
|
-
"permit2 gas sponsoring extensions",
|
|
2230
|
-
"upto scheme",
|
|
2231
|
-
"batch-settlement scheme",
|
|
2232
|
-
"auth-capture scheme"
|
|
2233
|
-
]
|
|
2350
|
+
status: descriptorStatus(x402_default),
|
|
2351
|
+
unsupported: exclusionNames(x402_default)
|
|
2234
2352
|
};
|
|
2235
2353
|
const svmModule = hasSvm ? loadOptionalModule(() => import('./svm-4HR5OEP7.js'), "Solana offers need @x402/svm and @solana/kit") : void 0;
|
|
2236
2354
|
const nearModule = hasNear ? loadOptionalModule(() => import('./near-FH7HPZV3.js'), "NEAR offers need @x402/near") : void 0;
|
|
@@ -2263,8 +2381,9 @@ function createX402PaymentProvider(options) {
|
|
|
2263
2381
|
ctx,
|
|
2264
2382
|
createSvmFeePayerSource(supported)
|
|
2265
2383
|
);
|
|
2266
|
-
const
|
|
2267
|
-
const
|
|
2384
|
+
const bazaar = createBazaarForwarding(ctx, supported);
|
|
2385
|
+
const verify = createVerify(ctx, createNearRelayerSource(supported, logger), bazaar);
|
|
2386
|
+
const settle = createSettle(ctx, bazaar);
|
|
2268
2387
|
const health = createHealthCheck(ctx);
|
|
2269
2388
|
return {
|
|
2270
2389
|
name: "x402",
|
|
@@ -2298,5 +2417,5 @@ function loadOptionalModule(load, missing) {
|
|
|
2298
2417
|
}
|
|
2299
2418
|
|
|
2300
2419
|
export { DEFAULT_IDS, chainIdFromCaip2, createX402PaymentProvider, parseCanonicalAmount };
|
|
2301
|
-
//# sourceMappingURL=chunk-
|
|
2302
|
-
//# sourceMappingURL=chunk-
|
|
2420
|
+
//# sourceMappingURL=chunk-QZW5YL3G.js.map
|
|
2421
|
+
//# sourceMappingURL=chunk-QZW5YL3G.js.map
|