@x402-lens/express 0.2.0 → 0.2.4
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 +21 -6
- package/dist/index.cjs +254 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +18 -6
- package/dist/index.d.ts +18 -6
- package/dist/index.js +258 -61
- package/dist/index.js.map +1 -1
- package/package.json +55 -55
- package/dist/.tsbuildinfo +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/context.ts","../src/observe.ts"],"sourcesContent":["/**\r\n * `paymentLens()` — x402 v2 payments for Express, with observability that\r\n * explains itself.\r\n *\r\n * This is a thin layer over `@x402/express`, not a reimplementation. The\r\n * official middleware owns the protocol: it builds `PaymentRequired`, sets\r\n * `PAYMENT-REQUIRED`, calls the facilitator's `/verify` and `/settle`, and\r\n * settles only after a successful handler. Everything here attaches to it.\r\n *\r\n * What we add:\r\n *\r\n * - An event per payment lifecycle step, with the fields needed to answer\r\n * \"why did this fail\": route, amount, network, buyer, tx hash, plus findings.\r\n * - A readable 402 body next to the canonical header, so `curl | jq` works.\r\n * - Config loading that refuses to guess a facilitator, network, or address.\r\n */\r\n\r\nimport { randomUUID } from \"node:crypto\";\r\nimport type { NextFunction, Request, RequestHandler, Response } from \"express\";\r\nimport {\r\n EventBus,\r\n PrometheusRegistry,\r\n callbackSink,\r\n consoleSink,\r\n diagnose,\r\n jsonlFileSink,\r\n loadConfig,\r\n makeEvent,\r\n openTelemetrySink,\r\n prometheusSink,\r\n resolveConfig,\r\n sentryBreadcrumbSink,\r\n toRoutesConfig,\r\n type Finding,\r\n type LensConfig,\r\n type LensConfigInput,\r\n type LensEvent,\r\n type LensSink,\r\n type OtelTracerLike,\r\n type PaymentScheme,\r\n type RouteInput,\r\n type SentryLike,\r\n type WirePaymentPayload,\r\n type WirePaymentRequired,\r\n type WireSettleResponse,\r\n type WireVerifyResponse,\r\n} from \"@x402-lens/core\";\r\nimport {\r\n HTTPFacilitatorClient,\r\n x402HTTPResourceServer,\r\n x402ResourceServer,\r\n type FacilitatorClient,\r\n type HTTPRequestContext,\r\n type RoutesConfig,\r\n} from \"@x402/core/server\";\r\nimport { paymentMiddlewareFromHTTPServer } from \"@x402/express\";\r\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\r\nimport { UptoEvmScheme } from \"@x402/evm/upto/server\";\r\nimport { ExactSvmScheme } from \"@x402/svm/exact/server\";\r\nimport { UptoSvmScheme } from \"@x402/svm/upto/server\";\r\nimport { currentRequestContext, runWithRequestContext } from \"./context.js\";\r\nimport { observePaymentRequired } from \"./observe.js\";\r\n\r\n/** Where the lens should send events. */\r\nexport interface LensSinkOptions {\r\n /** Print a compact line per event. Defaults to `true`. */\r\n console?: boolean;\r\n /** Append newline-delimited JSON to this path. */\r\n jsonlPath?: string;\r\n /** Called for every event. Exceptions are caught and never reach the caller. */\r\n onEvent?: (event: LensEvent) => void;\r\n /**\r\n * Record counters for Prometheus. Pass `true` for the shared registry, or a\r\n * `PrometheusRegistry` you will serve from `/metrics` via `prometheusHandler`.\r\n */\r\n prometheus?: boolean | PrometheusRegistry;\r\n /**\r\n * OpenTelemetry tracer (`trace.getTracer(\"x402-lens\")`). Opens a short span\r\n * per event. `@opentelemetry/api` is not a dependency of this package.\r\n */\r\n otel?: OtelTracerLike;\r\n /**\r\n * Sentry-compatible handle (`import * as Sentry from \"@sentry/node\"`).\r\n * Records each event as a breadcrumb. Sentry is not a dependency.\r\n */\r\n sentry?: SentryLike;\r\n}\r\n\r\n/** Short route form: a bare price, or the full per-route options. */\r\nexport type RouteMap = Record<string, string | Omit<RouteInput, \"route\">>;\r\n\r\nexport interface PaymentLensOptions extends Omit<LensConfigInput, \"routes\"> {\r\n /**\r\n * Route prices, in either the short map form\r\n * (`{ \"GET /weather\": \"$0.001\" }`) or the `RouteInput[]` form. Overrides the\r\n * config file and `X402_PRICE__*`.\r\n */\r\n routes?: RouteMap | RouteInput[];\r\n /** Pre-resolved config. Skips loading entirely, including validation. */\r\n config?: LensConfig;\r\n /** Where events go. Defaults to console. */\r\n sinks?: LensSinkOptions;\r\n /** Extra sinks, appended after the ones built from `sinks`. */\r\n extraSinks?: LensSink[];\r\n /** Override the `RoutesConfig` handed to `@x402/express`, for advanced setups. */\r\n routesConfig?: RoutesConfig;\r\n /**\r\n * Mirror the decoded challenge into the 402 JSON body. On by default: the v2\r\n * spec leaves the body to the server, and a readable body is the difference\r\n * between a debuggable endpoint and a base64 scavenger hunt.\r\n */\r\n readableBody?: boolean;\r\n /**\r\n * Expose the payment headers for browser buyers. Off by default so an app\r\n * with its own CORS layer is never surprised.\r\n *\r\n * Without this, a cross-origin `fetch()` cannot read `PAYMENT-REQUIRED` or\r\n * `PAYMENT-RESPONSE`, and the browser strips `PAYMENT-SIGNATURE` from the\r\n * retry — the payment silently never happens. `x402-lens inspect` reports it.\r\n *\r\n * Pass `true` to let x402-lens set the headers, or `{ origin }` to also emit\r\n * `Access-Control-Allow-Origin`. If your app already has a CORS middleware,\r\n * leave this off and add the three headers there instead.\r\n */\r\n cors?: boolean | { origin?: string };\r\n /**\r\n * Replace the facilitator client entirely.\r\n *\r\n * For a facilitator that is not plain HTTP (an in-process one, a queue-backed\r\n * one, a proxy that signs requests), or to wrap the SDK client with retries,\r\n * caching, or metrics. When supplied, `facilitatorUrl` is still validated but\r\n * only used for event metadata and doctor output.\r\n */\r\n facilitatorClient?: FacilitatorClient;\r\n /**\r\n * Grant access without payment for a request.\r\n *\r\n * Runs before verification on every request to a protected route. Return\r\n * `true` to let the handler run unpaid (health checks, internal traffic, a\r\n * free tier), or a reason string to deny with a 403. Every decision is\r\n * emitted as `access.granted` / `access.denied`, so a bypass is never silent.\r\n *\r\n * Returning `false`/`undefined` continues to the normal payment flow.\r\n */\r\n grant?: (request: GrantContext) => boolean | string | undefined | Promise<boolean | string | undefined>;\r\n}\r\n\r\nexport interface PaymentLens {\r\n /** Mount in Express before your routes. */\r\n middleware: RequestHandler;\r\n /** The underlying resource server, for custom hooks or extensions. */\r\n server: x402ResourceServer;\r\n /** The underlying HTTP resource server. */\r\n httpServer: x402HTTPResourceServer;\r\n /** Resolved and validated configuration. */\r\n config: LensConfig;\r\n /** Subscribe to events programmatically. */\r\n on(listener: (event: LensEvent) => void): () => void;\r\n /** Flush sinks and stop emitting. */\r\n close(): Promise<void>;\r\n}\r\n\r\n/** What a `grant` callback is given about the request it may let through. */\r\nexport interface GrantContext {\r\n /** HTTP method, e.g. `GET`. */\r\n method: string;\r\n /** Request path, e.g. `/weather`. */\r\n path: string;\r\n /** `\"<METHOD> <path>\"`, the same key the route map uses. */\r\n route: string;\r\n /**\r\n * Read a request header, case-insensitively-ish (exactly as the adapter\r\n * reports it). The SDK gives hooks an accessor rather than a header map, so\r\n * this is a function — use it to check an API key or an internal marker.\r\n */\r\n header(name: string): string | undefined;\r\n /** Query parameters, when the adapter can provide them. */\r\n query: Record<string, string | string[]>;\r\n /** The route's own configuration, including its prices and metadata. */\r\n config: unknown;\r\n}\r\n\r\n/**\r\n * Build x402 payment middleware for Express.\r\n *\r\n * Configuration precedence is explicit options → `X402_*` environment variables.\r\n * Use {@link paymentLensAsync} when it should also read `x402.config.json`.\r\n *\r\n * @param options - Routes, configuration, and sinks\r\n * @returns Middleware plus handles for events and the underlying servers\r\n * @throws {ConfigError} When a required setting is missing or malformed\r\n */\r\nexport function paymentLens(options: PaymentLensOptions = {}): PaymentLens {\r\n const config = options.config ?? resolveConfig({\r\n ...options,\r\n routes: normaliseRouteInput(options.routes),\r\n });\r\n return buildLens(config, options);\r\n}\r\n\r\n/**\r\n * Async variant that also reads `x402.config.json` from the working directory.\r\n *\r\n * @param options - Routes, configuration, and sinks\r\n * @returns Middleware plus handles for events and the underlying servers\r\n * @throws {ConfigError} When a required setting is missing or malformed\r\n */\r\nexport async function paymentLensAsync(\r\n options: PaymentLensOptions = {},\r\n): Promise<PaymentLens> {\r\n const config = options.config ?? await loadConfig({\r\n ...options,\r\n routes: normaliseRouteInput(options.routes),\r\n });\r\n return buildLens(config, options);\r\n}\r\n\r\nfunction normaliseRouteInput(routes: PaymentLensOptions[\"routes\"]): RouteInput[] | undefined {\r\n if (!routes) return undefined;\r\n if (Array.isArray(routes)) return routes;\r\n // A bare string is the common case; an object allows per-route options such as\r\n // `paymentFlow` without dropping to the array form.\r\n return Object.entries(routes).map(([route, value]) =>\r\n typeof value === \"string\" ? { route, price: value } : { route, ...value },\r\n );\r\n}\r\n\r\nfunction buildLens(config: LensConfig, options: PaymentLensOptions): PaymentLens {\r\n const bus = new EventBus([\r\n ...buildSinks(options.sinks),\r\n ...(options.extraSinks ?? []),\r\n ]);\r\n const readableBody = options.readableBody ?? true;\r\n\r\n const facilitatorClient =\r\n options.facilitatorClient ?? buildFacilitatorClient(config);\r\n const server = new x402ResourceServer(facilitatorClient);\r\n const schemes = schemesInUse(config);\r\n for (const network of config.networks) registerScheme(server, network, schemes);\r\n\r\n const routes = options.routesConfig ?? (toRoutesConfig(config) as unknown as RoutesConfig);\r\n\r\n attachHooks(server, bus, config);\r\n\r\n const httpServer = new x402HTTPResourceServer(server, routes);\r\n const inner = paymentMiddlewareFromHTTPServer(httpServer);\r\n const corsHeaders = buildCorsHeaders(options.cors);\r\n\r\n if (options.grant) {\r\n const grant = options.grant;\r\n httpServer.onProtectedRequest(async (context, routeConfig) => {\r\n const method = safeCall(() => context.adapter.getMethod()) ?? \"GET\";\r\n const path = safeCall(() => context.adapter.getPath()) ?? context.path ?? \"/\";\r\n const decision = await grant({\r\n method,\r\n path,\r\n route: `${method} ${path}`,\r\n header: (name: string) => safeCall(() => context.adapter.getHeader(name)),\r\n query: safeCall(() => context.adapter.getQueryParams?.() ?? {}) ?? {},\r\n config: routeConfig,\r\n });\r\n\r\n if (decision === true) {\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n type: \"access.granted\",\r\n requestId: currentRequestContext()?.requestId ?? randomUUID(),\r\n route: `${method} ${path}`,\r\n scheme: \"exact\",\r\n network: config.network,\r\n amount: \"0\",\r\n asset: \"\",\r\n payTo: config.payTo,\r\n } as LensEvent),\r\n );\r\n return { grantAccess: true };\r\n }\r\n\r\n if (typeof decision === \"string\") {\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n type: \"access.denied\",\r\n requestId: currentRequestContext()?.requestId ?? randomUUID(),\r\n route: `${method} ${path}`,\r\n scheme: \"exact\",\r\n network: config.network,\r\n amount: \"0\",\r\n asset: \"\",\r\n payTo: config.payTo,\r\n reason: decision,\r\n } as LensEvent),\r\n );\r\n return { abort: true, reason: decision };\r\n }\r\n\r\n return undefined;\r\n });\r\n }\r\n\r\n const middleware: RequestHandler = (req: Request, res: Response, next: NextFunction) => {\r\n const context = {\r\n requestId: randomUUID(),\r\n startedAt: Date.now(),\r\n method: req.method,\r\n path: req.path,\r\n };\r\n\r\n if (corsHeaders) applyCorsHeaders(res, corsHeaders);\r\n\r\n const emitRequired = (paymentRequired: WirePaymentRequired): void => {\r\n const entries = paymentRequired.accepts ?? [];\r\n const entry = entries[0];\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n type: \"payment.required\",\r\n requestId: context.requestId,\r\n route: `${context.method} ${context.path}`,\r\n scheme: entry?.scheme ?? \"exact\",\r\n network: entry?.network ?? config.network,\r\n amount: entry?.amount ?? \"0\",\r\n asset: entry?.asset ?? \"\",\r\n payTo: entry?.payTo ?? config.payTo,\r\n offers: entries.length,\r\n durationMs: Date.now() - context.startedAt,\r\n findings: diagnose({ paymentRequired, now: context.startedAt }),\r\n } as LensEvent),\r\n );\r\n };\r\n\r\n observePaymentRequired(res, emitRequired, { mirrorBody: readableBody });\r\n\r\n runWithRequestContext(context, () => inner(req, res, next));\r\n };\r\n\r\n return {\r\n middleware,\r\n server,\r\n httpServer,\r\n config,\r\n on(listener) {\r\n const sink = callbackSink(listener);\r\n bus.add(sink);\r\n return () => {\r\n bus.remove(sink);\r\n };\r\n },\r\n close() {\r\n return bus.close();\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Call an adapter accessor, treating a throw as \"not available\".\r\n *\r\n * Adapters are third-party code; a missing or throwing accessor must not turn\r\n * an access decision into a 500.\r\n */\r\nfunction safeCall<T>(read: () => T): T | undefined {\r\n try {\r\n return read();\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/**\r\n * Build the SDK facilitator client, carrying auth headers and a request\r\n * timeout when configured.\r\n *\r\n * The SDK requires auth headers keyed by endpoint; passing a flat object throws\r\n * at request time, so the shape is validated once here rather than surfacing as\r\n * a failed payment later.\r\n */\r\nfunction buildFacilitatorClient(config: LensConfig): HTTPFacilitatorClient {\r\n const authHeaders = config.facilitatorHeaders;\r\n const timeoutMs = config.facilitatorTimeoutMs;\r\n\r\n return new HTTPFacilitatorClient({\r\n url: config.facilitatorUrl,\r\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\r\n ...(authHeaders ? { createAuthHeaders: async () => authHeaders } : {}),\r\n });\r\n}\r\n\r\nfunction buildSinks(sinkOptions: LensSinkOptions | undefined): LensSink[] {\r\n const sinks: LensSink[] = [];\r\n if (sinkOptions?.console ?? true) sinks.push(consoleSink());\r\n if (sinkOptions?.jsonlPath) sinks.push(jsonlFileSink(sinkOptions.jsonlPath));\r\n if (sinkOptions?.onEvent) sinks.push(callbackSink(sinkOptions.onEvent));\r\n if (sinkOptions?.prometheus) {\r\n sinks.push(\r\n prometheusSink(\r\n sinkOptions.prometheus === true\r\n ? undefined\r\n : sinkOptions.prometheus,\r\n ),\r\n );\r\n }\r\n if (sinkOptions?.otel) sinks.push(openTelemetrySink(sinkOptions.otel));\r\n if (sinkOptions?.sentry) sinks.push(sentryBreadcrumbSink(sinkOptions.sentry));\r\n return sinks;\r\n}\r\n\r\n/**\r\n * The three headers a browser buyer needs, and nothing else.\r\n *\r\n * A literal `*` does not cover any of them on a credentialed request, so they\r\n * have to be named. `Access-Control-Allow-Headers` also needs `Content-Type`\r\n * whenever the retry carries a JSON body, because that alone triggers a\r\n * preflight before the payment header is even considered.\r\n */\r\nfunction buildCorsHeaders(\r\n cors: PaymentLensOptions[\"cors\"],\r\n): Record<string, string> | undefined {\r\n if (!cors) return undefined;\r\n const headers: Record<string, string> = {\r\n \"Access-Control-Expose-Headers\": \"PAYMENT-REQUIRED, PAYMENT-RESPONSE\",\r\n \"Access-Control-Allow-Headers\": \"Content-Type, PAYMENT-SIGNATURE\",\r\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, PATCH, DELETE, OPTIONS\",\r\n };\r\n if (typeof cors === \"object\" && cors.origin) {\r\n headers[\"Access-Control-Allow-Origin\"] = cors.origin;\r\n if (cors.origin !== \"*\") headers.Vary = \"Origin\";\r\n }\r\n return headers;\r\n}\r\n\r\n/**\r\n * Merge our headers into whatever the response already has, so an app's own\r\n * CORS layer keeps working.\r\n */\r\nfunction applyCorsHeaders(res: Response, headers: Record<string, string>): void {\r\n for (const [name, value] of Object.entries(headers)) {\r\n const existing = res.getHeader(name);\r\n if (existing === undefined) {\r\n res.setHeader(name, value);\r\n continue;\r\n }\r\n const merged = new Set(\r\n String(existing)\r\n .split(\",\")\r\n .map(part => part.trim())\r\n .filter(Boolean),\r\n );\r\n for (const item of value.split(\",\").map(part => part.trim())) merged.add(item);\r\n res.setHeader(name, Array.from(merged).join(\", \"));\r\n }\r\n}\r\n\r\n/**\r\n * Register the schemes this package supports on one network.\r\n *\r\n * `exact` is always registered; `upto` only when a route asks for it, so the\r\n * challenge for an all-`exact` deployment stays byte-identical to before.\r\n *\r\n * @param server - Resource server to register on\r\n * @param network - CAIP-2 network, already validated\r\n * @param schemes - Schemes any route on this network needs\r\n */\r\nfunction registerScheme(\r\n server: x402ResourceServer,\r\n network: string,\r\n schemes: ReadonlySet<PaymentScheme>,\r\n): void {\r\n const separator = network.indexOf(\":\");\r\n const namespace = separator === -1 ? network : network.slice(0, separator);\r\n // `Network` is a template-literal type; the value was validated as CAIP-2 by\r\n // `resolveConfig` before reaching here.\r\n const caip2 = network as `${string}:${string}`;\r\n\r\n switch (namespace) {\r\n case \"eip155\": {\r\n server.register(caip2, new ExactEvmScheme());\r\n if (schemes.has(\"upto\")) server.register(caip2, new UptoEvmScheme());\r\n return;\r\n }\r\n case \"solana\": {\r\n server.register(caip2, new ExactSvmScheme());\r\n if (schemes.has(\"upto\")) server.register(caip2, new UptoSvmScheme({}));\r\n return;\r\n }\r\n default:\r\n throw new Error(\r\n `[x402-lens] No scheme for namespace \"${namespace}\". This package registers exact (and upto) schemes for eip155 and solana. For any other network, keep the returned server instance and call server.register(network, scheme) yourself.`,\r\n );\r\n }\r\n}\r\n\r\n/** Which schemes the configured routes actually need. */\r\nfunction schemesInUse(config: LensConfig): Set<PaymentScheme> {\r\n const used = new Set<PaymentScheme>();\r\n for (const route of config.routes) used.add(route.scheme ?? \"exact\");\r\n return used;\r\n}\r\n\r\n/** The three fields every event needs from a `PaymentRequirements`. */\r\ninterface RequirementsShape {\r\n scheme: string;\r\n network: string;\r\n amount: string;\r\n asset: string;\r\n payTo: string;\r\n}\r\n\r\nfunction attachHooks(server: x402ResourceServer, bus: EventBus, config: LensConfig): void {\r\n server.onAfterVerify(async context => {\r\n const requirements = context.requirements as unknown as RequirementsShape;\r\n const result = context.result as unknown as WireVerifyResponse;\r\n const payload = context.paymentPayload as unknown as WirePaymentPayload;\r\n const base = baseEvent(requirements, config, result.isValid ? result.payer : undefined);\r\n const findings: Finding[] = diagnose({\r\n verifyResponse: result,\r\n paymentPayload: payload,\r\n paymentRequired: syntheticChallenge(requirements),\r\n });\r\n\r\n if (!result.isValid) {\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n ...base,\r\n type: \"payment.failed\",\r\n reason: result.invalidReason ?? \"unknown\",\r\n findings,\r\n } as LensEvent),\r\n );\r\n return;\r\n }\r\n\r\n bus.emit(makeEvent<LensEvent>({ ...base, type: \"payment.verified\" } as LensEvent));\r\n });\r\n\r\n server.onVerifyFailure(async context => {\r\n const requirements = context.requirements as unknown as RequirementsShape;\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n ...baseEvent(requirements, config),\r\n type: \"facilitator.error\",\r\n message: context.error.message,\r\n } as LensEvent),\r\n );\r\n });\r\n\r\n server.onAfterSettle(async context => {\r\n const requirements = context.requirements as unknown as RequirementsShape;\r\n const result = context.result as unknown as WireSettleResponse;\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n ...baseEvent(requirements, config, result.payer),\r\n type: \"payment.settled\",\r\n txHash: result.transaction ?? \"\",\r\n phase: context.phase,\r\n findings: diagnose({ settleResponse: result }),\r\n } as LensEvent),\r\n );\r\n });\r\n\r\n server.onSettleFailure(async context => {\r\n const requirements = context.requirements as unknown as RequirementsShape;\r\n const settle = settleFromError(context.error);\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n ...baseEvent(requirements, config, settle?.payer),\r\n type: \"payment.settle_failed\",\r\n reason: settle?.errorReason ?? context.error.message,\r\n ...(settle?.transaction ? { txHash: settle.transaction } : {}),\r\n phase: context.phase,\r\n findings: diagnose({ settleResponse: settle }),\r\n } as LensEvent),\r\n );\r\n });\r\n\r\n server.onVerifiedPaymentCanceled(async context => {\r\n const requirements = context.requirements as unknown as RequirementsShape;\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n ...baseEvent(requirements, config),\r\n type: \"payment.canceled\",\r\n cancelReason: context.reason,\r\n phase: context.phase,\r\n } as LensEvent),\r\n );\r\n });\r\n}\r\n\r\nfunction baseEvent(\r\n requirements: RequirementsShape,\r\n config: LensConfig,\r\n buyer?: string,\r\n): Omit<LensEvent, \"type\"> {\r\n const context = currentRequestContext();\r\n return {\r\n ts: new Date().toISOString(),\r\n requestId: context?.requestId ?? randomUUID(),\r\n route: `${context?.method ?? \"GET\"} ${context?.path ?? \"/\"}`,\r\n scheme: requirements.scheme ?? \"exact\",\r\n network: requirements.network ?? config.network,\r\n amount: requirements.amount ?? \"0\",\r\n asset: requirements.asset ?? \"\",\r\n payTo: requirements.payTo ?? config.payTo,\r\n ...(buyer ? { buyer } : {}),\r\n ...(context ? { durationMs: Date.now() - context.startedAt } : {}),\r\n } as Omit<LensEvent, \"type\">;\r\n}\r\n\r\n/**\r\n * Hooks receive the matched requirement, not the whole challenge. Rebuilding a\r\n * one-entry challenge lets the same findings rules run on both paths.\r\n */\r\nfunction syntheticChallenge(requirements: RequirementsShape): WirePaymentRequired {\r\n return {\r\n x402Version: 2,\r\n accepts: [requirements as unknown as NonNullable<WirePaymentRequired[\"accepts\"]>[number]],\r\n };\r\n}\r\n\r\n/** Settlement failures arrive as a thrown error carrying the settle response. */\r\nfunction settleFromError(error: unknown): WireSettleResponse | undefined {\r\n if (!error || typeof error !== \"object\") return undefined;\r\n const candidate = error as {\r\n settleResponse?: WireSettleResponse;\r\n result?: WireSettleResponse;\r\n body?: WireSettleResponse;\r\n };\r\n return candidate.settleResponse ?? candidate.result ?? candidate.body;\r\n}\r\n\r\nexport type { HTTPRequestContext };\r\nexport {\r\n PrometheusRegistry,\r\n prometheusHandler,\r\n} from \"@x402-lens/core\";","/**\r\n * Per-request context carried through the async call chain.\r\n *\r\n * The official middleware builds its own `HTTPTransportContext`, so hooks only\r\n * receive a path and method — not the request id or the start time. An\r\n * AsyncLocalStorage store gives hooks the full picture without reaching into\r\n * private fields of the SDK's adapter, and without keying state on a route that\r\n * may have many concurrent requests.\r\n */\r\n\r\nimport { AsyncLocalStorage } from \"node:async_hooks\";\r\n\r\n/** What we know at the moment a request enters our middleware. */\r\nexport interface RequestContext {\r\n requestId: string;\r\n startedAt: number;\r\n method: string;\r\n path: string;\r\n}\r\n\r\nconst storage = new AsyncLocalStorage<RequestContext>();\r\n\r\n/** Run `fn` with `context` bound to the current async chain. */\r\nexport function runWithRequestContext<T>(context: RequestContext, fn: () => T): T {\r\n return storage.run(context, fn);\r\n}\r\n\r\n/** The context for the request currently being handled, if any. */\r\nexport function currentRequestContext(): RequestContext | undefined {\r\n return storage.getStore();\r\n}\r\n","/**\r\n * Observing the 402 without changing it.\r\n *\r\n * The official Express middleware builds `PaymentRequired`, puts it in the\r\n * base64 `PAYMENT-REQUIRED` header, and sends a small JSON body. There is no\r\n * hook for \"a challenge was issued\", so we watch the response instead: wrap the\r\n * few methods that can commit headers or a body, decode the header, and emit.\r\n *\r\n * Everything is restored on `finish`, and nothing we do alters the wire form of\r\n * the header. The one deliberate addition is to the JSON body: v2 treats the\r\n * response body as server-defined, and mirroring the challenge there is what\r\n * makes `curl | jq` usable without base64 in the loop.\r\n */\r\n\r\nimport type { Response } from \"express\";\r\nimport { decodePaymentRequiredHeader } from \"@x402/core/http\";\r\nimport type { WirePaymentRequired } from \"@x402-lens/core\";\r\n\r\n/** Fields a client needs to see without base64-decoding the header. */\r\nexport function bodyFieldsFromChallenge(\r\n paymentRequired: WirePaymentRequired,\r\n): Record<string, unknown> {\r\n return {\r\n x402Version: paymentRequired.x402Version,\r\n ...(paymentRequired.error ? { error: paymentRequired.error } : {}),\r\n ...(paymentRequired.resource ? { resource: paymentRequired.resource } : {}),\r\n ...(paymentRequired.accepts ? { accepts: paymentRequired.accepts } : {}),\r\n };\r\n}\r\n\r\nexport interface ObserveOptions {\r\n /**\r\n * Mirror the decoded challenge into the 402 JSON body. The v2 spec leaves the\r\n * body to the server; a readable body is what makes `curl | jq` usable\r\n * without base64 in the loop. Set false to leave the body untouched.\r\n */\r\n mirrorBody?: boolean;\r\n}\r\n\r\ntype AnyFunction = (...args: unknown[]) => unknown;\r\n\r\ninterface Patchable {\r\n setHeader: AnyFunction;\r\n writeHead: AnyFunction;\r\n json: AnyFunction;\r\n}\r\n\r\n/**\r\n * Attach an observer to one response.\r\n *\r\n * @param res - The Express response to watch\r\n * @param onChallenge - Called once per 402 that carries a decodable challenge\r\n * @param options - Whether to mirror the challenge into the body\r\n * @returns A function that removes the observer early\r\n */\r\nexport function observePaymentRequired(\r\n res: Response,\r\n onChallenge: (paymentRequired: WirePaymentRequired) => void,\r\n options: ObserveOptions = {},\r\n): () => void {\r\n const mirrorBody = options.mirrorBody ?? true;\r\n const target = res as unknown as Patchable;\r\n const originalSetHeader = target.setHeader;\r\n const originalWriteHead = target.writeHead;\r\n const originalJson = target.json;\r\n\r\n let captured: WirePaymentRequired | undefined;\r\n let capturedRaw: string | undefined;\r\n let emitted = false;\r\n let restored = false;\r\n\r\n const capture = (value: unknown): void => {\r\n if (typeof value !== \"string\" || value.length === 0) return;\r\n if (value === capturedRaw) return;\r\n try {\r\n captured = decodePaymentRequiredHeader(value) as unknown as WirePaymentRequired;\r\n capturedRaw = value;\r\n } catch {\r\n // A malformed header is the SDK's problem to surface, not ours.\r\n }\r\n };\r\n\r\n const emitIfChallenge = (): void => {\r\n if (emitted || !captured) return;\r\n emitted = true;\r\n onChallenge(captured);\r\n };\r\n\r\n target.setHeader = function patchedSetHeader(\r\n this: unknown,\r\n name: unknown,\r\n value: unknown,\r\n ) {\r\n if (typeof name === \"string\" && name.toLowerCase() === \"payment-required\") {\r\n capture(value);\r\n }\r\n return originalSetHeader.call(this, name, value);\r\n } as AnyFunction;\r\n\r\n target.writeHead = function patchedWriteHead(\r\n this: unknown,\r\n statusCode: unknown,\r\n ...rest: unknown[]\r\n ) {\r\n if (statusCode === 402) {\r\n // Some setups pass the header bag to writeHead instead of setHeader.\r\n for (const candidate of rest) {\r\n if (candidate && typeof candidate === \"object\") {\r\n for (const [key, value] of Object.entries(candidate as Record<string, unknown>)) {\r\n if (key.toLowerCase() === \"payment-required\") capture(value);\r\n }\r\n }\r\n }\r\n emitIfChallenge();\r\n }\r\n return originalWriteHead.call(this, statusCode, ...rest);\r\n } as AnyFunction;\r\n\r\n target.json = function patchedJson(this: unknown, body: unknown, ...rest: unknown[]) {\r\n if (res.statusCode === 402 && captured) {\r\n emitIfChallenge();\r\n if (!mirrorBody) return originalJson.call(this, body, ...rest);\r\n const base =\r\n body && typeof body === \"object\" && !Array.isArray(body)\r\n ? (body as Record<string, unknown>)\r\n : {};\r\n return originalJson.call(this, { ...base, ...bodyFieldsFromChallenge(captured) }, ...rest);\r\n }\r\n return originalJson.call(this, body, ...rest);\r\n } as AnyFunction;\r\n\r\n const restore = (): void => {\r\n if (restored) return;\r\n restored = true;\r\n target.setHeader = originalSetHeader;\r\n target.writeHead = originalWriteHead;\r\n target.json = originalJson;\r\n res.off(\"finish\", restore);\r\n res.off(\"close\", restore);\r\n };\r\n\r\n res.on(\"finish\", restore);\r\n res.on(\"close\", restore);\r\n\r\n return restore;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,yBAA2B;AAE3B,kBA2BO;AACP,oBAOO;AACP,qBAAgD;AAChD,IAAAA,iBAA+B;AAC/B,IAAAA,iBAA8B;AAC9B,IAAAA,iBAA+B;AAC/B,IAAAA,iBAA8B;;;ACjD9B,8BAAkC;AAUlC,IAAM,UAAU,IAAI,0CAAkC;AAG/C,SAAS,sBAAyB,SAAyB,IAAgB;AAChF,SAAO,QAAQ,IAAI,SAAS,EAAE;AAChC;AAGO,SAAS,wBAAoD;AAClE,SAAO,QAAQ,SAAS;AAC1B;;;ACfA,kBAA4C;AAIrC,SAAS,wBACd,iBACyB;AACzB,SAAO;AAAA,IACL,aAAa,gBAAgB;AAAA,IAC7B,GAAI,gBAAgB,QAAQ,EAAE,OAAO,gBAAgB,MAAM,IAAI,CAAC;AAAA,IAChE,GAAI,gBAAgB,WAAW,EAAE,UAAU,gBAAgB,SAAS,IAAI,CAAC;AAAA,IACzE,GAAI,gBAAgB,UAAU,EAAE,SAAS,gBAAgB,QAAQ,IAAI,CAAC;AAAA,EACxE;AACF;AA2BO,SAAS,uBACd,KACA,aACA,UAA0B,CAAC,GACf;AACZ,QAAM,aAAa,QAAQ,cAAc;AACzC,QAAM,SAAS;AACf,QAAM,oBAAoB,OAAO;AACjC,QAAM,oBAAoB,OAAO;AACjC,QAAM,eAAe,OAAO;AAE5B,MAAI;AACJ,MAAI;AACJ,MAAI,UAAU;AACd,MAAI,WAAW;AAEf,QAAM,UAA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AO;AAAA,IACpC,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;AAAA,IACzB,GAAI,UAAU,EAAE,YAAY,KAAK,IAAI,IAAI,QAAQ,UAAU,IAAI,CAAC;AAAA,EAClE;AACF;AAMA,SAAS,mBAAmB,cAAsD;AAChF,SAAO;AAAA,IACL,aAAa;AAAA,IACb,SAAS,CAAC,YAA8E;AAAA,EAC1F;AACF;AAGA,SAAS,gBAAgB,OAAgD;AACvE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,YAAY;AAKlB,SAAO,UAAU,kBAAkB,UAAU,UAAU,UAAU;AACnE;","names":["import_server","import_core"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/context.ts","../src/observe.ts"],"sourcesContent":["/**\r\n * `paymentLens()` — x402 v2 payments for Express, with observability that\r\n * explains itself.\r\n *\r\n * This is a thin layer over `@x402/express`, not a reimplementation. The\r\n * official middleware owns the protocol: it builds `PaymentRequired`, sets\r\n * `PAYMENT-REQUIRED`, calls the facilitator's `/verify` and `/settle`, and\r\n * settles only after a successful handler. Everything here attaches to it.\r\n *\r\n * What we add:\r\n *\r\n * - An event per payment lifecycle step, with the fields needed to answer\r\n * \"why did this fail\": route, amount, network, buyer, tx hash, plus findings.\r\n * - A readable 402 body next to the canonical header, so `curl | jq` works.\r\n * - Config loading that refuses to guess a facilitator, network, or address.\r\n */\r\n\r\nimport { randomUUID } from \"node:crypto\";\r\nimport type { NextFunction, Request, RequestHandler, Response } from \"express\";\r\nimport {\r\n EventBus,\r\n PrometheusRegistry,\r\n callbackSink,\r\n consoleSink,\r\n diagnose,\r\n jsonlFileSink,\r\n loadConfig,\r\n makeEvent,\r\n openTelemetrySink,\r\n prometheusSink,\r\n resolveConfig,\r\n sentryBreadcrumbSink,\r\n assertLensConfig,\r\n ConfigError,\r\n settleResponseFromError,\r\n toRoutesConfig,\r\n type Finding,\r\n type LensConfig,\r\n type LensConfigInput,\r\n type LensEvent,\r\n type LensSink,\r\n type OtelTracerLike,\r\n type PaymentScheme,\r\n type RouteInput,\r\n type RoutePrice,\r\n type SentryLike,\r\n type WirePaymentPayload,\r\n type WirePaymentRequired,\r\n type WireSettleResponse,\r\n type WireVerifyResponse,\r\n} from \"@x402-lens/core\";\r\nimport {\r\n HTTPFacilitatorClient,\r\n x402HTTPResourceServer,\r\n x402ResourceServer,\r\n type FacilitatorClient,\r\n type HTTPRequestContext,\r\n type RoutesConfig,\r\n} from \"@x402/core/server\";\r\nimport { ExpressAdapter, paymentMiddlewareFromHTTPServer } from \"@x402/express\";\r\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\r\nimport { UptoEvmScheme } from \"@x402/evm/upto/server\";\r\nimport { ExactSvmScheme } from \"@x402/svm/exact/server\";\r\nimport { UptoSvmScheme } from \"@x402/svm/upto/server\";\r\nimport { currentRequestContext, runWithRequestContext } from \"./context.js\";\r\nimport { observePaymentRequired } from \"./observe.js\";\r\n\r\n/**\r\n * Buyer-facing body when the facilitator cannot be reached at init (or the\r\n * inner middleware rejects for the same reason). Full SDK detail stays on the\r\n * `facilitator.error` event — never in this JSON.\r\n */\r\nconst FACILITATOR_UNAVAILABLE_BODY = {\r\n error: \"facilitator_unavailable\",\r\n code: \"FACILITATOR_UNAVAILABLE\",\r\n} as const;\r\n\r\n/** Where the lens should send events. */\r\nexport interface LensSinkOptions {\r\n /** Print a compact line per event. Defaults to `true`. */\r\n console?: boolean;\r\n /** Append newline-delimited JSON to this path. */\r\n jsonlPath?: string;\r\n /** Called for every event. Exceptions are caught and never reach the caller. */\r\n onEvent?: (event: LensEvent) => void;\r\n /**\r\n * Record counters for Prometheus. Pass `true` for the shared registry, or a\r\n * `PrometheusRegistry` you will serve from `/metrics` via `prometheusHandler`.\r\n */\r\n prometheus?: boolean | PrometheusRegistry;\r\n /**\r\n * OpenTelemetry tracer (`trace.getTracer(\"x402-lens\")`). Opens a short span\r\n * per event. `@opentelemetry/api` is not a dependency of this package.\r\n */\r\n otel?: OtelTracerLike;\r\n /**\r\n * Sentry-compatible handle (`import * as Sentry from \"@sentry/node\"`).\r\n * Records each event as a breadcrumb. Sentry is not a dependency.\r\n */\r\n sentry?: SentryLike;\r\n}\r\n\r\n/** Short route form: a bare price, or the full per-route options. */\r\nexport type RouteMap = Record<string, string | Omit<RouteInput, \"route\">>;\r\n\r\nexport interface PaymentLensOptions extends Omit<LensConfigInput, \"routes\"> {\r\n /**\r\n * Route prices, in either the short map form\r\n * (`{ \"GET /weather\": \"$0.001\" }`) or the `RouteInput[]` form. Overrides the\r\n * config file and `X402_PRICE__*`.\r\n */\r\n routes?: RouteMap | RouteInput[];\r\n /**\r\n * Pre-resolved config. Skips file/env loading, but still runs\r\n * {@link assertLensConfig} (URL, payTo, paths, schemes, headers).\r\n */\r\n config?: LensConfig;\r\n /** Where events go. Defaults to console. */\r\n sinks?: LensSinkOptions;\r\n /** Extra sinks, appended after the ones built from `sinks`. */\r\n extraSinks?: LensSink[];\r\n /** Override the `RoutesConfig` handed to `@x402/express`, for advanced setups. */\r\n routesConfig?: RoutesConfig;\r\n /**\r\n * Mirror the decoded challenge into the 402 JSON body. On by default: the v2\r\n * spec leaves the body to the server, and a readable body is the difference\r\n * between a debuggable endpoint and a base64 scavenger hunt.\r\n */\r\n readableBody?: boolean;\r\n /**\r\n * Expose the payment headers for browser buyers. Off by default so an app\r\n * with its own CORS layer is never surprised.\r\n *\r\n * Without this, a cross-origin `fetch()` cannot read `PAYMENT-REQUIRED` or\r\n * `PAYMENT-RESPONSE`, and the browser strips `PAYMENT-SIGNATURE` from the\r\n * retry — the payment silently never happens. `x402-lens inspect` reports it.\r\n *\r\n * Pass `true` to let x402-lens set the headers, or `{ origin }` to also emit\r\n * `Access-Control-Allow-Origin`. If your app already has a CORS middleware,\r\n * leave this off and add the three headers there instead.\r\n */\r\n cors?: boolean | { origin?: string };\r\n /**\r\n * Replace the facilitator client entirely.\r\n *\r\n * For a facilitator that is not plain HTTP (an in-process one, a queue-backed\r\n * one, a proxy that signs requests), or to wrap the SDK client with retries,\r\n * caching, or metrics. When supplied, `facilitatorUrl` is still validated but\r\n * only used for event metadata and doctor output.\r\n */\r\n facilitatorClient?: FacilitatorClient;\r\n /**\r\n * Grant access without payment for a request.\r\n *\r\n * Runs before verification on every request to a protected route. Return\r\n * `true` to let the handler run unpaid (health checks, internal traffic, a\r\n * free tier), or a reason string to deny with a 403. The buyer always sees\r\n * `{ error: \"access_denied\" }`; the reason is only on the event. Every\r\n * decision emits `access.granted` / `access.denied`.\r\n *\r\n * Returning `false`/`undefined` continues to the normal payment flow.\r\n */\r\n grant?: (request: GrantContext) => boolean | string | undefined | Promise<boolean | string | undefined>;\r\n}\r\n\r\nexport interface PaymentLens {\r\n /** Mount in Express before your routes. */\r\n middleware: RequestHandler;\r\n /** The underlying resource server, for custom hooks or extensions. */\r\n server: x402ResourceServer;\r\n /** The underlying HTTP resource server. */\r\n httpServer: x402HTTPResourceServer;\r\n /** Resolved and validated configuration. */\r\n config: LensConfig;\r\n /**\r\n * Settles when the facilitator `/supported` probe succeeds.\r\n *\r\n * Rejects when the facilitator cannot be reached or advertises no usable\r\n * kinds. Await this before accepting traffic so a dead facilitator fails\r\n * the deploy instead of the first buyer's request.\r\n */\r\n ready: Promise<void>;\r\n /** Subscribe to events programmatically. */\r\n on(listener: (event: LensEvent) => void): () => void;\r\n /** Flush sinks and stop emitting. */\r\n close(): Promise<void>;\r\n}\r\n\r\n/** What a `grant` callback is given about the request it may let through. */\r\nexport interface GrantContext {\r\n /** HTTP method, e.g. `GET`. */\r\n method: string;\r\n /** Request path, e.g. `/weather`. */\r\n path: string;\r\n /** `\"<METHOD> <path>\"`, the same key the route map uses. */\r\n route: string;\r\n /**\r\n * Read a request header, case-insensitively-ish (exactly as the adapter\r\n * reports it). The SDK gives hooks an accessor rather than a header map, so\r\n * this is a function — use it to check an API key or an internal marker.\r\n */\r\n header(name: string): string | undefined;\r\n /** Query parameters, when the adapter can provide them. */\r\n query: Record<string, string | string[]>;\r\n /** The matched route's configuration (price, scheme, metadata), when known. */\r\n config: RouteInput | RoutePrice | undefined;\r\n}\r\n\r\n/**\r\n * Build x402 payment middleware for Express.\r\n *\r\n * Configuration precedence is explicit options → `X402_*` environment variables.\r\n * Use {@link paymentLensAsync} when it should also read `x402.config.json`.\r\n *\r\n * @param options - Routes, configuration, and sinks\r\n * @returns Middleware plus handles for events and the underlying servers\r\n * @throws {ConfigError} When a required setting is missing or malformed\r\n */\r\nexport function paymentLens(options: PaymentLensOptions = {}): PaymentLens {\r\n const config = options.config\r\n ? (assertLensConfig(options.config), normalisePassedConfig(options.config))\r\n : resolveConfig({\r\n ...options,\r\n routes: normaliseRouteInput(options.routes),\r\n });\r\n return buildLens(config, options);\r\n}\r\n\r\n/**\r\n * Async variant that also reads `x402.config.json` from the working directory.\r\n *\r\n * @param options - Routes, configuration, and sinks\r\n * @returns Middleware plus handles for events and the underlying servers\r\n * @throws {ConfigError} When a required setting is missing or malformed\r\n */\r\nexport async function paymentLensAsync(\r\n options: PaymentLensOptions = {},\r\n): Promise<PaymentLens> {\r\n const config = options.config\r\n ? (assertLensConfig(options.config), normalisePassedConfig(options.config))\r\n : await loadConfig({\r\n ...options,\r\n routes: normaliseRouteInput(options.routes),\r\n });\r\n return buildLens(config, options);\r\n}\r\n\r\n/** Match `resolveConfig` trailing-slash stripping for pre-built configs. */\r\nfunction normalisePassedConfig(config: LensConfig): LensConfig {\r\n return {\r\n ...config,\r\n facilitatorUrl: config.facilitatorUrl.replace(/\\/+$/, \"\"),\r\n };\r\n}\r\n\r\nfunction normaliseRouteInput(routes: PaymentLensOptions[\"routes\"]): RouteInput[] | undefined {\r\n if (!routes) return undefined;\r\n if (Array.isArray(routes)) return routes;\r\n // A bare string is the common case; an object allows per-route options such as\r\n // `paymentFlow` without dropping to the array form.\r\n return Object.entries(routes).map(([route, value]) => {\r\n if (typeof value === \"string\") return { route, price: value };\r\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\r\n return { route, ...value };\r\n }\r\n throw new ConfigError(\r\n \"routes\",\r\n `routes[\"${route}\"] must be a price string or an options object, got ${JSON.stringify(value)}.`,\r\n );\r\n });\r\n}\r\n\r\nfunction decodedRoutePath(path: string): string {\r\n try {\r\n return decodeURIComponent(path);\r\n } catch {\r\n return path;\r\n }\r\n}\r\n\r\nfunction buildLens(config: LensConfig, options: PaymentLensOptions): PaymentLens {\r\n const bus = new EventBus([\r\n ...buildSinks(options.sinks),\r\n ...(options.extraSinks ?? []),\r\n ]);\r\n const readableBody = options.readableBody ?? true;\r\n\r\n const facilitatorClient =\r\n options.facilitatorClient ?? buildFacilitatorClient(config);\r\n const server = new x402ResourceServer(facilitatorClient);\r\n const schemes = schemesInUse(config);\r\n for (const network of config.networks) registerScheme(server, network, schemes);\r\n\r\n if (options.routesConfig && Object.keys(options.routesConfig).length === 0) {\r\n throw new ConfigError(\r\n \"routesConfig\",\r\n \"routesConfig is empty. Omit it to use config.routes, or pass at least one protected route — an empty map silently disables payment protection.\",\r\n );\r\n }\r\n const routes = options.routesConfig ?? (toRoutesConfig(config) as unknown as RoutesConfig);\r\n\r\n attachHooks(server, bus, config);\r\n\r\n const httpServer = new x402HTTPResourceServer(server, routes);\r\n let initFailure: Error | undefined;\r\n let initFailureEmitted = false;\r\n\r\n const emitInitFailure = (error: Error): void => {\r\n if (initFailureEmitted) return;\r\n initFailureEmitted = true;\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n type: \"facilitator.error\",\r\n ts: new Date().toISOString(),\r\n requestId: randomUUID(),\r\n route: \"INIT /supported\",\r\n scheme: \"exact\",\r\n network: config.network,\r\n amount: \"0\",\r\n asset: \"\",\r\n payTo: config.payTo,\r\n message: error.message,\r\n } as LensEvent),\r\n );\r\n };\r\n\r\n // Own the facilitator probe so a failure is observable (`ready` + events)\r\n // instead of an opaque HTTP 500 from the SDK's lazy init path.\r\n const ready = httpServer.initialize().then(\r\n () => undefined,\r\n error => {\r\n const asError = error instanceof Error ? error : new Error(String(error));\r\n initFailure = asError;\r\n emitInitFailure(asError);\r\n throw asError;\r\n },\r\n );\r\n // Keep `ready` rejectable for awaiters, but do not crash the process when\r\n // nobody has attached yet (apps may mount middleware before awaiting ready).\r\n void ready.catch(() => {});\r\n\r\n // Disable the SDK's parallel syncFacilitatorOnStart probe — `ready` above is\r\n // the single source of truth for initialization.\r\n const inner = paymentMiddlewareFromHTTPServer(\r\n httpServer,\r\n undefined,\r\n undefined,\r\n false,\r\n );\r\n const corsHeaders = buildCorsHeaders(options.cors);\r\n if (options.cors === true) {\r\n // #region agent note — surface at build time without throwing\r\n process.emitWarning(\r\n \"[x402-lens] cors: true does not set Access-Control-Allow-Origin. Pass cors: { origin: \\\"…\\\" } for browser buyers.\",\r\n \"X402LensCors\",\r\n );\r\n // #endregion\r\n }\r\n\r\n const grant = options.grant;\r\n\r\n const respondFacilitatorUnavailable = (res: Response, requestId: string, route: string, error: Error): void => {\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n type: \"facilitator.error\",\r\n ts: new Date().toISOString(),\r\n requestId,\r\n route,\r\n scheme: \"exact\",\r\n network: config.network,\r\n amount: \"0\",\r\n asset: \"\",\r\n payTo: config.payTo,\r\n message: error.message,\r\n } as LensEvent),\r\n );\r\n if (!res.headersSent) {\r\n res.status(502).json(FACILITATOR_UNAVAILABLE_BODY);\r\n } else if (!res.writableEnded) {\r\n res.end();\r\n }\r\n };\r\n\r\n const middleware: RequestHandler = (req: Request, res: Response, next: NextFunction) => {\r\n const context = {\r\n requestId: randomUUID(),\r\n startedAt: Date.now(),\r\n method: req.method,\r\n path: req.path,\r\n };\r\n\r\n if (corsHeaders) applyCorsHeaders(res, corsHeaders);\r\n\r\n // Browser preflight must never hit the payment path (wildcard routes included).\r\n if (req.method === \"OPTIONS\") {\r\n // When lens owns CORS, complete preflight here — otherwise Express 404s\r\n // and browsers never send PAYMENT-SIGNATURE. When cors is off, the app's\r\n // own CORS middleware must answer.\r\n if (corsHeaders) {\r\n if (!res.headersSent) res.sendStatus(204);\r\n return;\r\n }\r\n next();\r\n return;\r\n }\r\n\r\n const emitRequired = (paymentRequired: WirePaymentRequired): void => {\r\n const entries = paymentRequired.accepts ?? [];\r\n const entry = entries[0];\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n type: \"payment.required\",\r\n requestId: context.requestId,\r\n route: `${context.method} ${context.path}`,\r\n scheme: entry?.scheme ?? \"exact\",\r\n network: entry?.network ?? config.network,\r\n amount: entry?.amount ?? \"0\",\r\n asset: entry?.asset ?? \"\",\r\n payTo: entry?.payTo ?? config.payTo,\r\n offers: entries.length,\r\n durationMs: Date.now() - context.startedAt,\r\n findings: diagnose({ paymentRequired, now: context.startedAt }),\r\n } as LensEvent),\r\n );\r\n };\r\n\r\n observePaymentRequired(res, emitRequired, { mirrorBody: readableBody });\r\n\r\n // Enter ALS before grant/ready so hooks share the same requestId.\r\n runWithRequestContext(context, () => {\r\n void (async () => {\r\n const adapter = new ExpressAdapter(req);\r\n const httpContext = {\r\n adapter,\r\n path: req.path,\r\n decodedPath: decodedRoutePath(req.path),\r\n method: req.method,\r\n paymentHeader:\r\n adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"x-payment\"),\r\n };\r\n\r\n // Unprotected routes must not depend on facilitator readiness (health checks).\r\n if (!httpServer.requiresPayment(httpContext)) {\r\n next();\r\n return;\r\n }\r\n\r\n // Grant runs before ready so internal bypass still works when the\r\n // facilitator is down.\r\n if (grant) {\r\n try {\r\n const decision = await grant({\r\n method: context.method,\r\n path: context.path,\r\n route: `${context.method} ${context.path}`,\r\n header: (name: string) => safeCall(() => adapter.getHeader(name)),\r\n query: safeCall(() => adapter.getQueryParams?.() ?? {}) ?? {},\r\n config: matchRouteConfig(config, context.method, context.path),\r\n });\r\n\r\n if (decision === true) {\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n type: \"access.granted\",\r\n requestId: context.requestId,\r\n route: `${context.method} ${context.path}`,\r\n scheme: \"exact\",\r\n network: config.network,\r\n amount: \"0\",\r\n asset: \"\",\r\n payTo: config.payTo,\r\n } as LensEvent),\r\n );\r\n next();\r\n return;\r\n }\r\n\r\n if (typeof decision === \"string\") {\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n type: \"access.denied\",\r\n requestId: context.requestId,\r\n route: `${context.method} ${context.path}`,\r\n scheme: \"exact\",\r\n network: config.network,\r\n amount: \"0\",\r\n asset: \"\",\r\n payTo: config.payTo,\r\n reason: decision,\r\n } as LensEvent),\r\n );\r\n if (!res.headersSent) res.status(403).json({ error: \"access_denied\" });\r\n return;\r\n }\r\n } catch (error) {\r\n const reason =\r\n error instanceof Error ? error.message.slice(0, 200) : \"grant_error\";\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n type: \"access.denied\",\r\n requestId: context.requestId,\r\n route: `${context.method} ${context.path}`,\r\n scheme: \"exact\",\r\n network: config.network,\r\n amount: \"0\",\r\n asset: \"\",\r\n payTo: config.payTo,\r\n reason,\r\n } as LensEvent),\r\n );\r\n if (!res.headersSent) {\r\n res.status(403).json({ error: \"access_denied\" });\r\n }\r\n return;\r\n }\r\n }\r\n\r\n try {\r\n await ready;\r\n } catch (error) {\r\n const asError =\r\n initFailure ??\r\n (error instanceof Error ? error : new Error(String(error)));\r\n emitInitFailure(asError);\r\n if (!res.headersSent) {\r\n res.status(502).json(FACILITATOR_UNAVAILABLE_BODY);\r\n } else if (!res.writableEnded) {\r\n res.end();\r\n }\r\n return;\r\n }\r\n\r\n void Promise.resolve(inner(req, res, next)).catch((error: unknown) => {\r\n const asError = error instanceof Error ? error : new Error(String(error));\r\n respondFacilitatorUnavailable(\r\n res,\r\n context.requestId,\r\n `${context.method} ${context.path}`,\r\n asError,\r\n );\r\n });\r\n })().catch((error: unknown) => {\r\n const asError = error instanceof Error ? error : new Error(String(error));\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n type: \"facilitator.error\",\r\n ts: new Date().toISOString(),\r\n requestId: context.requestId,\r\n route: `${context.method} ${context.path}`,\r\n scheme: \"exact\",\r\n network: config.network,\r\n amount: \"0\",\r\n asset: \"\",\r\n payTo: config.payTo,\r\n message: `middleware: ${asError.message}`,\r\n } as LensEvent),\r\n );\r\n if (!res.headersSent) {\r\n res.status(500).json({ error: \"internal_error\", code: \"MIDDLEWARE_ERROR\" });\r\n } else if (!res.writableEnded) {\r\n res.end();\r\n }\r\n });\r\n });\r\n };\r\n\r\n return {\r\n middleware,\r\n server,\r\n httpServer,\r\n config,\r\n ready,\r\n on(listener) {\r\n const sink = callbackSink(listener);\r\n bus.add(sink);\r\n return () => {\r\n bus.remove(sink);\r\n };\r\n },\r\n close() {\r\n return bus.close();\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Find the configured route that covers this method/path for grant callbacks.\r\n * Exact matches win; then Express-style `:param` / `*` segments; then method `*`.\r\n */\r\nfunction matchRouteConfig(\r\n config: LensConfig,\r\n method: string,\r\n path: string,\r\n): RoutePrice | undefined {\r\n const candidates = config.routes.filter(\r\n route => route.method === method || route.method === \"*\",\r\n );\r\n const exact = candidates.find(route => route.path === path);\r\n if (exact) return exact;\r\n return candidates.find(route => pathMatchesPattern(route.path, path));\r\n}\r\n\r\n/** Match `/users/:id` and `/files/*` style patterns against a request path. */\r\nfunction pathMatchesPattern(pattern: string, path: string): boolean {\r\n if (pattern === path) return true;\r\n const patternParts = pattern.split(\"/\");\r\n const pathParts = path.split(\"/\");\r\n if (patternParts.length !== pathParts.length) return false;\r\n for (let index = 0; index < patternParts.length; index += 1) {\r\n const expected = patternParts[index] ?? \"\";\r\n const actual = pathParts[index] ?? \"\";\r\n if (expected.startsWith(\":\") || expected === \"*\") continue;\r\n if (expected !== actual) return false;\r\n }\r\n return true;\r\n}\r\n\r\n/**\r\n * Call an adapter accessor, treating a throw as \"not available\".\r\n *\r\n * Adapters are third-party code; a missing or throwing accessor must not turn\r\n * an access decision into a 500.\r\n */\r\nfunction safeCall<T>(read: () => T): T | undefined {\r\n try {\r\n return read();\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/**\r\n * Build the SDK facilitator client, carrying auth headers and a request\r\n * timeout when configured.\r\n *\r\n * Auth headers must be keyed by facilitator path (`verify` / `settle` /\r\n * `supported`). Flat objects are rejected by `resolveConfig` before this runs,\r\n * so a misconfigured client never reaches the first payment request as HTTP 500.\r\n */\r\nfunction buildFacilitatorClient(config: LensConfig): HTTPFacilitatorClient {\r\n const authHeaders = config.facilitatorHeaders;\r\n const timeoutMs = config.facilitatorTimeoutMs;\r\n\r\n return new HTTPFacilitatorClient({\r\n url: config.facilitatorUrl,\r\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\r\n ...(authHeaders ? { createAuthHeaders: async () => authHeaders } : {}),\r\n });\r\n}\r\n\r\nfunction buildSinks(sinkOptions: LensSinkOptions | undefined): LensSink[] {\r\n const sinks: LensSink[] = [];\r\n if (sinkOptions?.console ?? true) sinks.push(consoleSink());\r\n if (sinkOptions?.jsonlPath) sinks.push(jsonlFileSink(sinkOptions.jsonlPath));\r\n if (sinkOptions?.onEvent) sinks.push(callbackSink(sinkOptions.onEvent));\r\n if (sinkOptions?.prometheus) {\r\n sinks.push(\r\n prometheusSink(\r\n sinkOptions.prometheus === true\r\n ? undefined\r\n : sinkOptions.prometheus,\r\n ),\r\n );\r\n }\r\n if (sinkOptions?.otel) sinks.push(openTelemetrySink(sinkOptions.otel));\r\n if (sinkOptions?.sentry) sinks.push(sentryBreadcrumbSink(sinkOptions.sentry));\r\n return sinks;\r\n}\r\n\r\n/**\r\n * The three headers a browser buyer needs, and nothing else.\r\n *\r\n * A literal `*` does not cover any of them on a credentialed request, so they\r\n * have to be named. `Access-Control-Allow-Headers` also needs `Content-Type`\r\n * whenever the retry carries a JSON body, because that alone triggers a\r\n * preflight before the payment header is even considered.\r\n */\r\nfunction buildCorsHeaders(\r\n cors: PaymentLensOptions[\"cors\"],\r\n): Record<string, string> | undefined {\r\n if (!cors) return undefined;\r\n const headers: Record<string, string> = {\r\n \"Access-Control-Expose-Headers\": \"PAYMENT-REQUIRED, PAYMENT-RESPONSE\",\r\n \"Access-Control-Allow-Headers\": \"Content-Type, PAYMENT-SIGNATURE\",\r\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, PATCH, DELETE, OPTIONS\",\r\n };\r\n if (typeof cors === \"object\" && cors.origin) {\r\n headers[\"Access-Control-Allow-Origin\"] = cors.origin;\r\n if (cors.origin !== \"*\") headers.Vary = \"Origin\";\r\n }\r\n return headers;\r\n}\r\n\r\n/**\r\n * Merge our headers into whatever the response already has, so an app's own\r\n * CORS layer keeps working.\r\n *\r\n * List headers (Expose/Allow-Headers/Methods) are unioned. Singleton CORS\r\n * headers (`Access-Control-Allow-Origin`, `Vary`) replace — comma-joining ACAO\r\n * produces a value browsers reject.\r\n */\r\nfunction applyCorsHeaders(res: Response, headers: Record<string, string>): void {\r\n const replaceHeaders = new Set([\"access-control-allow-origin\", \"vary\"]);\r\n for (const [name, value] of Object.entries(headers)) {\r\n const existing = res.getHeader(name);\r\n if (existing === undefined || replaceHeaders.has(name.toLowerCase())) {\r\n res.setHeader(name, value);\r\n continue;\r\n }\r\n const merged = new Set(\r\n String(existing)\r\n .split(\",\")\r\n .map(part => part.trim())\r\n .filter(Boolean),\r\n );\r\n for (const item of value.split(\",\").map(part => part.trim())) merged.add(item);\r\n res.setHeader(name, Array.from(merged).join(\", \"));\r\n }\r\n}\r\n\r\n/**\r\n * Register the schemes this package supports on one network.\r\n *\r\n * `exact` is always registered; `upto` only when a route asks for it, so the\r\n * challenge for an all-`exact` deployment stays byte-identical to before.\r\n *\r\n * @param server - Resource server to register on\r\n * @param network - CAIP-2 network, already validated\r\n * @param schemes - Schemes any route on this network needs\r\n */\r\nfunction registerScheme(\r\n server: x402ResourceServer,\r\n network: string,\r\n schemes: ReadonlySet<PaymentScheme>,\r\n): void {\r\n const separator = network.indexOf(\":\");\r\n const namespace = separator === -1 ? network : network.slice(0, separator);\r\n // `Network` is a template-literal type; the value was validated as CAIP-2 by\r\n // `resolveConfig` before reaching here.\r\n const caip2 = network as `${string}:${string}`;\r\n\r\n switch (namespace) {\r\n case \"eip155\": {\r\n server.register(caip2, new ExactEvmScheme());\r\n if (schemes.has(\"upto\")) server.register(caip2, new UptoEvmScheme());\r\n return;\r\n }\r\n case \"solana\": {\r\n server.register(caip2, new ExactSvmScheme());\r\n if (schemes.has(\"upto\")) server.register(caip2, new UptoSvmScheme({}));\r\n return;\r\n }\r\n default:\r\n throw new Error(\r\n `[x402-lens] No scheme for namespace \"${namespace}\". This package registers exact (and upto) schemes for eip155 and solana. For any other network, keep the returned server instance and call server.register(network, scheme) yourself.`,\r\n );\r\n }\r\n}\r\n\r\n/** Which schemes the configured routes actually need. */\r\nfunction schemesInUse(config: LensConfig): Set<PaymentScheme> {\r\n const used = new Set<PaymentScheme>();\r\n for (const route of config.routes) used.add(route.scheme ?? \"exact\");\r\n return used;\r\n}\r\n\r\n/** The three fields every event needs from a `PaymentRequirements`. */\r\ninterface RequirementsShape {\r\n scheme: string;\r\n network: string;\r\n amount: string;\r\n asset: string;\r\n payTo: string;\r\n}\r\n\r\nfunction attachHooks(server: x402ResourceServer, bus: EventBus, config: LensConfig): void {\r\n server.onAfterVerify(async context => {\r\n const requirements = context.requirements as unknown as RequirementsShape;\r\n const result = context.result as unknown as WireVerifyResponse;\r\n const payload = context.paymentPayload as unknown as WirePaymentPayload;\r\n const base = baseEvent(requirements, config, result.isValid ? result.payer : undefined);\r\n const findings: Finding[] = diagnose({\r\n verifyResponse: result,\r\n paymentPayload: payload,\r\n paymentRequired: syntheticChallenge(requirements),\r\n });\r\n\r\n if (!result.isValid) {\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n ...base,\r\n type: \"payment.failed\",\r\n reason: result.invalidReason ?? \"unknown\",\r\n findings,\r\n } as LensEvent),\r\n );\r\n return;\r\n }\r\n\r\n bus.emit(makeEvent<LensEvent>({ ...base, type: \"payment.verified\" } as LensEvent));\r\n });\r\n\r\n server.onVerifyFailure(async context => {\r\n const requirements = context.requirements as unknown as RequirementsShape;\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n ...baseEvent(requirements, config),\r\n type: \"facilitator.error\",\r\n message: context.error.message,\r\n } as LensEvent),\r\n );\r\n });\r\n\r\n server.onAfterSettle(async context => {\r\n const requirements = context.requirements as unknown as RequirementsShape;\r\n const result = context.result as unknown as WireSettleResponse;\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n ...baseEvent(requirements, config, result.payer),\r\n type: \"payment.settled\",\r\n txHash: result.transaction ?? \"\",\r\n phase: context.phase,\r\n findings: diagnose({ settleResponse: result }),\r\n } as LensEvent),\r\n );\r\n });\r\n\r\n server.onSettleFailure(async context => {\r\n const requirements = context.requirements as unknown as RequirementsShape;\r\n const settle = settleResponseFromError(context.error);\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n ...baseEvent(requirements, config, settle?.payer),\r\n type: \"payment.settle_failed\",\r\n reason: settle?.errorReason ?? context.error.message,\r\n ...(settle?.transaction ? { txHash: settle.transaction } : {}),\r\n phase: context.phase,\r\n findings: diagnose({ settleResponse: settle }),\r\n } as LensEvent),\r\n );\r\n });\r\n\r\n server.onVerifiedPaymentCanceled(async context => {\r\n const requirements = context.requirements as unknown as RequirementsShape;\r\n bus.emit(\r\n makeEvent<LensEvent>({\r\n ...baseEvent(requirements, config),\r\n type: \"payment.canceled\",\r\n cancelReason: context.reason,\r\n phase: context.phase,\r\n } as LensEvent),\r\n );\r\n });\r\n}\r\n\r\nfunction baseEvent(\r\n requirements: RequirementsShape,\r\n config: LensConfig,\r\n buyer?: string,\r\n): Omit<LensEvent, \"type\"> {\r\n const context = currentRequestContext();\r\n return {\r\n ts: new Date().toISOString(),\r\n requestId: context?.requestId ?? randomUUID(),\r\n route: `${context?.method ?? \"GET\"} ${context?.path ?? \"/\"}`,\r\n scheme: requirements.scheme ?? \"exact\",\r\n network: requirements.network ?? config.network,\r\n amount: requirements.amount ?? \"0\",\r\n asset: requirements.asset ?? \"\",\r\n payTo: requirements.payTo ?? config.payTo,\r\n ...(buyer ? { buyer } : {}),\r\n ...(context ? { durationMs: Date.now() - context.startedAt } : {}),\r\n } as Omit<LensEvent, \"type\">;\r\n}\r\n\r\n/**\r\n * Hooks receive the matched requirement, not the whole challenge. Rebuilding a\r\n * one-entry challenge lets the same findings rules run on both paths.\r\n */\r\nfunction syntheticChallenge(requirements: RequirementsShape): WirePaymentRequired {\r\n return {\r\n x402Version: 2,\r\n accepts: [requirements as unknown as NonNullable<WirePaymentRequired[\"accepts\"]>[number]],\r\n };\r\n}\r\n\r\nexport type { HTTPRequestContext };\r\nexport {\r\n PrometheusRegistry,\r\n prometheusHandler,\r\n} from \"@x402-lens/core\";","/**\r\n * Per-request context carried through the async call chain.\r\n *\r\n * The official middleware builds its own `HTTPTransportContext`, so hooks only\r\n * receive a path and method — not the request id or the start time. An\r\n * AsyncLocalStorage store gives hooks the full picture without reaching into\r\n * private fields of the SDK's adapter, and without keying state on a route that\r\n * may have many concurrent requests.\r\n */\r\n\r\nimport { AsyncLocalStorage } from \"node:async_hooks\";\r\n\r\n/** What we know at the moment a request enters our middleware. */\r\nexport interface RequestContext {\r\n requestId: string;\r\n startedAt: number;\r\n method: string;\r\n path: string;\r\n}\r\n\r\nconst storage = new AsyncLocalStorage<RequestContext>();\r\n\r\n/** Run `fn` with `context` bound to the current async chain. */\r\nexport function runWithRequestContext<T>(context: RequestContext, fn: () => T): T {\r\n return storage.run(context, fn);\r\n}\r\n\r\n/** The context for the request currently being handled, if any. */\r\nexport function currentRequestContext(): RequestContext | undefined {\r\n return storage.getStore();\r\n}\r\n","/**\r\n * Observing the 402 without changing it.\r\n *\r\n * The official Express middleware builds `PaymentRequired`, puts it in the\r\n * base64 `PAYMENT-REQUIRED` header, and sends a small JSON body. There is no\r\n * hook for \"a challenge was issued\", so we watch the response instead: wrap the\r\n * few methods that can commit headers or a body, decode the header, and emit.\r\n *\r\n * Everything is restored on `finish`, and nothing we do alters the wire form of\r\n * the header. The one deliberate addition is to the JSON body: v2 treats the\r\n * response body as server-defined, and mirroring the challenge there is what\r\n * makes `curl | jq` usable without base64 in the loop.\r\n */\r\n\r\nimport type { Response } from \"express\";\r\nimport { decodePaymentRequiredHeader } from \"@x402/core/http\";\r\nimport type { WirePaymentRequired } from \"@x402-lens/core\";\r\n\r\n/** Fields a client needs to see without base64-decoding the header. */\r\nexport function bodyFieldsFromChallenge(\r\n paymentRequired: WirePaymentRequired,\r\n): Record<string, unknown> {\r\n return {\r\n x402Version: paymentRequired.x402Version,\r\n ...(paymentRequired.error ? { error: paymentRequired.error } : {}),\r\n ...(paymentRequired.resource ? { resource: paymentRequired.resource } : {}),\r\n ...(paymentRequired.accepts ? { accepts: paymentRequired.accepts } : {}),\r\n };\r\n}\r\n\r\nexport interface ObserveOptions {\r\n /**\r\n * Mirror the decoded challenge into the 402 JSON body. The v2 spec leaves the\r\n * body to the server; a readable body is what makes `curl | jq` usable\r\n * without base64 in the loop. Set false to leave the body untouched.\r\n */\r\n mirrorBody?: boolean;\r\n}\r\n\r\ntype AnyFunction = (...args: unknown[]) => unknown;\r\n\r\ninterface Patchable {\r\n setHeader: AnyFunction;\r\n writeHead: AnyFunction;\r\n json: AnyFunction;\r\n}\r\n\r\n/**\r\n * Attach an observer to one response.\r\n *\r\n * @param res - The Express response to watch\r\n * @param onChallenge - Called once per 402 that carries a decodable challenge\r\n * @param options - Whether to mirror the challenge into the body\r\n * @returns A function that removes the observer early\r\n */\r\nexport function observePaymentRequired(\r\n res: Response,\r\n onChallenge: (paymentRequired: WirePaymentRequired) => void,\r\n options: ObserveOptions = {},\r\n): () => void {\r\n const mirrorBody = options.mirrorBody ?? true;\r\n const target = res as unknown as Patchable;\r\n const originalSetHeader = target.setHeader;\r\n const originalWriteHead = target.writeHead;\r\n const originalJson = target.json;\r\n\r\n let captured: WirePaymentRequired | undefined;\r\n let capturedRaw: string | undefined;\r\n let emitted = false;\r\n let restored = false;\r\n\r\n const capture = (value: unknown): void => {\r\n if (typeof value !== \"string\" || value.length === 0) return;\r\n if (value === capturedRaw) return;\r\n try {\r\n captured = decodePaymentRequiredHeader(value) as unknown as WirePaymentRequired;\r\n capturedRaw = value;\r\n } catch {\r\n // A malformed header is the SDK's problem to surface, not ours.\r\n }\r\n };\r\n\r\n const emitIfChallenge = (): void => {\r\n if (emitted || !captured) return;\r\n emitted = true;\r\n onChallenge(captured);\r\n };\r\n\r\n target.setHeader = function patchedSetHeader(\r\n this: unknown,\r\n name: unknown,\r\n value: unknown,\r\n ) {\r\n if (typeof name === \"string\" && name.toLowerCase() === \"payment-required\") {\r\n capture(value);\r\n }\r\n return originalSetHeader.call(this, name, value);\r\n } as AnyFunction;\r\n\r\n target.writeHead = function patchedWriteHead(\r\n this: unknown,\r\n statusCode: unknown,\r\n ...rest: unknown[]\r\n ) {\r\n if (statusCode === 402) {\r\n // Some setups pass the header bag to writeHead instead of setHeader.\r\n for (const candidate of rest) {\r\n if (candidate && typeof candidate === \"object\") {\r\n for (const [key, value] of Object.entries(candidate as Record<string, unknown>)) {\r\n if (key.toLowerCase() === \"payment-required\") capture(value);\r\n }\r\n }\r\n }\r\n emitIfChallenge();\r\n }\r\n return originalWriteHead.call(this, statusCode, ...rest);\r\n } as AnyFunction;\r\n\r\n target.json = function patchedJson(this: unknown, body: unknown, ...rest: unknown[]) {\r\n if (res.statusCode === 402 && captured) {\r\n emitIfChallenge();\r\n if (!mirrorBody) return originalJson.call(this, body, ...rest);\r\n const base =\r\n body && typeof body === \"object\" && !Array.isArray(body)\r\n ? (body as Record<string, unknown>)\r\n : {};\r\n return originalJson.call(this, { ...base, ...bodyFieldsFromChallenge(captured) }, ...rest);\r\n }\r\n return originalJson.call(this, body, ...rest);\r\n } as AnyFunction;\r\n\r\n const restore = (): void => {\r\n if (restored) return;\r\n restored = true;\r\n target.setHeader = originalSetHeader;\r\n target.writeHead = originalWriteHead;\r\n target.json = originalJson;\r\n res.off(\"finish\", restore);\r\n res.off(\"close\", restore);\r\n };\r\n\r\n res.on(\"finish\", restore);\r\n res.on(\"close\", restore);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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RequestHandler } from 'express';
|
|
2
|
-
import { LensEvent, PrometheusRegistry, OtelTracerLike, SentryLike, LensConfig, LensConfigInput,
|
|
2
|
+
import { RouteInput, RoutePrice, LensEvent, PrometheusRegistry, OtelTracerLike, SentryLike, LensConfig, LensConfigInput, LensSink } from '@x402-lens/core';
|
|
3
3
|
export { PrometheusRegistry, prometheusHandler } from '@x402-lens/core';
|
|
4
4
|
import { x402ResourceServer, x402HTTPResourceServer, RoutesConfig, FacilitatorClient } from '@x402/core/server';
|
|
5
5
|
export { HTTPRequestContext } from '@x402/core/server';
|
|
@@ -54,7 +54,10 @@ interface PaymentLensOptions extends Omit<LensConfigInput, "routes"> {
|
|
|
54
54
|
* config file and `X402_PRICE__*`.
|
|
55
55
|
*/
|
|
56
56
|
routes?: RouteMap | RouteInput[];
|
|
57
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* Pre-resolved config. Skips file/env loading, but still runs
|
|
59
|
+
* {@link assertLensConfig} (URL, payTo, paths, schemes, headers).
|
|
60
|
+
*/
|
|
58
61
|
config?: LensConfig;
|
|
59
62
|
/** Where events go. Defaults to console. */
|
|
60
63
|
sinks?: LensSinkOptions;
|
|
@@ -97,8 +100,9 @@ interface PaymentLensOptions extends Omit<LensConfigInput, "routes"> {
|
|
|
97
100
|
*
|
|
98
101
|
* Runs before verification on every request to a protected route. Return
|
|
99
102
|
* `true` to let the handler run unpaid (health checks, internal traffic, a
|
|
100
|
-
* free tier), or a reason string to deny with a 403.
|
|
101
|
-
*
|
|
103
|
+
* free tier), or a reason string to deny with a 403. The buyer always sees
|
|
104
|
+
* `{ error: "access_denied" }`; the reason is only on the event. Every
|
|
105
|
+
* decision emits `access.granted` / `access.denied`.
|
|
102
106
|
*
|
|
103
107
|
* Returning `false`/`undefined` continues to the normal payment flow.
|
|
104
108
|
*/
|
|
@@ -113,6 +117,14 @@ interface PaymentLens {
|
|
|
113
117
|
httpServer: x402HTTPResourceServer;
|
|
114
118
|
/** Resolved and validated configuration. */
|
|
115
119
|
config: LensConfig;
|
|
120
|
+
/**
|
|
121
|
+
* Settles when the facilitator `/supported` probe succeeds.
|
|
122
|
+
*
|
|
123
|
+
* Rejects when the facilitator cannot be reached or advertises no usable
|
|
124
|
+
* kinds. Await this before accepting traffic so a dead facilitator fails
|
|
125
|
+
* the deploy instead of the first buyer's request.
|
|
126
|
+
*/
|
|
127
|
+
ready: Promise<void>;
|
|
116
128
|
/** Subscribe to events programmatically. */
|
|
117
129
|
on(listener: (event: LensEvent) => void): () => void;
|
|
118
130
|
/** Flush sinks and stop emitting. */
|
|
@@ -134,8 +146,8 @@ interface GrantContext {
|
|
|
134
146
|
header(name: string): string | undefined;
|
|
135
147
|
/** Query parameters, when the adapter can provide them. */
|
|
136
148
|
query: Record<string, string | string[]>;
|
|
137
|
-
/** The route's
|
|
138
|
-
config:
|
|
149
|
+
/** The matched route's configuration (price, scheme, metadata), when known. */
|
|
150
|
+
config: RouteInput | RoutePrice | undefined;
|
|
139
151
|
}
|
|
140
152
|
/**
|
|
141
153
|
* Build x402 payment middleware for Express.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RequestHandler } from 'express';
|
|
2
|
-
import { LensEvent, PrometheusRegistry, OtelTracerLike, SentryLike, LensConfig, LensConfigInput,
|
|
2
|
+
import { RouteInput, RoutePrice, LensEvent, PrometheusRegistry, OtelTracerLike, SentryLike, LensConfig, LensConfigInput, LensSink } from '@x402-lens/core';
|
|
3
3
|
export { PrometheusRegistry, prometheusHandler } from '@x402-lens/core';
|
|
4
4
|
import { x402ResourceServer, x402HTTPResourceServer, RoutesConfig, FacilitatorClient } from '@x402/core/server';
|
|
5
5
|
export { HTTPRequestContext } from '@x402/core/server';
|
|
@@ -54,7 +54,10 @@ interface PaymentLensOptions extends Omit<LensConfigInput, "routes"> {
|
|
|
54
54
|
* config file and `X402_PRICE__*`.
|
|
55
55
|
*/
|
|
56
56
|
routes?: RouteMap | RouteInput[];
|
|
57
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* Pre-resolved config. Skips file/env loading, but still runs
|
|
59
|
+
* {@link assertLensConfig} (URL, payTo, paths, schemes, headers).
|
|
60
|
+
*/
|
|
58
61
|
config?: LensConfig;
|
|
59
62
|
/** Where events go. Defaults to console. */
|
|
60
63
|
sinks?: LensSinkOptions;
|
|
@@ -97,8 +100,9 @@ interface PaymentLensOptions extends Omit<LensConfigInput, "routes"> {
|
|
|
97
100
|
*
|
|
98
101
|
* Runs before verification on every request to a protected route. Return
|
|
99
102
|
* `true` to let the handler run unpaid (health checks, internal traffic, a
|
|
100
|
-
* free tier), or a reason string to deny with a 403.
|
|
101
|
-
*
|
|
103
|
+
* free tier), or a reason string to deny with a 403. The buyer always sees
|
|
104
|
+
* `{ error: "access_denied" }`; the reason is only on the event. Every
|
|
105
|
+
* decision emits `access.granted` / `access.denied`.
|
|
102
106
|
*
|
|
103
107
|
* Returning `false`/`undefined` continues to the normal payment flow.
|
|
104
108
|
*/
|
|
@@ -113,6 +117,14 @@ interface PaymentLens {
|
|
|
113
117
|
httpServer: x402HTTPResourceServer;
|
|
114
118
|
/** Resolved and validated configuration. */
|
|
115
119
|
config: LensConfig;
|
|
120
|
+
/**
|
|
121
|
+
* Settles when the facilitator `/supported` probe succeeds.
|
|
122
|
+
*
|
|
123
|
+
* Rejects when the facilitator cannot be reached or advertises no usable
|
|
124
|
+
* kinds. Await this before accepting traffic so a dead facilitator fails
|
|
125
|
+
* the deploy instead of the first buyer's request.
|
|
126
|
+
*/
|
|
127
|
+
ready: Promise<void>;
|
|
116
128
|
/** Subscribe to events programmatically. */
|
|
117
129
|
on(listener: (event: LensEvent) => void): () => void;
|
|
118
130
|
/** Flush sinks and stop emitting. */
|
|
@@ -134,8 +146,8 @@ interface GrantContext {
|
|
|
134
146
|
header(name: string): string | undefined;
|
|
135
147
|
/** Query parameters, when the adapter can provide them. */
|
|
136
148
|
query: Record<string, string | string[]>;
|
|
137
|
-
/** The route's
|
|
138
|
-
config:
|
|
149
|
+
/** The matched route's configuration (price, scheme, metadata), when known. */
|
|
150
|
+
config: RouteInput | RoutePrice | undefined;
|
|
139
151
|
}
|
|
140
152
|
/**
|
|
141
153
|
* Build x402 payment middleware for Express.
|