@devlab.group/agent-commerce 1.6.1 → 2.0.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/LICENSE +187 -2
- package/README.md +6 -6
- package/dist/ap2.d.ts +2 -2
- package/dist/ap2.js +94 -28
- package/dist/ap2.js.map +1 -1
- package/dist/{chunk-V2V2E7HX.js → chunk-3LUJHVKX.js} +4 -4
- package/dist/{chunk-V2V2E7HX.js.map → chunk-3LUJHVKX.js.map} +1 -1
- package/dist/{chunk-N5KRK7YA.js → chunk-53WXXIPR.js} +3 -3
- package/dist/{chunk-N5KRK7YA.js.map → chunk-53WXXIPR.js.map} +1 -1
- package/dist/chunk-CKJRITWY.js +113 -0
- package/dist/chunk-CKJRITWY.js.map +1 -0
- package/dist/chunk-HOZA3IWP.js +115 -0
- package/dist/chunk-HOZA3IWP.js.map +1 -0
- package/dist/{chunk-JKEKKXRJ.js → chunk-RKBGCPCK.js} +78 -25
- package/dist/chunk-RKBGCPCK.js.map +1 -0
- package/dist/{chunk-VKDXMXHL.js → chunk-SYEGCNJZ.js} +3 -3
- package/dist/{chunk-VKDXMXHL.js.map → chunk-SYEGCNJZ.js.map} +1 -1
- package/dist/{chunk-CBJIT7QP.js → chunk-TWRUNWDR.js} +11 -4
- package/dist/chunk-TWRUNWDR.js.map +1 -0
- package/dist/cli/index.js +142 -33
- package/dist/cli/index.js.map +1 -1
- package/dist/{constants-Bkq04FRZ.d.ts → constants-BSBRlKRR.d.ts} +2 -2
- package/dist/index.d.ts +42 -22
- package/dist/index.js +1254 -377
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +247 -94
- package/dist/mcp.js.map +1 -1
- package/dist/mpp.d.ts +6 -2
- package/dist/mpp.js +65 -28
- package/dist/mpp.js.map +1 -1
- package/dist/{guardrails-71XwtXlT.d.ts → payment-flow-DCS882tR.d.ts} +9 -1
- package/dist/{protocol-adapter-DTkrXTev.d.ts → protocol-adapter-DonxfAwa.d.ts} +2 -0
- package/dist/{types-O6lg3Q5V.d.ts → types-CVw6Sf46.d.ts} +11 -0
- package/dist/x402.d.ts +11 -3
- package/dist/x402.js +4 -4
- package/package.json +16 -13
- package/dist/chunk-AFI2CEZS.js +0 -10
- package/dist/chunk-AFI2CEZS.js.map +0 -1
- package/dist/chunk-CBJIT7QP.js.map +0 -1
- package/dist/chunk-JKEKKXRJ.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/domain/common.ts","../src/core/domain/event.ts","../src/core/domain/resource.ts","../src/core/errors/codes.ts","../src/core/errors/commerce-error.ts","../src/core/is-record.ts","../src/core/domain/wire.ts","../src/core/interfaces/logger.ts","../src/core/interfaces/protocol-adapter.ts","../src/core/interfaces/runtime.ts","../src/version.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;;;ACwBO,IAAM,0BAAA,GAA6B;;;ACxCnC,IAAM,oBAAA,GAAuB;AAAA,EAClC,gBAAA;AAAA,EACA,oBAAA;AAAA,EACA,eAAA;AAAA,EACA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GAAI,aAAA,KAAkB,MAAA,GAAY,EAAE,aAAA,KAAkB;AAAC,GACzD;AACF;;;AC1UO,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;ACGO,IAAM,eAAA,GACmC,OAAA","file":"chunk-N5KRK7YA.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\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 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","// 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\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 * Typed domain error codes. FROZEN CONTRACT. Protocol adapters map them into\n * their own response format. Never throw a bare string or untyped Error across\n * an area boundary.\n */\nexport const COMMERCE_ERROR_CODES = [\n 'CONFIG_INVALID',\n 'RESOURCE_NOT_FOUND',\n 'INPUT_INVALID',\n 'PAYMENT_REQUIRED',\n 'PAYMENT_INVALID',\n 'PAYMENT_REPLAYED',\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'PAYMENT_SETTLEMENT_FAILED',\n 'AUTHORIZATION_REQUIRED',\n 'AUTHORIZATION_INVALID',\n 'AUTHORIZATION_REPLAYED',\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n 'BACKEND_ERROR',\n 'PROTOCOL_UNSUPPORTED',\n 'GATEWAY_BUSY',\n 'STORAGE_ERROR',\n 'INTERNAL_ERROR',\n] as const;\n\nexport type CommerceErrorCode = (typeof COMMERCE_ERROR_CODES)[number];\n\n/**\n * Canonical HTTP status for each error code. Every payment failure maps to a\n * 4xx or 5xx status, never to a delivery.\n */\nexport const COMMERCE_ERROR_HTTP_STATUS: Readonly<Record<CommerceErrorCode, number>> = {\n CONFIG_INVALID: 500,\n RESOURCE_NOT_FOUND: 404,\n INPUT_INVALID: 400,\n PAYMENT_REQUIRED: 402,\n PAYMENT_INVALID: 402,\n PAYMENT_REPLAYED: 409,\n PAYMENT_PROVIDER_UNAVAILABLE: 503,\n PAYMENT_SETTLEMENT_FAILED: 502,\n // 403, not 402: a 402 tells a client to pay and retry, which cannot fix a\n // missing or rejected mandate, and a client that auto-pays on 402 would be\n // charged for a request that was never going to be delivered\n AUTHORIZATION_REQUIRED: 403,\n AUTHORIZATION_INVALID: 403,\n AUTHORIZATION_REPLAYED: 409,\n AUTHORIZATION_PROVIDER_UNAVAILABLE: 503,\n BACKEND_TIMEOUT: 504,\n BACKEND_ERROR: 502,\n PROTOCOL_UNSUPPORTED: 501,\n GATEWAY_BUSY: 503,\n STORAGE_ERROR: 500,\n INTERNAL_ERROR: 500,\n};\n\n/** Codes for which a client may reasonably retry the same request */\nexport const RETRYABLE_ERROR_CODES: ReadonlySet<CommerceErrorCode> = new Set([\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n // The verifier or replay store was unreachable, so the mandate got no\n // verdict. The same proof can verify once the outage clears.\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n // Load shedding is transient: the caller should back off and try again.\n // Clients act on this flag, and leaving it out would make a momentary\n // throttle look like a permanent failure.\n 'GATEWAY_BUSY',\n]);\n","// The single error type crossing area boundaries. FROZEN CONTRACT\nimport { COMMERCE_ERROR_HTTP_STATUS, type CommerceErrorCode, RETRYABLE_ERROR_CODES } from './codes';\n\nexport interface CommerceErrorOptions {\n /** Structured, non-secret detail safe to return to a client */\n readonly details?: Readonly<Record<string, unknown>>;\n readonly cause?: unknown;\n readonly requestId?: string;\n readonly resourceId?: string;\n /** Override the default HTTP status for this code */\n readonly httpStatus?: number;\n}\n\n/** Serializable wire form of a CommerceError */\nexport interface CommerceErrorInfo {\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport class CommerceError extends Error {\n readonly code: CommerceErrorCode;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n readonly requestId?: string;\n readonly resourceId?: string;\n\n constructor(code: CommerceErrorCode, message: string, options: CommerceErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = 'CommerceError';\n this.code = code;\n this.httpStatus = options.httpStatus ?? COMMERCE_ERROR_HTTP_STATUS[code];\n this.retryable = RETRYABLE_ERROR_CODES.has(code);\n if (options.details !== undefined) this.details = options.details;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.resourceId !== undefined) this.resourceId = options.resourceId;\n Error.captureStackTrace?.(this, CommerceError);\n }\n\n /** Non-secret, client-safe representation. `cause` is never included */\n toInfo(): CommerceErrorInfo {\n return {\n code: this.code,\n message: this.message,\n httpStatus: this.httpStatus,\n retryable: this.retryable,\n ...(this.requestId !== undefined ? { requestId: this.requestId } : {}),\n ...(this.resourceId !== undefined ? { resourceId: this.resourceId } : {}),\n ...(this.details !== undefined ? { details: this.details } : {}),\n };\n }\n}\n\nexport function isCommerceError(value: unknown): value is CommerceError {\n return value instanceof CommerceError;\n}\n\n/**\n * Passes an existing CommerceError through. Other thrown values become a\n * CommerceError with a caller-chosen message, for example\n * `toCommerceError(err, 'BACKEND_ERROR', 'Backend call failed')`.\n *\n * Arbitrary Error messages may contain internal URLs, hostnames or file paths.\n * The original value remains on `cause` for internal logging; `toInfo()` and\n * `toErrorEnvelope()` do not serialize it.\n */\nexport function toCommerceError(\n value: unknown,\n fallbackCode: CommerceErrorCode = 'INTERNAL_ERROR',\n fallbackMessage = 'Unexpected internal error',\n): CommerceError {\n if (isCommerceError(value)) return value;\n return new CommerceError(fallbackCode, fallbackMessage, { cause: value });\n}\n\n/** A thrown value reduced to its message and name, for a log line */\nexport function describeError(error: unknown): { message: string; name?: string } {\n if (error instanceof Error) return { message: error.message, name: error.name };\n return { message: String(error) };\n}\n\n/**\n * `Name: message` for a log line, with every URL cut to its scheme and host,\n * because a backend or RPC URL can carry a credential in its userinfo, path or\n * query\n */\nexport function redactedErrorText(value: unknown): string {\n const text = value instanceof Error ? `${value.name}: ${value.message}` : String(value);\n return text.replace(/\\b[a-z][a-z\\d+.-]*:\\/\\/[^\\s\"'<>]+/gi, (match) => {\n try {\n const url = new URL(match);\n return `${url.protocol}//${url.host}`;\n } catch {\n return '[unparseable URL]';\n }\n });\n}\n\n// Deepest `cause` level toLogInfo() follows, which also ends a cyclic chain\nconst MAX_LOGGED_CAUSES = 5;\n\n/**\n * An error for an operator log line: the `toInfo()` fields plus the `cause`\n * chain that `toInfo()` leaves out, each level as `redactedErrorText()` gives it\n */\nexport function toLogInfo(\n value: unknown,\n): CommerceErrorInfo & { readonly cause?: readonly string[] } {\n const error = toCommerceError(value);\n const cause: string[] = [];\n let current = error.cause;\n while (current !== undefined && cause.length < MAX_LOGGED_CAUSES) {\n cause.push(redactedErrorText(current));\n current = current instanceof Error ? current.cause : undefined;\n }\n return cause.length > 0 ? { ...error.toInfo(), cause } : error.toInfo();\n}\n","/** A non-null, non-array object. The prototype is not checked */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\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 readonly destination: string;\n readonly network?: string;\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 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\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 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 };\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 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","/**\n * The package version, resolved once for the whole package.\n *\n * The build injects `__OAC_PACKAGE_VERSION__` (tsup.config.ts), because a\n * relative manifest path resolves from the wrong depth once `src/**` is\n * bundled. From source, the root manifest is read instead. `typeof` on an\n * undeclared identifier is safe, so the source path runs without the constant.\n */\nimport { createRequire } from 'node:module';\n\ndeclare const __OAC_PACKAGE_VERSION__: string | undefined;\n\nfunction readFromManifest(): string {\n try {\n const require = createRequire(import.meta.url);\n // src/version.ts -> repository root\n return (require('../package.json') as { version?: string }).version ?? '0.0.0-unknown';\n } catch {\n return '0.0.0-unknown';\n }\n}\n\nexport const PACKAGE_VERSION: string =\n typeof __OAC_PACKAGE_VERSION__ === 'string' ? __OAC_PACKAGE_VERSION__ : readFromManifest();\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/domain/common.ts","../src/core/domain/event.ts","../src/core/domain/resource.ts","../src/core/errors/codes.ts","../src/core/errors/commerce-error.ts","../src/core/is-record.ts","../src/core/domain/wire.ts","../src/core/interfaces/logger.ts","../src/core/interfaces/protocol-adapter.ts","../src/core/interfaces/runtime.ts","../src/version.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,CAA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AAA,EAAU,cAAA,CAAe,CAAC,CAAA;AACzC,EAAA,MAAM,OAAA,GACJ,OAAO,YAAA,KAAiB,QAAA,IAAY,YAAA,CAAa,MAAA,GAAS,CAAA,IAAK,MAAA,KAAW,MAAA,GACrE,EAAE,MAAA,EAAQ,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;;;AC1UO,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;ACGO,IAAM,eAAA,GACmC,OAAA","file":"chunk-53WXXIPR.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\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 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","// 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\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 * Typed domain error codes. FROZEN CONTRACT. Protocol adapters map them into\n * their own response format. Never throw a bare string or untyped Error across\n * an area boundary.\n */\nexport const COMMERCE_ERROR_CODES = [\n 'CONFIG_INVALID',\n 'RESOURCE_NOT_FOUND',\n 'INPUT_INVALID',\n 'PAYMENT_REQUIRED',\n 'PAYMENT_INVALID',\n 'PAYMENT_REPLAYED',\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'PAYMENT_SETTLEMENT_FAILED',\n 'AUTHORIZATION_REQUIRED',\n 'AUTHORIZATION_INVALID',\n 'AUTHORIZATION_REPLAYED',\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n 'BACKEND_ERROR',\n 'PROTOCOL_UNSUPPORTED',\n 'GATEWAY_BUSY',\n 'STORAGE_ERROR',\n 'INTERNAL_ERROR',\n] as const;\n\nexport type CommerceErrorCode = (typeof COMMERCE_ERROR_CODES)[number];\n\n/**\n * Canonical HTTP status for each error code. Every payment failure maps to a\n * 4xx or 5xx status, never to a delivery.\n */\nexport const COMMERCE_ERROR_HTTP_STATUS: Readonly<Record<CommerceErrorCode, number>> = {\n CONFIG_INVALID: 500,\n RESOURCE_NOT_FOUND: 404,\n INPUT_INVALID: 400,\n PAYMENT_REQUIRED: 402,\n PAYMENT_INVALID: 402,\n PAYMENT_REPLAYED: 409,\n PAYMENT_PROVIDER_UNAVAILABLE: 503,\n PAYMENT_SETTLEMENT_FAILED: 502,\n // 403, not 402: a 402 tells a client to pay and retry, which cannot fix a\n // missing or rejected mandate, and a client that auto-pays on 402 would be\n // charged for a request that was never going to be delivered\n AUTHORIZATION_REQUIRED: 403,\n AUTHORIZATION_INVALID: 403,\n AUTHORIZATION_REPLAYED: 409,\n AUTHORIZATION_PROVIDER_UNAVAILABLE: 503,\n BACKEND_TIMEOUT: 504,\n BACKEND_ERROR: 502,\n PROTOCOL_UNSUPPORTED: 501,\n GATEWAY_BUSY: 503,\n STORAGE_ERROR: 500,\n INTERNAL_ERROR: 500,\n};\n\n/** Codes for which a client may reasonably retry the same request */\nexport const RETRYABLE_ERROR_CODES: ReadonlySet<CommerceErrorCode> = new Set([\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n // The verifier or replay store was unreachable, so the mandate got no\n // verdict. The same proof can verify once the outage clears.\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n // Load shedding is transient: the caller should back off and try again.\n // Clients act on this flag, and leaving it out would make a momentary\n // throttle look like a permanent failure.\n 'GATEWAY_BUSY',\n]);\n","// The single error type crossing area boundaries. FROZEN CONTRACT\nimport { COMMERCE_ERROR_HTTP_STATUS, type CommerceErrorCode, RETRYABLE_ERROR_CODES } from './codes';\n\nexport interface CommerceErrorOptions {\n /** Structured, non-secret detail safe to return to a client */\n readonly details?: Readonly<Record<string, unknown>>;\n readonly cause?: unknown;\n readonly requestId?: string;\n readonly resourceId?: string;\n /** Override the default HTTP status for this code */\n readonly httpStatus?: number;\n}\n\n/** Serializable wire form of a CommerceError */\nexport interface CommerceErrorInfo {\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport class CommerceError extends Error {\n readonly code: CommerceErrorCode;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n readonly requestId?: string;\n readonly resourceId?: string;\n\n constructor(code: CommerceErrorCode, message: string, options: CommerceErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = 'CommerceError';\n this.code = code;\n this.httpStatus = options.httpStatus ?? COMMERCE_ERROR_HTTP_STATUS[code];\n this.retryable = RETRYABLE_ERROR_CODES.has(code);\n if (options.details !== undefined) this.details = options.details;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.resourceId !== undefined) this.resourceId = options.resourceId;\n Error.captureStackTrace?.(this, CommerceError);\n }\n\n /** Non-secret, client-safe representation. `cause` is never included */\n toInfo(): CommerceErrorInfo {\n return {\n code: this.code,\n message: this.message,\n httpStatus: this.httpStatus,\n retryable: this.retryable,\n ...(this.requestId !== undefined ? { requestId: this.requestId } : {}),\n ...(this.resourceId !== undefined ? { resourceId: this.resourceId } : {}),\n ...(this.details !== undefined ? { details: this.details } : {}),\n };\n }\n}\n\nexport function isCommerceError(value: unknown): value is CommerceError {\n return value instanceof CommerceError;\n}\n\n/**\n * Passes an existing CommerceError through. Other thrown values become a\n * CommerceError with a caller-chosen message, for example\n * `toCommerceError(err, 'BACKEND_ERROR', 'Backend call failed')`.\n *\n * Arbitrary Error messages may contain internal URLs, hostnames or file paths.\n * The original value remains on `cause` for internal logging; `toInfo()` and\n * `toErrorEnvelope()` do not serialize it.\n */\nexport function toCommerceError(\n value: unknown,\n fallbackCode: CommerceErrorCode = 'INTERNAL_ERROR',\n fallbackMessage = 'Unexpected internal error',\n): CommerceError {\n if (isCommerceError(value)) return value;\n return new CommerceError(fallbackCode, fallbackMessage, { cause: value });\n}\n\n/** A thrown value reduced to its message and name, for a log line */\nexport function describeError(error: unknown): { message: string; name?: string } {\n if (error instanceof Error) return { message: error.message, name: error.name };\n return { message: String(error) };\n}\n\n/**\n * `Name: message` for a log line, with every URL cut to its scheme and host,\n * because a backend or RPC URL can carry a credential in its userinfo, path or\n * query\n */\nexport function redactedErrorText(value: unknown): string {\n const text = value instanceof Error ? `${value.name}: ${value.message}` : String(value);\n return text.replace(/\\b[a-z][a-z\\d+.-]*:\\/\\/[^\\s\"'<>]+/gi, (match) => {\n try {\n const url = new URL(match);\n return `${url.protocol}//${url.host}`;\n } catch {\n return '[unparseable URL]';\n }\n });\n}\n\n// Deepest `cause` level toLogInfo() follows, which also ends a cyclic chain\nconst MAX_LOGGED_CAUSES = 5;\n\n/**\n * An error for an operator log line: the `toInfo()` fields plus the `cause`\n * chain that `toInfo()` leaves out, each level as `redactedErrorText()` gives it\n */\nexport function toLogInfo(\n value: unknown,\n): CommerceErrorInfo & { readonly cause?: readonly string[] } {\n const error = toCommerceError(value);\n const cause: string[] = [];\n let current = error.cause;\n while (current !== undefined && cause.length < MAX_LOGGED_CAUSES) {\n cause.push(redactedErrorText(current));\n current = current instanceof Error ? current.cause : undefined;\n }\n return cause.length > 0 ? { ...error.toInfo(), cause } : error.toInfo();\n}\n","/** A non-null, non-array object. The prototype is not checked */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\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 readonly destination: string;\n readonly network?: string;\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 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\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 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 };\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 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","/**\n * The package version, resolved once for the whole package.\n *\n * The build injects `__OAC_PACKAGE_VERSION__` (tsup.config.ts), because a\n * relative manifest path resolves from the wrong depth once `src/**` is\n * bundled. From source, the root manifest is read instead. `typeof` on an\n * undeclared identifier is safe, so the source path runs without the constant.\n */\nimport { createRequire } from 'node:module';\n\ndeclare const __OAC_PACKAGE_VERSION__: string | undefined;\n\nfunction readFromManifest(): string {\n try {\n const require = createRequire(import.meta.url);\n // src/version.ts -> repository root\n return (require('../package.json') as { version?: string }).version ?? '0.0.0-unknown';\n } catch {\n return '0.0.0-unknown';\n }\n}\n\nexport const PACKAGE_VERSION: string =\n typeof __OAC_PACKAGE_VERSION__ === 'string' ? __OAC_PACKAGE_VERSION__ : readFromManifest();\n"]}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { isRecord } from './chunk-53WXXIPR.js';
|
|
2
|
+
import { createHash } from 'crypto';
|
|
3
|
+
|
|
4
|
+
// src/payments/mpp/problems.ts
|
|
5
|
+
var MPP_PROBLEM_BASE_URI = "https://paymentauth.org/problems/";
|
|
6
|
+
var TITLES = {
|
|
7
|
+
"payment-required": "Payment Required",
|
|
8
|
+
"malformed-credential": "Malformed Credential",
|
|
9
|
+
"invalid-challenge": "Invalid Challenge",
|
|
10
|
+
"payment-expired": "Payment Expired",
|
|
11
|
+
"verification-failed": "Verification Failed",
|
|
12
|
+
"internal-payment-error": "Internal Payment Error"
|
|
13
|
+
};
|
|
14
|
+
var REASON_TYPES = /* @__PURE__ */ new Map([
|
|
15
|
+
["malformed_credential", "malformed-credential"],
|
|
16
|
+
["invalid_payload", "malformed-credential"],
|
|
17
|
+
["invalid_challenge", "invalid-challenge"],
|
|
18
|
+
["challenge_not_issued", "invalid-challenge"],
|
|
19
|
+
["wrong_realm", "invalid-challenge"],
|
|
20
|
+
["wrong_resource", "invalid-challenge"],
|
|
21
|
+
["challenge_already_used", "invalid-challenge"],
|
|
22
|
+
["challenge_expired", "payment-expired"],
|
|
23
|
+
["authorization_expired", "payment-expired"]
|
|
24
|
+
]);
|
|
25
|
+
function mppProblem(code, httpStatus, reason) {
|
|
26
|
+
const problem = problemType(code, httpStatus, reason);
|
|
27
|
+
return { type: `${MPP_PROBLEM_BASE_URI}${problem}`, title: TITLES[problem] };
|
|
28
|
+
}
|
|
29
|
+
var REASON_DETAILS = /* @__PURE__ */ new Map([
|
|
30
|
+
["wrong_provider", "The challenge was issued for another payment method."],
|
|
31
|
+
["missing_challenge", "No challenge is available for this request."],
|
|
32
|
+
["malformed_credential", "The credential could not be decoded."],
|
|
33
|
+
["invalid_payload", "The credential payload does not match the expected format."],
|
|
34
|
+
["invalid_challenge", "The credential does not answer a valid challenge."],
|
|
35
|
+
["challenge_not_issued", "The challenge was not issued by this server or was altered."],
|
|
36
|
+
["challenge_already_used", "The challenge has already been used for a payment."],
|
|
37
|
+
["challenge_expired", "The challenge has expired."],
|
|
38
|
+
["wrong_realm", "The challenge was issued for another realm."],
|
|
39
|
+
["wrong_resource", "The challenge was issued for another resource."],
|
|
40
|
+
[
|
|
41
|
+
"unsupported_method",
|
|
42
|
+
"The challenge names a payment method or intent this server does not accept."
|
|
43
|
+
],
|
|
44
|
+
["unsupported_credential", "The credential type is not accepted for this challenge."],
|
|
45
|
+
["body_digest_mismatch", "The request body differs from the one the challenge was issued for."],
|
|
46
|
+
["wrong_amount", "The payment amount does not match the challenge."],
|
|
47
|
+
["wrong_recipient", "The payment recipient does not match the challenge."],
|
|
48
|
+
["wrong_network", "The payment uses a different network from the challenge."],
|
|
49
|
+
["wrong_asset", "The payment uses a different asset from the challenge."],
|
|
50
|
+
["wrong_terms", "The payment terms do not match the challenge."],
|
|
51
|
+
["wrong_nonce", "The authorization nonce is not derived from the challenge."],
|
|
52
|
+
["invalid_signature", "The authorization signature does not match the payer."],
|
|
53
|
+
["source_mismatch", "The credential source is not the account that signed the authorization."],
|
|
54
|
+
["authorization_not_yet_valid", "The authorization is not valid yet."],
|
|
55
|
+
["authorization_expired", "The authorization has expired."],
|
|
56
|
+
["authorization_invalid", "The authorization failed verification."],
|
|
57
|
+
["settlement_rejected", "The payment was refused before settlement."],
|
|
58
|
+
["settlement_mismatch", "The payment could not be matched to its settlement."],
|
|
59
|
+
["invalid_exact_evm_insufficient_balance", "The payer balance is too low for this payment."],
|
|
60
|
+
[
|
|
61
|
+
"invalid_exact_evm_transaction_simulation_failed",
|
|
62
|
+
"The transfer failed in simulation, so it was not submitted."
|
|
63
|
+
]
|
|
64
|
+
]);
|
|
65
|
+
function mppProblemDetail(reason, fallback) {
|
|
66
|
+
if (reason === void 0) return fallback;
|
|
67
|
+
return REASON_DETAILS.get(reason) ?? `The payment was refused: ${reason}.`;
|
|
68
|
+
}
|
|
69
|
+
function problemType(code, httpStatus, reason) {
|
|
70
|
+
if (code === "PAYMENT_REQUIRED") return "payment-required";
|
|
71
|
+
if (httpStatus >= 500) return "internal-payment-error";
|
|
72
|
+
if (code === "PAYMENT_REPLAYED") return "invalid-challenge";
|
|
73
|
+
return (reason !== void 0 ? REASON_TYPES.get(reason) : void 0) ?? "verification-failed";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// src/payments/mpp/transport.ts
|
|
77
|
+
var CONTENT_DIGEST_METADATA_KEY = "contentDigest";
|
|
78
|
+
function contentDigest(body) {
|
|
79
|
+
return `sha-256=:${createHash("sha256").update(body).digest("base64")}:`;
|
|
80
|
+
}
|
|
81
|
+
var MPP_MCP_CREDENTIAL_META_KEY = "org.paymentauth/credential";
|
|
82
|
+
var MPP_MCP_PAYMENT_REQUIRED_META_KEY = "org.paymentauth/payment-required";
|
|
83
|
+
var MPP_MCP_RECEIPT_META_KEY = "org.paymentauth/receipt";
|
|
84
|
+
function mcpPaymentRequired(envelope, refusal) {
|
|
85
|
+
const challenges = isRecord(envelope) ? envelope["challenges"] : void 0;
|
|
86
|
+
if (!Array.isArray(challenges) || challenges.length === 0) return void 0;
|
|
87
|
+
const reason = typeof refusal?.reason === "string" ? refusal.reason : void 0;
|
|
88
|
+
return {
|
|
89
|
+
httpStatus: 402,
|
|
90
|
+
challenges,
|
|
91
|
+
...refusal !== void 0 ? {
|
|
92
|
+
problem: {
|
|
93
|
+
...mppProblem(refusal.code, 402, reason),
|
|
94
|
+
status: 402,
|
|
95
|
+
detail: mppProblemDetail(reason, refusal.detail),
|
|
96
|
+
...reason !== void 0 ? { reason } : {}
|
|
97
|
+
}
|
|
98
|
+
} : {}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function receiptObject(serialized) {
|
|
102
|
+
if (typeof serialized !== "string") return void 0;
|
|
103
|
+
try {
|
|
104
|
+
const decoded = JSON.parse(Buffer.from(serialized, "base64url").toString("utf8"));
|
|
105
|
+
return isRecord(decoded) ? decoded : void 0;
|
|
106
|
+
} catch {
|
|
107
|
+
return void 0;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export { CONTENT_DIGEST_METADATA_KEY, MPP_MCP_CREDENTIAL_META_KEY, MPP_MCP_PAYMENT_REQUIRED_META_KEY, MPP_MCP_RECEIPT_META_KEY, contentDigest, mcpPaymentRequired, mppProblem, mppProblemDetail, receiptObject };
|
|
112
|
+
//# sourceMappingURL=chunk-CKJRITWY.js.map
|
|
113
|
+
//# sourceMappingURL=chunk-CKJRITWY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/payments/mpp/problems.ts","../src/payments/mpp/transport.ts"],"names":[],"mappings":";;;;AAMO,IAAM,oBAAA,GAAuB,mCAAA;AAUpC,IAAM,MAAA,GAAmD;AAAA,EACvD,kBAAA,EAAoB,kBAAA;AAAA,EACpB,sBAAA,EAAwB,sBAAA;AAAA,EACxB,mBAAA,EAAqB,mBAAA;AAAA,EACrB,iBAAA,EAAmB,iBAAA;AAAA,EACnB,qBAAA,EAAuB,qBAAA;AAAA,EACvB,wBAAA,EAA0B;AAC5B,CAAA;AAIA,IAAM,YAAA,uBAAwD,GAAA,CAAI;AAAA,EAChE,CAAC,wBAAwB,sBAAsB,CAAA;AAAA,EAC/C,CAAC,mBAAmB,sBAAsB,CAAA;AAAA,EAC1C,CAAC,qBAAqB,mBAAmB,CAAA;AAAA,EACzC,CAAC,wBAAwB,mBAAmB,CAAA;AAAA,EAC5C,CAAC,eAAe,mBAAmB,CAAA;AAAA,EACnC,CAAC,kBAAkB,mBAAmB,CAAA;AAAA,EACtC,CAAC,0BAA0B,mBAAmB,CAAA;AAAA,EAC9C,CAAC,qBAAqB,iBAAiB,CAAA;AAAA,EACvC,CAAC,yBAAyB,iBAAiB;AAC7C,CAAC,CAAA;AAGM,SAAS,UAAA,CACd,IAAA,EACA,UAAA,EACA,MAAA,EACmD;AACnD,EAAA,MAAM,OAAA,GAAU,WAAA,CAAY,IAAA,EAAM,UAAA,EAAY,MAAM,CAAA;AACpD,EAAA,OAAO,EAAE,IAAA,EAAM,CAAA,EAAG,oBAAoB,CAAA,EAAG,OAAO,CAAA,CAAA,EAAI,KAAA,EAAO,MAAA,CAAO,OAAO,C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,MACE,OAAA,EAAS;AAAA,QACP,GAAG,UAAA,CAAW,OAAA,CAAQ,IAAA,EAAM,KAAK,MAAM,CAAA;AAAA,QACvC,MAAA,EAAQ,GAAA;AAAA,QACR,MAAA,EAAQ,gBAAA,CAAiB,MAAA,EAAQ,OAAA,CAAQ,MAAM,CAAA;AAAA,QAC/C,GAAI,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,KAAW;AAAC;AAC3C,QAEF;AAAC,GACP;AACF;AAGO,SAAS,cAAc,UAAA,EAA0D;AACtF,EAAA,IAAI,OAAO,UAAA,KAAe,QAAA,EAAU,OAAO,MAAA;AAC3C,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,GAAmB,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,YAAY,WAAW,CAAA,CAAE,QAAA,CAAS,MAAM,CAAC,CAAA;AACzF,IAAA,OAAO,QAAA,CAAS,OAAO,CAAA,GAAI,OAAA,GAAU,KAAA,CAAA;AAAA,EACvC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-CKJRITWY.js","sourcesContent":["/**\n * Map MPP payment errors to the Problem Details types in\n * `draft-httpauth-payment-01`. This module has no optional peer imports, so\n * the main HTTP route can use it.\n */\n\nexport const MPP_PROBLEM_BASE_URI = 'https://paymentauth.org/problems/';\n\nexport type MppProblemType =\n | 'payment-required'\n | 'malformed-credential'\n | 'invalid-challenge'\n | 'payment-expired'\n | 'verification-failed'\n | 'internal-payment-error';\n\nconst TITLES: Readonly<Record<MppProblemType, string>> = {\n 'payment-required': 'Payment Required',\n 'malformed-credential': 'Malformed Credential',\n 'invalid-challenge': 'Invalid Challenge',\n 'payment-expired': 'Payment Expired',\n 'verification-failed': 'Verification Failed',\n 'internal-payment-error': 'Internal Payment Error',\n};\n\n// Map known MPP refusal reasons to problem types; other reasons use\n// `verification-failed`. A Map keeps facilitator text out of Object.prototype\nconst REASON_TYPES: ReadonlyMap<string, MppProblemType> = new Map([\n ['malformed_credential', 'malformed-credential'],\n ['invalid_payload', 'malformed-credential'],\n ['invalid_challenge', 'invalid-challenge'],\n ['challenge_not_issued', 'invalid-challenge'],\n ['wrong_realm', 'invalid-challenge'],\n ['wrong_resource', 'invalid-challenge'],\n ['challenge_already_used', 'invalid-challenge'],\n ['challenge_expired', 'payment-expired'],\n ['authorization_expired', 'payment-expired'],\n]);\n\n/** The Problem Details `type` URI and `title` for an MPP payment error */\nexport function mppProblem(\n code: string,\n httpStatus: number,\n reason?: string,\n): { readonly type: string; readonly title: string } {\n const problem = problemType(code, httpStatus, reason);\n return { type: `${MPP_PROBLEM_BASE_URI}${problem}`, title: TITLES[problem] };\n}\n\n// Descriptions for MPP reasons and two x402 facilitator refusals\nconst REASON_DETAILS: ReadonlyMap<string, string> = new Map([\n ['wrong_provider', 'The challenge was issued for another payment method.'],\n ['missing_challenge', 'No challenge is available for this request.'],\n ['malformed_credential', 'The credential could not be decoded.'],\n ['invalid_payload', 'The credential payload does not match the expected format.'],\n ['invalid_challenge', 'The credential does not answer a valid challenge.'],\n ['challenge_not_issued', 'The challenge was not issued by this server or was altered.'],\n ['challenge_already_used', 'The challenge has already been used for a payment.'],\n ['challenge_expired', 'The challenge has expired.'],\n ['wrong_realm', 'The challenge was issued for another realm.'],\n ['wrong_resource', 'The challenge was issued for another resource.'],\n [\n 'unsupported_method',\n 'The challenge names a payment method or intent this server does not accept.',\n ],\n ['unsupported_credential', 'The credential type is not accepted for this challenge.'],\n ['body_digest_mismatch', 'The request body differs from the one the challenge was issued for.'],\n ['wrong_amount', 'The payment amount does not match the challenge.'],\n ['wrong_recipient', 'The payment recipient does not match the challenge.'],\n ['wrong_network', 'The payment uses a different network from the challenge.'],\n ['wrong_asset', 'The payment uses a different asset from the challenge.'],\n ['wrong_terms', 'The payment terms do not match the challenge.'],\n ['wrong_nonce', 'The authorization nonce is not derived from the challenge.'],\n ['invalid_signature', 'The authorization signature does not match the payer.'],\n ['source_mismatch', 'The credential source is not the account that signed the authorization.'],\n ['authorization_not_yet_valid', 'The authorization is not valid yet.'],\n ['authorization_expired', 'The authorization has expired.'],\n ['authorization_invalid', 'The authorization failed verification.'],\n ['settlement_rejected', 'The payment was refused before settlement.'],\n ['settlement_mismatch', 'The payment could not be matched to its settlement.'],\n ['invalid_exact_evm_insufficient_balance', 'The payer balance is too low for this payment.'],\n [\n 'invalid_exact_evm_transaction_simulation_failed',\n 'The transfer failed in simulation, so it was not submitted.',\n ],\n]);\n\n/** Return a sentence for a known reason, or quote an unknown reason */\nexport function mppProblemDetail(reason: string | undefined, fallback: string): string {\n if (reason === undefined) return fallback;\n return REASON_DETAILS.get(reason) ?? `The payment was refused: ${reason}.`;\n}\n\nfunction problemType(code: string, httpStatus: number, reason?: string): MppProblemType {\n if (code === 'PAYMENT_REQUIRED') return 'payment-required';\n if (httpStatus >= 500) return 'internal-payment-error';\n // A replayed credential reuses its challenge because the replay key\n // includes the challenge-derived nonce\n if (code === 'PAYMENT_REPLAYED') return 'invalid-challenge';\n return (reason !== undefined ? REASON_TYPES.get(reason) : undefined) ?? 'verification-failed';\n}\n","/**\n * Build MPP MCP metadata accepted by the `mppx` client. This module has no\n * optional peer imports, so the `./mcp` subpath can use it.\n */\n\nimport { createHash } from 'node:crypto';\nimport { isRecord } from '../../core/is-record';\nimport { mppProblem, mppProblemDetail } from './problems';\n\n/**\n * `CanonicalRequest.metadata` key for the digest of an HTTP request body. The\n * MPP provider binds it into the challenge when present, so a credential\n * cannot pay for a different body.\n */\nexport const CONTENT_DIGEST_METADATA_KEY = 'contentDigest';\n\n/** RFC 9530 `sha-256` digest of a request body, the form of the MPP `digest` parameter */\nexport function contentDigest(body: Uint8Array): string {\n return `sha-256=:${createHash('sha256').update(body).digest('base64')}:`;\n}\n\n/** MCP `_meta` key of a tool call's credential object */\nexport const MPP_MCP_CREDENTIAL_META_KEY = 'org.paymentauth/credential';\n\n/** MCP `_meta` key of a tool result's challenges */\nexport const MPP_MCP_PAYMENT_REQUIRED_META_KEY = 'org.paymentauth/payment-required';\n\n/** MCP `_meta` key of a paid tool result's receipt object */\nexport const MPP_MCP_RECEIPT_META_KEY = 'org.paymentauth/receipt';\n\n/**\n * Build payment-required metadata from the provider's challenge objects.\n * Return undefined if the envelope has none. The draft uses JSON-RPC error\n * -32042; this gateway puts the data in a tool result's `_meta`, which\n * `mppx` also reads. A refusal adds its Problem Details, with the provider's\n * reason token in the `reason` member.\n */\nexport function mcpPaymentRequired(\n envelope: unknown,\n refusal?: { readonly code: string; readonly reason?: unknown; readonly detail: string },\n): Record<string, unknown> | undefined {\n const challenges = isRecord(envelope) ? envelope['challenges'] : undefined;\n if (!Array.isArray(challenges) || challenges.length === 0) return undefined;\n const reason = typeof refusal?.reason === 'string' ? refusal.reason : undefined;\n return {\n httpStatus: 402,\n challenges,\n ...(refusal !== undefined\n ? {\n problem: {\n ...mppProblem(refusal.code, 402, reason),\n status: 402,\n detail: mppProblemDetail(reason, refusal.detail),\n ...(reason !== undefined ? { reason } : {}),\n },\n }\n : {}),\n };\n}\n\n/** The receipt object from a serialized `Payment-Receipt` value, base64url JSON */\nexport function receiptObject(serialized: unknown): Record<string, unknown> | undefined {\n if (typeof serialized !== 'string') return undefined;\n try {\n const decoded: unknown = JSON.parse(Buffer.from(serialized, 'base64url').toString('utf8'));\n return isRecord(decoded) ? decoded : undefined;\n } catch {\n return undefined;\n }\n}\n"]}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { isRecord } from './chunk-53WXXIPR.js';
|
|
2
|
+
import { timingSafeEqual, createHash } from 'crypto';
|
|
3
|
+
|
|
4
|
+
// src/protocols/mcp/constants.ts
|
|
5
|
+
var MCP_TOOL_NAME_CHARS = "A-Za-z0-9._-";
|
|
6
|
+
var MCP_TOOL_NAME_MAX_LENGTH = 128;
|
|
7
|
+
var MCP_TOOL_NAME_PATTERN = new RegExp(
|
|
8
|
+
`^[${MCP_TOOL_NAME_CHARS}]{1,${MCP_TOOL_NAME_MAX_LENGTH}}$`
|
|
9
|
+
);
|
|
10
|
+
var MCP_MODERN_PROTOCOL_REVISION = "2026-07-28";
|
|
11
|
+
var BEARER_PREFIX = /^Bearer +/i;
|
|
12
|
+
function createBearerCheck(expectedToken) {
|
|
13
|
+
const expected = sha256(expectedToken);
|
|
14
|
+
return (header) => {
|
|
15
|
+
if (header === void 0 || !BEARER_PREFIX.test(header)) return false;
|
|
16
|
+
const presented = header.replace(BEARER_PREFIX, "");
|
|
17
|
+
return presented.length > 0 && timingSafeEqual(sha256(presented), expected);
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function sha256(value) {
|
|
21
|
+
return createHash("sha256").update(value, "utf8").digest();
|
|
22
|
+
}
|
|
23
|
+
async function readCappedBody(req, maxBytes) {
|
|
24
|
+
const chunks = [];
|
|
25
|
+
let total = 0;
|
|
26
|
+
try {
|
|
27
|
+
for await (const chunk of req) {
|
|
28
|
+
const buffer = chunk;
|
|
29
|
+
total += buffer.length;
|
|
30
|
+
if (total > maxBytes) return { kind: "too-large" };
|
|
31
|
+
chunks.push(buffer);
|
|
32
|
+
}
|
|
33
|
+
} catch {
|
|
34
|
+
return { kind: "unreadable" };
|
|
35
|
+
}
|
|
36
|
+
return { kind: "ok", text: Buffer.concat(chunks).toString("utf8") };
|
|
37
|
+
}
|
|
38
|
+
function joinUrl(baseUrl, mountPath) {
|
|
39
|
+
return `${baseUrl.replace(/\/+$/, "")}/${mountPath.replace(/^\/+|\/+$/g, "")}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/payments/x402/transport.ts
|
|
43
|
+
var X402_MCP_PAYMENT_META_KEY = "x402/payment";
|
|
44
|
+
var X402_MCP_ERROR_META_KEY = "x402/error";
|
|
45
|
+
function x402McpPaymentSubmission(value) {
|
|
46
|
+
if (value === void 0 || value === null) return void 0;
|
|
47
|
+
if (typeof value === "string") return value;
|
|
48
|
+
return Buffer.from(JSON.stringify(value), "utf8").toString("base64");
|
|
49
|
+
}
|
|
50
|
+
var X402_MCP_PAYMENT_RESPONSE_META_KEY = "x402/payment-response";
|
|
51
|
+
function x402ErrorCode(code, reason) {
|
|
52
|
+
if (code === "PAYMENT_REPLAYED") return "invalid_exact_evm_nonce_already_used";
|
|
53
|
+
return typeof reason === "string" ? reason : "unexpected_verify_error";
|
|
54
|
+
}
|
|
55
|
+
function settlementDocument(payment) {
|
|
56
|
+
return {
|
|
57
|
+
success: payment.status === "settled",
|
|
58
|
+
transaction: payment.externalReference ?? "",
|
|
59
|
+
network: payment.network ?? "",
|
|
60
|
+
...payment.payer !== void 0 ? { payer: payment.payer } : {},
|
|
61
|
+
...payment.amountBaseUnits !== void 0 ? { amount: payment.amountBaseUnits } : {},
|
|
62
|
+
status: payment.status,
|
|
63
|
+
provider: payment.provider,
|
|
64
|
+
currency: payment.currency,
|
|
65
|
+
...payment.externalReference !== void 0 ? { externalReference: payment.externalReference } : {}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function settlementResponse(payment) {
|
|
69
|
+
const amountBaseUnits = payment.metadata?.["amountBaseUnits"];
|
|
70
|
+
return settlementDocument({
|
|
71
|
+
...payment,
|
|
72
|
+
...typeof amountBaseUnits === "string" ? { amountBaseUnits } : {}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
function settlementResponseFromDetails(details) {
|
|
76
|
+
const payment = details?.["payment"];
|
|
77
|
+
if (!isRecord(payment)) return void 0;
|
|
78
|
+
const text = (key) => typeof payment[key] === "string" ? payment[key] : void 0;
|
|
79
|
+
const status = text("status");
|
|
80
|
+
const provider = text("provider");
|
|
81
|
+
const currency = text("currency");
|
|
82
|
+
if (status === void 0 || provider === void 0 || currency === void 0) return void 0;
|
|
83
|
+
return settlementDocument({
|
|
84
|
+
status,
|
|
85
|
+
provider,
|
|
86
|
+
currency,
|
|
87
|
+
network: text("network"),
|
|
88
|
+
externalReference: text("externalReference"),
|
|
89
|
+
payer: text("payer"),
|
|
90
|
+
amountBaseUnits: text("amountBaseUnits")
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
function settlementFailure(details) {
|
|
94
|
+
const text = (key) => {
|
|
95
|
+
const value = details?.[key];
|
|
96
|
+
return typeof value === "string" ? value : void 0;
|
|
97
|
+
};
|
|
98
|
+
const transaction = text("transactionHash");
|
|
99
|
+
const payer = text("payer");
|
|
100
|
+
let errorReason = text("reason") ?? "unexpected_settle_error";
|
|
101
|
+
if (details?.["settlementUncertain"] === true) {
|
|
102
|
+
errorReason = transaction !== void 0 ? "settlement_pending" : "unexpected_settle_error";
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
success: false,
|
|
106
|
+
errorReason,
|
|
107
|
+
transaction: transaction ?? "",
|
|
108
|
+
network: text("network") ?? "",
|
|
109
|
+
...payer !== void 0 ? { payer } : {}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export { MCP_MODERN_PROTOCOL_REVISION, MCP_TOOL_NAME_PATTERN, X402_MCP_ERROR_META_KEY, X402_MCP_PAYMENT_META_KEY, X402_MCP_PAYMENT_RESPONSE_META_KEY, createBearerCheck, joinUrl, readCappedBody, settlementFailure, settlementResponse, settlementResponseFromDetails, x402ErrorCode, x402McpPaymentSubmission };
|
|
114
|
+
//# sourceMappingURL=chunk-HOZA3IWP.js.map
|
|
115
|
+
//# sourceMappingURL=chunk-HOZA3IWP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/protocols/mcp/constants.ts","../src/protocols/http.ts","../src/payments/x402/transport.ts"],"names":[],"mappings":";;;;AAUO,IAAM,mBAAA,GAAsB,cAAA;AAG5B,IAAM,wBAAA,GAA2B,GAAA;AAQjC,IAAM,wBAAwB,IAAI,MAAA;AAAA,EACvC,CAAA,EAAA,EAAK,mBAAmB,CAAA,IAAA,EAAO,wBAAwB,CAAA,EAAA;AACzD;AAMO,IAAM,4BAAA,GAA+B;ACzB5C,IAAM,aAAA,GAAgB,YAAA;AAQf,SAAS,kBAAk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CAAA;AAC3B,IAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAAQ,MAAA;AAAA,EAC7C,CAAA;AACA,EAAA,MAAM,WAAA,GAAc,KAAK,iBAAiB,CAAA;AAC1C,EAAA,MAAM,KAAA,GAAQ,KAAK,OAAO,CAAA;AAC1B,EAAA,IAAI,WAAA,GAAc,IAAA,CAAK,QAAQ,CAAA,IAAK,yBAAA;AACpC,EAAA,IAAI,OAAA,GAAU,qBAAqB,CAAA,KAAM,IAAA,EAAM;AAC7C,IAAA,WAAA,GAAc,WAAA,KAAgB,SAAY,oBAAA,GAAuB,yBAAA;AAAA,EACnE;AACA,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT,WAAA;AAAA,IACA,aAAa,WAAA,IAAe,EAAA;AAAA,IAC5B,OAAA,EAAS,IAAA,CAAK,SAAS,CAAA,IAAK,EAAA;AAAA,IAC5B,GAAI,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,KAAU;AAAC,GACzC;AACF","file":"chunk-HOZA3IWP.js","sourcesContent":["/**\n * MCP protocol constants shared by the config layer, the adapter and the\n * OpenAPI importer.\n *\n * Kept dependency-free: `src/config` validates tool names at load time, so\n * anything imported here would become a config-load dependency too, and the\n * MCP SDK is an optional peer the main entry and CLI must never load.\n */\n\n/** Characters SEP-986 allows in an MCP tool name, as a regex character class body */\nexport const MCP_TOOL_NAME_CHARS = 'A-Za-z0-9._-';\n\n/** Longest MCP tool name SEP-986 allows */\nexport const MCP_TOOL_NAME_MAX_LENGTH = 128;\n\n/**\n * MCP tool names per SEP-986: 1-128 chars of [A-Za-z0-9._-], the SDK's own\n * `TOOL_NAME_REGEX`, which it does not export. Config refuses an mcp-exposed\n * resource whose id fails it; the low-level `Server` checks no names, so the\n * adapter also skips such an id with a warning.\n */\nexport const MCP_TOOL_NAME_PATTERN = new RegExp(\n `^[${MCP_TOOL_NAME_CHARS}]{1,${MCP_TOOL_NAME_MAX_LENGTH}}$`,\n);\n\n/**\n * The modern revision served by the SDK. A v2 client negotiates this value\n * in the conformance test.\n */\nexport const MCP_MODERN_PROTOCOL_REVISION = '2026-07-28';\n","// HTTP helpers shared by the A2A and ACP adapters and the gateway's admin-token gate\nimport { createHash, timingSafeEqual } from 'node:crypto';\nimport type { IncomingMessage } from 'node:http';\n\nconst BEARER_PREFIX = /^Bearer +/i;\n\n/**\n * Builds a check of an `Authorization: Bearer <token>` header against a fixed\n * token. The scheme is case-insensitive (RFC 9110). Both sides are compared as\n * SHA-256 digests, because `timingSafeEqual` throws on a length mismatch and\n * would reveal the token's length; the expected digest is computed once here.\n */\nexport function createBearerCheck(expectedToken: string): (header: string | undefined) => boolean {\n const expected = sha256(expectedToken);\n return (header) => {\n if (header === undefined || !BEARER_PREFIX.test(header)) return false;\n const presented = header.replace(BEARER_PREFIX, '');\n return presented.length > 0 && timingSafeEqual(sha256(presented), expected);\n };\n}\n\nfunction sha256(value: string): Buffer {\n return createHash('sha256').update(value, 'utf8').digest();\n}\n\n/** A tagged result, so no body text can be mistaken for a failure */\nexport type BodyRead =\n | { readonly kind: 'ok'; readonly text: string }\n | { readonly kind: 'too-large' }\n | { readonly kind: 'unreadable' };\n\n/**\n * Reads the unconsumed request stream the gateway hands an adapter, stopping\n * at the cap rather than buffering whatever arrives\n */\nexport async function readCappedBody(req: IncomingMessage, maxBytes: number): Promise<BodyRead> {\n const chunks: Buffer[] = [];\n let total = 0;\n try {\n for await (const chunk of req) {\n const buffer = chunk as Buffer;\n total += buffer.length;\n if (total > maxBytes) return { kind: 'too-large' };\n chunks.push(buffer);\n }\n } catch {\n return { kind: 'unreadable' };\n }\n return { kind: 'ok', text: Buffer.concat(chunks).toString('utf8') };\n}\n\n/**\n * Joins a base URL and a mount path with exactly one slash between them and\n * none at the end. Plain concatenation can yield `https://host//a2a`, which a\n * router may treat as a different path.\n */\nexport function joinUrl(baseUrl: string, mountPath: string): string {\n return `${baseUrl.replace(/\\/+$/, '')}/${mountPath.replace(/^\\/+|\\/+$/g, '')}`;\n}\n","/**\n * Build x402 v2 responses for the HTTP route and MCP adapter. This module\n * has no optional peer imports, so both entries can use it.\n */\n\nimport type { PaymentResult } from '../../core';\nimport { isRecord } from '../../core/is-record';\n\n/** MCP `_meta` key of a tool call's `PaymentPayload` (x402 MCP transport) */\nexport const X402_MCP_PAYMENT_META_KEY = 'x402/payment';\n\n/** Challenge key read by the `cloudflare/agents` x402 MCP client */\nexport const X402_MCP_ERROR_META_KEY = 'x402/error';\n\n/**\n * Accept an object or base64 string from `x402/payment` and return the string\n * the provider decodes. An absent value returns undefined; other JSON\n * values are encoded for provider validation.\n */\nexport function x402McpPaymentSubmission(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === 'string') return value;\n return Buffer.from(JSON.stringify(value), 'utf8').toString('base64');\n}\n\n/** MCP `_meta` key of a tool result's settlement response (x402 MCP transport) */\nexport const X402_MCP_PAYMENT_RESPONSE_META_KEY = 'x402/payment-response';\n\n/**\n * Return the provider's x402 refusal reason when available. For a replay,\n * use the spent-nonce code returned by x402 facilitators.\n */\nexport function x402ErrorCode(code: string, reason: unknown): string {\n if (code === 'PAYMENT_REPLAYED') return 'invalid_exact_evm_nonce_already_used';\n return typeof reason === 'string' ? reason : 'unexpected_verify_error';\n}\n\ninterface SettledPayment {\n readonly status: string;\n readonly provider: string;\n readonly currency: string;\n readonly network?: string | undefined;\n readonly externalReference?: string | undefined;\n readonly payer?: string | undefined;\n readonly amountBaseUnits?: string | undefined;\n}\n\n// The `SettleResponse` shape. When present, `amount` uses base units.\n// `status`, `provider`, `currency`, and `externalReference` are gateway\n// extensions; an x402 v2 client ignores fields it does not know.\nfunction settlementDocument(payment: SettledPayment): Record<string, unknown> {\n return {\n success: payment.status === 'settled',\n transaction: payment.externalReference ?? '',\n network: payment.network ?? '',\n ...(payment.payer !== undefined ? { payer: payment.payer } : {}),\n ...(payment.amountBaseUnits !== undefined ? { amount: payment.amountBaseUnits } : {}),\n status: payment.status,\n provider: payment.provider,\n currency: payment.currency,\n ...(payment.externalReference !== undefined\n ? { externalReference: payment.externalReference }\n : {}),\n };\n}\n\n/** A delivered payment's settlement response */\nexport function settlementResponse(payment: PaymentResult): Record<string, unknown> {\n const amountBaseUnits = payment.metadata?.['amountBaseUnits'];\n return settlementDocument({\n ...payment,\n ...(typeof amountBaseUnits === 'string' ? { amountBaseUnits } : {}),\n });\n}\n\n/**\n * The settlement response for a backend failure after settlement, from the\n * error's `details.payment`; undefined when the error carries none\n */\nexport function settlementResponseFromDetails(\n details: Readonly<Record<string, unknown>> | undefined,\n): Record<string, unknown> | undefined {\n const payment = details?.['payment'];\n if (!isRecord(payment)) return undefined;\n const text = (key: string): string | undefined =>\n typeof payment[key] === 'string' ? payment[key] : undefined;\n const status = text('status');\n const provider = text('provider');\n const currency = text('currency');\n if (status === undefined || provider === undefined || currency === undefined) return undefined;\n return settlementDocument({\n status,\n provider,\n currency,\n network: text('network'),\n externalReference: text('externalReference'),\n payer: text('payer'),\n amountBaseUnits: text('amountBaseUnits'),\n });\n}\n\n/**\n * A refused or unconfirmed settlement as a failed `SettleResponse`. An\n * unconfirmed transfer with a hash uses x402's `settlement_pending` reason.\n */\nexport function settlementFailure(\n details: Readonly<Record<string, unknown>> | undefined,\n): Record<string, unknown> {\n const text = (key: string): string | undefined => {\n const value = details?.[key];\n return typeof value === 'string' ? value : undefined;\n };\n const transaction = text('transactionHash');\n const payer = text('payer');\n let errorReason = text('reason') ?? 'unexpected_settle_error';\n if (details?.['settlementUncertain'] === true) {\n errorReason = transaction !== undefined ? 'settlement_pending' : 'unexpected_settle_error';\n }\n return {\n success: false,\n errorReason,\n transaction: transaction ?? '',\n network: text('network') ?? '',\n ...(payer !== undefined ? { payer } : {}),\n };\n}\n"]}
|