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 type { PreapprovalClient } from '@/modules/billing/lib'; import { verifyMpSignature } from '@/modules/billing/lib/webhook-signature'; const secret = 'webhook-secret'; const credentials = () => ok({ 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 { country: '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 = { byPreapprovalId: 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) { return new HandleBillingWebhook({ db: deps.db as never, sync: deps.sync as never, client: deps.client, credentials, }); } 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( 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.byPreapprovalId).not.toHaveBeenCalled(); }); it('re-fetches the preapproval instead of trusting the body', async () => { const deps = makeDeps(); const result = await handler(deps).execute(request({ type: 'subscription_preapproval', dataId: 'pre-1' })); expect(result).toEqual(ok({ duplicate: false, applied: true })); expect(deps.sync.byPreapprovalId).toHaveBeenCalledWith('AR', 'pre-1'); expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { country: 'AR', dedupeKey: 'req-1' } }); }); it('resolves an invoice notification to its subscription', async () => { const deps = makeDeps(); await handler(deps).execute(request({ type: 'subscription_authorized_payment', dataId: 'inv-1' })); expect(deps.client.getAuthorizedPayment).toHaveBeenCalledWith('platform-token', 'inv-1'); expect(deps.sync.byPreapprovalId).toHaveBeenCalledWith('AR', 'pre-9'); }); 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(request({ type: 'subscription_preapproval', dataId: 'pre-1' })); expect(result).toEqual(ok({ duplicate: true, applied: false })); expect(deps.sync.byPreapprovalId).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(request({ type: 'subscription_preapproval', dataId: 'pre-1' })); expect(result).toEqual(err('sync_failed')); expect(deps.db.billingWebhookEvent.delete).toHaveBeenCalledWith({ where: { country_dedupeKey: { country: 'AR', dedupeKey: 'req-1' } }, }); }); it('acknowledges topics it does not handle', async () => { const deps = makeDeps(); const result = await handler(deps).execute(request({ type: 'payment', dataId: '123' })); expect(result).toEqual(ok({ duplicate: false, applied: false })); expect(deps.sync.byPreapprovalId).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('GET', '/api/v1/billing/webhooks/mp/ar')).toBe(false); expect(isPublicApiRequest('POST', '/api/v1/billing/subscribe')).toBe(false); }); });