diff --git a/example-x402/.env.example b/example-x402/.env.example new file mode 100644 index 00000000..ff777562 --- /dev/null +++ b/example-x402/.env.example @@ -0,0 +1,5 @@ +# Stripe — fresh crypto deposit addresses are minted via Stripe PaymentIntents +STRIPE_SECRET_KEY=sk_test_... + +# Optional — defaults to https://www.x402.org/facilitator +FACILITATOR_URL=https://www.x402.org/facilitator diff --git a/example-x402/.gitignore b/example-x402/.gitignore new file mode 100644 index 00000000..b1640b50 --- /dev/null +++ b/example-x402/.gitignore @@ -0,0 +1,4 @@ +node_modules +dist +.env +.env.local diff --git a/example-x402/README.md b/example-x402/README.md new file mode 100644 index 00000000..dc2629b6 --- /dev/null +++ b/example-x402/README.md @@ -0,0 +1,76 @@ +# example-x402 + +A spiceflow app that protects a single API route (`GET /paid`) with the +[x402](https://www.x402.org) payment protocol. Each request costs **$0.01**, +settled on **Base Sepolia** in USDC. Fresh deposit addresses are minted via +Stripe PaymentIntents, mirroring [stripe-samples/machine-payments](https://github.com/stripe-samples/machine-payments). + +## Shape + +``` +app (root Spiceflow) +├── serveStatic('/public') +├── layout '/*' +├── page '/' ← RSC page with a client comp +└── use(paidApp) + paidApp (Spiceflow sub-app) + ├── use(x402({ price, network, payTo })) ← only runs for paidApp routes + └── get '/paid' → () => ({ foo: 'bar' }) +``` + +Spiceflow scopes middleware by **sub-app ownership**, not by path. Mounting +`paidApp` via `app.use(paidApp)` means the x402 handshake only runs for routes +defined on `paidApp`. Anything on the parent app (`/`, static files, RSC +pages) is untouched. + +## Why a custom middleware instead of `@x402/hono` + +`@x402/hono`'s `paymentMiddleware` is ~380 lines and wraps a ~1000-line +`x402HTTPResourceServer`. It carries its own route matcher, HTML paywall +generator, Hono context adapter, bazaar extension loader, and settlement +overrides header. Spiceflow already has a trie router, so a bespoke ~180-line +middleware at [`src/x402-middleware.ts`](./src/x402-middleware.ts) is enough. +It only imports from `@x402/core/server`, `@x402/core/http`, `@x402/core/types`, +and `@x402/evm/exact/server`. + +## Setup + +```bash +cp .env.example .env +# fill in STRIPE_SECRET_KEY +pnpm install +pnpm dev +``` + +Open and click **Call /paid** to see the 402 challenge, +or hit the route directly with curl: + +```bash +curl -i http://localhost:3000/paid +# HTTP/1.1 402 Payment Required +# www-authenticate: x402 scheme="exact" +# content-type: application/json +# +# {"x402Version":2,"error":"Payment required","accepts":[...]} +``` + +A real x402 client would sign an on-chain payment to the `payTo` address in +the challenge and retry with an `x-payment` header. See +[x402.org](https://www.x402.org) for client libraries. + +## Environment + +| Variable | Required | Default | +|---------------------|----------|-------------------------------------------| +| `STRIPE_SECRET_KEY` | yes | — | +| `FACILITATOR_URL` | no | `https://www.x402.org/facilitator` | +| `PORT` | no | `3000` | + +## Tests + +```bash +pnpm test +``` + +The middleware unit tests inject a fake `x402ResourceServer` via the +undocumented `server` option on `x402()`. No network, no mocks. diff --git a/example-x402/package.json b/example-x402/package.json new file mode 100644 index 00000000..75b14950 --- /dev/null +++ b/example-x402/package.json @@ -0,0 +1,32 @@ +{ + "name": "example-x402", + "private": true, + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "start": "node dist/rsc/index.js", + "test": "vitest --run" + }, + "dependencies": { + "@tailwindcss/vite": "^4.2.2", + "@types/react": "19.2.14", + "@types/react-dom": "19.2.3", + "@x402/core": "^2.9.0", + "@x402/evm": "^2.9.0", + "dotenv": "^17.4.0", + "errore": "^0.14.0", + "node-cache": "^5.1.2", + "react": "19.2.4", + "react-dom": "19.2.4", + "spiceflow": "workspace:^", + "stripe": "^21.0.1", + "tailwindcss": "4.0.6", + "typescript": "5.7.3", + "vite": "^8.0.8" + }, + "devDependencies": { + "@vitejs/plugin-react": "^6.0.1", + "vitest": "^4.1.4" + } +} diff --git a/example-x402/public/favicon.ico b/example-x402/public/favicon.ico new file mode 100644 index 00000000..718d6fea Binary files /dev/null and b/example-x402/public/favicon.ico differ diff --git a/example-x402/src/globals.css b/example-x402/src/globals.css new file mode 100644 index 00000000..0f4e93b6 --- /dev/null +++ b/example-x402/src/globals.css @@ -0,0 +1,19 @@ +@import 'tailwindcss'; + +:root { + --foreground-rgb: 0, 0, 0; + --background-rgb: 255, 255, 255; +} + +@media (prefers-color-scheme: dark) { + :root { + --foreground-rgb: 255, 255, 255; + --background-rgb: 10, 10, 10; + } +} + +body { + color: rgb(var(--foreground-rgb)); + background: rgb(var(--background-rgb)); + font-family: system-ui, -apple-system, sans-serif; +} diff --git a/example-x402/src/main.tsx b/example-x402/src/main.tsx new file mode 100644 index 00000000..d9869470 --- /dev/null +++ b/example-x402/src/main.tsx @@ -0,0 +1,87 @@ +// Spiceflow + x402 example. +// +// Shape: +// app (root) +// ├── serveStatic('/public') +// ├── layout '/*' — RSC layout +// ├── page '/' — RSC page with a client component +// └── use(paidApp) +// paidApp (sub-app) +// ├── use(x402({...})) ← only applies to routes on paidApp +// └── get '/paid' → () => ({ foo: 'bar' }) +// +// Request flow: +// GET / → rootApp.page('/'), no x402 middleware in chain, renders HTML +// GET /paid → paidApp.get('/paid'), x402 middleware enforces payment +import './globals.css' +import { Spiceflow, serveStatic } from 'spiceflow' +import { Head, Link } from 'spiceflow/react' +import Stripe from 'stripe' +import { x402, stripeDepositAddress } from './x402-middleware.js' +import { PaidData } from './paid-data.js' + +const stripe = new Stripe(process.env.STRIPE_SECRET_KEY ?? 'sk_test_placeholder') + +// Sub-app that owns every x402-protected route. Middleware registered on +// paidApp only runs for routes defined on paidApp (see +// getAppsInScope in spiceflow.tsx), so `/` below is untouched. +export const paidApp = new Spiceflow() + .use( + x402({ + price: '$0.01', + network: 'eip155:84532', // Base Sepolia + facilitatorUrl: + process.env.FACILITATOR_URL ?? 'https://www.x402.org/facilitator', + payTo: stripeDepositAddress({ stripe, network: 'base' }), + }), + ) + .get('/paid', () => ({ foo: 'bar' })) + +export const app = new Spiceflow() + .use(serveStatic({ root: './public' })) + .use(paidApp) + .layout('/*', ({ children }) => ( + {children} + )) + .page('/', function Home() { + return ( +
+

x402 + spiceflow

+

+ /paid is protected by the x402 + payment protocol. Each call costs $0.01, settled on + Base Sepolia, with a fresh deposit address minted via Stripe. +

+ +
+

+ Hit it directly to see the 402 challenge:{' '} + + /paid + +

+

+ Or from a shell:{' '} + curl -i http://localhost:3000/paid +

+
+
+ ) + }) + +function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + x402 + spiceflow + + {children} + + ) +} + +void app.listen(Number(process.env.PORT || 3000)) + +declare module 'spiceflow/react' { + interface SpiceflowRegister { app: typeof app } +} diff --git a/example-x402/src/paid-data.tsx b/example-x402/src/paid-data.tsx new file mode 100644 index 00000000..3a11a2eb --- /dev/null +++ b/example-x402/src/paid-data.tsx @@ -0,0 +1,90 @@ +'use client' + +// Client component that demonstrates the x402 handshake from the browser. +// The first fetch gets a 402 with the payment challenge; the real "agent" +// flow would then sign an on-chain payment and retry with an x-payment +// header. We just show the challenge body so you can see it. +import { useState } from 'react' + +interface Challenge { + x402Version: number + error: string + accepts: Array<{ + scheme: string + network: string + payTo: string + amount: string + asset?: string + }> +} + +export function PaidData() { + const [state, setState] = useState< + | { kind: 'idle' } + | { kind: 'loading' } + | { kind: 'challenge'; status: number; body: Challenge } + | { kind: 'paid'; body: unknown } + | { kind: 'error'; message: string } + >({ kind: 'idle' }) + + return ( +
+
+ + status: {state.kind} +
+ + {state.kind === 'challenge' && ( +
+ + {state.status} Payment Required — {state.body.error} + +
+            {JSON.stringify(state.body.accepts, null, 2)}
+          
+

+ An x402 client would sign an on-chain payment to{' '} + payTo and retry with an x-payment header. +

+
+ )} + + {state.kind === 'paid' && ( +
+          {JSON.stringify(state.body, null, 2)}
+        
+ )} + + {state.kind === 'error' && ( + {state.message} + )} +
+ ) +} diff --git a/example-x402/src/x402-middleware.test.ts b/example-x402/src/x402-middleware.test.ts new file mode 100644 index 00000000..e9116b6b --- /dev/null +++ b/example-x402/src/x402-middleware.test.ts @@ -0,0 +1,259 @@ +// Tests for the x402() spiceflow middleware. +// +// We inject a plain object that matches the narrow X402Server interface via +// the `server` option on x402(). No type assertions, no vi.mock, no +// facilitator network calls. +import { describe, expect, test } from 'vitest' +import { Spiceflow } from 'spiceflow' +import type { + PaymentPayload, + PaymentRequirements, + VerifyResponse, + SettleResponse, +} from '@x402/core/types' +import { x402, type X402Server } from './x402-middleware.js' + +const reqs: PaymentRequirements[] = [ + { + scheme: 'exact', + network: 'eip155:84532', + amount: '10000', + asset: '0xUSDCSepoliaAsset', + payTo: '0xFakeRecipient', + maxTimeoutSeconds: 300, + extra: {}, + }, +] + +interface FakeConfig { + verify?: VerifyResponse + settle?: SettleResponse + match?: boolean +} + +function fakeServer(cfg: FakeConfig = {}): X402Server & { + calls: { build: number; verify: number; settle: number } +} { + const calls = { build: 0, verify: 0, settle: 0 } + return { + calls, + buildPaymentRequirements: async () => { + calls.build++ + return reqs + }, + findMatchingRequirements: (available) => + cfg.match === false ? undefined : available[0], + verifyPayment: async () => { + calls.verify++ + return cfg.verify ?? { isValid: true } + }, + settlePayment: async () => { + calls.settle++ + return ( + cfg.settle ?? { + success: true, + transaction: '0xabc', + network: 'eip155:84532', + } + ) + }, + } +} + +function makeApp(cfg: FakeConfig = {}) { + return new Spiceflow() + .use( + x402({ + price: '$0.01', + network: 'eip155:84532', + payTo: '0xFakeRecipient', + server: fakeServer(cfg), + }), + ) + .get('/paid', () => ({ foo: 'bar' })) +} + +function validPaymentHeader(): string { + // Minimal base64-encoded payload that findMatchingRequirements will + // accept when the fake returns reqs[0]. Shape is not validated by the + // fake server — we only need decode to succeed. + const payload: PaymentPayload = { + x402Version: 2, + accepted: reqs[0]!, + payload: { + signature: '0xdeadbeef', + authorization: { + from: '0xpayer', + to: '0xFakeRecipient', + value: '10000', + validAfter: '0', + validBefore: '9999999999', + nonce: '0x00', + }, + }, + } + return Buffer.from(JSON.stringify(payload)).toString('base64') +} + +describe('x402 middleware', () => { + test('no payment header → 402 with challenge body', async () => { + const app = makeApp() + const res = await app.handle(new Request('http://localhost/paid')) + expect(res.status).toBe(402) + expect(res.headers.get('www-authenticate')).toBe('x402 scheme="exact"') + const body = await res.json() + expect(body.error).toBe('Payment required') + expect(body.x402Version).toBe(2) + expect(body.resource.url).toBe('/paid') + expect(body.accepts).toHaveLength(1) + expect(body.accepts[0]!.scheme).toBe('exact') + }) + + test('unparseable payment header → 402 with decode error', async () => { + const app = makeApp() + const res = await app.handle( + new Request('http://localhost/paid', { + headers: { 'x-payment': '!!!not-base64!!!' }, + }), + ) + expect(res.status).toBe(402) + const body = await res.json() + expect(body.error).toContain('decode payment header') + }) + + test('valid payment, verify succeeds, settle succeeds → 200 with receipt', async () => { + const app = makeApp() + const res = await app.handle( + new Request('http://localhost/paid', { + headers: { 'x-payment': validPaymentHeader() }, + }), + ) + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ foo: 'bar' }) + const receipt = res.headers.get('x-payment-response') + expect(typeof receipt).toBe('string') + expect(receipt!.length).toBeGreaterThan(0) + }) + + test('verify fails → 402 with reason, handler never runs', async () => { + let handlerCalls = 0 + const app = new Spiceflow() + .use( + x402({ + price: '$0.01', + network: 'eip155:84532', + payTo: '0xFakeRecipient', + server: fakeServer({ + verify: { isValid: false, invalidReason: 'insufficient_funds' }, + }), + }), + ) + .get('/paid', () => { + handlerCalls++ + return { foo: 'bar' } + }) + const res = await app.handle( + new Request('http://localhost/paid', { + headers: { 'x-payment': validPaymentHeader() }, + }), + ) + expect(res.status).toBe(402) + const body = await res.json() + expect(body.error).toBe('insufficient_funds') + expect(handlerCalls).toBe(0) + }) + + test('no matching requirements → 402', async () => { + const app = makeApp({ match: false }) + const res = await app.handle( + new Request('http://localhost/paid', { + headers: { 'x-payment': validPaymentHeader() }, + }), + ) + expect(res.status).toBe(402) + const body = await res.json() + expect(body.error).toBe('No matching payment requirements') + }) + + test('handler errors after verify → settle is skipped, error passes through', async () => { + const server = fakeServer() + const app = new Spiceflow() + .use( + x402({ + price: '$0.01', + network: 'eip155:84532', + payTo: '0xFakeRecipient', + server, + }), + ) + .get('/paid', () => { + return new Response('boom', { status: 500 }) + }) + const res = await app.handle( + new Request('http://localhost/paid', { + headers: { 'x-payment': validPaymentHeader() }, + }), + ) + expect(res.status).toBe(500) + expect(server.calls.settle).toBe(0) + }) + + test('dynamic payTo resolver is called with the middleware context', async () => { + let receivedPath: string | undefined + const app = new Spiceflow() + .use( + x402({ + price: '$0.01', + network: 'eip155:84532', + payTo: (ctx) => { + receivedPath = new URL(ctx.request.url).pathname + return '0xDynamicRecipient' + }, + server: fakeServer(), + }), + ) + .get('/paid', () => ({ foo: 'bar' })) + const res = await app.handle(new Request('http://localhost/paid')) + expect(res.status).toBe(402) + expect(receivedPath).toBe('/paid') + }) + + test('routes outside the paidApp sub-app are not gated', async () => { + const paid = new Spiceflow() + .use( + x402({ + price: '$0.01', + network: 'eip155:84532', + payTo: '0xFakeRecipient', + server: fakeServer(), + }), + ) + .get('/paid', () => ({ foo: 'bar' })) + + const root = new Spiceflow().get('/free', () => ({ ok: true })).use(paid) + + const free = await root.handle(new Request('http://localhost/free')) + expect(free.status).toBe(200) + expect(await free.json()).toEqual({ ok: true }) + + const paidRes = await root.handle(new Request('http://localhost/paid')) + expect(paidRes.status).toBe(402) + }) + + test('payTo resolver returning an Error → 500 with error message', async () => { + const app = new Spiceflow() + .use( + x402({ + price: '$0.01', + network: 'eip155:84532', + payTo: () => new Error('wallet is offline'), + server: fakeServer(), + }), + ) + .get('/paid', () => ({ foo: 'bar' })) + const res = await app.handle(new Request('http://localhost/paid')) + expect(res.status).toBe(500) + const body = await res.json() + expect(body.error).toContain('wallet is offline') + }) +}) diff --git a/example-x402/src/x402-middleware.ts b/example-x402/src/x402-middleware.ts new file mode 100644 index 00000000..f5ba5d58 --- /dev/null +++ b/example-x402/src/x402-middleware.ts @@ -0,0 +1,460 @@ +// Small spiceflow middleware that protects a sub-app with the x402 payment +// protocol. Lives inside the example (not spiceflow core) on purpose: it is +// ~250 lines and only depends on @x402/core, which makes it easy to read +// top-to-bottom as a reference implementation. +// +// Compared to @x402/hono's paymentMiddleware (~380 lines + a 1000-line +// x402HTTPResourceServer wrapper), this skips: +// - its own route matcher (spiceflow's trie router already matched) +// - HTML paywall generation (@x402/paywall) +// - dynamic bazaar extension loading +// - the Hono context adapter (we use web-standard Request directly) +// - settlement-overrides header magic +// +// Scoping is done by mounting a sub-app via `app.use(paidSubApp)`. Any route +// defined on the sub-app runs through this middleware; routes on the parent +// app do not. +// +// Error handling follows the `errore` pattern (errors as values via +// `Error | T` unions and `instanceof Error` narrowing). The middleware +// returns a Response directly for every failure mode so callers never need +// to handle thrown errors. + +import { + x402ResourceServer, + HTTPFacilitatorClient, + type FacilitatorClient, +} from '@x402/core/server' +import { + decodePaymentSignatureHeader, + encodePaymentResponseHeader, +} from '@x402/core/http' +import type { + PaymentPayload, + PaymentRequirements, + Network, + Price, +} from '@x402/core/types' +import type { VerifyResponse, SettleResponse } from '@x402/core/types' +import type { ResourceConfig } from '@x402/core/server' +import { ExactEvmScheme } from '@x402/evm/exact/server' +import type { MiddlewareHandler } from 'spiceflow' +import NodeCache from 'node-cache' +import type Stripe from 'stripe' +import * as errore from 'errore' + +type Ctx = Parameters[0] + +// ----------------------------------------------------------------------------- +// Domain errors +// ----------------------------------------------------------------------------- + +export class X402ConfigError extends errore.createTaggedError({ + name: 'X402ConfigError', + message: 'x402 configuration error: $reason', +}) {} + +export class X402VerifyError extends errore.createTaggedError({ + name: 'X402VerifyError', + message: 'x402 verify failed: $reason', +}) {} + +export class X402SettleError extends errore.createTaggedError({ + name: 'X402SettleError', + message: 'x402 settle failed: $reason', +}) {} + +export class X402PayToError extends errore.createTaggedError({ + name: 'X402PayToError', + message: 'Could not resolve payTo address: $reason', +}) {} + +export class StripeDepositError extends errore.createTaggedError({ + name: 'StripeDepositError', + message: 'Stripe deposit address error: $reason', +}) {} + +// ----------------------------------------------------------------------------- +// Narrow interface for the resource server +// ----------------------------------------------------------------------------- +// +// Declaring only the methods the middleware uses means: +// 1. Tests pass a plain object literal with these methods — no type +// assertions, no vi.mock, no fancy test doubles. +// 2. The middleware is explicit about which parts of @x402/core it depends +// on, so upstream API changes show up as type errors in one place. +// 3. `x402ResourceServer` satisfies this interface structurally, so +// production usage needs no adapter. +export interface X402Server { + buildPaymentRequirements( + config: ResourceConfig, + ): Promise + findMatchingRequirements( + availableRequirements: PaymentRequirements[], + paymentPayload: PaymentPayload, + ): PaymentRequirements | undefined + verifyPayment( + paymentPayload: PaymentPayload, + requirements: PaymentRequirements, + ): Promise + settlePayment( + paymentPayload: PaymentPayload, + requirements: PaymentRequirements, + ): Promise +} + +// ----------------------------------------------------------------------------- +// Middleware +// ----------------------------------------------------------------------------- + +/** Resolver that returns a payTo address, or an Error if it can't. */ +export type PayToResolver = ( + ctx: Ctx, +) => Promise | string | Error + +export interface X402Options { + /** USD price per request, e.g. `"$0.01"`. */ + price: Price + /** CAIP-2 network id, e.g. `"eip155:84532"` for Base Sepolia. */ + network: Network + /** + * Recipient address. Either a literal string, or a resolver that returns + * the address (or an Error). Use `stripeDepositAddress()` to mint a fresh + * Stripe-custody address per request. + */ + payTo: string | PayToResolver + /** Defaults to `https://www.x402.org/facilitator`. */ + facilitatorUrl?: string + /** Defaults to `"exact"`. */ + scheme?: string + /** + * Escape hatch for tests: inject a fake (or custom) resource server + * instead of lazily building one. + */ + server?: X402Server +} + +/** + * Create a spiceflow middleware that enforces an x402 payment on every + * request that reaches it. Mount it on a sub-app to scope which routes + * it protects. + * + * ```ts + * const paidApp = new Spiceflow() + * .use(x402({ price: '$0.01', network: 'eip155:84532', payTo: '0x...' })) + * .get('/paid', () => ({ foo: 'bar' })) + * + * const app = new Spiceflow().use(paidApp) + * ``` + */ +export function x402(options: X402Options): MiddlewareHandler { + const scheme = options.scheme ?? 'exact' + const facilitatorUrl = + options.facilitatorUrl ?? 'https://www.x402.org/facilitator' + + // Lazy singleton: the first request to this middleware constructs and + // initializes the resource server. initialize() fetches the facilitator's + // supported schemes/networks over HTTP, which we can't do at module load. + let server: X402Server | null = options.server ?? null + let initPromise: Promise | null = null + + const getServer = async (): Promise => { + if (server) return server + if (!initPromise) { + initPromise = (async () => { + const client: FacilitatorClient = new HTTPFacilitatorClient({ + url: facilitatorUrl, + }) + const fresh = new x402ResourceServer(client).register( + options.network, + new ExactEvmScheme(), + ) + const init = await fresh.initialize().then( + () => fresh, + (e) => new X402ConfigError({ reason: 'initialize', cause: e }), + ) + if (init instanceof Error) return init + server = init + return init + })() + } + return initPromise + } + + return async (ctx, next) => { + const { request } = ctx + const resource = new URL(request.url).pathname + + const resourceServer = await getServer() + if (resourceServer instanceof Error) { + return serverError(resourceServer) + } + + const payTo = await resolvePayTo(options.payTo, ctx) + if (payTo instanceof Error) return serverError(payTo) + + const requirements = await resourceServer + .buildPaymentRequirements({ + scheme, + network: options.network, + payTo, + price: options.price, + }) + .catch( + (e) => + new X402ConfigError({ reason: 'buildPaymentRequirements', cause: e }), + ) + if (requirements instanceof Error) return serverError(requirements) + + const header = + request.headers.get('x-payment') ?? + request.headers.get('payment-signature') + + if (!header) { + return paymentRequired({ + error: 'Payment required', + requirements, + resource, + }) + } + + const payload = errore.try({ + try: () => decodePaymentSignatureHeader(header), + catch: (e) => + new X402VerifyError({ reason: 'decode payment header', cause: e }), + }) + if (payload instanceof Error) { + return paymentRequired({ + error: payload.message, + requirements, + resource, + }) + } + + const match = resourceServer.findMatchingRequirements(requirements, payload) + if (!match) { + return paymentRequired({ + error: 'No matching payment requirements', + requirements, + resource, + }) + } + + const verify = await resourceServer + .verifyPayment(payload, match) + .catch( + (e) => new X402VerifyError({ reason: 'verifyPayment', cause: e }), + ) + if (verify instanceof Error) { + return paymentRequired({ + error: verify.message, + requirements, + resource, + }) + } + if (!verify.isValid) { + return paymentRequired({ + error: verify.invalidReason ?? 'Invalid payment', + requirements, + resource, + }) + } + + // Payment is verified, run the real handler. + const res = await next() + // If the handler errored, skip settlement — the client should not be + // charged for a failed response. + if (!res || res.status >= 400) return res + + const settle = await resourceServer + .settlePayment(payload, match) + .catch( + (e) => new X402SettleError({ reason: 'settlePayment', cause: e }), + ) + if (settle instanceof Error) { + return new Response( + JSON.stringify({ error: 'settlement failed', reason: settle.message }), + { status: 402, headers: { 'content-type': 'application/json' } }, + ) + } + if (!settle.success) { + return new Response( + JSON.stringify({ + error: 'settlement failed', + reason: settle.errorReason, + }), + { status: 402, headers: { 'content-type': 'application/json' } }, + ) + } + + // Attach the signed settlement receipt so the client can verify on-chain. + res.headers.set('x-payment-response', encodePaymentResponseHeader(settle)) + return res + } +} + +async function resolvePayTo( + payTo: string | PayToResolver, + ctx: Ctx, +): Promise { + if (typeof payTo === 'string') return payTo + const result = await payTo(ctx) + if (result instanceof Error) { + return new X402PayToError({ reason: result.message, cause: result }) + } + return result +} + +function paymentRequired({ + error, + requirements, + resource, +}: { + error: string + requirements: PaymentRequirements[] + resource: string +}): Response { + const body = { + x402Version: 2, + error, + resource: { url: resource, description: '', mimeType: 'application/json' }, + accepts: requirements, + } + return new Response(JSON.stringify(body), { + status: 402, + headers: { + 'content-type': 'application/json', + 'www-authenticate': `x402 scheme="${requirements[0]?.scheme ?? 'exact'}"`, + }, + }) +} + +function serverError(err: Error): Response { + console.error('[x402 middleware]', err) + return new Response(JSON.stringify({ error: err.message }), { + status: 500, + headers: { 'content-type': 'application/json' }, + }) +} + +// ----------------------------------------------------------------------------- +// Stripe-backed payTo resolver +// ----------------------------------------------------------------------------- + +export interface StripeDepositAddressOptions { + stripe: Stripe + /** `"base"` for Base (Sepolia) or `"tempo"` for Stripe's Tempo network. */ + network: 'base' | 'tempo' + /** + * Nominal deposit amount quoted to Stripe when minting the address. + * The underlying crypto deposit address is pre-funded; the actual per-call + * price is enforced by x402. Defaults to $100. + */ + amountUsd?: number + /** Address cache TTL in seconds. Defaults to 5 minutes. */ + ttlSeconds?: number +} + +// readField pulls a field off an unknown value without type assertions or +// `in` operator checks. Returns undefined if the value isn't an object or +// the field doesn't exist. This is the narrowing primitive used to walk +// loosely-typed objects from Stripe and x402 payment payloads. +function readField(value: unknown, key: string): unknown { + if (typeof value !== 'object' || value === null) return undefined + return Reflect.get(value, key) +} + +// The Stripe SDK types don't yet include the preview crypto deposit fields, +// so we walk pi.next_action via readField and pull the address out by name. +function toCryptoDepositAddress( + nextAction: unknown, + network: string, +): string | null { + const details = readField(nextAction, 'crypto_display_details') + const addresses = readField(details, 'deposit_addresses') + const entry = readField(addresses, network) + const address = readField(entry, 'address') + return typeof address === 'string' ? address : null +} + +function extractRecipient(payload: PaymentPayload): string | null { + // EVM "exact" scheme: recipient lives at payload.payload.authorization.to. + const to = readField(readField(payload.payload, 'authorization'), 'to') + return typeof to === 'string' ? to : null +} + +/** + * Returns a payTo resolver that asks Stripe for a fresh crypto deposit + * address on first hit, then re-uses it while the client retries with its + * signed payment. Mirrors the `createPayToAddress` helper from + * `stripe-samples/machine-payments` but scoped to a closure so the cache + * and Stripe client are encapsulated. + */ +export function stripeDepositAddress( + options: StripeDepositAddressOptions, +): PayToResolver { + const cache = new NodeCache({ stdTTL: options.ttlSeconds ?? 300 }) + const amountUsd = options.amountUsd ?? 100 + + return async ({ request }) => { + // Retry branch: the client attached an authorization header. Verify + // the recipient address came from us (i.e. is in cache) to prevent a + // forged credential from redirecting settlement elsewhere. + const paymentHeader = request.headers.get('x-payment') + if (paymentHeader) { + const payload = errore.try({ + try: () => decodePaymentSignatureHeader(paymentHeader), + catch: (e) => + new StripeDepositError({ + reason: 'decode payment header', + cause: e, + }), + }) + if (payload instanceof Error) return payload + + const to = extractRecipient(payload)?.toLowerCase() ?? null + if (to === null || !cache.has(to)) { + return new StripeDepositError({ + reason: 'payTo address not present in server cache', + }) + } + return to + } + + // Fresh-address branch: mint a new deposit address via Stripe. + // The `mode: 'deposit'` and `deposit_options` fields on payment_method_ + // options.crypto are part of a preview API that isn't in the Stripe SDK's + // types yet, so we use @ts-expect-error for the one offending call + // instead of leaking `as any` assertions through the codebase. + const pi = await options.stripe.paymentIntents + .create({ + amount: amountUsd * 100 * 10_000, + currency: 'usd', + payment_method_types: ['crypto'], + payment_method_data: { type: 'crypto' }, + payment_method_options: { + crypto: { + // @ts-expect-error Stripe crypto deposit preview API not in SDK types + mode: 'deposit', + deposit_options: { networks: [options.network] }, + }, + }, + confirm: true, + }) + .catch( + (e) => + new StripeDepositError({ reason: 'paymentIntents.create', cause: e }), + ) + if (pi instanceof Error) return pi + + const address = toCryptoDepositAddress(pi.next_action, options.network) + if (address === null) { + return new StripeDepositError({ + reason: `no deposit address for network "${options.network}"`, + }) + } + const lower = address.toLowerCase() + cache.set(lower, true) + return lower + } +} diff --git a/example-x402/tsconfig.json b/example-x402/tsconfig.json new file mode 100644 index 00000000..4620fa4a --- /dev/null +++ b/example-x402/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "target": "ESNext", + "lib": ["ESNext", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "allowImportingTsExtensions": true, + "rewriteRelativeImportExtensions": true, + "declaration": true, + "declarationMap": true, + "strict": true, + "noImplicitAny": false, + "skipLibCheck": true, + "isolatedModules": true, + "jsx": "react-jsx", + "types": ["vite/client", "node"] + }, + "include": ["src"] +} diff --git a/example-x402/vite.config.ts b/example-x402/vite.config.ts new file mode 100644 index 00000000..5273d3e6 --- /dev/null +++ b/example-x402/vite.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import spiceflow from 'spiceflow/vite' +import tailwindcss from '@tailwindcss/vite' + +export default defineConfig({ + clearScreen: false, + plugins: [ + spiceflow({ + entry: './src/main.tsx', + }), + react(), + tailwindcss(), + ], +}) diff --git a/example-x402/vitest.config.ts b/example-x402/vitest.config.ts new file mode 100644 index 00000000..2b1c323f --- /dev/null +++ b/example-x402/vitest.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + environment: 'node', + }, +})