import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync, } from 'node:fs'; import { dirname } from 'node:path'; import { token, type Time, type RandomSource } from 'pgstencil'; import { Stripe, STRIPE_API_VERSION } from './index.ts'; export interface StripeDevOptions { /** * Price ID → billing interval for each recurring Price beyond the built-in * `price_dev_monthly` and `price_dev_yearly`. Subscription Checkout rejects * any other Price, as Stripe does. */ recurring?: Record; } /** Stateful, local Stripe substitute. Uses the real SDK and webhook signatures. */ export async function createStripeDev( time: Time, random: RandomSource, statePath?: string, options: StripeDevOptions = {}, ) { const customers = new Map>(); const checkouts = new Map(); const subscriptions = new Map(); const charges = new Map(); const parameters = new Map(); const idempotency = new Map(); const requests: { method: string; path: string; body: Record; key?: string; }[] = []; const events: Stripe.Event[] = []; const failures = new Map(); if (statePath && existsSync(statePath)) { const state = JSON.parse(readFileSync(statePath, 'utf8')); for (const [key, value] of state.customers) customers.set(key, value); for (const [key, value] of state.checkouts) checkouts.set(key, value); for (const [key, value] of state.subscriptions) subscriptions.set(key, value); for (const [key, value] of state.charges ?? []) charges.set(key, value); for (const [key, value] of state.parameters) parameters.set(key, new URLSearchParams(value)); for (const [key, value] of state.idempotency) idempotency.set(key, value); events.push(...state.events); } let saved = ''; function save() { if (!statePath) return; const text = JSON.stringify({ customers: [...customers], checkouts: [...checkouts], subscriptions: [...subscriptions], charges: [...charges], parameters: [...parameters].map(([k, v]) => [k, v.toString()]), idempotency: [...idempotency], events, }); // Reads outnumber writes here; skip the rewrite when nothing changed. if (text === saved) return; mkdirSync(dirname(statePath), { recursive: true }); writeFileSync(`${statePath}.tmp`, text, { mode: 0o600 }); renameSync(`${statePath}.tmp`, statePath); saved = text; } const prices = { monthly: 'price_dev_monthly', yearly: 'price_dev_yearly' }; const intervals = new Map([ [prices.monthly, 'month'], [prices.yearly, 'year'], ...Object.entries(options.recurring ?? {}), ]); const webhookSecret = 'whsec_pgstencil_local_only'; let origin = ''; let webhookTarget: string | undefined; const id = (prefix: string) => `${prefix}_${token(random, 12)}`; const seconds = () => Math.floor(time.now().getTime() / 1000); function event(type: Stripe.Event.Type, object: unknown) { const value = { id: id('evt'), object: 'event', api_version: STRIPE_API_VERSION, created: seconds(), livemode: false, type, data: { object }, pending_webhooks: 1, request: null, } as Stripe.Event; events.push(structuredClone(value)); return value; } function periodEnd(price: string) { const end = time.now(); if (intervals.get(price) === 'year') end.setUTCFullYear(end.getUTCFullYear() + 1); else end.setUTCMonth(end.getUTCMonth() + 1); return Math.floor(end.getTime() / 1000); } function completeCheckout(sessionId: string) { const session = checkouts.get(sessionId); if (!session || session.status !== 'open') throw new Error('No open checkout'); if (session.expires_at <= seconds()) throw new Error('Checkout expired'); const p = parameters.get(sessionId)!; if (p.get('payment_method_collection') !== 'always') throw new Error('Expected card collection'); const days = Number(p.get('subscription_data[trial_period_days]') ?? 0); const price = p.get('line_items[0][price]')!; const sub = { id: id('sub'), object: 'subscription', customer: session.customer, livemode: false, status: days ? 'trialing' : 'active', start_date: seconds(), ended_at: null, canceled_at: null, trial_end: days ? seconds() + days * 86400 : null, trial_settings: { end_behavior: { billing_cycle_anchor: null, missing_payment_method: p.get( 'subscription_data[trial_settings][end_behavior][missing_payment_method]', ) ?? 'create_invoice', }, }, pending_update: null, cancel_at: null, cancel_at_period_end: false, metadata: Object.fromEntries( [...p] .filter(([key]) => /^subscription_data\[metadata\]\[[^\]]+\]$/.test(key), ) .map(([key, value]) => [key.slice(28, -1), value]), ), items: { object: 'list', has_more: false, data: [ { id: id('si'), quantity: 1, price: { id: price }, current_trial: null, current_period_start: seconds(), current_period_end: days ? seconds() + days * 86400 : periodEnd(price), }, ], }, } as unknown as Stripe.Subscription; subscriptions.set(sub.id, sub); session.status = 'complete'; session.subscription = sub.id; session.payment_status = days ? 'no_payment_required' : 'paid'; event('checkout.session.completed', session); event('customer.subscription.created', sub); save(); return sub; } function completePayment(sessionId: string) { const session = checkouts.get(sessionId); if ( !session || session.mode !== 'payment' || session.status !== 'open' || session.expires_at <= seconds() ) throw new Error('No open payment checkout'); session.status = 'complete'; session.payment_status = 'paid'; event('checkout.session.completed', session); save(); return session; } /** * A charge to `customer` and a dispute of it, emitting * `charge.dispute.created`. Its object names only the charge, as Stripe's * does; `charges.retrieve` reads the customer. */ function dispute( customer: string, status: Stripe.Dispute.Status = 'needs_response', ) { const charge = { id: id('ch'), object: 'charge', customer, livemode: false, } as Stripe.Charge; charges.set(charge.id, charge); const result = event('charge.dispute.created', { id: id('dp'), object: 'dispute', charge: charge.id, status, livemode: false, }); save(); return result; } /** An immediate cancellation, as `subscriptions.cancel` or a refund makes. */ function cancel(sub: Stripe.Subscription) { sub.status = 'canceled'; sub.canceled_at = seconds(); sub.ended_at = seconds(); return event('customer.subscription.deleted', sub); } /** Starts the item's next billing period now. */ function newPeriod(sub: Stripe.Subscription) { const item = sub.items.data[0]!; item.current_period_start = seconds(); item.current_period_end = periodEnd(item.price.id); } function transition( subscriptionId: string, action: | 'renew' | 'payment-failed' | 'cancel' | 'cancel-at-period-end' | 'portal-cancel' | 'pause' | 'resume', ) { const sub = subscriptions.get(subscriptionId); if (!sub) throw new Error('Subscription not found'); let result: Stripe.Event; if (action === 'cancel') result = cancel(sub); else if (action === 'pause') { // As the pause endpoint, or the portal's subscription_pause flow, makes: // the period stops advancing until the subscription resumes. if (!['active', 'trialing', 'past_due'].includes(sub.status)) throw new Error('Only an active subscription can be paused'); sub.status = 'paused'; sub.status_details = { paused: { type: 'subscription', subscription: { type: 'pause_requested' }, transitioned_at: seconds(), }, }; event('customer.subscription.updated', sub); result = event('customer.subscription.paused', sub); } else if (action === 'resume') { // Resuming resets the billing cycle anchor to now, Stripe's default. if (sub.status !== 'paused') throw new Error('Subscription is not paused'); sub.status = 'active'; delete sub.status_details; newPeriod(sub); event('customer.subscription.updated', sub); result = event('customer.subscription.resumed', sub); } else { if (action === 'cancel-at-period-end') sub.cancel_at_period_end = true; else if (action === 'portal-cancel') sub.cancel_at = sub.items.data[0]!.current_period_end; else { sub.status = action === 'renew' ? 'active' : 'past_due'; newPeriod(sub); } result = event('customer.subscription.updated', sub); } save(); return result; } const server = createServer(async (req, res) => { try { const url = new URL(req.url!, origin); const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(Buffer.from(chunk)); const raw = Buffer.concat(chunks).toString(); const body = new URLSearchParams(raw); const path = url.pathname; // This UI contains no card fields and cannot charge anyone. if (path.startsWith('/checkout/')) { const session = checkouts.get(path.split('/')[2]!); if (!session) { res.writeHead(404).end(); return; } if (req.method === 'POST') { if (req.headers.origin !== origin) { res.writeHead(403).end(); return; } if (session.mode === 'payment') completePayment(session.id); else completeCheckout(session.id); if (webhookTarget) await deliver(webhookTarget); const success = new URL( parameters .get(session.id)! .get('success_url')! .replaceAll('{CHECKOUT_SESSION_ID}', session.id), ); res .writeHead(303, { location: success.href, }) .end(); } else { res .writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) .end( 'StripeDev

Local Stripe checkout

This simulates providing a card. No real payment is possible.

', ); } return; } if (path.startsWith('/portal/')) { res .writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) .end( 'StripeDev portal

Local billing portal

Subscription changes are controlled by the StripeDev test API. Production uses Stripe’s hosted billing portal.

', ); return; } const key = typeof req.headers['idempotency-key'] === 'string' ? req.headers['idempotency-key'] : undefined; requests.push({ method: req.method!, path, // The SDK sends a GET's or DELETE's parameters in its query string. body: Object.fromEntries( req.method === 'GET' || req.method === 'DELETE' ? url.searchParams : body, ), ...(key ? { key } : {}), }); const failure = failures.get(path); failures.delete(path); if (failure && !failure.afterCommit) { res .writeHead(503) .end( JSON.stringify({ error: { message: 'StripeDev injected outage' } }), ); return; } const cacheKey = `${path}:${key}`; const cached = key ? idempotency.get(cacheKey) : undefined; let result: unknown; if (cached) { if (cached.input !== raw) throw new Error('Idempotency parameters changed'); result = cached.result; } else if (path === '/v1/customers' && req.method === 'POST') { result = { id: id('cus'), object: 'customer', email: body.get('email'), livemode: false, }; customers.set( (result as { id: string }).id, result as Record, ); } else if (path === '/v1/checkout/sessions' && req.method === 'POST') { // Removed from Checkout creation at the endive API versions. if ( [...body.keys()].some((key) => key.startsWith('payment_method_types')) ) throw new Error('Received unknown parameter: payment_method_types'); const allowed = [...body] .filter(([key]) => /^allowed_payment_method_types\[\d+\]$/.test(key)) .map(([, value]) => value); const sessionId = id('cs'); const session = { id: sessionId, object: 'checkout.session', status: 'open', mode: body.get('mode'), customer: body.get('customer'), client_reference_id: body.get('client_reference_id'), metadata: Object.fromEntries( [...body] .filter(([key]) => /^metadata\[[^\]]+\]$/.test(key)) .map(([key, value]) => [key.slice(9, -1), value]), ), subscription: null, allowed_payment_method_types: allowed.length ? allowed : null, payment_status: 'unpaid', livemode: false, expires_at: Number(body.get('expires_at')), url: `${origin}/checkout/${sessionId}`, } as Stripe.Checkout.Session; if (session.mode === 'payment') { session.customer_email = body.get('customer_email'); session.line_items = { object: 'list', has_more: false, url: '', data: [ { id: id('li'), quantity: Number(body.get('line_items[0][quantity]')), price: { id: body.get('line_items[0][price]') }, } as Stripe.LineItem, ], }; } if ( session.mode === 'subscription' && !intervals.has(body.get('line_items[0][price]') ?? '') ) throw new Error('No such price'); // Recorded, not modeled: StripeDev calculates no tax. Like Stripe, it // refuses automatic tax for a customer with nowhere to save an address. const automaticTax = body.get('automatic_tax[enabled]') === 'true'; session.automatic_tax = { enabled: automaticTax, liability: null, provider: null, status: null, }; if ( automaticTax && session.customer && !customers.get(session.customer as string)?.address && body.get('customer_update[address]') !== 'auto' && body.get('customer_update[shipping]') !== 'auto' ) throw new Error( 'Automatic tax calculation in Checkout requires a valid address on the Customer', ); checkouts.set(sessionId, session); parameters.set(sessionId, body); result = session; } else if (path.startsWith('/v1/checkout/sessions/')) { const session = checkouts.get(path.split('/')[4]!); if (!session) throw new Error('Unknown checkout'); if (path.endsWith('/expire')) { if (session.status !== 'open') throw new Error('Checkout is not open'); session.status = 'expired'; } else if (session.status === 'open' && session.expires_at <= seconds()) session.status = 'expired'; session.url = `${origin}/checkout/${session.id}`; result = session; } else if (path === '/v1/subscriptions' && req.method === 'GET') { // As Stripe lists: newest first, `limit` (1-100, default 10) at a // time, resuming after the `starting_after` ID, with `has_more` true // while any remain. The `status` filter is not modeled. const query = url.searchParams; const limit = Number(query.get('limit') ?? 10); if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error('limit must be an integer between 1 and 100'); if (query.has('ending_before')) throw new Error('StripeDev does not support ending_before'); const listed = [...subscriptions.values()] .filter((s) => s.customer === query.get('customer')) .reverse(); const after = query.get('starting_after'); const start = after === null ? 0 : listed.findIndex((s) => s.id === after) + 1; if (after !== null && !start) throw new Error(`No such subscription: '${after}'`); result = { object: 'list', url: '/v1/subscriptions', has_more: start + limit < listed.length, data: listed.slice(start, start + limit), }; } else if (path.startsWith('/v1/charges/') && req.method === 'GET') { const charge = charges.get(path.split('/')[3]!); if (!charge) throw new Error('No such charge'); result = charge; } else if ( path.startsWith('/v1/subscriptions/') && req.method === 'DELETE' ) { const sub = subscriptions.get(path.split('/')[3]!); if (!sub) throw new Error('No such subscription'); if (['canceled', 'incomplete_expired'].includes(sub.status)) throw new Error('Subscription is already canceled'); cancel(sub); result = sub; } else if ( path === '/v1/billing_portal/sessions' && req.method === 'POST' ) { result = { id: id('bps'), object: 'billing_portal.session', url: `${origin}/portal/${body.get('customer')}`, }; } else { res.writeHead(404).end( JSON.stringify({ error: { message: 'Unsupported StripeDev endpoint' }, }), ); return; } if (key && !cached) idempotency.set(cacheKey, { input: raw, result: structuredClone(result), }); save(); if (failure?.afterCommit) { res .writeHead(503, { 'content-type': 'application/json', 'stripe-should-retry': 'false', }) .end( JSON.stringify({ error: { message: 'StripeDev lost response after committing operation', }, }), ); return; } res .writeHead(200, { 'content-type': 'application/json' }) .end(JSON.stringify(result)); } catch (error) { res .writeHead(400, { 'content-type': 'application/json' }) .end(JSON.stringify({ error: { message: String(error) } })); } }); await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); }); const port = (server.address() as AddressInfo).port; origin = `http://127.0.0.1:${port}`; const stripe = new Stripe('sk_test_pgstencil_local_only', { host: '127.0.0.1', port, protocol: 'http', maxNetworkRetries: 0, timeout: 5000, }); function signed(value: Stripe.Event) { const body = JSON.stringify(value); const signature = stripe.webhooks.generateTestHeaderString({ payload: body, secret: webhookSecret, timestamp: seconds(), }); return { body, signature }; } async function deliver(target: string) { while (events.length) { const { body, signature } = signed(events[0]!); const response = await fetch(target, { method: 'POST', headers: { 'content-type': 'application/json', 'stripe-signature': signature, }, body, signal: AbortSignal.timeout(5000), }); if (!response.ok) throw new Error(`Webhook delivery failed: ${response.status}`); events.shift(); save(); } } return { stripe, prices, webhookSecret, origin, customers, checkouts, requests, events, completeCheckout, completePayment, transition, dispute, signed, deliver, setWebhookTarget(target: string) { webhookTarget = target; }, failNext(path: string, afterCommit = false) { failures.set(path, { afterCommit }); }, async close() { server.closeAllConnections(); await new Promise((resolve, reject) => server.close((err) => (err ? reject(err) : resolve())), ); }, }; }