@bankofai/x402-core 2.6.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +293 -0
- package/dist/cjs/assetRegistry-CL0zA4s0.d.ts +831 -0
- package/dist/cjs/assetRegistry-CRVM0KEs.d.ts +831 -0
- package/dist/cjs/client/index.d.ts +329 -0
- package/dist/cjs/client/index.js +712 -0
- package/dist/cjs/client/index.js.map +1 -0
- package/dist/cjs/facilitator/index.d.ts +206 -0
- package/dist/cjs/facilitator/index.js +625 -0
- package/dist/cjs/facilitator/index.js.map +1 -0
- package/dist/cjs/http/index.d.ts +51 -0
- package/dist/cjs/http/index.js +1178 -0
- package/dist/cjs/http/index.js.map +1 -0
- package/dist/cjs/index.d.ts +13 -0
- package/dist/cjs/index.js +250 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/mechanisms-q7I6xfUE.d.ts +726 -0
- package/dist/cjs/schemas/index.d.ts +825 -0
- package/dist/cjs/schemas/index.js +212 -0
- package/dist/cjs/schemas/index.js.map +1 -0
- package/dist/cjs/server/index.d.ts +2 -0
- package/dist/cjs/server/index.js +1782 -0
- package/dist/cjs/server/index.js.map +1 -0
- package/dist/cjs/types/index.d.ts +1 -0
- package/dist/cjs/types/index.js +72 -0
- package/dist/cjs/types/index.js.map +1 -0
- package/dist/cjs/types/v1/index.d.ts +1 -0
- package/dist/cjs/types/v1/index.js +19 -0
- package/dist/cjs/types/v1/index.js.map +1 -0
- package/dist/cjs/utils/index.d.ts +48 -0
- package/dist/cjs/utils/index.js +116 -0
- package/dist/cjs/utils/index.js.map +1 -0
- package/dist/cjs/x402HTTPResourceServer-BFVo1_74.d.ts +433 -0
- package/dist/cjs/x402HTTPResourceServer-DaU2yFzy.d.ts +434 -0
- package/dist/cjs/x402HTTPResourceServer-DswI2hZQ.d.ts +434 -0
- package/dist/esm/assetRegistry-CRVM0KEs.d.mts +831 -0
- package/dist/esm/chunk-BJTO5JO5.mjs +11 -0
- package/dist/esm/chunk-BJTO5JO5.mjs.map +1 -0
- package/dist/esm/chunk-DACUCTGT.mjs +891 -0
- package/dist/esm/chunk-DACUCTGT.mjs.map +1 -0
- package/dist/esm/chunk-DFUINDLZ.mjs +221 -0
- package/dist/esm/chunk-DFUINDLZ.mjs.map +1 -0
- package/dist/esm/chunk-HRQUGJ3Y.mjs +45 -0
- package/dist/esm/chunk-HRQUGJ3Y.mjs.map +1 -0
- package/dist/esm/chunk-TDLQZ6MP.mjs +86 -0
- package/dist/esm/chunk-TDLQZ6MP.mjs.map +1 -0
- package/dist/esm/client/index.d.mts +329 -0
- package/dist/esm/client/index.mjs +330 -0
- package/dist/esm/client/index.mjs.map +1 -0
- package/dist/esm/facilitator/index.d.mts +206 -0
- package/dist/esm/facilitator/index.mjs +398 -0
- package/dist/esm/facilitator/index.mjs.map +1 -0
- package/dist/esm/http/index.d.mts +51 -0
- package/dist/esm/http/index.mjs +29 -0
- package/dist/esm/http/index.mjs.map +1 -0
- package/dist/esm/index.d.mts +13 -0
- package/dist/esm/index.mjs +14 -0
- package/dist/esm/index.mjs.map +1 -0
- package/dist/esm/schemas/index.d.mts +825 -0
- package/dist/esm/schemas/index.mjs +158 -0
- package/dist/esm/schemas/index.mjs.map +1 -0
- package/dist/esm/server/index.d.mts +2 -0
- package/dist/esm/server/index.mjs +712 -0
- package/dist/esm/server/index.mjs.map +1 -0
- package/dist/esm/types/index.d.mts +1 -0
- package/dist/esm/types/index.mjs +10 -0
- package/dist/esm/types/index.mjs.map +1 -0
- package/dist/esm/types/v1/index.d.mts +1 -0
- package/dist/esm/types/v1/index.mjs +1 -0
- package/dist/esm/types/v1/index.mjs.map +1 -0
- package/dist/esm/utils/index.d.mts +48 -0
- package/dist/esm/utils/index.mjs +20 -0
- package/dist/esm/utils/index.mjs.map +1 -0
- package/dist/esm/x402HTTPResourceServer-B6uf_UDm.d.mts +434 -0
- package/package.json +139 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"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 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 assets?: string[];\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 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 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/*\" 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\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 @bankofai/x402-paywall if available (optional dependency)\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const paywall = require(\"@bankofai/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 // @bankofai/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 @bankofai/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>@bankofai/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} from \"../types/facilitator\";\n\nconst DEFAULT_FACILITATOR_URL = \"https://x402.org/facilitator\";\n\nexport interface FacilitatorConfig {\n url?: string;\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\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 const data = await response.json();\n\n if (typeof data === \"object\" && data !== null && \"isValid\" in data) {\n const verifyResponse = data as VerifyResponse;\n if (!response.ok) {\n throw new VerifyError(response.status, verifyResponse);\n }\n return verifyResponse;\n }\n\n throw new Error(`Facilitator verify failed (${response.status}): ${JSON.stringify(data)}`);\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 const data = await response.json();\n\n if (typeof data === \"object\" && data !== null && \"success\" in data) {\n const settleResponse = data as SettleResponse;\n if (!response.ok) {\n throw new SettleError(response.status, settleResponse);\n }\n return settleResponse;\n }\n\n throw new Error(`Facilitator settle failed (${response.status}): ${JSON.stringify(data)}`);\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 (await response.json()) as SupportedResponse;\n }\n\n const errorText = await response.text().catch(() => response.statusText);\n lastError = new Error(`Facilitator getSupported failed (${response.status}): ${errorText}`);\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 payment requirements.\n * Delegates to the underlying x402Client.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Promise resolving to the payment payload\n */\n async createPaymentPayload(paymentRequired: PaymentRequired): Promise<PaymentPayload> {\n return this.client.createPaymentPayload(paymentRequired);\n }\n}\n","import { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { Base64EncodedRegex, safeBase64Decode, safeBase64Encode } from \"../utils\";\n\n// HTTP Methods that typically use query parameters\nexport type QueryParamMethods = \"GET\" | \"HEAD\" | \"DELETE\";\n\n// HTTP Methods that typically use request body\nexport type BodyMethods = \"POST\" | \"PUT\" | \"PATCH\";\n\n/**\n * Encodes a payment payload as a base64 header value.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns Base64 encoded string representation of the payment payload\n */\nexport function encodePaymentSignatureHeader(paymentPayload: PaymentPayload): string {\n return safeBase64Encode(JSON.stringify(paymentPayload));\n}\n\n/**\n * Decodes a base64 payment signature header into a payment payload.\n *\n * @param paymentSignatureHeader - The base64 encoded payment signature header\n * @returns The decoded payment payload\n */\nexport function decodePaymentSignatureHeader(paymentSignatureHeader: string): PaymentPayload {\n if (!Base64EncodedRegex.test(paymentSignatureHeader)) {\n throw new Error(\"Invalid payment signature header\");\n }\n return JSON.parse(safeBase64Decode(paymentSignatureHeader)) as PaymentPayload;\n}\n\n/**\n * Encodes a payment required object as a base64 header value.\n *\n * @param paymentRequired - The payment required object to encode\n * @returns Base64 encoded string representation of the payment required object\n */\nexport function encodePaymentRequiredHeader(paymentRequired: PaymentRequired): string {\n return safeBase64Encode(JSON.stringify(paymentRequired));\n}\n\n/**\n * Decodes a base64 payment required header into a payment required object.\n *\n * @param paymentRequiredHeader - The base64 encoded payment required header\n * @returns The decoded payment required object\n */\nexport function decodePaymentRequiredHeader(paymentRequiredHeader: string): PaymentRequired {\n if (!Base64EncodedRegex.test(paymentRequiredHeader)) {\n throw new Error(\"Invalid payment required header\");\n }\n return JSON.parse(safeBase64Decode(paymentRequiredHeader)) as PaymentRequired;\n}\n\n/**\n * Encodes a payment response as a base64 header value.\n *\n * @param paymentResponse - The payment response to encode\n * @returns Base64 encoded string representation of the payment response\n */\nexport function encodePaymentResponseHeader(paymentResponse: SettleResponse): string {\n return safeBase64Encode(JSON.stringify(paymentResponse));\n}\n\n/**\n * Decodes a base64 payment response header into a settle response.\n *\n * @param paymentResponseHeader - The base64 encoded payment response header\n * @returns The decoded settle response\n */\nexport function decodePaymentResponseHeader(paymentResponseHeader: string): SettleResponse {\n if (!Base64EncodedRegex.test(paymentResponseHeader)) {\n throw new Error(\"Invalid payment response header\");\n }\n return JSON.parse(safeBase64Decode(paymentResponseHeader)) as SettleResponse;\n}\n\n// Export HTTP service and types\nexport {\n x402HTTPResourceServer,\n HTTPAdapter,\n HTTPRequestContext,\n HTTPTransportContext,\n HTTPResponseInstructions,\n HTTPProcessResult,\n PaywallConfig,\n PaywallProvider,\n PaymentOption,\n RouteConfig,\n RoutesConfig,\n CompiledRoute,\n DynamicPayTo,\n DynamicPrice,\n UnpaidResponseBody,\n HTTPResponseBody,\n SettlementFailedResponseBody,\n ProcessSettleResultResponse,\n ProcessSettleSuccessResponse,\n ProcessSettleFailureResponse,\n RouteValidationError,\n RouteConfigurationError,\n ProtectedRequestHook,\n} from \"./x402HTTPResourceServer\";\nexport {\n HTTPFacilitatorClient,\n FacilitatorClient,\n FacilitatorConfig,\n} from \"./httpFacilitatorClient\";\nexport { x402HTTPClient, PaymentRequiredContext, PaymentRequiredHook } from \"./x402HTTPClient\";\n"],"mappings":";;;;;;;;;;;;;;;;;AA2RO,IAAM,0BAAN,cAAsC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASjD,YA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;AAQO,SAAS,4BAA4B,uBAAgD;AAC1F,MAAI,CAAC,mBAAmB,KAAK,qBAAqB,GAAG;AACnD,UAAM,IAAI,MAAM,iCAAiC;AAAA,EACnD;AACA,SAAO,KAAK,MAAM,iBAAiB,qBAAqB,CAAC;AAC3D;AAQO,SAAS,4BAA4B,iBAAyC;AACnF,SAAO,iBAAiB,KAAK,UAAU,eAAe,CAAC;AACzD;AAQO,SAAS,4BAA4B,uBAA+C;AACzF,MAAI,CAAC,mBAAmB,KAAK,qBAAqB,GAAG;AACnD,UAAM,IAAI,MAAM,iCAAiC;AAAA,EACnD;AACA,SAAO,KAAK,MAAM,iBAAiB,qBAAqB,CAAC;AAC3D;","names":["errorReason","settleResponse","failure","response","displayAmount","resource"]}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// src/registry/assetRegistry.ts
|
|
2
|
+
var AssetRegistry = class {
|
|
3
|
+
/** Creates a new AssetRegistry pre-populated with built-in token data. */
|
|
4
|
+
constructor() {
|
|
5
|
+
this.assets = /* @__PURE__ */ new Map();
|
|
6
|
+
this.defaults = /* @__PURE__ */ new Map();
|
|
7
|
+
this.registerBuiltins();
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Register a single asset for a network.
|
|
11
|
+
*
|
|
12
|
+
* @param network - The network identifier (e.g. "eip155:1")
|
|
13
|
+
* @param symbol - The token symbol (e.g. "USDT")
|
|
14
|
+
* @param info - Asset metadata
|
|
15
|
+
*/
|
|
16
|
+
register(network, symbol, info) {
|
|
17
|
+
if (!this.assets.has(network)) {
|
|
18
|
+
this.assets.set(network, /* @__PURE__ */ new Map());
|
|
19
|
+
}
|
|
20
|
+
this.assets.get(network).set(symbol, info);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Batch-register multiple assets for a network.
|
|
24
|
+
*
|
|
25
|
+
* @param network - The network identifier
|
|
26
|
+
* @param assets - Map of symbol to AssetInfo
|
|
27
|
+
*/
|
|
28
|
+
registerAll(network, assets) {
|
|
29
|
+
for (const [symbol, info] of Object.entries(assets)) {
|
|
30
|
+
this.register(network, symbol, info);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Set the default asset symbol for a network.
|
|
35
|
+
*
|
|
36
|
+
* @param network - The network identifier
|
|
37
|
+
* @param symbol - The symbol to set as default
|
|
38
|
+
*/
|
|
39
|
+
setDefault(network, symbol) {
|
|
40
|
+
if (!this.has(network, symbol)) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
`Cannot set default: asset "${symbol}" is not registered on network "${network}"`
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
this.defaults.set(network, symbol);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Resolve a symbol to its AssetInfo on a network.
|
|
49
|
+
*
|
|
50
|
+
* @param network - The network identifier
|
|
51
|
+
* @param symbol - The token symbol
|
|
52
|
+
* @returns The resolved AssetInfo
|
|
53
|
+
* @throws If the asset is not registered
|
|
54
|
+
*/
|
|
55
|
+
resolve(network, symbol) {
|
|
56
|
+
const networkAssets = this.assets.get(network);
|
|
57
|
+
if (!networkAssets || !networkAssets.has(symbol)) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
`Asset "${symbol}" is not registered on network "${network}". Available: ${networkAssets ? Array.from(networkAssets.keys()).join(", ") : "none"}`
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return networkAssets.get(symbol);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Get the default asset for a network.
|
|
66
|
+
*
|
|
67
|
+
* @param network - The network identifier
|
|
68
|
+
* @returns The default symbol and its AssetInfo
|
|
69
|
+
* @throws If no default is configured
|
|
70
|
+
*/
|
|
71
|
+
getDefault(network) {
|
|
72
|
+
const symbol = this.defaults.get(network);
|
|
73
|
+
if (!symbol) {
|
|
74
|
+
throw new Error(`No default asset configured for network "${network}"`);
|
|
75
|
+
}
|
|
76
|
+
return { symbol, info: this.resolve(network, symbol) };
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* List all registered symbols for a network.
|
|
80
|
+
*
|
|
81
|
+
* @param network - The network identifier
|
|
82
|
+
* @returns Array of registered symbols
|
|
83
|
+
*/
|
|
84
|
+
getSymbols(network) {
|
|
85
|
+
const networkAssets = this.assets.get(network);
|
|
86
|
+
return networkAssets ? Array.from(networkAssets.keys()) : [];
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Check if an asset is registered on a network.
|
|
90
|
+
*
|
|
91
|
+
* @param network - The network identifier
|
|
92
|
+
* @param symbol - The token symbol
|
|
93
|
+
* @returns True if the asset is registered
|
|
94
|
+
*/
|
|
95
|
+
has(network, symbol) {
|
|
96
|
+
return this.assets.get(network)?.has(symbol) ?? false;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Register built-in known assets.
|
|
100
|
+
* Data sourced from mechanism defaults and built-in registry.
|
|
101
|
+
*/
|
|
102
|
+
registerBuiltins() {
|
|
103
|
+
this.registerAll("eip155:1", {
|
|
104
|
+
USDC: {
|
|
105
|
+
address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
|
|
106
|
+
decimals: 6,
|
|
107
|
+
name: "USD Coin",
|
|
108
|
+
version: "2"
|
|
109
|
+
},
|
|
110
|
+
USDT: {
|
|
111
|
+
address: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
|
|
112
|
+
decimals: 6,
|
|
113
|
+
name: "Tether USD",
|
|
114
|
+
version: "1",
|
|
115
|
+
assetTransferMethod: "permit2"
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
this.defaults.set("eip155:1", "USDC");
|
|
119
|
+
this.registerAll("eip155:56", {
|
|
120
|
+
USDC: {
|
|
121
|
+
address: "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
|
|
122
|
+
decimals: 18,
|
|
123
|
+
name: "USD Coin",
|
|
124
|
+
version: "1",
|
|
125
|
+
assetTransferMethod: "permit2"
|
|
126
|
+
},
|
|
127
|
+
USDT: {
|
|
128
|
+
address: "0x55d398326f99059fF775485246999027B3197955",
|
|
129
|
+
decimals: 18,
|
|
130
|
+
name: "Tether USD",
|
|
131
|
+
version: "1",
|
|
132
|
+
assetTransferMethod: "permit2"
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
this.defaults.set("eip155:56", "USDC");
|
|
136
|
+
this.registerAll("eip155:97", {
|
|
137
|
+
USDT: {
|
|
138
|
+
address: "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd",
|
|
139
|
+
decimals: 18,
|
|
140
|
+
name: "Tether USD",
|
|
141
|
+
version: "1",
|
|
142
|
+
assetTransferMethod: "permit2"
|
|
143
|
+
},
|
|
144
|
+
USDC: {
|
|
145
|
+
address: "0x64544969ed7EBf5f083679233325356EbE738930",
|
|
146
|
+
decimals: 18,
|
|
147
|
+
name: "USD Coin",
|
|
148
|
+
version: "1",
|
|
149
|
+
assetTransferMethod: "permit2"
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
this.defaults.set("eip155:97", "USDT");
|
|
153
|
+
this.registerAll("tron:mainnet", {
|
|
154
|
+
USDT: {
|
|
155
|
+
address: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
|
156
|
+
decimals: 6,
|
|
157
|
+
name: "Tether USD",
|
|
158
|
+
version: "1",
|
|
159
|
+
assetTransferMethod: "permit2"
|
|
160
|
+
},
|
|
161
|
+
USDD: {
|
|
162
|
+
address: "TXDk8mbtRbXeYuMNS83CfKPaYYT8XWv9Hz",
|
|
163
|
+
decimals: 18,
|
|
164
|
+
name: "Decentralized USD",
|
|
165
|
+
version: "1",
|
|
166
|
+
supportsEip2612: true,
|
|
167
|
+
assetTransferMethod: "permit2"
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
this.defaults.set("tron:mainnet", "USDT");
|
|
171
|
+
this.register("tron:shasta", "USDT", {
|
|
172
|
+
address: "TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs",
|
|
173
|
+
decimals: 6,
|
|
174
|
+
name: "Tether USD",
|
|
175
|
+
version: "1",
|
|
176
|
+
assetTransferMethod: "permit2"
|
|
177
|
+
});
|
|
178
|
+
this.defaults.set("tron:shasta", "USDT");
|
|
179
|
+
this.registerAll("tron:nile", {
|
|
180
|
+
USDT: {
|
|
181
|
+
address: "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf",
|
|
182
|
+
decimals: 6,
|
|
183
|
+
name: "Tether USD",
|
|
184
|
+
version: "1",
|
|
185
|
+
assetTransferMethod: "permit2"
|
|
186
|
+
},
|
|
187
|
+
USDD: {
|
|
188
|
+
address: "TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK",
|
|
189
|
+
decimals: 18,
|
|
190
|
+
name: "Decentralized USD",
|
|
191
|
+
version: "1",
|
|
192
|
+
supportsEip2612: true,
|
|
193
|
+
assetTransferMethod: "permit2"
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
this.defaults.set("tron:nile", "USDT");
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
function convertMoney(price, decimals) {
|
|
200
|
+
const numericAmount = typeof price === "string" ? parseFloat(price.replace(/^\$/, "").trim()) : price;
|
|
201
|
+
if (isNaN(numericAmount)) {
|
|
202
|
+
throw new Error(`Invalid money format: ${price}`);
|
|
203
|
+
}
|
|
204
|
+
const [intPart, decPart = ""] = String(numericAmount).split(".");
|
|
205
|
+
const paddedDec = decPart.padEnd(decimals, "0").slice(0, decimals);
|
|
206
|
+
return (intPart + paddedDec).replace(/^0+/, "") || "0";
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// src/registry/index.ts
|
|
210
|
+
var globalAssetRegistry = new AssetRegistry();
|
|
211
|
+
|
|
212
|
+
// src/index.ts
|
|
213
|
+
var x402Version = 2;
|
|
214
|
+
|
|
215
|
+
export {
|
|
216
|
+
AssetRegistry,
|
|
217
|
+
convertMoney,
|
|
218
|
+
globalAssetRegistry,
|
|
219
|
+
x402Version
|
|
220
|
+
};
|
|
221
|
+
//# sourceMappingURL=chunk-DFUINDLZ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/registry/assetRegistry.ts","../../src/registry/index.ts","../../src/index.ts"],"sourcesContent":["import { Network } from \"../types/index.js\";\n\n/**\n * Information about a token asset on a specific network.\n */\nexport interface AssetInfo {\n /** Token contract address */\n address: string;\n /** Number of decimal places */\n decimals: number;\n /** Human-readable token name (used in EIP-712 domain) */\n name?: string;\n /** Token version string (used in EIP-712 domain) */\n version?: string;\n /** Transfer method identifier (e.g. \"permit2\") */\n assetTransferMethod?: string;\n /** Whether the token supports EIP-2612 permit */\n supportsEip2612?: boolean;\n /** Additional metadata */\n // eslint-disable-next-line @typescript-eslint/member-ordering\n [key: string]: unknown;\n}\n\n/**\n * Registry of known token assets across networks.\n * Provides symbol-based lookup for token metadata.\n */\nexport class AssetRegistry {\n private assets: Map<string, Map<string, AssetInfo>> = new Map();\n private defaults: Map<string, string> = new Map();\n\n /** Creates a new AssetRegistry pre-populated with built-in token data. */\n constructor() {\n this.registerBuiltins();\n }\n\n /**\n * Register a single asset for a network.\n *\n * @param network - The network identifier (e.g. \"eip155:1\")\n * @param symbol - The token symbol (e.g. \"USDT\")\n * @param info - Asset metadata\n */\n register(network: Network, symbol: string, info: AssetInfo): void {\n if (!this.assets.has(network)) {\n this.assets.set(network, new Map());\n }\n this.assets.get(network)!.set(symbol, info);\n }\n\n /**\n * Batch-register multiple assets for a network.\n *\n * @param network - The network identifier\n * @param assets - Map of symbol to AssetInfo\n */\n registerAll(network: Network, assets: Record<string, AssetInfo>): void {\n for (const [symbol, info] of Object.entries(assets)) {\n this.register(network, symbol, info);\n }\n }\n\n /**\n * Set the default asset symbol for a network.\n *\n * @param network - The network identifier\n * @param symbol - The symbol to set as default\n */\n setDefault(network: Network, symbol: string): void {\n if (!this.has(network, symbol)) {\n throw new Error(\n `Cannot set default: asset \"${symbol}\" is not registered on network \"${network}\"`,\n );\n }\n this.defaults.set(network, symbol);\n }\n\n /**\n * Resolve a symbol to its AssetInfo on a network.\n *\n * @param network - The network identifier\n * @param symbol - The token symbol\n * @returns The resolved AssetInfo\n * @throws If the asset is not registered\n */\n resolve(network: Network, symbol: string): AssetInfo {\n const networkAssets = this.assets.get(network);\n if (!networkAssets || !networkAssets.has(symbol)) {\n throw new Error(\n `Asset \"${symbol}\" is not registered on network \"${network}\". ` +\n `Available: ${networkAssets ? Array.from(networkAssets.keys()).join(\", \") : \"none\"}`,\n );\n }\n return networkAssets.get(symbol)!;\n }\n\n /**\n * Get the default asset for a network.\n *\n * @param network - The network identifier\n * @returns The default symbol and its AssetInfo\n * @throws If no default is configured\n */\n getDefault(network: Network): { symbol: string; info: AssetInfo } {\n const symbol = this.defaults.get(network);\n if (!symbol) {\n throw new Error(`No default asset configured for network \"${network}\"`);\n }\n return { symbol, info: this.resolve(network, symbol) };\n }\n\n /**\n * List all registered symbols for a network.\n *\n * @param network - The network identifier\n * @returns Array of registered symbols\n */\n getSymbols(network: Network): string[] {\n const networkAssets = this.assets.get(network);\n return networkAssets ? Array.from(networkAssets.keys()) : [];\n }\n\n /**\n * Check if an asset is registered on a network.\n *\n * @param network - The network identifier\n * @param symbol - The token symbol\n * @returns True if the asset is registered\n */\n has(network: Network, symbol: string): boolean {\n return this.assets.get(network)?.has(symbol) ?? false;\n }\n\n /**\n * Register built-in known assets.\n * Data sourced from mechanism defaults and built-in registry.\n */\n private registerBuiltins(): void {\n // ── EVM Networks ──────────────────────────────────────────────\n\n // eip155:1 — Ethereum Mainnet\n this.registerAll(\"eip155:1\" as Network, {\n USDC: {\n address: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n decimals: 6,\n name: \"USD Coin\",\n version: \"2\",\n },\n USDT: {\n address: \"0xdAC17F958D2ee523a2206206994597C13D831ec7\",\n decimals: 6,\n name: \"Tether USD\",\n version: \"1\",\n assetTransferMethod: \"permit2\",\n },\n });\n this.defaults.set(\"eip155:1\", \"USDC\");\n\n // eip155:56 — BSC Mainnet (BEP-20, no EIP-3009/EIP-2612)\n this.registerAll(\"eip155:56\" as Network, {\n USDC: {\n address: \"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d\",\n decimals: 18,\n name: \"USD Coin\",\n version: \"1\",\n assetTransferMethod: \"permit2\",\n },\n USDT: {\n address: \"0x55d398326f99059fF775485246999027B3197955\",\n decimals: 18,\n name: \"Tether USD\",\n version: \"1\",\n assetTransferMethod: \"permit2\",\n },\n });\n this.defaults.set(\"eip155:56\", \"USDC\");\n\n // eip155:97 — BSC Testnet (BEP-20, no EIP-3009/EIP-2612)\n this.registerAll(\"eip155:97\" as Network, {\n USDT: {\n address: \"0x337610d27c682E347C9cD60BD4b3b107C9d34dDd\",\n decimals: 18,\n name: \"Tether USD\",\n version: \"1\",\n assetTransferMethod: \"permit2\",\n },\n USDC: {\n address: \"0x64544969ed7EBf5f083679233325356EbE738930\",\n decimals: 18,\n name: \"USD Coin\",\n version: \"1\",\n assetTransferMethod: \"permit2\",\n },\n });\n this.defaults.set(\"eip155:97\", \"USDT\");\n\n // ── TRON Networks ─────────────────────────────────────────────\n\n // tron:mainnet\n this.registerAll(\"tron:mainnet\" as Network, {\n USDT: {\n address: \"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t\",\n decimals: 6,\n name: \"Tether USD\",\n version: \"1\",\n assetTransferMethod: \"permit2\",\n },\n USDD: {\n address: \"TXDk8mbtRbXeYuMNS83CfKPaYYT8XWv9Hz\",\n decimals: 18,\n name: \"Decentralized USD\",\n version: \"1\",\n supportsEip2612: true,\n assetTransferMethod: \"permit2\",\n },\n });\n this.defaults.set(\"tron:mainnet\", \"USDT\");\n\n // tron:shasta\n this.register(\"tron:shasta\" as Network, \"USDT\", {\n address: \"TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs\",\n decimals: 6,\n name: \"Tether USD\",\n version: \"1\",\n assetTransferMethod: \"permit2\",\n });\n this.defaults.set(\"tron:shasta\", \"USDT\");\n\n // tron:nile\n this.registerAll(\"tron:nile\" as Network, {\n USDT: {\n address: \"TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf\",\n decimals: 6,\n name: \"Tether USD\",\n version: \"1\",\n assetTransferMethod: \"permit2\",\n },\n USDD: {\n address: \"TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK\",\n decimals: 18,\n name: \"Decentralized USD\",\n version: \"1\",\n supportsEip2612: true,\n assetTransferMethod: \"permit2\",\n },\n });\n this.defaults.set(\"tron:nile\", \"USDT\");\n }\n}\n\n/**\n * Convert a Money value (e.g., \"$1.50\", 1.5) to token smallest-unit string\n * using the given decimals.\n *\n * @param price - The price as a string or number\n * @param decimals - The number of decimal places for the token\n * @returns The amount in smallest units as a string\n */\nexport function convertMoney(price: string | number, decimals: number): string {\n const numericAmount =\n typeof price === \"string\" ? parseFloat(price.replace(/^\\$/, \"\").trim()) : price;\n\n if (isNaN(numericAmount)) {\n throw new Error(`Invalid money format: ${price}`);\n }\n\n // Use string math to avoid floating point issues\n const [intPart, decPart = \"\"] = String(numericAmount).split(\".\");\n const paddedDec = decPart.padEnd(decimals, \"0\").slice(0, decimals);\n return (intPart + paddedDec).replace(/^0+/, \"\") || \"0\";\n}\n","import { AssetRegistry } from \"./assetRegistry.js\";\n\nexport { AssetRegistry, convertMoney } from \"./assetRegistry.js\";\nexport type { AssetInfo } from \"./assetRegistry.js\";\n\n/**\n * Global shared AssetRegistry instance with built-in token data.\n * Used by default in x402ResourceServer. Developers can register\n * custom tokens on this instance or create their own if isolation is needed.\n */\nexport const globalAssetRegistry = new AssetRegistry();\n","export const x402Version = 2;\n\nexport { AssetRegistry, convertMoney, globalAssetRegistry } from \"./registry/index.js\";\nexport type { AssetInfo } from \"./registry/index.js\";\n"],"mappings":";AA2BO,IAAM,gBAAN,MAAoB;AAAA;AAAA,EAKzB,cAAc;AAJd,SAAQ,SAA8C,oBAAI,IAAI;AAC9D,SA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AM,aAAa,GAAG;AACxB,UAAM,IAAI,MAAM,yBAAyB,KAAK,EAAE;AAAA,EAClD;AAGA,QAAM,CAAC,SAAS,UAAU,EAAE,IAAI,OAAO,aAAa,EAAE,MAAM,GAAG;AAC/D,QAAM,YAAY,QAAQ,OAAO,UAAU,GAAG,EAAE,MAAM,GAAG,QAAQ;AACjE,UAAQ,UAAU,WAAW,QAAQ,OAAO,EAAE,KAAK;AACrD;;;ACpQO,IAAM,sBAAsB,IAAI,cAAc;;;ACV9C,IAAM,cAAc;","names":[]}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// src/types/facilitator.ts
|
|
2
|
+
var VerifyError = class extends Error {
|
|
3
|
+
/**
|
|
4
|
+
* Creates a VerifyError from a failed verification response.
|
|
5
|
+
*
|
|
6
|
+
* @param statusCode - HTTP status code from the facilitator
|
|
7
|
+
* @param response - The verify response containing error details
|
|
8
|
+
*/
|
|
9
|
+
constructor(statusCode, response) {
|
|
10
|
+
const reason = response.invalidReason || "unknown reason";
|
|
11
|
+
const message = response.invalidMessage;
|
|
12
|
+
super(message ? `${reason}: ${message}` : reason);
|
|
13
|
+
this.name = "VerifyError";
|
|
14
|
+
this.statusCode = statusCode;
|
|
15
|
+
this.invalidReason = response.invalidReason;
|
|
16
|
+
this.invalidMessage = response.invalidMessage;
|
|
17
|
+
this.payer = response.payer;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
var SettleError = class extends Error {
|
|
21
|
+
/**
|
|
22
|
+
* Creates a SettleError from a failed settlement response.
|
|
23
|
+
*
|
|
24
|
+
* @param statusCode - HTTP status code from the facilitator
|
|
25
|
+
* @param response - The settle response containing error details
|
|
26
|
+
*/
|
|
27
|
+
constructor(statusCode, response) {
|
|
28
|
+
const reason = response.errorReason || "unknown reason";
|
|
29
|
+
const message = response.errorMessage;
|
|
30
|
+
super(message ? `${reason}: ${message}` : reason);
|
|
31
|
+
this.name = "SettleError";
|
|
32
|
+
this.statusCode = statusCode;
|
|
33
|
+
this.errorReason = response.errorReason;
|
|
34
|
+
this.errorMessage = response.errorMessage;
|
|
35
|
+
this.payer = response.payer;
|
|
36
|
+
this.transaction = response.transaction;
|
|
37
|
+
this.network = response.network;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export {
|
|
42
|
+
VerifyError,
|
|
43
|
+
SettleError
|
|
44
|
+
};
|
|
45
|
+
//# sourceMappingURL=chunk-HRQUGJ3Y.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/types/facilitator.ts"],"sourcesContent":["import { PaymentPayload, PaymentRequirements } from \"./payments\";\nimport { Network } from \"./\";\n\nexport type VerifyRequest = {\n x402Version: number;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n};\n\nexport type VerifyResponse = {\n isValid: boolean;\n invalidReason?: string;\n invalidMessage?: string;\n payer?: string;\n extensions?: Record<string, unknown>;\n};\n\nexport type SettleRequest = {\n x402Version: number;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n};\n\nexport type SettleResponse = {\n success: boolean;\n errorReason?: string;\n errorMessage?: string;\n payer?: string;\n transaction: string;\n network: Network;\n extensions?: Record<string, unknown>;\n};\n\nexport type SupportedKind = {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n};\n\nexport type SupportedResponse = {\n kinds: SupportedKind[];\n extensions: string[];\n signers: Record<string, string[]>; // CAIP family pattern → Signer addresses\n};\n\n/**\n * Error thrown when payment verification fails.\n */\nexport class VerifyError extends Error {\n readonly invalidReason?: string;\n readonly invalidMessage?: string;\n readonly payer?: string;\n readonly statusCode: number;\n\n /**\n * Creates a VerifyError from a failed verification response.\n *\n * @param statusCode - HTTP status code from the facilitator\n * @param response - The verify response containing error details\n */\n constructor(statusCode: number, response: VerifyResponse) {\n const reason = response.invalidReason || \"unknown reason\";\n const message = response.invalidMessage;\n super(message ? `${reason}: ${message}` : reason);\n this.name = \"VerifyError\";\n this.statusCode = statusCode;\n this.invalidReason = response.invalidReason;\n this.invalidMessage = response.invalidMessage;\n this.payer = response.payer;\n }\n}\n\n/**\n * Error thrown when payment settlement fails.\n */\nexport class SettleError extends Error {\n readonly errorReason?: string;\n readonly errorMessage?: string;\n readonly payer?: string;\n readonly transaction: string;\n readonly network: Network;\n readonly statusCode: number;\n\n /**\n * Creates a SettleError from a failed settlement response.\n *\n * @param statusCode - HTTP status code from the facilitator\n * @param response - The settle response containing error details\n */\n constructor(statusCode: number, response: SettleResponse) {\n const reason = response.errorReason || \"unknown reason\";\n const message = response.errorMessage;\n super(message ? `${reason}: ${message}` : reason);\n this.name = \"SettleError\";\n this.statusCode = statusCode;\n this.errorReason = response.errorReason;\n this.errorMessage = response.errorMessage;\n this.payer = response.payer;\n this.transaction = response.transaction;\n this.network = response.network;\n }\n}\n"],"mappings":";AAiDO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYrC,YAAY,YAAoB,UAA0B;AACxD,UAAM,SAAS,SAAS,iBAAiB;AACzC,UAAM,UAAU,SAAS;AACzB,UAAM,UAAU,GAAG,MAAM,KAAK,OAAO,KAAK,MAAM;AAChD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,gBAAgB,SAAS;AAC9B,SAAK,iBAAiB,SAAS;AAC/B,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAKO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcrC,YAAY,YAAoB,UAA0B;AACxD,UAAM,SAAS,SAAS,eAAe;AACvC,UAAM,UAAU,SAAS;AACzB,UAAM,UAAU,GAAG,MAAM,KAAK,OAAO,KAAK,MAAM;AAChD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,cAAc,SAAS;AAC5B,SAAK,eAAe,SAAS;AAC7B,SAAK,QAAQ,SAAS;AACtB,SAAK,cAAc,SAAS;AAC5B,SAAK,UAAU,SAAS;AAAA,EAC1B;AACF;","names":[]}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// src/utils/index.ts
|
|
2
|
+
var findSchemesByNetwork = (map, network) => {
|
|
3
|
+
let implementationsByScheme = map.get(network);
|
|
4
|
+
if (!implementationsByScheme) {
|
|
5
|
+
for (const [registeredNetworkPattern, implementations] of map.entries()) {
|
|
6
|
+
const pattern = registeredNetworkPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*");
|
|
7
|
+
const regex = new RegExp(`^${pattern}$`);
|
|
8
|
+
if (regex.test(network)) {
|
|
9
|
+
implementationsByScheme = implementations;
|
|
10
|
+
break;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
return implementationsByScheme;
|
|
15
|
+
};
|
|
16
|
+
var findByNetworkAndScheme = (map, scheme, network) => {
|
|
17
|
+
return findSchemesByNetwork(map, network)?.get(scheme);
|
|
18
|
+
};
|
|
19
|
+
var findFacilitatorBySchemeAndNetwork = (schemeMap, scheme, network) => {
|
|
20
|
+
const schemeData = schemeMap.get(scheme);
|
|
21
|
+
if (!schemeData) return void 0;
|
|
22
|
+
if (schemeData.networks.has(network)) {
|
|
23
|
+
return schemeData.facilitator;
|
|
24
|
+
}
|
|
25
|
+
const patternRegex = new RegExp("^" + schemeData.pattern.replace("*", ".*") + "$");
|
|
26
|
+
if (patternRegex.test(network)) {
|
|
27
|
+
return schemeData.facilitator;
|
|
28
|
+
}
|
|
29
|
+
return void 0;
|
|
30
|
+
};
|
|
31
|
+
var Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
32
|
+
function safeBase64Encode(data) {
|
|
33
|
+
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
|
|
34
|
+
const bytes = new TextEncoder().encode(data);
|
|
35
|
+
const binaryString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
|
|
36
|
+
return globalThis.btoa(binaryString);
|
|
37
|
+
}
|
|
38
|
+
return Buffer.from(data, "utf8").toString("base64");
|
|
39
|
+
}
|
|
40
|
+
function safeBase64Decode(data) {
|
|
41
|
+
if (typeof globalThis !== "undefined" && typeof globalThis.atob === "function") {
|
|
42
|
+
const binaryString = globalThis.atob(data);
|
|
43
|
+
const bytes = new Uint8Array(binaryString.length);
|
|
44
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
45
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
46
|
+
}
|
|
47
|
+
const decoder = new TextDecoder("utf-8");
|
|
48
|
+
return decoder.decode(bytes);
|
|
49
|
+
}
|
|
50
|
+
return Buffer.from(data, "base64").toString("utf-8");
|
|
51
|
+
}
|
|
52
|
+
function deepEqual(obj1, obj2) {
|
|
53
|
+
const normalize = (obj) => {
|
|
54
|
+
if (obj === null || obj === void 0) return JSON.stringify(obj);
|
|
55
|
+
if (typeof obj !== "object") return JSON.stringify(obj);
|
|
56
|
+
if (Array.isArray(obj)) {
|
|
57
|
+
return JSON.stringify(
|
|
58
|
+
obj.map(
|
|
59
|
+
(item) => typeof item === "object" && item !== null ? JSON.parse(normalize(item)) : item
|
|
60
|
+
)
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
const sorted = {};
|
|
64
|
+
Object.keys(obj).sort().forEach((key) => {
|
|
65
|
+
const value = obj[key];
|
|
66
|
+
sorted[key] = typeof value === "object" && value !== null ? JSON.parse(normalize(value)) : value;
|
|
67
|
+
});
|
|
68
|
+
return JSON.stringify(sorted);
|
|
69
|
+
};
|
|
70
|
+
try {
|
|
71
|
+
return normalize(obj1) === normalize(obj2);
|
|
72
|
+
} catch {
|
|
73
|
+
return JSON.stringify(obj1) === JSON.stringify(obj2);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export {
|
|
78
|
+
findSchemesByNetwork,
|
|
79
|
+
findByNetworkAndScheme,
|
|
80
|
+
findFacilitatorBySchemeAndNetwork,
|
|
81
|
+
Base64EncodedRegex,
|
|
82
|
+
safeBase64Encode,
|
|
83
|
+
safeBase64Decode,
|
|
84
|
+
deepEqual
|
|
85
|
+
};
|
|
86
|
+
//# sourceMappingURL=chunk-TDLQZ6MP.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/index.ts"],"sourcesContent":["import { Network } from \"../types\";\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData<T> {\n facilitator: T;\n networks: Set<Network>;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = <T>(\n map: Map<string, Map<string, T>>,\n network: Network,\n): Map<string, T> | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = <T>(\n map: Map<string, Map<string, T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = <T>(\n schemeMap: Map<string, SchemeData<T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n const bytes = new TextEncoder().encode(data);\n const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join(\"\");\n return globalThis.btoa(binaryString);\n }\n return Buffer.from(data, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n const binaryString = globalThis.atob(data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record<string, unknown> = {};\n Object.keys(obj as Record<string, unknown>)\n .sort()\n .forEach(key => {\n const value = (obj as Record<string, unknown>)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n"],"mappings":";AAWO,IAAM,uBAAuB,CAClC,KACA,YAC+B;AAE/B,MAAI,0BAA0B,IAAI,IAAI,OAAO;AAE7C,MAAI,CAAC,yBAAyB;AAE5B,eAAW,CAAC,0BAA0B,eAAe,KAAK,IAAI,QAAQ,GAAG;AAGvE,YAAM,UAAU,yBACb,QAAQ,uBAAuB,MAAM,EACrC,QAAQ,SAAS,IAAI;AAExB,YAAM,QAAQ,IAAI,OAAO,IAAI,OAAO,GAAG;AAEvC,UAAI,MAAM,KAAK,OAAO,GAAG;AACvB,kCAA0B;AAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,IAAM,yBAAyB,CACpC,KACA,QACA,YACkB;AAClB,SAAO,qBAAqB,KAAK,OAAO,GAAG,IAAI,MAAM;AACvD;AAWO,IAAM,oCAAoC,CAC/C,WACA,QACA,YACkB;AAClB,QAAM,aAAa,UAAU,IAAI,MAAM;AACvC,MAAI,CAAC,WAAY,QAAO;AAGxB,MAAI,WAAW,SAAS,IAAI,OAAO,GAAG;AACpC,WAAO,WAAW;AAAA,EACpB;AAGA,QAAM,eAAe,IAAI,OAAO,MAAM,WAAW,QAAQ,QAAQ,KAAK,IAAI,IAAI,GAAG;AACjF,MAAI,aAAa,KAAK,OAAO,GAAG;AAC9B,WAAO,WAAW;AAAA,EACpB;AAEA,SAAO;AACT;AAEO,IAAM,qBAAqB;AAQ3B,SAAS,iBAAiB,MAAsB;AACrD,MAAI,OAAO,eAA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