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 und trägt pending_update (ausstehende Aktualisierung, Task 9), bis st.applyPendingUpdate(id) * die Änderung übernimmt oder st.expirePendingUpdate(id) sie verwirft. 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). * Listen (Finanzen): GET /v1/invoices (expand data.customer ersetzt customer durch das Objekt aus st.customers, * sofern vorhanden; customer=cus_... nur die Rechnungen dieses Kunden) und GET /v1/payouts (st.payouts) blaettern wie * Stripe mit limit (hoechstens 100) und starting_after samt has_more; die Reihenfolge ist die Einfuegereihenfolge der Map. * PDF-Links (Kunden-Tab Rechnungen): GET /pdf/invoices/:id liefert fuer eine bekannte Rechnung ein kleines PDF * (application/pdf), sonst 404; failNext gilt auch hier. Tests setzen invoice_pdf auf `${st.url}/pdf/invoices/`. * * Rechnungen schreiben (Finanzen, Projektrechnungen): POST /v1/invoices (Entwurf; send_invoice braucht * days_until_due), POST /v1/invoiceitems (mit invoice=... als Zeile mit quantity und unit_amount_decimal, * Summe = Menge mal Einzelpreis; nur an Entwuerfe), POST /v1/invoices/:id (Metadaten zusammenfuehren, leerer * Wert loescht), .../finalize (nur draft -> open, vergibt die Nummer WK-0001, WK-0002, ... und die Faelligkeit), * .../send (nur open), .../void (nur open -> void), .../pay (nur open -> paid, auch paid_out_of_band; wie die echte API * liefert die Rechnung danach kein Feld paid_out_of_band, nur der Aufruf in calls zeigt es) und * DELETE /v1/invoices/:id (nur draft); jeder andere Zustand ist wie bei Stripe ein 400. * custom_fields (hoechstens 4, Name 1 bis 40, Wert 1 bis 140 Zeichen) und rendering[pdf][page_size] (a4, auto, letter) werden wie * bei Stripe geprueft, gespeichert (sonst null) und mit der Rechnung geliefert; Rechnungsposten mit amount (auch negativ) * tragen weder quantity noch unit_amount_decimal. Der Kunde einer neuen * Rechnung muss nicht in st.customers stehen (dann bleiben Name und E-Mail leer). Traegt ein Aufruf die Kopfzeile * Idempotency-Key, steht sie als idempotencyKey in calls; delayNext verzoegert eine Antwort (Zeitgrenzen testen). * Kunden: GET /v1/customers/search (Metadaten), POST /v1/customers (anlegen) und POST /v1/customers/:id (aendern: * email, name, address, metadata; unbekannte ID -> 404). Wie Stripe fuehrt ein Update die Anschrift feldweise zusammen * (nur gesendete Felder aendern sich) und ein leerer Text loescht das Feld (gespeichert als null). * * Connect (Webshop D1): die Kopfzeile Stripe-Account steht als account in calls (nur bei Aufrufen mit Konto). POST /v1/accounts * (v1 mit controller; Konto startet unfertig: charges_enabled false, requirements.currently_due ['external_account']; * gleicher Idempotency-Key liefert dasselbe Konto), GET /v1/accounts/:id (unbekannt -> 404), POST /v1/account_links * (Konto muss existieren). st.setAccount(id, patch) legt ein Konto an oder aendert es (requirements wird feldweise gemischt). * Aufrufe mit Stripe-Account arbeiten auf der Ablage dieses Kontos (st.accountSessions(id), st.refunds(id)); ohne Kopfzeile * bleibt alles wie bisher in st.checkoutSessions. Dort: POST /v1/checkout/sessions, GET .../:id, POST .../:id/expire (nur open), * POST /v1/refunds (amount fehlt = Rest der Zahlung; Zahlungen legt st.setPaymentIntent(acct, id, { amount }) an; Summe der * Erstattungen darf die Zahlung nicht uebersteigen) und GET /v1/refunds/:id. Idempotency-Key wiederholt die erste Antwort * (je Konto und Schluessel) fuer Sitzungen und Erstattungen. */ // 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 payouts = new Map() // Rechnungsposten ohne Rechnung (pending invoice items), je ID const invoiceItems = new Map() const checkoutSessions = new Map() // Connect: Konten, deren Sitzungen, Zahlungen und Erstattungen (je Konto-ID), Antworten je Idempotency-Key const accounts = new Map() const accountSessionMaps = new Map() const paymentIntentMaps = new Map() const refundMaps = new Map() const idempotentReplies = new Map() const bucket = (maps, accountId) => { if (!maps.has(accountId)) maps.set(accountId, new Map()) return maps.get(accountId) } // Abo-Aenderungen, die Stripe bis zur Zahlung zurueckhaelt (pending_update), je Abo-ID const pendingUpdates = new Map() const calls = [] let seq = 0 // Fortlaufende Rechnungsnummer, die finalize vergibt (WK-0001, ...) let invoiceNumberSeq = 0 let nextSubscriptionUpdate = null let invoicePreview = null // Eingeplanter Fehler (failNext, F41d): der naechste passende Aufruf scheitert einmalig let pendingFailure = null // Eingeplante Verzoegerung (delayNext): die Antwort des naechsten passenden Aufrufs kommt erst nach ms let pendingDelay = null const nextId = (prefix) => `${prefix}_test_${(seq += 1)}` const matchesPath = (path, pathname) => (path instanceof RegExp ? path.test(pathname) : path === pathname) const plannedFailure = (method, pathname) => { if (!pendingFailure) return null if (pendingFailure.method && pendingFailure.method !== method) return null if (pendingFailure.path && !matchesPath(pendingFailure.path, pathname)) return null if (pendingFailure.after > 0) { pendingFailure.after -= 1 return null } const { status, message } = pendingFailure pendingFailure = null return [status, { error: { type: status >= 500 ? 'api_error' : 'invalid_request_error', message: message || `Nachbau: eingeplanter Fehler ${status}` } }] } const plannedDelay = (method, pathname) => { if (!pendingDelay) return 0 if (pendingDelay.method && pendingDelay.method !== method) return 0 if (pendingDelay.path && !matchesPath(pendingDelay.path, pathname)) return 0 if (pendingDelay.after > 0) { pendingDelay.after -= 1 return 0 } const { ms } = pendingDelay pendingDelay = null return ms } 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 nowUnix = () => Math.floor(Date.now() / 1000) // Rechnungen aendern: nur Entwuerfe nehmen Posten an, finalize/send/void/pay haben feste Ausgangszustaende const wrongState = (what, invoice, needed) => invalid(undefined, `This invoice is ${invoice.status}; ${what} is only possible for ${needed} invoices.`) // Metadaten wie Stripe: Schluessel hoechstens 40, Werte hoechstens 500 Zeichen, leerer Wert loescht const mergeMetadata = (existing, incoming) => { for (const [key, value] of Object.entries(incoming || {})) { 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 metadata = { ...(existing || {}) } for (const [key, value] of Object.entries(incoming || {})) { if (value === '') delete metadata[key] else metadata[key] = value } return metadata } 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 // Listenantwort wie Stripe: limit (Standard 10, hoechstens 100) und starting_after (ID des letzten Eintrags der Vorseite) const pageOf = (items, query, url) => { const limit = Math.min(Number(query.get('limit')) || 10, 100) const after = query.get('starting_after') const afterIndex = after ? items.findIndex((item) => item.id === after) : -1 if (after && afterIndex < 0) return invalid('starting_after', `No such object: '${after}'`) const start = afterIndex + 1 return [200, { object: 'list', data: items.slice(start, start + limit), has_more: start + limit < items.length, url }] } 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 } // Anschrift eines Kunden: ein Hash wird feldweise in die bestehende Anschrift geschrieben, '' loescht das Feld (null); // ein leerer Text statt eines Hashes loescht die ganze Anschrift (wie Stripe) const mergeAddress = (current, incoming) => { if (incoming === undefined) return current ?? null if (typeof incoming !== 'object' || incoming === null) return incoming === '' ? null : (current ?? null) const merged = { ...(current || {}) } for (const [field, value] of Object.entries(incoming)) merged[field] = value === '' ? null : value return merged } const route = (method, path, query, body, account = null) => { let m // ---- Connect ---- if (method === 'POST' && path === '/v1/accounts') { const data = unflatten(body) const id = `acct_test${(seq += 1)}` const obj = { id, object: 'account', type: 'standard', country: data.country || 'DE', email: data.email ?? null, business_profile: data.business_profile || {}, controller: { type: 'application', is_controller: false, ...(data.controller || {}) }, capabilities: Object.fromEntries(Object.keys(data.capabilities || {}).map((k) => [k, 'inactive'])), metadata: data.metadata || {}, charges_enabled: false, payouts_enabled: false, details_submitted: false, requirements: { currently_due: ['external_account'], eventually_due: ['external_account'], past_due: [], errors: [], disabled_reason: null }, } accounts.set(id, obj) return [200, obj] } if (method === 'GET' && (m = path.match(/^\/v1\/accounts\/([^/]+)$/))) { return accounts.has(m[1]) ? [200, accounts.get(m[1])] : noSuch('account', m[1]) } if (method === 'POST' && path === '/v1/account_links') { const data = unflatten(body) if (!accounts.has(data.account)) return noSuch('account', data.account) if (!data.type) return invalid('type', 'Missing required param: type.') return [200, { object: 'account_link', created: nowUnix(), expires_at: nowUnix() + 300, url: `https://connect.stripe.test/setup/${data.account}/${(seq += 1)}`, }] } if (account) { const sessions = bucket(accountSessionMaps, account) 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', client_reference_id: data.client_reference_id ?? null, success_url: data.success_url ?? null, cancel_url: data.cancel_url ?? null, expires_at: data.expires_at ? Number(data.expires_at) : nowUnix() + 86400, metadata: data.metadata || {}, status: 'open', payment_status: 'unpaid', payment_intent: null, amount_total: null, currency: 'eur', customer_details: null, } sessions.set(id, obj) return [200, obj] } if (method === 'GET' && (m = path.match(/^\/v1\/checkout\/sessions\/([^/]+)$/))) { return sessions.has(m[1]) ? [200, sessions.get(m[1])] : noSuch('checkout.session', m[1]) } if (method === 'POST' && (m = path.match(/^\/v1\/checkout\/sessions\/([^/]+)\/expire$/))) { const found = sessions.get(m[1]) if (!found) return noSuch('checkout.session', m[1]) if (found.status !== 'open') return invalid(undefined, 'Only Checkout Sessions with a status in open can be expired.') const expired = { ...found, status: 'expired' } sessions.set(found.id, expired) return [200, expired] } if (method === 'POST' && path === '/v1/refunds') { const data = unflatten(body) const intents = bucket(paymentIntentMaps, account) const refunds = bucket(refundMaps, account) const intent = intents.get(data.payment_intent) if (!data.payment_intent) return invalid('payment_intent', 'Either payment_intent or charge must be provided.') if (!intent && !data.amount) return noSuch('payment_intent', data.payment_intent) const already = [...refunds.values()].filter((r) => r.payment_intent === data.payment_intent).reduce((sum, r) => sum + r.amount, 0) const rest = intent ? intent.amount - already : null const amount = data.amount ? Number(data.amount) : rest if (!Number.isInteger(amount) || amount <= 0) return invalid('amount', 'Invalid positive integer') if (rest !== null && amount > rest) return invalid('amount', `Refund amount (${amount}) is greater than unrefunded amount on payment (${rest}).`) const obj = { id: nextId('re'), object: 'refund', amount, currency: 'eur', payment_intent: data.payment_intent, reason: data.reason ?? null, metadata: data.metadata || {}, status: 'succeeded', created: nowUnix(), } refunds.set(obj.id, obj) return [200, obj] } if (method === 'GET' && path === '/v1/refunds') { const pi = query.get('payment_intent') const items = [...bucket(refundMaps, account).values()].filter((r) => !pi || r.payment_intent === pi) return [200, { object: 'list', data: items, has_more: false, url: '/v1/refunds' }] } if (method === 'GET' && (m = path.match(/^\/v1\/refunds\/([^/]+)$/))) { const found = bucket(refundMaps, account).get(m[1]) return found ? [200, found] : noSuch('refund', m[1]) } } // ---- Plattform ---- 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 und traegt pending_update, bis die Rechnung bezahlt ist (applyPendingUpdate) oder die // Aenderung verfaellt (expirePendingUpdate) pendingUpdates.set(m[1], updated) subscriptions.set(m[1], { ...existing, pending_update: extra.pending_update }) 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' && path === '/v1/invoices') { const expandCustomer = [...query.entries()].some(([k, v]) => k.startsWith('expand') && v === 'data.customer') // Wie Stripe: customer=cus_... liefert nur die Rechnungen dieses Kunden const customerFilter = query.get('customer') const all = [...invoices.values()] .filter((inv) => !customerFilter || (typeof inv.customer === 'string' ? inv.customer : inv.customer?.id) === customerFilter) .map((inv) => expandCustomer && typeof inv.customer === 'string' && customers.has(inv.customer) ? { ...inv, customer: customers.get(inv.customer) } : inv ) return pageOf(all, query, '/v1/invoices') } if (method === 'GET' && path === '/v1/payouts') { return pageOf([...payouts.values()], query, '/v1/payouts') } 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]) const stored = invoices.get(m[1]) const expandCustomer = [...query.entries()].some(([k, v]) => k.startsWith('expand') && v === 'customer') return [ 200, { ...stored, ...(expandCustomer && typeof stored.customer === 'string' && customers.has(stored.customer) ? { customer: customers.get(stored.customer) } : {}), 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 }] } // Rechnungen schreiben (Finanzen): Entwurf anlegen, Posten anhaengen, finalisieren, senden, stornieren, bezahlen, loeschen if (method === 'POST' && path === '/v1/invoices') { const data = unflatten(body) if (!data.customer) return invalid('customer', 'Missing required param: customer.') const collectionMethod = data.collection_method || 'charge_automatically' if (collectionMethod === 'send_invoice' && data.days_until_due === undefined && data.due_date === undefined) { return invalid('days_until_due', 'Either days_until_due or due_date must be set when collection_method=send_invoice.') } const metadata = mergeMetadata({}, data.metadata) if (Array.isArray(metadata)) return metadata const customFields = data.custom_fields if (customFields !== undefined) { if (!Array.isArray(customFields) || customFields.length > 4) return invalid('custom_fields', 'You can specify up to 4 custom fields.') for (const [i, field] of customFields.entries()) { if (typeof field?.name !== 'string' || field.name.length < 1 || field.name.length > 40) { return invalid(`custom_fields[${i}][name]`, 'Custom field names must be between 1 and 40 characters.') } if (typeof field.value !== 'string' || field.value.length < 1 || field.value.length > 140) { return invalid(`custom_fields[${i}][value]`, 'Custom field values must be between 1 and 140 characters.') } } } const pageSize = data.rendering?.pdf?.page_size if (pageSize !== undefined && !['a4', 'auto', 'letter'].includes(pageSize)) { return invalid('rendering[pdf][page_size]', 'Invalid page_size: must be one of a4, auto, letter.') } const customer = customers.get(data.customer) const invoice = { id: nextId('in'), object: 'invoice', number: null, status: 'draft', customer: data.customer, customer_name: customer?.name ?? null, customer_email: customer?.email ?? null, collection_method: collectionMethod, days_until_due: data.days_until_due !== undefined ? Number(data.days_until_due) : null, due_date: null, auto_advance: data.auto_advance === 'true', pending_invoice_items_behavior: data.pending_invoice_items_behavior || 'exclude', currency: data.currency || 'eur', description: data.description ?? null, footer: data.footer ?? null, metadata, custom_fields: customFields ?? null, rendering: data.rendering ?? null, created: nowUnix(), total: 0, subtotal: 0, amount_due: 0, amount_paid: 0, amount_remaining: 0, status_transitions: { finalized_at: null, paid_at: null, voided_at: null }, hosted_invoice_url: null, invoice_pdf: null, lines: { object: 'list', data: [], has_more: false, url: '' }, } invoices.set(invoice.id, invoice) return [200, invoice] } if (method === 'POST' && path === '/v1/invoiceitems') { const data = unflatten(body) if (!data.customer) return invalid('customer', 'Missing required param: customer.') if (data.amount !== undefined && (data.quantity !== undefined || data.unit_amount_decimal !== undefined)) { return invalid('amount', 'You may only specify one of these parameters: amount, or quantity with unit_amount_decimal.') } const quantity = data.quantity !== undefined ? Number(data.quantity) : 1 if (!Number.isInteger(quantity) || quantity < 0) return invalid('quantity', 'Invalid non-negative integer: quantity.') let unit = null if (data.unit_amount_decimal !== undefined) { if (!/^-?\d+(\.\d+)?$/.test(data.unit_amount_decimal)) return invalid('unit_amount_decimal', `Invalid decimal: ${data.unit_amount_decimal}`) unit = data.unit_amount_decimal } else if (data.amount !== undefined) { unit = String(Number(data.amount)) } else { return invalid('amount', 'Missing required param: amount, unit_amount_decimal or pricing.') } const amount = Math.round(Number(unit) * (data.unit_amount_decimal !== undefined ? quantity : 1)) const item = { id: nextId('ii'), object: 'line_item', description: data.description ?? null, quantity: data.unit_amount_decimal !== undefined ? quantity : 1, amount, currency: data.currency || 'eur', pricing: { type: 'price_details', unit_amount_decimal: unit }, metadata: data.metadata || {}, } if (data.invoice) { const invoice = invoices.get(data.invoice) if (!invoice) return noSuch('invoice', data.invoice) if (invoice.status !== 'draft') return invalid('invoice', 'You can only add invoice items to draft invoices.') const total = invoice.total + amount invoices.set(invoice.id, { ...invoice, total, subtotal: total, amount_due: total, amount_remaining: total, lines: { object: 'list', has_more: false, ...invoice.lines, data: [...(invoice.lines?.data || []), item] }, }) item.invoice = invoice.id } else { item.invoice = null } invoiceItems.set(item.id, item) return [200, { ...item, object: 'invoiceitem', customer: data.customer }] } if (method === 'POST' && (m = path.match(/^\/v1\/invoices\/([^/]+)\/(finalize|send|void|pay)$/))) { const invoice = invoices.get(m[1]) if (!invoice) return noSuch('invoice', m[1]) const data = unflatten(body) const at = nowUnix() let updated if (m[2] === 'finalize') { if (invoice.status !== 'draft') return wrongState('finalizing', invoice, 'draft') invoiceNumberSeq += 1 updated = { ...invoice, status: 'open', number: `WK-${String(invoiceNumberSeq).padStart(4, '0')}`, auto_advance: data.auto_advance !== undefined ? data.auto_advance === 'true' : invoice.auto_advance, due_date: invoice.collection_method === 'send_invoice' && invoice.days_until_due !== null ? at + invoice.days_until_due * 86_400 : null, hosted_invoice_url: `https://invoice.stripe.test/i/${invoice.id}`, invoice_pdf: `https://invoice.stripe.test/i/${invoice.id}/pdf`, status_transitions: { ...invoice.status_transitions, finalized_at: at }, } } else if (m[2] === 'send') { if (invoice.status !== 'open') return wrongState('sending', invoice, 'open') updated = { ...invoice, sent_at: at } } else if (m[2] === 'void') { if (invoice.status !== 'open') return wrongState('voiding', invoice, 'open') updated = { ...invoice, status: 'void', status_transitions: { ...invoice.status_transitions, voided_at: at } } } else { if (invoice.status !== 'open') return wrongState('paying', invoice, 'open') updated = { ...invoice, status: 'paid', paid: true, amount_paid: invoice.total, amount_remaining: 0, status_transitions: { ...invoice.status_transitions, paid_at: at }, } } invoices.set(invoice.id, updated) return [200, updated] } if (method === 'POST' && (m = path.match(/^\/v1\/invoices\/([^/]+)$/))) { const invoice = invoices.get(m[1]) if (!invoice) return noSuch('invoice', m[1]) const data = unflatten(body) const metadata = data.metadata ? mergeMetadata(invoice.metadata, data.metadata) : invoice.metadata if (Array.isArray(metadata)) return metadata const updated = { ...invoice, metadata } invoices.set(invoice.id, updated) return [200, updated] } if (method === 'DELETE' && (m = path.match(/^\/v1\/invoices\/([^/]+)$/))) { const invoice = invoices.get(m[1]) if (!invoice) return noSuch('invoice', m[1]) if (invoice.status !== 'draft') { return invalid(undefined, 'You can only delete draft invoices. Finalized invoices must be voided or marked uncollectible instead.') } invoices.delete(m[1]) return [200, { id: m[1], object: 'invoice', deleted: true }] } // 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 === 'GET' && path === '/v1/products') { const active = query.get('active') return [200, listOf([...products.values()].filter((p) => active === null || String(p.active !== false) === active))] } 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: mergeAddress(null, data.address), invoice_settings: data.invoice_settings || {}, metadata: data.metadata || {}, } customers.set(obj.id, obj) return [200, obj] } // Kunde aendern (stripe.customers.update): email, name, address (ersetzt) und metadata (zusammengefuehrt) werden uebernommen if (method === 'POST' && (m = path.match(/^\/v1\/customers\/([^/]+)$/))) { const customer = customers.get(m[1]) if (!customer) return noSuch('customer', m[1]) const data = unflatten(body) const metadata = data.metadata ? mergeMetadata(customer.metadata, data.metadata) : customer.metadata if (Array.isArray(metadata)) return metadata const updated = { ...customer, ...(data.email !== undefined ? { email: data.email || null } : {}), ...(data.name !== undefined ? { name: data.name || null } : {}), ...(data.address !== undefined ? { address: mergeAddress(customer.address, data.address) } : {}), metadata, } customers.set(customer.id, updated) return [200, updated] } 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 || {}, status: 'open', payment_status: 'unpaid', invoice: null, } checkoutSessions.set(id, obj) return [200, obj] } // Sitzung abrufen (Funktions-Checkout); expand=invoice ersetzt die Rechnungs-ID durch das Objekt. // Tests setzen status/payment_status/invoice direkt im Objekt aus st.checkoutSessions. if (method === 'GET' && (m = path.match(/^\/v1\/checkout\/sessions\/([^/]+)$/))) { const found = checkoutSessions.get(m[1]) if (!found) return noSuch('checkout.session', m[1]) const expandInvoice = [...query.entries()].some(([k, v]) => k.startsWith('expand') && v === 'invoice') const inv = typeof found.invoice === 'string' ? invoices.get(found.invoice) : null return [200, expandInvoice && inv ? { ...found, invoice: inv } : found] } 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) // idempotencyKey (Kopfzeile Idempotency-Key) steht nur an Aufrufen, die einen mitschicken const idempotencyKey = req.headers['idempotency-key'] // Connect: Kopfzeile Stripe-Account (Aufruf im Namen eines Haendlerkontos) const account = req.headers['stripe-account'] calls.push({ method: req.method, path: url.pathname, query: flat(url.searchParams), body: flat(body), ...(idempotencyKey ? { idempotencyKey } : {}), ...(account ? { account } : {}) }) const delay = plannedDelay(req.method, url.pathname) if (delay) await new Promise((resolve) => setTimeout(resolve, delay)) const failure = plannedFailure(req.method, url.pathname) // PDF einer Rechnung (invoice_pdf zeigt in Tests hierher): kleines PDF statt JSON const pdfMatch = !failure && req.method === 'GET' && url.pathname.match(/^\/pdf\/invoices\/([^/]+)$/) if (pdfMatch) { if (!invoices.has(pdfMatch[1])) { res.writeHead(404, { 'Content-Type': 'text/plain' }) return res.end('Not found') } res.writeHead(200, { 'Content-Type': 'application/pdf' }) return res.end(`%PDF-1.4\n% Stripe-Nachbau ${pdfMatch[1]}\n%%EOF\n`) } // Wiederholung mit gleichem Idempotency-Key (nur Connect-Aufrufe und Kontoanlage): erste Antwort, kein neuer Zustand const replyKey = !failure && req.method === 'POST' && idempotencyKey && (account || url.pathname === '/v1/accounts') ? `${account || ''}|${idempotencyKey}` : null const [status, payload] = failure || (replyKey && idempotentReplies.get(replyKey)) || route(req.method, url.pathname, url.searchParams, body, account || null) if (replyKey && status === 200 && !idempotentReplies.has(replyKey)) idempotentReplies.set(replyKey, [status, payload]) 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, payouts, invoiceItems, checkoutSessions, accounts, /** Sitzungen eines Haendlerkontos (Map id -> Sitzung); Tests setzen status/payment_status/payment_intent direkt darin. */ accountSessions: (accountId) => bucket(accountSessionMaps, accountId), /** Erstattungen eines Haendlerkontos (Map id -> Erstattung). */ refunds: (accountId) => bucket(refundMaps, accountId), /** Konto anlegen oder aendern (z. B. { charges_enabled: true, details_submitted: true, requirements: { currently_due: [] } }). */ setAccount(id, patch = {}) { const base = accounts.get(id) || { id, object: 'account', type: 'standard', country: 'DE', email: null, business_profile: {}, metadata: {}, controller: { type: 'application', is_controller: false }, capabilities: {}, charges_enabled: false, payouts_enabled: false, details_submitted: false, requirements: { currently_due: ['external_account'], eventually_due: [], past_due: [], errors: [], disabled_reason: null }, } const next = { ...base, ...patch, requirements: { ...base.requirements, ...(patch.requirements || {}) } } accounts.set(id, next) return next }, /** * Sitzung eines Haendlerkontos als abgeschlossen markieren (status complete) und die Felder setzen, die Stripe nach der Kasse * liefert: completeSession('acct_x', 'cs_x', { payment_status: 'paid', amount_total, customer_details, shipping, payment_intent, * payment_method_types }). shipping steht wie bei Stripe unter collected_information.shipping_details und shipping_details. * Gibt die neue Sitzung zurueck (so schickt der Webhook sie). */ completeSession(accountId, id, { payment_status = 'paid', amount_total = null, customer_details = null, shipping = null, payment_intent = null, payment_method_types } = {}) { const sessions = bucket(accountSessionMaps, accountId) const found = sessions.get(id) if (!found) throw new Error(`Stripe-Nachbau: keine Sitzung ${id} bei ${accountId}`) const next = { ...found, status: 'complete', payment_status, amount_total, customer_details, payment_intent, ...(payment_method_types ? { payment_method_types } : {}), ...(shipping ? { collected_information: { shipping_details: shipping }, shipping_details: shipping } : {}), } sessions.set(id, next) return next }, /** Zahlung eines Haendlerkontos (Betrag in Cent) fuer Erstattungen: setPaymentIntent('acct_x', 'pi_x', { amount: 2500 }). */ setPaymentIntent(accountId, id, { amount, currency = 'eur' }) { const obj = { id, object: 'payment_intent', amount, currency } bucket(paymentIntentMaps, accountId).set(id, obj) return obj }, /** * 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 (und traegt pending_update), bis * applyPendingUpdate(id) die Aenderung uebernimmt oder expirePendingUpdate(id) sie verwirft. */ 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) const applied = { ...updated, pending_update: null } subscriptions.set(id, applied) return applied }, /** Zurueckgehaltene Aenderung verfaellt (Stripe storniert die Rechnung und verwirft pending_update). */ expirePendingUpdate(id) { if (!pendingUpdates.has(id)) throw new Error(`Stripe-Nachbau: keine ausstehende Aktualisierung fuer ${id}`) pendingUpdates.delete(id) subscriptions.set(id, { ...subscriptions.get(id), pending_update: null }) }, /** Antwort von POST /v1/invoices/create_preview: Objekt oder Funktion (body) => Objekt; null = leere Vorschau. */ get invoicePreview() { return invoicePreview }, set invoicePreview(value) { invoicePreview = value }, /** * Naechster passender Aufruf (method, path als String oder RegExp) scheitert einmalig mit status; after * passende Aufrufe gehen vorher durch. Der Aufruf steht trotzdem in calls. 4xx wiederholt stripe-node * nicht, 5xx schon (maxNetworkRetries) - fuer "Stripe lehnt ab" also 4xx einplanen. */ failNext: ({ method = null, path = null, status = 500, message = '', after = 0 }) => { pendingFailure = { method, path, status, message, after } }, /** * Die Antwort auf den naechsten passenden Aufruf (method, path als String oder RegExp) kommt erst nach ms * Millisekunden; after passende Aufrufe gehen vorher ohne Verzoegerung durch. Der Aufruf steht sofort in calls. */ delayNext: ({ method = null, path = null, ms, after = 0 }) => { pendingDelay = { method, path, ms, after } }, close: () => new Promise((resolve) => server.close(resolve)), } }