also looking at this
feat(billing): issue the license from Stripe, not only from the thank-you page
#49
9 files
+439
-2
| @@ -0,0 +1,225 @@ | ||
| 1 | import type { LicenseRecord, LicenseStore, LicenseStripe } from '../../../app/Billing/licenses' | |
| 2 | import { describe, expect, it } from 'bun:test' | |
| 3 | import { createHmac } from 'node:crypto' | |
| 4 | import process from 'node:process' | |
| 5 | import { Licenses } from '../../../app/Billing/licenses' | |
| 6 | import { bodyFor, receiveWebhook, statusFor, webhookSecret } from '../../../app/Billing/webhook' | |
| 7 | ||
| 8 | const SECRET = 'whsec_test_secret' | |
| 9 | const PERIOD_END = 1_800_000_000 | |
| 10 | ||
| 11 | function memoryStore(): LicenseStore & { rows: LicenseRecord[] } { | |
| 12 | const rows: LicenseRecord[] = [] | |
| 13 | return { | |
| 14 | rows, | |
| 15 | byKey: async key => rows.find(r => r.key === key) ?? null, | |
| 16 | bySession: async id => rows.find(r => r.stripeCheckoutSessionId === id) ?? null, | |
| 17 | create: async (license) => { rows.push({ ...license }) }, | |
| 18 | update: async (key, patch) => { Object.assign(rows.find(r => r.key === key)!, patch) }, | |
| 19 | } | |
| 20 | } | |
| 21 | ||
| 22 | function fakeStripe(): LicenseStripe { | |
| 23 | const sessions: Record<string, any> = { | |
| 24 | cs_test_monthly: { status: 'complete', payment_status: 'paid', metadata: { plan: 'monthly' }, subscription: 'sub_1', customer: 'cus_1', customer_details: { email: 'a@example.com' } }, | |
| 25 | // Paid by a method that settles after the redirect: `completed` arrives | |
| 26 | // while this is still unpaid, and `async_payment_succeeded` follows. | |
| 27 | cs_test_pending: { status: 'complete', payment_status: 'unpaid', metadata: { plan: 'monthly' }, subscription: 'sub_1', customer: 'cus_2', customer_details: { email: 'b@example.com' } }, | |
| 28 | } | |
| 29 | return { | |
| 30 | checkoutSession: async (id: string) => sessions[id], | |
| 31 | subscription: async () => ({ status: 'active', items: { data: [{ current_period_end: PERIOD_END }] }, cancel_at_period_end: false }) as any, | |
| 32 | } | |
| 33 | } | |
| 34 | ||
| 35 | /** A delivery as Stripe sends it: the signature is over these exact bytes. */ | |
| 36 | function delivery(type: string, sessionId: string, at = Math.floor(Date.now() / 1000)): { raw: string, signature: string } { | |
| 37 | const raw = JSON.stringify({ id: 'evt_1', type, data: { object: { object: 'checkout.session', id: sessionId } } }) | |
| 38 | return { raw, signature: sign(raw, at) } | |
| 39 | } | |
| 40 | ||
| 41 | function sign(raw: string, at: number, secret = SECRET): string { | |
| 42 | return `t=${at},v1=${createHmac('sha256', secret).update(`${at}.${raw}`).digest('hex')}` | |
| 43 | } | |
| 44 | ||
| 45 | /** The webhook and the thank-you page both go through `issue`. */ | |
| 46 | function billing() { | |
| 47 | const store = memoryStore() | |
| 48 | const emails: string[] = [] | |
| 49 | const licenses = new Licenses(store, fakeStripe(), undefined, async (license) => { emails.push(license.key) }) | |
| 50 | return { | |
| 51 | store, | |
| 52 | emails, | |
| 53 | page: (sessionId: string) => licenses.issue(sessionId), | |
| 54 | post: (sent: { raw: string, signature: string }, secret = SECRET) => | |
| 55 | receiveWebhook(sent.raw, sent.signature, { secret, issue: id => licenses.issue(id) }), | |
| 56 | } | |
| 57 | } | |
| 58 | ||
| 59 | describe('the Stripe webhook', () => { | |
| 60 | it('issues the license for a paid checkout, and says nothing about the key', async () => { | |
| 61 | const { post, store, emails } = billing() | |
| 62 | const outcome = await post(delivery('checkout.session.completed', 'cs_test_monthly')) | |
| 63 | ||
| 64 | expect(outcome.kind).toBe('licensed') | |
| 65 | expect(statusFor(outcome)).toBe(200) | |
| 66 | expect(store.rows).toHaveLength(1) | |
| 67 | expect(emails).toHaveLength(1) | |
| 68 | // The reply goes to Stripe, not to a buyer, so it carries no key. | |
| 69 | expect(JSON.stringify(bodyFor(outcome))).not.toContain(store.rows[0].key) | |
| 70 | }) | |
| 71 | ||
| 72 | it('issues on the event that follows a payment settling after the redirect', async () => { | |
| 73 | const { post, store } = billing() | |
| 74 | // `completed` arrives first, while Stripe still says unpaid. Retrying that | |
| 75 | // would not help, so it is acknowledged rather than failed. | |
| 76 | const early = await post(delivery('checkout.session.completed', 'cs_test_pending')) | |
| 77 | expect(early.kind).toBe('ignored') | |
| 78 | expect(statusFor(early)).toBe(200) | |
| 79 | expect(store.rows).toHaveLength(0) | |
| 80 | }) | |
| 81 | ||
| 82 | /** | |
| 83 | * The acceptance for #48: the webhook and the thank-you page can arrive in | |
| 84 | * either order, or twice, and the buyer ends up with one license and one | |
| 85 | * email. `issue` was already idempotent, so this pins it rather than adding | |
| 86 | * anything. | |
| 87 | */ | |
| 88 | it('produces one license and one email however the two arrive', async () => { | |
| 89 | for (const order of ['webhook first', 'page first'] as const) { | |
| 90 | const { post, page, store, emails } = billing() | |
| 91 | const sent = delivery('checkout.session.completed', 'cs_test_monthly') | |
| 92 | ||
| 93 | if (order === 'webhook first') { | |
| 94 | await post(sent) | |
| 95 | await post(sent) | |
| 96 | await page('cs_test_monthly') | |
| 97 | } | |
| 98 | else { | |
| 99 | await page('cs_test_monthly') | |
| 100 | await post(sent) | |
| 101 | await post(sent) | |
| 102 | } | |
| 103 | ||
| 104 | expect(store.rows).toHaveLength(1) | |
| 105 | expect(emails).toHaveLength(1) | |
| 106 | } | |
| 107 | }) | |
| 108 | ||
| 109 | it('acknowledges an event it has nothing to do with, rather than failing it', async () => { | |
| 110 | const { post, store } = billing() | |
| 111 | const outcome = await post(delivery('invoice.paid', 'cs_test_monthly')) | |
| 112 | expect(outcome.kind).toBe('ignored') | |
| 113 | expect(statusFor(outcome)).toBe(200) | |
| 114 | expect(store.rows).toHaveLength(0) | |
| 115 | }) | |
| 116 | ||
| 117 | it('refuses anything it cannot verify, and issues nothing', async () => { | |
| 118 | const { post, store, emails } = billing() | |
| 119 | const sent = delivery('checkout.session.completed', 'cs_test_monthly') | |
| 120 | ||
| 121 | const cases = [ | |
| 122 | ['signed with another secret', { ...sent, signature: sign(sent.raw, Math.floor(Date.now() / 1000), 'whsec_someone_else') }], | |
| 123 | ['no signature at all', { ...sent, signature: '' }], | |
| 124 | ['a body swapped after signing', { raw: sent.raw.replace('cs_test_monthly', 'cs_test_other'), signature: sent.signature }], | |
| 125 | ['an empty body', { raw: '', signature: sent.signature }], | |
| 126 | ['replayed from an hour ago', delivery('checkout.session.completed', 'cs_test_monthly', Math.floor(Date.now() / 1000) - 3600)], | |
| 127 | ] as const | |
| 128 | ||
| 129 | for (const [what, sentCase] of cases) { | |
| 130 | const outcome = await post(sentCase) | |
| 131 | expect(`${what}: ${outcome.kind}`).toBe(`${what}: rejected`) | |
| 132 | expect(statusFor(outcome)).toBe(400) | |
| 133 | } | |
| 134 | expect(store.rows).toHaveLength(0) | |
| 135 | expect(emails).toHaveLength(0) | |
| 136 | }) | |
| 137 | ||
| 138 | it('refuses a signed body that is not a Stripe event', async () => { | |
| 139 | const { post } = billing() | |
| 140 | for (const raw of ['not json', '{}', '[]', JSON.stringify({ type: 'checkout.session.completed', data: { object: { object: 'invoice', id: 'in_1' } } })]) { | |
| 141 | const outcome = await post({ raw, signature: sign(raw, Math.floor(Date.now() / 1000)) }) | |
| 142 | expect(outcome.kind).toBe('rejected') | |
| 143 | } | |
| 144 | }) | |
| 145 | ||
| 146 | /** | |
| 147 | * No secret means nothing can be verified, so nothing may be issued. A 500 | |
| 148 | * rather than a 200, because Stripe retries a 500 for days and this is a | |
| 149 | * misconfiguration someone can still fix in that time. | |
| 150 | */ | |
| 151 | it('issues nothing when the server has no signing secret', async () => { | |
| 152 | const { post, store } = billing() | |
| 153 | const outcome = await post(delivery('checkout.session.completed', 'cs_test_monthly'), '') | |
| 154 | expect(outcome.kind).toBe('unconfigured') | |
| 155 | expect(statusFor(outcome)).toBe(500) | |
| 156 | expect(store.rows).toHaveLength(0) | |
| 157 | }) | |
| 158 | ||
| 159 | it('asks Stripe to try again when issuing fails for a reason that might pass', async () => { | |
| 160 | const sent = delivery('checkout.session.completed', 'cs_test_monthly') | |
| 161 | const outcome = await receiveWebhook(sent.raw, sent.signature, { | |
| 162 | secret: SECRET, | |
| 163 | issue: async () => { throw new Error('the database is down') }, | |
| 164 | }) | |
| 165 | expect(outcome.kind).toBe('failed') | |
| 166 | expect(statusFor(outcome)).toBe(500) | |
| 167 | expect(bodyFor(outcome)).toEqual({ error: 'the database is down' }) | |
| 168 | }) | |
| 169 | ||
| 170 | it('reads its secret from the environment, trimmed', () => { | |
| 171 | expect(webhookSecret({ STRIPE_WEBHOOK_SECRET: ' whsec_x \n' })).toBe('whsec_x') | |
| 172 | expect(webhookSecret({})).toBe('') | |
| 173 | }) | |
| 174 | }) | |
| 175 | ||
| 176 | /** | |
| 177 | * The action itself, not the module under it. The one thing that cannot be | |
| 178 | * caught by reading the code is whether it verifies the bytes Stripe sent or a | |
| 179 | * re-serialized body, and a re-serialized one never matches the HMAC. | |
| 180 | */ | |
| 181 | describe('the webhook action', () => { | |
| 182 | function fakeRequest(raw: string, signature: string | null) { | |
| 183 | const reads = { rawBody: 0, parsed: 0 } | |
| 184 | return { | |
| 185 | reads, | |
| 186 | request: { | |
| 187 | headers: new Headers(signature === null ? {} : { 'stripe-signature': signature }), | |
| 188 | rawBody: async () => { reads.rawBody++; return raw }, | |
| 189 | // If the action ever reached for these, the signature would be over | |
| 190 | // bytes it never saw. | |
| 191 | get all() { reads.parsed++; return () => JSON.parse(raw) }, | |
| 192 | get jsonBody() { reads.parsed++; return JSON.parse(raw) }, | |
| 193 | } as any, | |
| 194 | } | |
| 195 | } | |
| 196 | ||
| 197 | it('verifies the bytes on the wire, not the parsed body', async () => { | |
| 198 | const action = (await import('../../../app/Actions/Billing/StripeWebhookAction')).default | |
| 199 | const sent = delivery('checkout.session.completed', 'cs_test_monthly') | |
| 200 | // Signed correctly, but this server has no secret, so it stops before | |
| 201 | // anything touches the database. | |
| 202 | const { request, reads } = fakeRequest(sent.raw, sent.signature) | |
| 203 | ||
| 204 | const answer = await action.handle(request) | |
| 205 | expect(answer.status).toBe(500) | |
| 206 | expect(reads.rawBody).toBe(1) | |
| 207 | expect(reads.parsed).toBe(0) | |
| 208 | }) | |
| 209 | ||
| 210 | it('answers 400 for a delivery it cannot verify', async () => { | |
| 211 | const action = (await import('../../../app/Actions/Billing/StripeWebhookAction')).default | |
| 212 | const sent = delivery('checkout.session.completed', 'cs_test_monthly') | |
| 213 | process.env.STRIPE_WEBHOOK_SECRET = SECRET | |
| 214 | try { | |
| 215 | const { request } = fakeRequest(sent.raw, 't=1,v1=deadbeef') | |
| 216 | expect((await action.handle(request)).status).toBe(400) | |
| 217 | ||
| 218 | const missing = fakeRequest(sent.raw, null) | |
| 219 | expect((await action.handle(missing.request)).status).toBe(400) | |
| 220 | } | |
| 221 | finally { | |
| 222 | delete process.env.STRIPE_WEBHOOK_SECRET | |
| 223 | } | |
| 224 | }) | |
| 225 | }) | |