import { describe, expect, it, mock } from 'bun:test'; import { createHmac } from 'node:crypto'; import { err, ok } from '@gruperly/shared'; import { billingProviderErrorProblem } from '@/http/problem-builders'; import { isPublicApiRequest } from '@/http/session-auth'; import { HandleBillingWebhook } from '@/modules/billing/features/webhook/use-case'; import { MercadoPagoBillingProvider, type PreapprovalClient, verifyMpSignature, } from '@/modules/billing/providers/mercado-pago'; import { StripeBillingProvider } from '@/modules/billing/providers/stripe'; const secret = 'webhook-secret'; const credentials = () => ({ accessToken: 'platform-token', webhookSecret: secret }); function sign(dataId: string, requestId: string, ts = '1729600000') { const v1 = createHmac('sha256', secret).update(`id:${dataId};request-id:${requestId};ts:${ts};`).digest('hex'); return `ts=${ts},v1=${v1}`; } function request(params: { type: string; dataId: string; requestId?: string; signature?: string }) { const requestId = params.requestId ?? 'req-1'; return { routeParam: 'ar', rawBody: JSON.stringify({ type: params.type, data: { id: params.dataId } }), headers: new Headers({ 'x-request-id': requestId, 'x-signature': params.signature ?? sign(params.dataId, requestId), }), query: new URLSearchParams({ 'data.id': params.dataId, type: params.type }), }; } function makeDeps(syncResult = ok({ synced: true, status: 'AUTHORIZED' as const })) { const db = { billingWebhookEvent: { create: mock(async () => ({})), delete: mock(async () => ({})), }, }; const sync = { byExternalId: mock(async () => syncResult) }; const client = { getAuthorizedPayment: mock(async () => ({ id: 'inv-1', preapprovalId: 'pre-9' })), } as unknown as PreapprovalClient; return { db, sync, client }; } function handler(deps: ReturnType) { const provider = new MercadoPagoBillingProvider({ client: deps.client, credentials }); return new HandleBillingWebhook({ db: deps.db as never, sync: deps.sync as never, providers: () => provider }); } describe('verifyMpSignature', () => { it('accepts Mercado Pago signatures and lower-cases alphanumeric ids', () => { const signature = sign('abc123', 'req-1'); expect(verifyMpSignature({ signature, requestId: 'req-1', dataId: 'ABC123', secret })).toBe(true); }); it('rejects a tampered or missing signature', () => { expect(verifyMpSignature({ signature: sign('1', 'req-1'), requestId: 'req-1', dataId: '2', secret })).toBe(false); expect(verifyMpSignature({ signature: 'ts=1,v1=short', requestId: 'req-1', dataId: '1', secret })).toBe(false); expect(verifyMpSignature({ signature: null, requestId: 'req-1', dataId: '1', secret })).toBe(false); }); }); describe('HandleBillingWebhook', () => { it('rejects a bad signature before touching anything', async () => { const deps = makeDeps(); const result = await handler(deps).execute( 'MERCADO_PAGO', request({ type: 'subscription_preapproval', dataId: 'pre-1', signature: 'ts=1,v1=deadbeef' }), ); expect(result).toEqual(err('invalid_signature')); expect(deps.db.billingWebhookEvent.create).not.toHaveBeenCalled(); expect(deps.sync.byExternalId).not.toHaveBeenCalled(); }); it('re-fetches the preapproval instead of trusting the body', async () => { const deps = makeDeps(); const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_preapproval', dataId: 'pre-1' })); expect(result).toEqual(ok({ duplicate: false, applied: true })); expect(deps.sync.byExternalId).toHaveBeenCalledWith('MERCADO_PAGO', 'pre-1', 'AR'); expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { source: 'mp:AR', dedupeKey: 'req-1' } }); }); it('resolves an invoice notification to its subscription', async () => { const deps = makeDeps(); await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_authorized_payment', dataId: 'inv-1' })); expect(deps.client.getAuthorizedPayment).toHaveBeenCalledWith('platform-token', 'inv-1'); expect(deps.sync.byExternalId).toHaveBeenCalledWith('MERCADO_PAGO', 'pre-9', 'AR'); }); it('answers a repeated delivery as a duplicate', async () => { const deps = makeDeps(); deps.db.billingWebhookEvent.create = mock(async () => { throw Object.assign(new Error('unique'), { code: 'P2002' }); }); const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_preapproval', dataId: 'pre-1' })); expect(result).toEqual(ok({ duplicate: true, applied: false })); expect(deps.sync.byExternalId).not.toHaveBeenCalled(); }); it('un-burns the dedupe key when syncing fails, so the retry gets in', async () => { const deps = makeDeps(err(billingProviderErrorProblem()) as never); const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_preapproval', dataId: 'pre-1' })); expect(result).toEqual(err('sync_failed')); expect(deps.db.billingWebhookEvent.delete).toHaveBeenCalledWith({ where: { source_dedupeKey: { source: 'mp:AR', dedupeKey: 'req-1' } }, }); }); it('acknowledges topics it does not handle', async () => { const deps = makeDeps(); const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'payment', dataId: '123' })); expect(result).toEqual(ok({ duplicate: false, applied: false })); expect(deps.sync.byExternalId).not.toHaveBeenCalled(); }); it('is reachable without a session, and only that path', () => { expect(isPublicApiRequest('POST', '/api/v1/billing/webhooks/mp/ar')).toBe(true); expect(isPublicApiRequest('POST', '/api/v1/billing/webhooks/stripe')).toBe(true); expect(isPublicApiRequest('GET', '/api/v1/billing/webhooks/stripe')).toBe(false); expect(isPublicApiRequest('GET', '/api/v1/billing/webhooks/mp/ar')).toBe(false); expect(isPublicApiRequest('POST', '/api/v1/billing/subscribe')).toBe(false); }); }); const stripeSecret = 'whsec_test'; const stripeNow = new Date('2026-10-22T12:00:00.000Z'); function stripeRequest(event: Record, signature?: string) { const rawBody = JSON.stringify(event); const t = Math.floor(stripeNow.getTime() / 1000); const v1 = createHmac('sha256', stripeSecret).update(`${t}.${rawBody}`).digest('hex'); return { routeParam: null, rawBody, headers: new Headers({ 'stripe-signature': signature ?? `t=${t},v1=${v1}` }), query: new URLSearchParams(), }; } function stripeHandler(deps: ReturnType) { const provider = new StripeBillingProvider({ config: () => ({ secretKey: 'sk_test', webhookSecret: stripeSecret }), fetch: mock(async () => { throw new Error('the webhook must not call Stripe'); }) as never, now: () => stripeNow, }); return new HandleBillingWebhook({ db: deps.db as never, sync: deps.sync as never, providers: () => provider }); } describe('HandleBillingWebhook with Stripe', () => { it('syncs the subscription of a completed checkout, deduplicated by event id', async () => { const deps = makeDeps(); const result = await stripeHandler(deps).execute( 'STRIPE', stripeRequest({ id: 'evt_1', type: 'checkout.session.completed', data: { object: { id: 'cs_1', mode: 'subscription', subscription: 'sub_1' } }, }), ); expect(result).toEqual(ok({ duplicate: false, applied: true })); expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { source: 'stripe', dedupeKey: 'evt_1' } }); expect(deps.sync.byExternalId).toHaveBeenCalledWith('STRIPE', 'sub_1', null); }); it('finds the subscription of an invoice event', async () => { const deps = makeDeps(); await stripeHandler(deps).execute( 'STRIPE', stripeRequest({ id: 'evt_2', type: 'invoice.paid', data: { object: { id: 'in_1', parent: { subscription_details: { subscription: 'sub_2' } } } }, }), ); expect(deps.sync.byExternalId).toHaveBeenCalledWith('STRIPE', 'sub_2', null); }); it('rejects a bad signature', async () => { const deps = makeDeps(); const result = await stripeHandler(deps).execute( 'STRIPE', stripeRequest({ id: 'evt_3', type: 'invoice.paid', data: { object: {} } }, 't=1,v1=deadbeef'), ); expect(result).toEqual(err('invalid_signature')); expect(deps.db.billingWebhookEvent.create).not.toHaveBeenCalled(); }); it('acknowledges events that do not concern a subscription', async () => { const deps = makeDeps(); const result = await stripeHandler(deps).execute( 'STRIPE', stripeRequest({ id: 'evt_4', type: 'customer.created', data: { object: { id: 'cus_1' } } }), ); expect(result).toEqual(ok({ duplicate: false, applied: false })); expect(deps.sync.byExternalId).not.toHaveBeenCalled(); }); });