import { describe, expect, it, mock } from 'bun:test'; import { createHmac } from 'node:crypto'; import { fromStripeUnitAmount, StripeBillingProvider, toForm, toStripeUnitAmount, verifyStripeSignature, } from '@/modules/billing/providers/stripe'; const now = new Date('2026-10-22T12:00:00.000Z'); const seconds = (date: Date) => Math.floor(date.getTime() / 1000); type Call = { url: string; method: string; body: URLSearchParams | null }; /** A fake `fetch` answering by "METHOD path" (query left out). */ function fakeStripe(routes: Record) { const calls: Call[] = []; const fetch = mock(async (input: string, init: RequestInit) => { const url = new URL(input); const method = init.method ?? 'GET'; calls.push({ url: input, method, body: init.body ? new URLSearchParams(String(init.body)) : null }); const key = `${method} ${url.pathname.replace('/v1', '')}`; if (!(key in routes)) return new Response(JSON.stringify({ error: { code: 'resource_missing' } }), { status: 404 }); return new Response(JSON.stringify(routes[key])); }); const provider = new StripeBillingProvider({ config: () => ({ secretKey: 'sk_test', webhookSecret: 'whsec' }), fetch: fetch as never, now: () => now, }); return { provider, calls }; } const startInput = { userId: 'user-1', country: 'MX' as const, amount: 199, currency: 'MXN', payerEmail: null, backUrl: 'http://web/billing?sub=return', }; describe('Stripe amounts', () => { it('uses minor units except for zero-decimal currencies', () => { expect(toStripeUnitAmount(199, 'MXN')).toBe(19900); expect(toStripeUnitAmount(9900, 'CLP')).toBe(9900); expect(fromStripeUnitAmount(19900, 'mxn')).toBe(199); expect(fromStripeUnitAmount(9900, 'clp')).toBe(9900); }); it('encodes nested params the way Stripe expects', () => { const form = toForm({ a: { b: [{ c: 1 }] }, skip: null }); expect(form.toString()).toBe(new URLSearchParams({ 'a[b][0][c]': '1' }).toString()); }); }); describe('StripeBillingProvider.start', () => { it('opens a subscription checkout priced inline in the local currency', async () => { const { provider, calls } = fakeStripe({ 'POST /checkout/sessions': { id: 'cs_1', url: 'https://checkout.stripe.com/cs_1' }, }); const started = await provider.start(startInput); expect(started).toEqual({ checkoutUrl: 'https://checkout.stripe.com/cs_1', externalId: null, checkoutRef: 'cs_1' }); const body = calls[0]?.body; expect(body?.get('mode')).toBe('subscription'); expect(body?.get('client_reference_id')).toBe('user-1'); expect(body?.get('line_items[0][price_data][currency]')).toBe('mxn'); expect(body?.get('line_items[0][price_data][unit_amount]')).toBe('19900'); expect(body?.get('line_items[0][price_data][recurring][interval]')).toBe('month'); expect(body?.get('subscription_data[metadata][gruperly_user_id]')).toBe('user-1'); expect(body?.has('customer_email')).toBe(false); expect(body?.has('subscription_data[trial_end]')).toBe(false); }); it('defers the first charge to the end of a paid period', async () => { const { provider, calls } = fakeStripe({ 'POST /checkout/sessions': { id: 'cs_1', url: 'https://x' } }); const startDate = new Date('2026-11-10T00:00:00.000Z'); await provider.start({ ...startInput, startDate }); expect(calls[0]?.body?.get('subscription_data[trial_end]')).toBe(String(seconds(startDate))); }); it('charges right away when the paid period ends sooner than Checkout allows', async () => { const { provider, calls } = fakeStripe({ 'POST /checkout/sessions': { id: 'cs_1', url: 'https://x' } }); await provider.start({ ...startInput, startDate: new Date('2026-10-23T00:00:00.000Z') }); expect(calls[0]?.body?.has('subscription_data[trial_end]')).toBe(false); }); }); describe('StripeBillingProvider.fetch', () => { it('is null while the checkout is open', async () => { const { provider } = fakeStripe({ 'GET /checkout/sessions/cs_1': { id: 'cs_1', status: 'open', subscription: null } }); expect(await provider.fetch({ country: 'MX', externalId: null, checkoutRef: 'cs_1' })).toBeNull(); }); it('resolves the subscription through a completed checkout', async () => { const periodEnd = new Date('2026-11-22T12:00:00.000Z'); const { provider } = fakeStripe({ 'GET /checkout/sessions/cs_1': { id: 'cs_1', status: 'complete', subscription: 'sub_1', customer_details: { email: 'card@mail.com' }, }, 'GET /subscriptions/sub_1': { id: 'sub_1', status: 'active', metadata: { gruperly_user_id: 'user-1' }, items: { data: [{ current_period_end: seconds(periodEnd) }] }, customer: { id: 'cus_1', email: 'other@mail.com' }, }, }); expect(await provider.fetch({ country: 'MX', externalId: null, checkoutRef: 'cs_1' })).toEqual({ externalId: 'sub_1', ownerUserId: 'user-1', status: 'AUTHORIZED', nextPaymentDate: periodEnd, payerEmail: 'card@mail.com', }); }); it('maps Stripe statuses to ours', async () => { const statusOf = async (status: string) => { const { provider } = fakeStripe({ 'GET /subscriptions/sub_1': { id: 'sub_1', status, metadata: {}, items: { data: [] } }, }); return (await provider.fetch({ country: null, externalId: 'sub_1', checkoutRef: null }))?.status; }; expect(await statusOf('incomplete')).toBe('PENDING'); expect(await statusOf('past_due')).toBe('AUTHORIZED'); expect(await statusOf('unpaid')).toBe('PAUSED'); expect(await statusOf('canceled')).toBe('CANCELLED'); expect(await statusOf('something_new')).toBeNull(); }); }); describe('StripeBillingProvider.listCharges', () => { it('turns invoices into charges covering their period', async () => { const paidAt = new Date('2026-10-22T12:00:00.000Z'); const periodEnd = new Date('2026-11-22T12:00:00.000Z'); const { provider } = fakeStripe({ 'GET /invoices': { data: [ { id: 'in_1', status: 'paid', total: 19900, amount_paid: 19900, currency: 'mxn', status_transitions: { paid_at: seconds(paidAt) }, lines: { data: [{ period: { end: seconds(periodEnd) } }] }, }, { id: 'in_2', status: 'open', total: 19900, amount_due: 19900, currency: 'mxn' }, { id: 'in_3', status: 'uncollectible', total: 19900, amount_due: 19900, currency: 'mxn' }, { id: 'in_trial', status: 'paid', total: 0, amount_paid: 0, currency: 'mxn' }, { id: 'in_draft', status: 'draft', total: 19900, currency: 'mxn' }, ], }, }); const charges = await provider.listCharges({ country: 'MX', externalId: 'sub_1', checkoutRef: null }); expect(charges).toEqual([ { externalId: 'in_1', amount: 199, currency: 'MXN', status: 'approved', paidAt, coveredUntil: periodEnd }, { externalId: 'in_2', amount: 199, currency: 'MXN', status: 'pending', paidAt: null, coveredUntil: null }, { externalId: 'in_3', amount: 199, currency: 'MXN', status: 'rejected', paidAt: null, coveredUntil: null }, ]); }); }); describe('StripeBillingProvider.cancel', () => { it('cancels a live subscription', async () => { const { provider, calls } = fakeStripe({ 'DELETE /subscriptions/sub_1': { id: 'sub_1', status: 'canceled' } }); await provider.cancel({ country: 'MX', externalId: 'sub_1', checkoutRef: 'cs_1' }); expect(calls.map((call) => `${call.method} ${new URL(call.url).pathname}`)).toEqual(['DELETE /v1/subscriptions/sub_1']); }); it('expires a checkout that is still open', async () => { const { provider, calls } = fakeStripe({ 'GET /checkout/sessions/cs_1': { id: 'cs_1', status: 'open' }, 'POST /checkout/sessions/cs_1/expire': { id: 'cs_1', status: 'expired' }, }); await provider.cancel({ country: 'MX', externalId: null, checkoutRef: 'cs_1' }); expect(calls.map((call) => call.method)).toEqual(['GET', 'POST']); }); it('cancels the subscription of a checkout completed meanwhile', async () => { const { provider, calls } = fakeStripe({ 'GET /checkout/sessions/cs_1': { id: 'cs_1', status: 'complete', subscription: 'sub_1' }, 'DELETE /subscriptions/sub_1': { id: 'sub_1' }, }); await provider.cancel({ country: 'MX', externalId: null, checkoutRef: 'cs_1' }); expect(calls.at(-1)?.method).toBe('DELETE'); }); }); describe('StripeBillingProvider without credentials', () => { it('is not available and refuses to call Stripe', async () => { const provider = new StripeBillingProvider({ config: () => null }); expect(provider.isAvailable('MX')).toBe(false); await expect(provider.start(startInput)).rejects.toThrow('not configured'); }); }); describe('verifyStripeSignature', () => { const secret = 'whsec_test'; const rawBody = '{"id":"evt_1"}'; const t = seconds(now); const sign = (ts: number, body = rawBody) => createHmac('sha256', secret).update(`${ts}.${body}`).digest('hex'); it('accepts a valid signature, including one among several v1', () => { expect(verifyStripeSignature({ signature: `t=${t},v1=${sign(t)}`, rawBody, secret, now })).toBe(true); expect(verifyStripeSignature({ signature: `t=${t},v1=${'0'.repeat(64)},v1=${sign(t)}`, rawBody, secret, now })).toBe( true, ); }); it('rejects a tampered body, a missing header and an old timestamp', () => { expect(verifyStripeSignature({ signature: `t=${t},v1=${sign(t)}`, rawBody: '{"id":"evt_2"}', secret, now })).toBe( false, ); expect(verifyStripeSignature({ signature: null, rawBody, secret, now })).toBe(false); const old = t - 10 * 60; expect(verifyStripeSignature({ signature: `t=${old},v1=${sign(old)}`, rawBody, secret, now })).toBe(false); }); });