UNPKG

@payai/x402

Version:

PayAI-distributed wrapper for @x402/core v2

1 lines 70.6 kB
{"version":3,"sources":["../../src/http/x402HTTPResourceServer.ts","../../src/http/httpFacilitatorClient.ts","../../src/http/x402HTTPClient.ts","../../src/http/index.ts"],"sourcesContent":["import { x402ResourceServer } from \"../server\";\nimport {\n decodePaymentSignatureHeader,\n encodePaymentRequiredHeader,\n encodePaymentResponseHeader,\n} from \".\";\nimport {\n PaymentPayload,\n PaymentRequired,\n SettleResponse,\n SettleError,\n FacilitatorResponseError,\n Price,\n Network,\n PaymentRequirements,\n} from \"../types\";\nimport { x402Version } from \"..\";\n\n/**\n * Framework-agnostic HTTP adapter interface\n * Implementations provide framework-specific HTTP operations\n */\nexport interface HTTPAdapter {\n getHeader(name: string): string | undefined;\n getMethod(): string;\n getPath(): string;\n getUrl(): string;\n getAcceptHeader(): string;\n getUserAgent(): string;\n\n /**\n * Get query parameters from the request URL\n *\n * @returns Record of query parameter key-value pairs\n */\n getQueryParams?(): Record<string, string | string[]>;\n\n /**\n * Get a specific query parameter by name\n *\n * @param name - The query parameter name\n * @returns The query parameter value(s) or undefined\n */\n getQueryParam?(name: string): string | string[] | undefined;\n\n /**\n * Get the parsed request body\n * Framework adapters should parse JSON/form data appropriately\n *\n * @returns The parsed request body\n */\n getBody?(): unknown;\n}\n\n/**\n * Paywall configuration for HTML responses\n */\nexport interface PaywallConfig {\n appName?: string;\n appLogo?: string;\n sessionTokenEndpoint?: string;\n currentUrl?: string;\n testnet?: boolean;\n}\n\n/**\n * Paywall provider interface for generating HTML\n */\nexport interface PaywallProvider {\n generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;\n}\n\n/**\n * Dynamic payTo function that receives HTTP request context\n */\nexport type DynamicPayTo = (context: HTTPRequestContext) => string | Promise<string>;\n\n/**\n * Dynamic price function that receives HTTP request context\n */\nexport type DynamicPrice = (context: HTTPRequestContext) => Price | Promise<Price>;\n\n/**\n * Result of response body callbacks containing content type and body.\n */\nexport interface HTTPResponseBody {\n /**\n * The content type for the response (e.g., 'application/json', 'text/plain').\n */\n contentType: string;\n\n /**\n * The response body to include in the 402 response.\n */\n body: unknown;\n}\n\n/**\n * Dynamic function to generate a custom response for unpaid requests.\n * Receives the HTTP request context and returns the content type and body to include in the 402 response.\n */\nexport type UnpaidResponseBody = (\n context: HTTPRequestContext,\n) => HTTPResponseBody | Promise<HTTPResponseBody>;\n\n/**\n * Dynamic function to generate a custom response for settlement failures.\n * Receives the HTTP request context and settle failure result, returns the content type and body.\n */\nexport type SettlementFailedResponseBody = (\n context: HTTPRequestContext,\n settleResult: Omit<ProcessSettleFailureResponse, \"response\">,\n) => HTTPResponseBody | Promise<HTTPResponseBody>;\n\n/**\n * A single payment option for a route\n * Represents one way a client can pay for access to the resource\n */\nexport interface PaymentOption {\n scheme: string;\n payTo: string | DynamicPayTo;\n price: Price | DynamicPrice;\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record<string, unknown>;\n}\n\n/**\n * Route configuration for HTTP endpoints\n *\n * The 'accepts' field defines payment options for the route.\n * Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.\n */\nexport interface RouteConfig {\n // Payment option(s): single or array\n accepts: PaymentOption | PaymentOption[];\n\n // HTTP-specific metadata\n resource?: string;\n description?: string;\n mimeType?: string;\n customPaywallHtml?: string;\n\n /**\n * Optional callback to generate a custom response for unpaid API requests.\n * This allows servers to return preview data, error messages, or other content\n * when a request lacks payment.\n *\n * For browser requests (Accept: text/html), the paywall HTML takes precedence.\n * This callback is only used for API clients.\n *\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @returns An object containing both contentType and body for the 402 response\n */\n unpaidResponseBody?: UnpaidResponseBody;\n\n /**\n * Optional callback to generate a custom response for settlement failures.\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @param settleResult - The settlement failure result\n * @returns An object containing both contentType and body for the 402 response\n */\n settlementFailedResponseBody?: SettlementFailedResponseBody;\n\n // Extensions\n extensions?: Record<string, unknown>;\n}\n\n/**\n * Routes configuration - maps path patterns to route configs\n */\nexport type RoutesConfig = Record<string, RouteConfig> | RouteConfig;\n\n/**\n * Hook that runs on every request to a protected route, before payment processing.\n * Can grant access without payment, deny the request, or continue to payment flow.\n *\n * @returns\n * - `void` - Continue to payment processing (default behavior)\n * - `{ grantAccess: true }` - Grant access without requiring payment\n * - `{ abort: true; reason: string }` - Deny the request (returns 403)\n */\nexport type ProtectedRequestHook = (\n context: HTTPRequestContext,\n routeConfig: RouteConfig,\n) => Promise<void | { grantAccess: true } | { abort: true; reason: string }>;\n\n/**\n * Compiled route for efficient matching\n */\nexport interface CompiledRoute {\n verb: string;\n regex: RegExp;\n config: RouteConfig;\n}\n\n/**\n * HTTP request context that encapsulates all request data\n */\nexport interface HTTPRequestContext {\n adapter: HTTPAdapter;\n path: string;\n method: string;\n paymentHeader?: string;\n}\n\n/**\n * HTTP transport context contains both request context and optional response data.\n */\nexport interface HTTPTransportContext {\n /** The HTTP request context */\n request: HTTPRequestContext;\n /** The response body buffer */\n responseBody?: Buffer;\n}\n\n/**\n * HTTP response instructions for the framework middleware\n */\nexport interface HTTPResponseInstructions {\n status: number;\n headers: Record<string, string>;\n body?: unknown; // e.g. Paywall for web browser requests, but could be any other type\n isHtml?: boolean; // e.g. if body is a paywall, then isHtml is true\n}\n\n/**\n * Result of processing an HTTP request for payment\n */\nexport type HTTPProcessResult =\n | { type: \"no-payment-required\" }\n | {\n type: \"payment-verified\";\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n declaredExtensions?: Record<string, unknown>;\n }\n | { type: \"payment-error\"; response: HTTPResponseInstructions };\n\n/**\n * Result of processSettlement\n */\nexport type ProcessSettleSuccessResponse = SettleResponse & {\n success: true;\n headers: Record<string, string>;\n requirements: PaymentRequirements;\n};\n\nexport type ProcessSettleFailureResponse = SettleResponse & {\n success: false;\n errorReason: string;\n errorMessage?: string;\n headers: Record<string, string>;\n response: HTTPResponseInstructions;\n};\n\nexport type ProcessSettleResultResponse =\n | ProcessSettleSuccessResponse\n | ProcessSettleFailureResponse;\n\n/**\n * Represents a validation error for a specific route's payment configuration.\n */\nexport interface RouteValidationError {\n /** The route pattern (e.g., \"GET /api/weather\") */\n routePattern: string;\n /** The payment scheme that failed validation */\n scheme: string;\n /** The network that failed validation */\n network: Network;\n /** The type of validation failure */\n reason: \"missing_scheme\" | \"missing_facilitator\";\n /** Human-readable error message */\n message: string;\n}\n\n/**\n * Error thrown when route configuration validation fails.\n */\nexport class RouteConfigurationError extends Error {\n /** The validation errors that caused this exception */\n public readonly errors: RouteValidationError[];\n\n /**\n * Creates a new RouteConfigurationError with the given validation errors.\n *\n * @param errors - The validation errors that caused this exception.\n */\n constructor(errors: RouteValidationError[]) {\n const message = `x402 Route Configuration Errors:\\n${errors.map(e => ` - ${e.message}`).join(\"\\n\")}`;\n super(message);\n this.name = \"RouteConfigurationError\";\n this.errors = errors;\n }\n}\n\n/**\n * HTTP-enhanced x402 resource server\n * Provides framework-agnostic HTTP protocol handling\n */\nexport class x402HTTPResourceServer {\n private ResourceServer: x402ResourceServer;\n private compiledRoutes: CompiledRoute[] = [];\n private routesConfig: RoutesConfig;\n private paywallProvider?: PaywallProvider;\n private protectedRequestHooks: ProtectedRequestHook[] = [];\n\n /**\n * Creates a new x402HTTPResourceServer instance.\n *\n * @param ResourceServer - The core x402ResourceServer instance to use\n * @param routes - Route configuration for payment-protected endpoints\n */\n constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig) {\n this.ResourceServer = ResourceServer;\n this.routesConfig = routes;\n\n // Handle both single route and multiple routes\n const normalizedRoutes =\n typeof routes === \"object\" && !(\"accepts\" in routes)\n ? (routes as Record<string, RouteConfig>)\n : { \"*\": routes as RouteConfig };\n\n for (const [pattern, config] of Object.entries(normalizedRoutes)) {\n const parsed = this.parseRoutePattern(pattern);\n this.compiledRoutes.push({\n verb: parsed.verb,\n regex: parsed.regex,\n config,\n });\n }\n }\n\n /**\n * Get the underlying x402ResourceServer instance.\n *\n * @returns The underlying x402ResourceServer instance\n */\n get server(): x402ResourceServer {\n return this.ResourceServer;\n }\n\n /**\n * Get the routes configuration.\n *\n * @returns The routes configuration\n */\n get routes(): RoutesConfig {\n return this.routesConfig;\n }\n\n /**\n * Initialize the HTTP resource server.\n *\n * This method initializes the underlying resource server (fetching facilitator support)\n * and then validates that all route payment configurations have corresponding\n * registered schemes and facilitator support.\n *\n * @throws RouteConfigurationError if any route's payment options don't have\n * corresponding registered schemes or facilitator support\n *\n * @example\n * ```typescript\n * const httpServer = new x402HTTPResourceServer(server, routes);\n * await httpServer.initialize();\n * ```\n */\n async initialize(): Promise<void> {\n // First, initialize the underlying resource server (fetches facilitator support)\n await this.ResourceServer.initialize();\n\n // Then validate route configuration\n const errors = this.validateRouteConfiguration();\n if (errors.length > 0) {\n throw new RouteConfigurationError(errors);\n }\n }\n\n /**\n * Register a custom paywall provider for generating HTML\n *\n * @param provider - PaywallProvider instance\n * @returns This service instance for chaining\n */\n registerPaywallProvider(provider: PaywallProvider): this {\n this.paywallProvider = provider;\n return this;\n }\n\n /**\n * Register a hook that runs on every request to a protected route, before payment processing.\n * Hooks are executed in order of registration. The first hook to return a non-void result wins.\n *\n * @param hook - The request hook function\n * @returns The x402HTTPResourceServer instance for chaining\n */\n onProtectedRequest(hook: ProtectedRequestHook): this {\n this.protectedRequestHooks.push(hook);\n return this;\n }\n\n /**\n * Process HTTP request and return response instructions\n * This is the main entry point for framework middleware\n *\n * @param context - HTTP request context\n * @param paywallConfig - Optional paywall configuration\n * @returns Process result indicating next action for middleware\n */\n async processHTTPRequest(\n context: HTTPRequestContext,\n paywallConfig?: PaywallConfig,\n ): Promise<HTTPProcessResult> {\n const { adapter, path, method } = context;\n\n // Find matching route\n const routeConfig = this.getRouteConfig(path, method);\n if (!routeConfig) {\n return { type: \"no-payment-required\" }; // No payment required for this route\n }\n\n // Execute request hooks before any payment processing\n for (const hook of this.protectedRequestHooks) {\n const result = await hook(context, routeConfig);\n if (result && \"grantAccess\" in result) {\n return { type: \"no-payment-required\" };\n }\n if (result && \"abort\" in result) {\n return {\n type: \"payment-error\",\n response: {\n status: 403,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: result.reason },\n },\n };\n }\n }\n\n // Normalize accepts field to array of payment options\n const paymentOptions = this.normalizePaymentOptions(routeConfig);\n\n // Check for payment header (v1 or v2)\n const paymentPayload = this.extractPayment(adapter);\n\n // Create resource info, using config override if provided\n const resourceInfo = {\n url: routeConfig.resource || context.adapter.getUrl(),\n description: routeConfig.description || \"\",\n mimeType: routeConfig.mimeType || \"\",\n };\n\n // Build requirements from all payment options\n // (this method handles resolving dynamic functions internally)\n let requirements = await this.ResourceServer.buildPaymentRequirementsFromOptions(\n paymentOptions,\n context,\n );\n\n let extensions = routeConfig.extensions;\n if (extensions) {\n extensions = this.ResourceServer.enrichExtensions(extensions, context);\n }\n\n // createPaymentRequiredResponse already handles extension enrichment in the core layer\n const transportContext: HTTPTransportContext = { request: context };\n const paymentRequired = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n !paymentPayload ? \"Payment required\" : undefined,\n extensions,\n transportContext,\n );\n\n // If no payment provided\n if (!paymentPayload) {\n // Resolve custom unpaid response body if provided\n const unpaidBody = routeConfig.unpaidResponseBody\n ? await routeConfig.unpaidResponseBody(context)\n : undefined;\n\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(\n paymentRequired,\n this.isWebBrowser(adapter),\n paywallConfig,\n routeConfig.customPaywallHtml,\n unpaidBody,\n ),\n };\n }\n\n // Verify payment\n try {\n const matchingRequirements = this.ResourceServer.findMatchingRequirements(\n paymentRequired.accepts,\n paymentPayload,\n );\n\n if (!matchingRequirements) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"No matching payment requirements\",\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n const verifyResult = await this.ResourceServer.verifyPayment(\n paymentPayload,\n matchingRequirements,\n );\n\n if (!verifyResult.isValid) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n verifyResult.invalidReason,\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n // Payment is valid, return data needed for settlement\n return {\n type: \"payment-verified\",\n paymentPayload,\n paymentRequirements: matchingRequirements,\n declaredExtensions: routeConfig.extensions,\n };\n } catch (error) {\n if (error instanceof FacilitatorResponseError) {\n throw error;\n }\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n error instanceof Error ? error.message : \"Payment verification failed\",\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n }\n\n /**\n * Process settlement after successful response\n *\n * @param paymentPayload - The verified payment payload\n * @param requirements - The matching payment requirements\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional HTTP transport context\n * @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure\n */\n async processSettlement(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n transportContext?: HTTPTransportContext,\n ): Promise<ProcessSettleResultResponse> {\n try {\n const settleResponse = await this.ResourceServer.settlePayment(\n paymentPayload,\n requirements,\n declaredExtensions,\n transportContext,\n );\n\n if (!settleResponse.success) {\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason: settleResponse.errorReason || \"Settlement failed\",\n errorMessage:\n settleResponse.errorMessage || settleResponse.errorReason || \"Settlement failed\",\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n\n return {\n ...settleResponse,\n success: true,\n headers: this.createSettlementHeaders(settleResponse),\n requirements,\n };\n } catch (error) {\n if (error instanceof FacilitatorResponseError) {\n throw error;\n }\n if (error instanceof SettleError) {\n const errorReason = error.errorReason || error.message;\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: error.errorMessage || errorReason,\n payer: error.payer,\n network: error.network,\n transaction: error.transaction,\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n const errorReason = error instanceof Error ? error.message : \"Settlement failed\";\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: errorReason,\n network: requirements.network as Network,\n transaction: \"\",\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n }\n\n /**\n * Check if a request requires payment based on route configuration\n *\n * @param context - HTTP request context\n * @returns True if the route requires payment, false otherwise\n */\n requiresPayment(context: HTTPRequestContext): boolean {\n const routeConfig = this.getRouteConfig(context.path, context.method);\n return routeConfig !== undefined;\n }\n\n /**\n * Build HTTPResponseInstructions for settlement failure.\n * Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.\n *\n * @param failure - Settlement failure result with headers\n * @param transportContext - Optional HTTP transport context for the request\n * @returns HTTP response instructions for the 402 settlement failure response\n */\n private async buildSettlementFailureResponse(\n failure: Omit<ProcessSettleFailureResponse, \"response\">,\n transportContext?: HTTPTransportContext,\n ): Promise<HTTPResponseInstructions> {\n const settlementHeaders = failure.headers;\n const routeConfig = transportContext\n ? this.getRouteConfig(transportContext.request.path, transportContext.request.method)\n : undefined;\n\n const customBody = routeConfig?.settlementFailedResponseBody\n ? await routeConfig.settlementFailedResponseBody(transportContext!.request, failure)\n : undefined;\n\n const contentType = customBody ? customBody.contentType : \"application/json\";\n const body = customBody ? customBody.body : {};\n\n return {\n status: 402,\n headers: {\n \"Content-Type\": contentType,\n ...settlementHeaders,\n },\n body,\n isHtml: contentType.includes(\"text/html\"),\n };\n }\n\n /**\n * Normalizes a RouteConfig's accepts field into an array of PaymentOptions\n * Handles both single PaymentOption and array formats\n *\n * @param routeConfig - Route configuration\n * @returns Array of payment options\n */\n private normalizePaymentOptions(routeConfig: RouteConfig): PaymentOption[] {\n return Array.isArray(routeConfig.accepts) ? routeConfig.accepts : [routeConfig.accepts];\n }\n\n /**\n * Validates that all payment options in routes have corresponding registered schemes\n * and facilitator support.\n *\n * @returns Array of validation errors (empty if all routes are valid)\n */\n private validateRouteConfiguration(): RouteValidationError[] {\n const errors: RouteValidationError[] = [];\n\n // Normalize routes to array of [pattern, config] pairs\n const normalizedRoutes =\n typeof this.routesConfig === \"object\" && !(\"accepts\" in this.routesConfig)\n ? Object.entries(this.routesConfig as Record<string, RouteConfig>)\n : [[\"*\", this.routesConfig as RouteConfig] as [string, RouteConfig]];\n\n for (const [pattern, config] of normalizedRoutes) {\n const paymentOptions = this.normalizePaymentOptions(config);\n\n for (const option of paymentOptions) {\n // Check 1: Is scheme registered?\n if (!this.ResourceServer.hasRegisteredScheme(option.network, option.scheme)) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_scheme\",\n message: `Route \"${pattern}\": No scheme implementation registered for \"${option.scheme}\" on network \"${option.network}\"`,\n });\n // Skip facilitator check if scheme isn't registered\n continue;\n }\n\n // Check 2: Does facilitator support this scheme/network combination?\n const supportedKind = this.ResourceServer.getSupportedKind(\n x402Version,\n option.network,\n option.scheme,\n );\n\n if (!supportedKind) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_facilitator\",\n message: `Route \"${pattern}\": Facilitator does not support scheme \"${option.scheme}\" on network \"${option.network}\"`,\n });\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Get route configuration for a request\n *\n * @param path - Request path\n * @param method - HTTP method\n * @returns Route configuration or undefined if no match\n */\n private getRouteConfig(path: string, method: string): RouteConfig | undefined {\n const normalizedPath = this.normalizePath(path);\n const upperMethod = method.toUpperCase();\n\n const matchingRoute = this.compiledRoutes.find(\n route =>\n route.regex.test(normalizedPath) && (route.verb === \"*\" || route.verb === upperMethod),\n );\n\n return matchingRoute?.config;\n }\n\n /**\n * Extract payment from HTTP headers (handles v1 and v2)\n *\n * @param adapter - HTTP adapter\n * @returns Decoded payment payload or null\n */\n private extractPayment(adapter: HTTPAdapter): PaymentPayload | null {\n // Check v2 header first (PAYMENT-SIGNATURE)\n const header = adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"PAYMENT-SIGNATURE\");\n\n if (header) {\n try {\n return decodePaymentSignatureHeader(header);\n } catch (error) {\n console.warn(\"Failed to decode PAYMENT-SIGNATURE header:\", error);\n }\n }\n\n return null;\n }\n\n /**\n * Check if request is from a web browser\n *\n * @param adapter - HTTP adapter\n * @returns True if request appears to be from a browser\n */\n private isWebBrowser(adapter: HTTPAdapter): boolean {\n const accept = adapter.getAcceptHeader();\n const userAgent = adapter.getUserAgent();\n return accept.includes(\"text/html\") && userAgent.includes(\"Mozilla\");\n }\n\n /**\n * Create HTTP response instructions from payment required\n *\n * @param paymentRequired - Payment requirements\n * @param isWebBrowser - Whether request is from browser\n * @param paywallConfig - Paywall configuration\n * @param customHtml - Custom HTML template\n * @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests\n * @returns Response instructions\n */\n private createHTTPResponse(\n paymentRequired: PaymentRequired,\n isWebBrowser: boolean,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n unpaidResponse?: HTTPResponseBody,\n ): HTTPResponseInstructions {\n // Use 412 Precondition Failed for permit2_allowance_required error\n // This signals client needs to approve Permit2 before retrying\n const status = paymentRequired.error === \"permit2_allowance_required\" ? 412 : 402;\n\n if (isWebBrowser) {\n const html = this.generatePaywallHTML(paymentRequired, paywallConfig, customHtml);\n return {\n status,\n headers: { \"Content-Type\": \"text/html\" },\n body: html,\n isHtml: true,\n };\n }\n\n const response = this.createHTTPPaymentRequiredResponse(paymentRequired);\n\n // Use callback result if provided, otherwise default to JSON with empty object\n const contentType = unpaidResponse ? unpaidResponse.contentType : \"application/json\";\n const body = unpaidResponse ? unpaidResponse.body : {};\n\n return {\n status,\n headers: {\n \"Content-Type\": contentType,\n ...response.headers,\n },\n body,\n };\n }\n\n /**\n * Create HTTP payment required response (v1 puts in body, v2 puts in header)\n *\n * @param paymentRequired - Payment required object\n * @returns Headers and body for the HTTP response\n */\n private createHTTPPaymentRequiredResponse(paymentRequired: PaymentRequired): {\n headers: Record<string, string>;\n } {\n return {\n headers: {\n \"PAYMENT-REQUIRED\": encodePaymentRequiredHeader(paymentRequired),\n },\n };\n }\n\n /**\n * Create settlement response headers\n *\n * @param settleResponse - Settlement response\n * @returns Headers to add to response\n */\n private createSettlementHeaders(settleResponse: SettleResponse): Record<string, string> {\n const encoded = encodePaymentResponseHeader(settleResponse);\n return { \"PAYMENT-RESPONSE\": encoded };\n }\n\n /**\n * Parse route pattern into verb and regex\n *\n * @param pattern - Route pattern like \"GET /api/*\", \"/api/[id]\", or \"/api/:id\"\n * @returns Parsed pattern with verb and regex\n */\n private parseRoutePattern(pattern: string): { verb: string; regex: RegExp } {\n const [verb, path] = pattern.includes(\" \") ? pattern.split(/\\s+/) : [\"*\", pattern];\n\n const regex = new RegExp(\n `^${\n path\n .replace(/[$()+.?^{|}]/g, \"\\\\$&\") // Escape regex special chars\n .replace(/\\*/g, \".*?\") // Wildcards\n .replace(/\\[([^\\]]+)\\]/g, \"[^/]+\") // Parameters (Next.js style [param])\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, \"[^/]+\") // Parameters (Express style :param)\n .replace(/\\//g, \"\\\\/\") // Escape slashes\n }$`,\n \"i\",\n );\n\n return { verb: verb.toUpperCase(), regex };\n }\n\n /**\n * Normalize path for matching\n *\n * @param path - Raw path from request\n * @returns Normalized path\n */\n private normalizePath(path: string): string {\n const pathWithoutQuery = path.split(/[?#]/)[0];\n\n let decodedOrRawPath: string;\n try {\n decodedOrRawPath = decodeURIComponent(pathWithoutQuery);\n } catch {\n decodedOrRawPath = pathWithoutQuery;\n }\n\n return decodedOrRawPath\n .replace(/\\\\/g, \"/\")\n .replace(/\\/+/g, \"/\")\n .replace(/(.+?)\\/+$/, \"$1\");\n }\n\n /**\n * Generate paywall HTML for browser requests\n *\n * @param paymentRequired - Payment required response\n * @param paywallConfig - Optional paywall configuration\n * @param customHtml - Optional custom HTML template\n * @returns HTML string\n */\n private generatePaywallHTML(\n paymentRequired: PaymentRequired,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n ): string {\n if (customHtml) {\n return customHtml;\n }\n\n // Use custom paywall provider if set\n if (this.paywallProvider) {\n return this.paywallProvider.generateHtml(paymentRequired, paywallConfig);\n }\n\n // Try to use @payai/x402-paywall if available (optional dependency)\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const paywall = require(\"@payai/x402-paywall\");\n const displayAmount = this.getDisplayAmount(paymentRequired);\n const resource = paymentRequired.resource;\n\n return paywall.getPaywallHtml({\n amount: displayAmount,\n paymentRequired,\n currentUrl: resource?.url || paywallConfig?.currentUrl || \"\",\n testnet: paywallConfig?.testnet ?? true,\n appName: paywallConfig?.appName,\n appLogo: paywallConfig?.appLogo,\n sessionTokenEndpoint: paywallConfig?.sessionTokenEndpoint,\n });\n } catch {\n // @payai/x402-paywall not installed, fall back to basic HTML\n }\n\n // Fallback: Basic HTML paywall\n const resource = paymentRequired.resource;\n const displayAmount = this.getDisplayAmount(paymentRequired);\n\n return `\n <!DOCTYPE html>\n <html>\n <head>\n <title>Payment Required</title>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n </head>\n <body>\n <div style=\"max-width: 600px; margin: 50px auto; padding: 20px; font-family: system-ui, -apple-system, sans-serif;\">\n ${paywallConfig?.appLogo ? `<img src=\"${paywallConfig.appLogo}\" alt=\"${paywallConfig.appName || \"App\"}\" style=\"max-width: 200px; margin-bottom: 20px;\">` : \"\"}\n <h1>Payment Required</h1>\n ${resource ? `<p><strong>Resource:</strong> ${resource.description || resource.url}</p>` : \"\"}\n <p><strong>Amount:</strong> $${displayAmount.toFixed(2)} USDC</p>\n <div id=\"payment-widget\" \n data-requirements='${JSON.stringify(paymentRequired)}'\n data-app-name=\"${paywallConfig?.appName || \"\"}\"\n data-testnet=\"${paywallConfig?.testnet || false}\">\n <!-- Install @payai/x402-paywall for full wallet integration -->\n <p style=\"margin-top: 2rem; padding: 1rem; background: #fef3c7; border-radius: 0.5rem;\">\n <strong>Note:</strong> Install <code>@payai/x402-paywall</code> for full wallet connection and payment UI.\n </p>\n </div>\n </div>\n </body>\n </html>\n `;\n }\n\n /**\n * Extract display amount from payment requirements.\n *\n * @param paymentRequired - The payment required object\n * @returns The display amount in decimal format\n */\n private getDisplayAmount(paymentRequired: PaymentRequired): number {\n const accepts = paymentRequired.accepts;\n if (accepts && accepts.length > 0) {\n const firstReq = accepts[0];\n if (\"amount\" in firstReq) {\n // V2 format\n return parseFloat(firstReq.amount) / 1000000; // Assuming USDC with 6 decimals\n }\n }\n return 0;\n }\n}\n","import { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport {\n VerifyResponse,\n SettleResponse,\n SupportedResponse,\n VerifyError,\n SettleError,\n FacilitatorResponseError,\n} from \"../types/facilitator\";\nimport { z } from \"../schemas\";\n\nconst DEFAULT_FACILITATOR_URL = \"https://facilitator.payai.network\";\n\nexport interface FacilitatorConfig {\n url?: string;\n /**\n * Custom auth header factory. Called before every facilitator request.\n * Return per-endpoint headers (e.g. `Authorization: Bearer <jwt>`).\n */\n createAuthHeaders?: () => Promise<{\n verify: Record<string, string>;\n settle: Record<string, string>;\n supported: Record<string, string>;\n }>;\n}\n\n/**\n * Interface for facilitator clients\n * Can be implemented for HTTP-based or local facilitators\n */\nexport interface FacilitatorClient {\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise<VerifyResponse>;\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise<SettleResponse>;\n\n /**\n * Get supported payment kinds and extensions from the facilitator\n *\n * @returns Supported payment kinds and extensions\n */\n getSupported(): Promise<SupportedResponse>;\n}\n\n/** Number of retries for getSupported() on 429 rate limit errors */\nconst GET_SUPPORTED_RETRIES = 3;\n/** Base delay in ms for exponential backoff on retries */\nconst GET_SUPPORTED_RETRY_DELAY_MS = 1000;\n\nconst verifyResponseSchema: z.ZodType<VerifyResponse, z.ZodTypeDef, unknown> = z.object({\n isValid: z.boolean(),\n invalidReason: z.string().optional(),\n invalidMessage: z.string().optional(),\n payer: z.string().optional(),\n extensions: z.record(z.string(), z.unknown()).optional(),\n});\n\nconst settleResponseSchema: z.ZodType<SettleResponse, z.ZodTypeDef, unknown> = z.object({\n success: z.boolean(),\n errorReason: z.string().optional(),\n errorMessage: z.string().optional(),\n payer: z.string().optional(),\n transaction: z.string(),\n network: z.custom<SettleResponse[\"network\"]>(value => typeof value === \"string\"),\n extensions: z.record(z.string(), z.unknown()).optional(),\n});\n\nconst supportedKindSchema: z.ZodType<SupportedResponse[\"kinds\"][number], z.ZodTypeDef, unknown> =\n z.object({\n x402Version: z.number(),\n scheme: z.string(),\n network: z.custom<SupportedResponse[\"kinds\"][number][\"network\"]>(\n value => typeof value === \"string\",\n ),\n extra: z.record(z.string(), z.unknown()).optional(),\n });\n\nconst supportedResponseSchema: z.ZodType<SupportedResponse, z.ZodTypeDef, unknown> = z.object({\n kinds: z.array(supportedKindSchema),\n extensions: z.array(z.string()).default([]),\n signers: z.record(z.string(), z.array(z.string())).default({}),\n});\n\n/**\n * Produces a compact excerpt of a facilitator response body for error messages.\n *\n * @param text - The raw response body text\n * @param limit - The maximum number of characters to include\n * @returns A normalized excerpt suitable for logs and thrown errors\n */\nfunction responseExcerpt(text: string, limit: number = 200): string {\n const compact = text.trim().replace(/\\s+/g, \" \");\n if (!compact) {\n return \"<empty response>\";\n }\n\n if (compact.length <= limit) {\n return compact;\n }\n\n return `${compact.slice(0, limit - 3)}...`;\n}\n\n/**\n * Parses and validates a successful facilitator response body.\n *\n * @param response - The HTTP response returned by the facilitator\n * @param schema - The schema used to validate the response payload\n * @param operation - The facilitator operation name for error reporting\n * @returns The validated facilitator payload\n */\nasync function parseSuccessResponse<T>(\n response: Response,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>,\n operation: string,\n): Promise<T> {\n const text = await response.text();\n\n let data: unknown;\n try {\n data = JSON.parse(text);\n } catch {\n throw new FacilitatorResponseError(\n `Facilitator ${operation} returned invalid JSON: ${responseExcerpt(text)}`,\n );\n }\n\n const parsed = schema.safeParse(data);\n if (!parsed.success) {\n throw new FacilitatorResponseError(\n `Facilitator ${operation} returned invalid data: ${responseExcerpt(text)}`,\n );\n }\n\n return parsed.data;\n}\n\n/**\n * HTTP-based client for interacting with x402 facilitator services\n * Handles HTTP communication with facilitator endpoints\n */\nexport class HTTPFacilitatorClient implements FacilitatorClient {\n readonly url: string;\n private readonly _createAuthHeaders?: FacilitatorConfig[\"createAuthHeaders\"];\n\n /**\n * Creates a new HTTPFacilitatorClient instance.\n *\n * @param config - Configuration options for the facilitator client\n */\n constructor(config?: FacilitatorConfig) {\n this.url = config?.url || DEFAULT_FACILITATOR_URL;\n this._createAuthHeaders = config?.createAuthHeaders;\n }\n\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n async verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"verify\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/verify`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n let data: unknown;\n try {\n data = JSON.parse(text);\n } catch {\n throw new Error(`Facilitator verify failed (${response.status}): ${responseExcerpt(text)}`);\n }\n\n if (typeof data === \"object\" && data !== null && \"isValid\" in data) {\n throw new VerifyError(response.status, data as VerifyResponse);\n }\n\n throw new Error(\n `Facilitator verify failed (${response.status}): ${responseExcerpt(JSON.stringify(data))}`,\n );\n }\n\n return parseSuccessResponse(response, verifyResponseSchema, \"verify\");\n }\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n async settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"settle\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/settle`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n let data: unknown;\n try {\n data = JSON.parse(text);\n } catch {\n throw new Error(`Facilitator settle failed (${response.status}): ${responseExcerpt(text)}`);\n }\n\n if (typeof data === \"object\" && data !== null && \"success\" in data) {\n throw new SettleError(response.status, data as SettleResponse);\n }\n\n throw new Error(\n `Facilitator settle failed (${response.status}): ${responseExcerpt(JSON.stringify(data))}`,\n );\n }\n\n return parseSuccessResponse(response, settleResponseSchema, \"settle\");\n }\n\n /**\n * Get supported payment kinds and extensions from the facilitator.\n * Retries with exponential backoff on 429 rate limit errors.\n *\n * @returns Supported payment kinds and extensions\n */\n async getSupported(): Promise<SupportedResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"supported\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n let lastError: Error | null = null;\n for (let attempt = 0; attempt < GET_SUPPORTED_RETRIES; attempt++) {\n const response = await fetch(`${this.url}/supported`, {\n method: \"GET\",\n headers,\n });\n\n if (response.ok) {\n return parseSuccessResponse(response, supportedResponseSchema, \"supported\");\n }\n\n const errorText = await response.text().catch(() => response.statusText);\n lastError = new Error(\n `Facilitator getSupported failed (${response.status}): ${responseExcerpt(errorText)}`,\n );\n\n // Retry on 429 rate limit errors with exponential backoff\n if (response.status === 429 && attempt < GET_SUPPORTED_RETRIES - 1) {\n const delay = GET_SUPPORTED_RETRY_DELAY_MS * Math.pow(2, attempt);\n await new Promise(resolve => setTimeout(resolve, delay));\n continue;\n }\n\n throw lastError;\n }\n\n throw lastError ?? new Error(\"Facilitator getSupported failed after retries\");\n }\n\n /**\n * Creates authentication headers for a specific path.\n *\n * @param path - The path to create authentication headers for (e.g., \"verify\", \"settle\", \"supported\")\n * @returns An object containing the authentication headers for the specified path\n */\n async createAuthHeaders(path: string): Promise<{\n headers: Record<string, string>;\n }> {\n if (this._createAuthHeaders) {\n const authHeaders = (await this._createAuthHeaders()) as Record<\n string,\n Record<string, string>\n >;\n return {\n headers: authHeaders[path] ?? {},\n };\n }\n return {\n headers: {},\n };\n }\n\n /**\n * Helper to convert objects to JSON-safe format.\n * Handles BigInt and other non-JSON types.\n *\n * @param obj - The object to convert\n * @returns The JSON-safe representation of the object\n */\n private toJsonSafe(obj: unknown): unknown {\n return JSON.parse(\n JSON.stringify(obj, (_, value) => (typeof value === \"bigint\" ? value.toString() : value)),\n );\n }\n}\n","import {\n decodePaymentRequiredHeader,\n decodePaymentResponseHeader,\n encodePaymentSignatureHeader,\n} from \".\";\nimport { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { x402Client } from \"../client/x402Client\";\n\n/**\n * Context provided to onPaymentRequired hooks.\n */\nexport interface PaymentRequiredContext {\n paymentRequired: PaymentRequired;\n}\n\n/**\n * Hook called when a 402 response is received, before payment processing.\n * Return headers to try before payment, or void to proceed directly to payment.\n */\nexport type PaymentRequiredHook = (\n context: PaymentRequiredContext,\n) => Promise<{ headers: Record<string, string> } | void>;\n\n/**\n * HTTP-specific client for handling x402 payment protocol over HTTP.\n *\n * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality\n * for payment headers and responses while maintaining the builder pattern.\n */\nexport class x402HTTPClient {\n private paymentRequiredHooks: PaymentRequiredHook[] = [];\n\n /**\n * Creates a new x402HTTPClient instance.\n *\n * @param client - The underlying x402Client for payment logic\n */\n constructor(private readonly client: x402Client) {}\n\n /**\n * Register a hook to handle 402 responses before payment.\n * Hooks run in order; first to return headers wins.\n *\n * @param hook - The hook function to register\n * @returns This instance for chaining\n */\n onPaymentRequired(hook: PaymentRequiredHook): this {\n this.paymentRequiredHooks.push(hook);\n return this;\n }\n\n /**\n * Run hooks and return headers if any hook provides them.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Headers to use for retry, or null to proceed to payment\n */\n async handlePaymentRequired(\n paymentRequired: PaymentRequired,\n ): Promise<Record<string, string> | null> {\n for (const hook of this.paymentRequiredHooks) {\n const result = await hook({ paymentRequired });\n if (result?.headers) {\n return result.headers;\n }\n }\n return null;\n }\n\n /**\n * Encodes a payment payload into appropriate HTTP headers based on version.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns HTTP headers containing the encoded payment signature\n */\n encodePaymentSignatureHeader(paymentPayload: PaymentPayload): Record<string, string> {\n switch (paymentPayload.x402Version) {\n case 2:\n return {\n \"PAYMENT-SIGNATURE\": encodePaymentSignatureHeader(paymentPayload),\n };\n case 1:\n return {\n \"X-PAYMENT\": encodePaymentSignatureHeader(paymentPayload),\n };\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Extracts payment required information from HTTP response.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @param body - Optional response body for v1 compatibility\n * @returns The payment required object\n */\n getPaymentRequiredResponse(\n getHeader: (name: string) => string | null | undefined,\n body?: unknown,\n ): PaymentRequired {\n // v2\n const paymentRequired = getHeader(\"PAYMENT-REQUIRED\");\n if (paymentRequired) {\n return decodePaymentRequiredHeader(paymentRequired);\n }\n\n // v1\n if (\n body &&\n body instanceof Object &&\n \"x402Version\" in body &&\n (body as PaymentRequired).x402Version === 1\n ) {\n return body as PaymentRequired;\n }\n\n throw new Error(\"Invalid payment required response\");\n }\n\n /**\n * Extracts payment settlement response from HTTP headers.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @returns The settlement response object\n */\n getPaymentSettleResponse(getHeader: (name: string) => string | null | undefined): SettleResponse {\n // v2\n const paymentResponse = getHeader(\"PAYMENT-RESPONSE\");\n if (paymentResponse) {\n return decodePaymentResponseHeader(paymentResponse);\n }\n\n // v1\n const xPaymentResponse = getHeader(\"X-PAYMENT-RESPONSE\");\n if (xPaymentResponse) {\n return decodePaymentResponseHeader(xPaymentResponse);\n }\n\n throw new Error(\"Payment response header not found\");\n }\n\n /**\n * Creates a payment payload for the given