import http from 'node:http' /** * Stripe-Nachbau für Tests. stripe-node spricht ihn über config.stripe.apiBase (STRIPE_API_BASE) * an. Objekte werden vorab in die Maps gelegt; jeder Aufruf landet in calls als * { method, path, query, body } (Formular-Schlüssel flach, z. B. 'items[0][price]'). * * Abo-Änderungen (F17): POST /v1/subscriptions/:id mischt items[i][id|price|quantity|deleted] und * metadata (leerer Wert löscht) in das gespeicherte Abo; st.nextSubscriptionUpdate wird einmalig nur * in die nächste Antwort gemischt (z. B. latest_invoice). Enthält er pending_update, bleibt das Abo wie bei * Stripe unverändert (ausstehende Aktualisierung, Task 9), bis st.applyPendingUpdate(id) die Änderung * übernimmt. Wie Stripe: mit payment_behavior=pending_if_incomplete nur die dafür erlaubten Parameter, * Metadaten-Schlüssel höchstens 40 und Werte höchstens 500 Zeichen. Rechnungen: GET /v1/invoices/:id * bettet wie Stripe höchstens 10 Zeilen ein, GET /v1/invoices/:id/lines blättert (limit, starting_after); * POST /v1/invoices/create_preview liefert st.invoicePreview (Objekt, oder Funktion des Aufruf-Bodys). */ // Parameter, die Stripe bei ausstehenden Aktualisierungen annimmt (docs.stripe.com/billing/subscriptions/ // pending-updates, "Unterstützte Attribute", geprüft am 28.09.2026); items[i][id] verweist auf die Position const PENDING_UPDATE_PARAMS = new Set([ 'expand', 'payment_behavior', 'proration_behavior', 'proration_date', 'billing_cycle_anchor', 'items', 'trial_end', 'trial_from_plan', 'metadata', 'discounts', 'cancel_at_period_end', 'coupon', 'promotion_code', 'add_invoice_items', ]) const PENDING_UPDATE_ITEM_PARAMS = new Set(['id', 'price', 'quantity', 'discounts']) export async function startFakeStripe() { const subscriptions = new Map() const prices = new Map() const invoices = new Map() const products = new Map() const coupons = new Map() const billingPortalConfigurations = new Map() const customers = new Map() const checkoutSessions = new Map() // Abo-Aenderungen, die Stripe bis zur Zahlung zurueckhaelt (pending_update), je Abo-ID const pendingUpdates = new Map() const calls = [] let seq = 0 let nextSubscriptionUpdate = null let invoicePreview = null const nextId = (prefix) => `${prefix}_test_${(seq += 1)}` const flat = (params) => Object.fromEntries(params.entries()) const noSuch = (what, id) => [404, { error: { type: 'invalid_request_error', code: 'resource_missing', message: `No such ${what}: '${id}'` } }] const invalid = (param, message) => [400, { error: { type: 'invalid_request_error', param, message } }] const listOf = (data) => ({ object: 'list', data, has_more: false, url: '/v1/list' }) // Rechnungszeilen mit IDs (fuer starting_after), wie Stripe sie liefert; die Quelle behaelt alle Zeilen const invoiceLinesOf = (invoiceId) => (invoices.get(invoiceId)?.lines?.data || []).map((line, i) => ({ id: `li_${invoiceId}_${i + 1}`, object: 'line_item', ...line })) const EMBEDDED_LINES = 10 const readBody = (req) => new Promise((resolve) => { let raw = '' req.on('data', (chunk) => (raw += chunk)) req.on('end', () => resolve(new URLSearchParams(raw))) }) // Stripe serialisiert verschachtelte Parameter (z. B. recurring[interval]=month) als flache // Formularschluessel. Fuer die Routen selbst wieder zu einem verschachtelten Objekt zusammenbauen. const unflatten = (params) => { const root = {} for (const [rawKey, value] of params.entries()) { const path = rawKey.match(/[^[\]]+/g) || [rawKey] let node = root path.forEach((key, i) => { if (i === path.length - 1) { node[key] = value } else { if (!(key in node)) node[key] = /^\d+$/.test(path[i + 1]) ? [] : {} node = node[key] } }) } return root } const route = (method, path, query, body) => { let m if (method === 'GET' && (m = path.match(/^\/v1\/subscriptions\/([^/]+)$/))) { return subscriptions.has(m[1]) ? [200, subscriptions.get(m[1])] : noSuch('subscription', m[1]) } if (method === 'POST' && (m = path.match(/^\/v1\/subscriptions\/([^/]+)$/))) { const existing = subscriptions.get(m[1]) if (!existing) return noSuch('subscription', m[1]) const data = unflatten(body) // Wie Stripe: mit pending_if_incomplete nur die Parameter, die ausstehende Aktualisierungen kennen if (data.payment_behavior === 'pending_if_incomplete') { const param = Object.keys(data).find((key) => !PENDING_UPDATE_PARAMS.has(key)) || (data.items || []).flatMap((entry, i) => Object.keys(entry).filter((key) => !PENDING_UPDATE_ITEM_PARAMS.has(key)).map((key) => `items[${i}][${key}]`))[0] if (param) return invalid(param, `Received unsupported parameter ${param} with payment_behavior=pending_if_incomplete.`) } // Wie Stripe: Metadaten-Schluessel hoechstens 40, Werte hoechstens 500 Zeichen for (const [key, value] of Object.entries(data.metadata || {})) { if (key.length > 40) return invalid(`metadata[${key}]`, 'Metadata keys can be at most 40 characters long.') if (String(value).length > 500) return invalid(`metadata[${key}]`, 'Metadata values can be at most 500 characters long.') } const items = (existing.items?.data || []).map((item) => ({ ...item })) for (const [i, entry] of (data.items || []).entries()) { if (entry.id) { // Vorhandene Position: Menge/Preis aendern oder entfernen const index = items.findIndex((item) => item.id === entry.id) if (index < 0) return invalid(`items[${i}][id]`, `No such subscription_item: '${entry.id}'`) if (entry.deleted === 'true') { items.splice(index, 1) continue } if (entry.price) { if (!prices.has(entry.price)) return invalid(`items[${i}][price]`, `No such price: '${entry.price}'`) items[index].price = prices.get(entry.price) } if (entry.quantity !== undefined) items[index].quantity = Number(entry.quantity) } else if (entry.price) { // Neue Position per Preis; wie Stripe: derselbe Preis hoechstens einmal je Abo if (!prices.has(entry.price)) return invalid(`items[${i}][price]`, `No such price: '${entry.price}'`) if (items.some((item) => item.price?.id === entry.price)) { return invalid(`items[${i}][price]`, 'You cannot combine multiple subscription items with the same price.') } items.push({ id: nextId('si'), object: 'subscription_item', quantity: entry.quantity !== undefined ? Number(entry.quantity) : 1, price: prices.get(entry.price), }) } else { return invalid(`items[${i}]`, 'Each subscription item must have an id or a price.') } } // Metadaten wie bei Stripe zusammenfuehren: leerer Wert loescht den Schluessel const metadata = { ...(existing.metadata || {}) } for (const [key, value] of Object.entries(data.metadata || {})) { if (value === '') delete metadata[key] else metadata[key] = value } const updated = { ...existing, items: { object: 'list', ...(existing.items || {}), data: items }, metadata } if (data.cancel_at_period_end !== undefined) updated.cancel_at_period_end = data.cancel_at_period_end === 'true' if (data.cancel_at !== undefined) updated.cancel_at = data.cancel_at === '' ? null : Number(data.cancel_at) // Einmaliger Zusatz nur fuer diese Antwort (pending_update, latest_invoice, ...), nicht gespeichert const extra = nextSubscriptionUpdate nextSubscriptionUpdate = null if (extra?.pending_update) { // Zahlung nicht erfolgt (Task 9): Stripe haelt die Aenderung in pending_update zurueck, das Abo bleibt // unveraendert, bis die Rechnung bezahlt ist (im Test: applyPendingUpdate) pendingUpdates.set(m[1], updated) return [200, { ...existing, ...extra }] } subscriptions.set(m[1], updated) return [200, extra ? { ...updated, ...extra } : updated] } if (method === 'GET' && (m = path.match(/^\/v1\/prices\/([^/]+)$/))) { return prices.has(m[1]) ? [200, prices.get(m[1])] : noSuch('price', m[1]) } if (method === 'GET' && path === '/v1/prices') { const keys = [...query.entries()].filter(([k]) => /^lookup_keys\[\d*\]$/.test(k)).map(([, v]) => v) const active = query.get('active') const found = [...prices.values()].filter( (p) => (!keys.length || keys.includes(p.lookup_key)) && (active === null || String(p.active !== false) === active) ) return [200, listOf(found)] } if (method === 'POST' && path === '/v1/prices') { const data = unflatten(body) // Wie echtes Stripe: ein lookup_key darf nur an einem aktiven Preis gleichzeitig haengen // (Fix round 1, Important 1 - haertet den Nachbau, ensurePrice fragt vorher ohnehin per GET) if (data.lookup_key) { const clash = [...prices.values()].find((p) => p.lookup_key === data.lookup_key && p.active !== false) if (clash) { return [400, { error: { type: 'invalid_request_error', param: 'lookup_key', message: `An active price already exists for lookup_key: '${data.lookup_key}'.` } }] } } const obj = { id: nextId('price'), object: 'price', active: true, product: data.product, currency: data.currency || 'eur', unit_amount: data.unit_amount != null ? Number(data.unit_amount) : null, recurring: data.recurring ? { interval: data.recurring.interval } : null, tax_behavior: data.tax_behavior || null, lookup_key: data.lookup_key || null, nickname: data.nickname || null, } prices.set(obj.id, obj) return [200, obj] } if (method === 'GET' && (m = path.match(/^\/v1\/invoices\/([^/]+)$/))) { if (!invoices.has(m[1])) return noSuch('invoice', m[1]) // Wie Stripe: hoechstens 10 Zeilen eingebettet, weitere ueber GET /v1/invoices/:id/lines (has_more) const lines = invoiceLinesOf(m[1]) return [ 200, { ...invoices.get(m[1]), lines: { object: 'list', data: lines.slice(0, EMBEDDED_LINES), has_more: lines.length > EMBEDDED_LINES, url: `/v1/invoices/${m[1]}/lines` }, }, ] } if (method === 'GET' && (m = path.match(/^\/v1\/invoices\/([^/]+)\/lines$/))) { if (!invoices.has(m[1])) return noSuch('invoice', m[1]) const lines = invoiceLinesOf(m[1]) const limit = Math.min(Number(query.get('limit')) || 10, 100) const after = query.get('starting_after') const afterIndex = after ? lines.findIndex((line) => line.id === after) : -1 if (after && afterIndex < 0) return invalid('starting_after', `No such line item: '${after}'`) const start = afterIndex + 1 return [200, { object: 'list', data: lines.slice(start, start + limit), has_more: start + limit < lines.length, url: `/v1/invoices/${m[1]}/lines` }] } if (method === 'POST' && path === '/v1/invoices/create_preview') { const data = unflatten(body) if (data.subscription && !subscriptions.has(data.subscription)) return noSuch('subscription', data.subscription) const preview = typeof invoicePreview === 'function' ? invoicePreview(data) : invoicePreview return [200, preview || { object: 'invoice', lines: { object: 'list', data: [], has_more: false }, amount_due: 0, subtotal: 0, total: 0 }] } // scripts/stripe-products.mjs --pruefen liest das Produkt zurueck (Beschreibung, Bild) if (method === 'GET' && (m = path.match(/^\/v1\/products\/([^/]+)$/))) { return products.has(m[1]) ? [200, products.get(m[1])] : noSuch('product', m[1]) } if (method === 'POST' && path === '/v1/products') { const data = unflatten(body) const obj = { id: nextId('prod'), object: 'product', active: true, name: data.name || '', description: data.description ?? null, statement_descriptor: data.statement_descriptor ?? null, images: data.images || [], metadata: data.metadata || {}, } products.set(obj.id, obj) return [200, obj] } if (method === 'GET' && (m = path.match(/^\/v1\/coupons\/([^/]+)$/))) { return coupons.has(m[1]) ? [200, coupons.get(m[1])] : noSuch('coupon', m[1]) } if (method === 'POST' && path === '/v1/coupons') { const data = unflatten(body) const id = data.id || nextId('coupon') // Wie echtes Stripe: Name auf 40 Zeichen begrenzt, IDs eindeutig (Fix round 1, Important 1) if (data.name && data.name.length > 40) { return [400, { error: { type: 'invalid_request_error', param: 'name', message: 'Name must be no more than 40 characters.' } }] } if (coupons.has(id)) { return [400, { error: { type: 'invalid_request_error', message: `Coupon with ID '${id}' already exists.` } }] } const obj = { id, object: 'coupon', valid: true, name: data.name || null, amount_off: data.amount_off != null ? Number(data.amount_off) : null, currency: data.currency || null, duration: data.duration || 'once', metadata: data.metadata || {}, } coupons.set(id, obj) return [200, obj] } // Checkout (Neuabschluss): Kunde suchen/anlegen, Checkout-Sitzung anlegen (F10) if (method === 'GET' && path === '/v1/customers/search') { // Suchsyntax wie in getOrCreateStripeCustomer: metadata['webklarCustomerId']:'c1' const m2 = (query.get('query') || '').match(/metadata\['(\w+)'\]:'([^']*)'/) const found = [...customers.values()].filter((c) => !m2 || c.metadata?.[m2[1]] === m2[2]) return [200, { object: 'search_result', data: found, has_more: false, url: '/v1/customers/search' }] } if (method === 'POST' && path === '/v1/customers') { const data = unflatten(body) const obj = { id: nextId('cus'), object: 'customer', email: data.email ?? null, name: data.name ?? null, address: data.address ?? null, invoice_settings: data.invoice_settings || {}, metadata: data.metadata || {}, } customers.set(obj.id, obj) return [200, obj] } if (method === 'POST' && path === '/v1/checkout/sessions') { const data = unflatten(body) const id = nextId('cs') const obj = { id, object: 'checkout.session', url: `https://checkout.stripe.test/c/pay/${id}`, mode: data.mode || 'payment', customer: data.customer ?? null, client_reference_id: data.client_reference_id ?? null, subscription: null, metadata: data.metadata || {}, subscription_data: data.subscription_data || {}, } checkoutSessions.set(id, obj) return [200, obj] } if (method === 'GET' && path === '/v1/billing_portal/configurations') { const active = query.get('active') const found = [...billingPortalConfigurations.values()].filter( (c) => active === null || String(c.active !== false) === active ) return [200, listOf(found)] } if (method === 'POST' && path === '/v1/billing_portal/configurations') { const data = unflatten(body) const obj = { id: nextId('bpc'), object: 'billing_portal.configuration', active: true, business_profile: data.business_profile || {}, default_return_url: data.default_return_url || null, features: data.features || {}, metadata: data.metadata || {}, } billingPortalConfigurations.set(obj.id, obj) return [200, obj] } if (method === 'POST' && (m = path.match(/^\/v1\/billing_portal\/configurations\/([^/]+)$/))) { const existing = billingPortalConfigurations.get(m[1]) if (!existing) return noSuch('configuration', m[1]) const data = unflatten(body) const updated = { ...existing, ...data, business_profile: { ...existing.business_profile, ...(data.business_profile || {}) }, features: { ...existing.features, ...(data.features || {}) }, metadata: { ...existing.metadata, ...(data.metadata || {}) }, } billingPortalConfigurations.set(m[1], updated) return [200, updated] } return [404, { error: { type: 'invalid_request_error', message: `No such route: ${method} ${path}` } }] } const server = http.createServer(async (req, res) => { const url = new URL(req.url, 'http://127.0.0.1') const body = await readBody(req) calls.push({ method: req.method, path: url.pathname, query: flat(url.searchParams), body: flat(body) }) const [status, payload] = route(req.method, url.pathname, url.searchParams, body) res.writeHead(status, { 'Content-Type': 'application/json', 'Request-Id': `req_test_${calls.length}` }) res.end(JSON.stringify(payload)) }) await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) return { url: `http://127.0.0.1:${server.address().port}`, calls, subscriptions, prices, invoices, products, coupons, billingPortalConfigurations, customers, checkoutSessions, /** * Einmalig in die naechste Antwort von POST /v1/subscriptions/:id gemischt (z. B. latest_invoice). Mit * pending_update bleibt das Abo wie bei Stripe unveraendert, bis applyPendingUpdate(id) die Aenderung * uebernimmt. */ get nextSubscriptionUpdate() { return nextSubscriptionUpdate }, set nextSubscriptionUpdate(value) { nextSubscriptionUpdate = value }, /** Zurueckgehaltene Aenderung uebernehmen (= Wechselrechnung bezahlt, Stripe wendet pending_update an). */ applyPendingUpdate(id) { const updated = pendingUpdates.get(id) if (!updated) throw new Error(`Stripe-Nachbau: keine ausstehende Aktualisierung fuer ${id}`) pendingUpdates.delete(id) subscriptions.set(id, updated) return updated }, /** Antwort von POST /v1/invoices/create_preview: Objekt oder Funktion (body) => Objekt; null = leere Vorschau. */ get invoicePreview() { return invoicePreview }, set invoicePreview(value) { invoicePreview = value }, close: () => new Promise((resolve) => server.close(resolve)), } }