import { type x402PaymentRequirements as x402PaymentRequirementsV1, type x402PaymentPayload as x402PaymentPayloadV1, type x402VerifyResponse as x402VerifyResponseV1, x402SettleResponse as x402SettleResponseV1 } from "@faremeter/types/x402"; import { type x402PaymentRequirements, type x402PaymentPayload, type x402ResourceInfo, x402SettleResponse, x402VerifyResponse } from "@faremeter/types/x402v2"; import type { FacilitatorHandler } from "@faremeter/types/facilitator"; import type { ResourcePricing, HandlerCapabilities } from "@faremeter/types/pricing"; import type { MPPMethodHandler, mppCredential, mppReceipt } from "@faremeter/types/mpp"; import type { AgedLRUCacheOpts } from "./cache.js"; /** * Finds the payment requirement that matches the client's v1 payment payload. * * @param accepts - Array of accepted payment requirements from the facilitator * @param payload - The client's payment payload * @returns The matching requirement, or undefined if no match found */ export declare function findMatchingPaymentRequirements(accepts: x402PaymentRequirementsV1[], payload: x402PaymentPayloadV1): { scheme: string; network: string; maxAmountRequired: string; resource: string; description: string; payTo: string; maxTimeoutSeconds: number; asset: string; mimeType?: string; outputSchema?: object; extra?: object; } | undefined; /** * Finds the payment requirement that matches the client's v2 payment payload. * * @param accepts - Array of accepted payment requirements from the facilitator * @param payload - The client's v2 payment payload * @returns The matching requirement, or undefined if no match found */ export declare function findMatchingPaymentRequirementsV2(accepts: x402PaymentRequirements[], payload: x402PaymentPayload): x402PaymentRequirements | undefined; export type RelaxedRequirements = Partial; export type RelaxedRequirementsV2 = Partial; /** * Converts v1 relaxed requirements to v2 format, preserving all fields * including `extra`. */ export declare function relaxedRequirementsToV2(req: RelaxedRequirements): RelaxedRequirementsV2; type PossibleStatusCodes = 400 | 402; type PossibleJSONResponse = object; /** * Configuration for which x402 protocol versions the middleware supports. * At least one version must be enabled. */ export type SupportedVersionsConfig = { /** Support x402 v1 protocol (JSON body responses, X-PAYMENT header). Default: true */ x402v1?: boolean; /** Support x402 v2 protocol (PAYMENT-REQUIRED header, PAYMENT-SIGNATURE header). Default: false */ x402v2?: boolean; }; /** * Resolve and validate supported versions config. * Returns resolved config with defaults applied. * Throws if configuration is invalid. */ export declare function resolveSupportedVersions(config?: SupportedVersionsConfig): Required; /** * Common configuration arguments shared by all middleware implementations. * Supports two mutually exclusive modes: in-process handlers or remote facilitator. */ export type CommonMiddlewareArgs = { /** x402 handlers for in-process settlement. */ x402Handlers?: FacilitatorHandler[]; /** MPP method handlers for in-process settlement. */ mppMethodHandlers?: MPPMethodHandler[]; /** Protocol-agnostic pricing for in-process handlers. */ pricing?: ResourcePricing[]; /** URL of a remote facilitator service (backward compat). */ facilitatorURL?: string; /** Payment requirements for the remote facilitator path. */ accepts?: (RelaxedRequirements | RelaxedRequirements[])[]; /** Cache configuration for remote facilitator responses. */ cacheConfig?: AgedLRUCacheOpts & { disable?: boolean; }; /** Which x402 protocol versions to support. */ supportedVersions?: SupportedVersionsConfig; }; /** * Validates that CommonMiddlewareArgs has exactly one configuration mode. */ export declare function validateMiddlewareArgs(args: CommonMiddlewareArgs): void; /** * Derives `HandlerCapabilities` from relaxed v1 requirements. * Used by framework adapters to construct capabilities for the HTTP wrapper * from the legacy `accepts` configuration. */ export declare function deriveCapabilities(accepts: RelaxedRequirements[]): HandlerCapabilities; /** * Derives the distinct set of x402 schemes from relaxed v1 requirements. * Sibling of {@link deriveCapabilities}; kept separate because schemes are * x402-specific and live on the handler rather than on * {@link HandlerCapabilities}. */ export declare function deriveSchemes(accepts: RelaxedRequirements[]): string[]; /** * Extracts resource info from v1 accepts entries. * Used by framework adapters to build the resource info for the 402 response. */ export declare function deriveResourceInfo(accepts: RelaxedRequirements[], resourceURL: string): x402ResourceInfo; export declare function acceptsToPricing(accepts: RelaxedRequirements[]): ResourcePricing[]; export type CreateRemoteX402HandlersArgs = { facilitatorURL: string; accepts: (RelaxedRequirements | RelaxedRequirements[])[]; cacheConfig?: AgedLRUCacheOpts & { disable?: boolean; }; }; /** * Creates x402 facilitator handlers backed by a remote HTTP facilitator. * * This is the composable equivalent of the `facilitatorURL` + `accepts` * shorthand on {@link CommonMiddlewareArgs}. Use it when you need to * combine a remote x402 facilitator with in-process MPP handlers in the * same middleware. * * @returns An array of `FacilitatorHandler` suitable for * `createMiddleware({ x402Handlers: ... })`. */ export declare function createRemoteX402Handlers(args: CreateRemoteX402HandlersArgs): FacilitatorHandler[]; export type ResolvedConfig = { handlers: FacilitatorHandler[]; pricing: ResourcePricing[]; mppHandlers: MPPMethodHandler[]; resourceInfo?: x402ResourceInfo; }; /** * Resolves {@link CommonMiddlewareArgs} into the handlers + pricing tuple * that {@link handleMiddlewareRequest} needs. For the `facilitatorURL` path, * creates an HTTP handler wrapper and converts accepts to pricing. */ export declare function resolveConfig(args: CommonMiddlewareArgs): ResolvedConfig; export type CaptureResultV1 = { success: true; response: x402SettleResponseV1; } | { success: false; errorResponse: MiddlewareResponse; errorMessage?: string; }; export type CaptureResultV2 = { success: true; response: x402SettleResponse; } | { success: false; errorResponse: MiddlewareResponse; errorMessage?: string; }; export type CaptureResult = CaptureResultV1 | CaptureResultV2; export type AuthorizeResultV1 = { success: true; response: x402VerifyResponseV1; } | { success: false; errorResponse: MiddlewareResponse; errorMessage?: string; }; export type AuthorizeResultV2 = { success: true; response: x402VerifyResponse; } | { success: false; errorResponse: MiddlewareResponse; errorMessage?: string; }; export type AuthorizeResult = AuthorizeResultV1 | AuthorizeResultV2; /** * When the body callback should drive capture. * * `"request"` — one-phase: body calls `capture()` immediately and the * payment clears before the resource is produced. * * `"response"` — two-phase: body calls `authorize()` now and defers * capture to a later phase (the OpenAPI gateway captures at * `/response` once the final amount is known). * * The middleware resolves this per-request via {@link resolveCapturesAt} * from the matched handler's authorize capability and the rule's * `hasAuthorize` flag, so the body callback never has to inspect the * context shape to decide which path to take. */ export type CapturesAt = "request" | "response"; /** * Per-operation payment policy. Restricts which protocol schemes / * methods are accepted for a given route and optionally pins specific * ones to one-phase or two-phase capture regardless of the handler's * declared capability. * * Keys in `allow` and `pin` are of the form `":"`: * * - `"x402:exact"`, `"x402:permit2"` — x402 schemes * - `"mpp:solana"` — MPP methods * * The protocol prefix is case-sensitive and uses the lowercase wire * form (`"mpp:"`, not `"MPP:"`), matching how schemes and methods are * identified on the protocol surface itself. * * `allow: undefined` permits every registered scheme and method. * `allow: []` denies all of them (the deny-all sentinel). * * `pin["x402:exact"].capturesAt: "request"` forces one-phase capture * for that scheme regardless of whether the handler supports * `handleVerify` and regardless of whether the rule has `authorize`. * A pin to `"response"` against a handler that cannot authorize is a * configuration error caught at construction. */ export type PaymentPolicy = { allow?: string[]; pin?: Record; }; /** * Context provided to the middleware body handler for v1 protocol requests. * Contains payment information and the industry-standard `authorize` / * `capture` operations. Under the hood these dispatch to the matched * x402 facilitator handler's `handleVerify` / `handleSettle`. */ export type MiddlewareBodyContextV1 = { protocolVersion: 1; capturesAt: CapturesAt; paymentRequirements: x402PaymentRequirementsV1; paymentPayload: x402PaymentPayloadV1; capture: () => Promise>; authorize: () => Promise>; }; /** * Context provided to the middleware body handler for v2 protocol requests. * Contains payment information and the industry-standard `authorize` / * `capture` operations. Under the hood these dispatch to the matched * x402 facilitator handler's `handleVerify` / `handleSettle`. */ export type MiddlewareBodyContextV2 = { protocolVersion: 2; capturesAt: CapturesAt; paymentRequirements: x402PaymentRequirements; paymentPayload: x402PaymentPayload; capture: () => Promise>; authorize: () => Promise>; }; export type CaptureResultMPP = { success: true; receipt: mppReceipt; } | { success: false; errorResponse: MiddlewareResponse; errorMessage?: string; }; export type AuthorizeResultMPP = { success: true; receipt: mppReceipt; } | { success: false; errorResponse: MiddlewareResponse; errorMessage?: string; }; /** * Context provided to the middleware body handler for MPP protocol requests. * * `authorize` is optional because not every MPP method handler implements * `handleVerify`. When `capturesAt === "response"` the middleware * guarantees `authorize` is defined (the resolver only picks * `"response"` when at least one matching handler can verify). */ export type MiddlewareBodyContextMPP = { protocolVersion: "mpp"; capturesAt: CapturesAt; credential: mppCredential; capture: () => Promise>; authorize?: (() => Promise>) | undefined; }; /** * Context provided to the middleware body handler. * Use protocolVersion to discriminate between v1, v2, and mpp request types. */ export type MiddlewareBodyContext = MiddlewareBodyContextV1 | MiddlewareBodyContextV2 | MiddlewareBodyContextMPP; /** * Arguments for the core middleware request handler. * Framework-specific middleware implementations adapt their request/response * objects to this interface. */ export type HandleMiddlewareRequestArgs = { /** x402 handlers for in-process settlement. */ x402Handlers?: FacilitatorHandler[]; /** MPP method handlers for in-process settlement. */ mppMethodHandlers?: MPPMethodHandler[]; /** Protocol-agnostic pricing entries for the current request. */ pricing: ResourcePricing[]; /** The resource URL being accessed. */ resource: string; /** Resolved supported versions configuration. */ supportedVersions: Required; /** Function to retrieve a request header value. */ getHeader: (key: string) => string | undefined; /** Function to send a JSON response with optional headers. */ sendJSONResponse: (status: PossibleStatusCodes, body?: PossibleJSONResponse, headers?: Record) => MiddlewareResponse; /** Handler function called when a valid payment is received. */ body: (context: MiddlewareBodyContext) => Promise; /** Optional function to set a response header. */ setResponseHeader?: (key: string, value: string) => void; /** Optional pre-built resource info for the 402 response. */ resourceInfo?: x402ResourceInfo; /** Optional accessor for the request body (for RFC 9530 digest). */ getBody?: () => Promise; /** * Whether the matched pricing rule has an explicit `authorize` * expression (i.e. is two-phase). Drives the per-handler `capturesAt` * decision resolved before each `body` invocation. Defaults to false; * non-OpenAPI callers that have no rule shape leave this unset and * the middleware treats every request as one-phase. */ hasAuthorize?: boolean; /** * Per-operation payment policy. Restricts which schemes / methods * are advertised in the 402 challenge, rejects payments for * disallowed schemes, and threads `pin` overrides into the * `capturesAt` resolution per matched handler. */ policy?: PaymentPolicy; }; /** * Resolves whether the body callback should capture at `/request` * (one-phase) or defer to `/response` (two-phase). * * | `canAuthorize` | `hasAuthorize` | `pin` | `capturesAt` | * |----------------|----------------|--------------|--------------| * | false | any | none | `request` | * | true | false | none | `request` | * | true | true | none | `response` | * | any | any | `"request"` | `request` | * | true | any | `"response"` | `response` | * * `canAuthorize` is "any handler that actually accepts THIS scheme / * method declares verification". For x402 the candidate set is * `narrowHandlers(handlers, requirements)` further filtered by * `h.schemes?.includes(requirements.scheme)` — the scheme filter is * load-bearing because `narrowHandlers` only checks network and * asset, so without it a multi-scheme handler set with one verify- * capable handler would leak `canAuthorize = true` to schemes * served only by settle-only handlers. For MPP the candidate set is * the handlers filtered by exact `method` match. The middleware * computes the predicate per request before invoking `body`, so the * body callback only has to read `context.capturesAt`. * * `pin` is the operator-supplied override from `PaymentPolicy.pin` * keyed by `:`. A pin to `"response"` * against a handler that cannot authorize is rejected at construction * by `validateOperationPolicies` in middleware-openapi. If one somehow * reaches this resolver at runtime (e.g. a programmatic spec that * bypasses validation) the body's `authorize()` call will throw "no * handler accepted the verification", which propagates up as a 500 -- * loud failure rather than a silent demotion to one-phase. */ export declare function resolveCapturesAt(canAuthorize: boolean, hasAuthorize: boolean, pin?: CapturesAt): CapturesAt; /** * Core middleware request handler that processes x402 and MPP payment flows. * * Delegates to protocol-specific glue layers for challenge generation, * settlement, and verification. The middleware formats HTTP responses * but never constructs protocol types directly. */ export declare function handleMiddlewareRequest(args: HandleMiddlewareRequestArgs): Promise; export {}; //# sourceMappingURL=common.d.ts.map