Files
gruperly/apps/backend/test/whatsapp-providers.test.ts
Jose Selesan f4d2c26e29 feat(whatsapp): vincular con el número de teléfono además del QR
Desde el teléfono no se puede escanear el QR de la propia pantalla. Con
OpenWA el profesor ahora puede escribir su número y recibir un código de
8 caracteres para ingresar en WhatsApp (POST /whatsapp/connect/pairing-code).
En mobile el modal arranca por el número y en desktop por el QR.

- Puerto: requestPairingCode opcional (Kapso no lo implementa).
- OpenWA: reintenta el 409 mientras la sesión arranca.
- Número normalizado con el país del profesor (toWhatsappE164).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:15:02 -03:00

642 lines
23 KiB
TypeScript

import { describe, expect, it, mock } from 'bun:test';
import { createHmac } from 'node:crypto';
import { KapsoProvider } from '@/modules/whatsapp/providers/kapso';
import type { WhatsappAccountRecord } from '@/modules/whatsapp/providers/messaging-provider';
import { OpenWaProvider, openWaSessionName } from '@/modules/whatsapp/providers/openwa';
/* Both adapters against a recorded `fetch`: the requests they make and how they
read the answers. No network, no `mock.module`. */
type Route = { method: string; path: string; status?: number; body?: unknown };
function fakeFetch(routes: Route[]) {
const calls: { method: string; url: string; headers: Record<string, string>; body: unknown }[] = [];
const fn = mock(async (url: string, init?: RequestInit) => {
const method = init?.method ?? 'GET';
calls.push({
method,
url,
headers: (init?.headers ?? {}) as Record<string, string>,
body: init?.body ? JSON.parse(String(init.body)) : undefined,
});
const route = routes.find((candidate) => candidate.method === method && url.endsWith(candidate.path));
if (!route) return new Response(JSON.stringify({ statusCode: 404 }), { status: 404 });
return new Response(route.body === undefined ? null : JSON.stringify(route.body), {
status: route.status ?? 200,
});
});
return { fn, calls };
}
const openWaConfig = {
apiUrl: 'http://openwa:2785/api',
apiKey: 'owa_k1_test',
webhookUrl: 'https://api.example.com/api/v1/whatsapp/webhooks/openwa',
webhookSecret: 'a-very-long-webhook-secret',
};
function openWaAccount(overrides: Partial<WhatsappAccountRecord> = {}): WhatsappAccountRecord {
return {
id: 'wa-1',
ownerId: 'user-1',
provider: 'OPENWA',
status: 'ACTIVE',
externalId: 'sess-1',
displayPhoneNumber: null,
providerData: { sessionName: 'gruperly-user-1', webhookId: 'wh-1' },
...overrides,
};
}
function sign(body: string, secret: string) {
return createHmac('sha256', secret).update(body).digest('hex');
}
describe('OpenWA provider', () => {
it('creates a session, subscribes the webhook, starts it and returns the QR', async () => {
const { fn, calls } = fakeFetch([
{
method: 'POST',
path: '/sessions',
status: 201,
body: { id: 'sess-1', name: 'gruperly-user-1', status: 'created', engineLoaded: false },
},
{ method: 'POST', path: '/sessions/sess-1/webhooks', status: 201, body: { id: 'wh-1' } },
{
method: 'POST',
path: '/sessions/sess-1/start',
body: { id: 'sess-1', name: 'gruperly-user-1', status: 'initializing', engineLoaded: true },
},
{ method: 'GET', path: '/sessions/sess-1/qr', body: { qrCode: 'data:image/png;base64,QR', status: 'qr_ready' } },
]);
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
const result = await provider.startConnection({
ownerId: 'user-1',
ownerName: 'Ana',
returnTo: 'settings',
account: null,
});
expect(result).toEqual({
ok: true,
value: {
start: { type: 'qr', qrCode: 'data:image/png;base64,QR' },
externalId: 'sess-1',
providerData: { sessionName: 'gruperly-user-1', webhookId: 'wh-1' },
},
});
expect(calls[0]).toMatchObject({ method: 'POST', body: { name: 'gruperly-user-1' } });
expect(calls[0]?.headers['X-API-Key']).toBe('owa_k1_test');
expect(calls[1]?.body).toMatchObject({
url: openWaConfig.webhookUrl,
secret: openWaConfig.webhookSecret,
events: expect.arrayContaining(['message.ack', 'session.authenticated']),
});
});
it('adopts a session that already exists under the teacher name', async () => {
const { fn } = fakeFetch([
{ method: 'POST', path: '/sessions', status: 409, body: { statusCode: 409 } },
{
method: 'GET',
path: '/sessions?name=gruperly-user-1',
body: [{ id: 'sess-9', name: 'gruperly-user-1', status: 'qr_ready', engineLoaded: true }],
},
{ method: 'POST', path: '/sessions/sess-9/webhooks', status: 201, body: { id: 'wh-9' } },
{ method: 'GET', path: '/sessions/sess-9/qr', status: 400, body: { statusCode: 400 } },
]);
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
const result = await provider.startConnection({
ownerId: 'user-1',
ownerName: 'Ana',
returnTo: 'settings',
account: null,
});
expect(result.ok && result.value).toMatchObject({
start: { type: 'qr', qrCode: null },
externalId: 'sess-9',
});
});
it('answers a provider problem when OpenWA is down', async () => {
const fn = mock(async () => {
throw new TypeError('fetch failed');
});
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
const result = await provider.startConnection({
ownerId: 'user-1',
ownerName: 'Ana',
returnTo: 'settings',
account: null,
});
expect(!result.ok && result.error.code).toBe('whatsapp_provider_error');
});
it('maps session states', async () => {
const cases = [
[{ status: 'ready', phone: '5491123456789', engineLoaded: true }, { state: 'active', displayPhoneNumber: '+5491123456789' }],
[{ status: 'initializing', engineLoaded: true }, { state: 'pending', qrCode: null }],
[{ status: 'disconnected', engineLoaded: true }, { state: 'pending', qrCode: null }],
[{ status: 'failed', lastError: 'boom', engineLoaded: false }, { state: 'disconnected', reason: 'boom' }],
] as const;
for (const [session, expected] of cases) {
const { fn } = fakeFetch([{ method: 'GET', path: '/sessions/sess-1', body: { id: 'sess-1', ...session } }]);
const result = await new OpenWaProvider(openWaConfig, { fetch: fn }).refreshConnection(
openWaAccount({ status: 'PENDING' }),
);
expect(result).toEqual({ ok: true, value: expected as never });
}
});
it('resolves recipients through the contact check', async () => {
const { fn, calls } = fakeFetch([
{
method: 'GET',
path: '/sessions/sess-1/contacts/check/5491123456789',
body: { exists: true, whatsappId: '541123456789@c.us' },
},
]);
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
expect(await provider.resolveRecipient(openWaAccount(), '+5491123456789')).toEqual({
ok: true,
to: '541123456789@c.us',
});
expect(calls).toHaveLength(1);
});
it('sends free text with an idempotency key', async () => {
const { fn, calls } = fakeFetch([
{
method: 'POST',
path: '/sessions/sess-1/messages/send-text',
status: 201,
body: { messageId: 'true_5491123456789@c.us_3EB0', timestamp: 1 },
},
]);
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
const outcome = await provider.send(
openWaAccount(),
'5491123456789@c.us',
{ kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga' },
'msg-1',
);
expect(outcome).toEqual({ ok: true, providerMessageId: 'true_5491123456789@c.us_3EB0' });
expect(calls[0]?.headers['Idempotency-Key']).toBe('msg-1');
expect(calls[0]?.body).toMatchObject({ chatId: '5491123456789@c.us' });
expect(String((calls[0]?.body as { text?: string } | undefined)?.text)).toStartWith('¡Hola Ana!');
});
it('turns send pacing into a rate limit for the account', async () => {
const { fn } = fakeFetch([
{
method: 'POST',
path: '/sessions/sess-1/messages/send-text',
status: 429,
body: { statusCode: 429, code: 'SEND_PACING_LIMITED', retryAfterSeconds: 120 },
},
]);
const outcome = await new OpenWaProvider(openWaConfig, { fetch: fn }).send(
openWaAccount(),
'x@c.us',
{ kind: 'REENGAGEMENT', studentName: 'Ana', groupName: 'Yoga' },
'msg-1',
);
expect(outcome).toMatchObject({ ok: false, rateLimitedForMs: 120_000, code: 'SEND_PACING_LIMITED' });
});
it('verifies the webhook signature and normalizes acks and session events', () => {
const provider = new OpenWaProvider(openWaConfig);
const ack = JSON.stringify({
event: 'message.ack',
sessionId: 'sess-1',
idempotencyKey: 'ack_sess-1_m1_read',
deliveryId: 'dlv_1',
data: { id: 'row', messageId: 'm1', status: 'read', ack: 3 },
});
const good = new Headers({
'X-OpenWA-Signature': `sha256=${sign(ack, openWaConfig.webhookSecret)}`,
'X-OpenWA-Idempotency-Key': 'ack_sess-1_m1_read',
});
expect(provider.parseWebhook(ack, good)).toEqual({
ok: true,
value: {
dedupeKey: 'ack_sess-1_m1_read',
events: [{ type: 'message_status', providerMessageId: 'm1', status: 'READ', errorCode: null }],
},
});
const tampered = new Headers({ 'X-OpenWA-Signature': `sha256=${sign(`${ack} `, openWaConfig.webhookSecret)}` });
expect(provider.parseWebhook(ack, tampered)).toEqual({ ok: false, error: 'invalid_signature' });
expect(provider.parseWebhook(ack, new Headers())).toEqual({ ok: false, error: 'invalid_signature' });
const auth = JSON.stringify({
event: 'session.authenticated',
sessionId: 'sess-1',
idempotencyKey: 'auth_1',
data: { sessionId: 'sess-1', phone: '5491123456789' },
});
const authHeaders = new Headers({ 'X-OpenWA-Signature': `sha256=${sign(auth, openWaConfig.webhookSecret)}` });
expect(provider.parseWebhook(auth, authHeaders)).toEqual({
ok: true,
value: {
dedupeKey: 'auth_1',
events: [
{ type: 'connection', externalId: 'sess-1', status: 'active', displayPhoneNumber: '+5491123456789' },
],
},
});
});
it('builds valid session names', () => {
expect(openWaSessionName('cmh1x2y3z0000abcd')).toBe('gruperly-cmh1x2y3z0000abcd');
expect(openWaSessionName('weird_id.with@chars')).toBe('gruperly-weirdidwithchars');
});
it('asks OpenWA for a pairing code with the digits of the number', async () => {
const { fn, calls } = fakeFetch([
{
method: 'POST',
path: '/sessions/sess-1/pairing-code',
status: 201,
body: { pairingCode: 'ABCD1234', status: 'qr_ready' },
},
]);
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
const result = await provider.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789');
expect(result).toEqual({ ok: true, value: 'ABCD1234' });
expect(calls[0]?.body).toEqual({ phoneNumber: '5491123456789' });
});
it('waits while the session is not ready for a code, then gives up with 409', async () => {
let answered = 0;
const fn = mock(async () => {
answered += 1;
return answered < 3
? new Response(JSON.stringify({ statusCode: 409 }), { status: 409 })
: new Response(JSON.stringify({ pairingCode: 'WXYZ9876' }), { status: 201 });
});
const sleep = mock(async () => {});
const provider = new OpenWaProvider(openWaConfig, { fetch: fn, sleep });
const result = await provider.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789');
expect(result).toEqual({ ok: true, value: 'WXYZ9876' });
expect(sleep).toHaveBeenCalledTimes(2);
const busy = mock(async () => new Response(JSON.stringify({ statusCode: 409 }), { status: 409 }));
const stuck = new OpenWaProvider(openWaConfig, { fetch: busy, sleep });
const failed = await stuck.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789');
expect(failed.ok).toBe(false);
if (!failed.ok) expect(failed.error.code).toBe('whatsapp_pairing_not_ready');
});
});
const kapsoConfig = {
apiUrl: 'https://api.kapso.ai',
apiKey: 'kapso-key',
callbackUrl: 'https://api.example.com/api/v1/whatsapp/callback',
webhookUrl: 'https://api.example.com/api/v1/whatsapp/webhooks/kapso',
webhookSecret: 'kapso-webhook-secret',
};
function kapsoAccount(overrides: Partial<WhatsappAccountRecord> = {}): WhatsappAccountRecord {
return {
id: 'wa-1',
ownerId: 'user-1',
provider: 'KAPSO',
status: 'PENDING',
externalId: null,
displayPhoneNumber: null,
providerData: { customerId: 'cust-1', setupLinkId: 'link-1' },
...overrides,
};
}
function kapsoDb() {
return {
whatsappAccount: { update: mock(async () => ({})) },
whatsappTemplate: {
findUnique: mock(async () => null as unknown),
findMany: mock(async () => [] as unknown[]),
create: mock(async () => ({})),
update: mock(async () => ({})),
},
};
}
describe('Kapso provider', () => {
it('creates the customer once and a customer-billed setup link', async () => {
const { fn, calls } = fakeFetch([
{ method: 'POST', path: '/platform/v1/customers', status: 201, body: { data: { id: 'cust-1' } } },
{
method: 'POST',
path: '/platform/v1/customers/cust-1/setup_links',
status: 201,
body: { data: { id: 'link-1', url: 'https://app.kapso.ai/whatsapp/setup/abc' } },
},
]);
const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
const result = await provider.startConnection({
ownerId: 'user-1',
ownerName: 'Ana Profe',
returnTo: 'onboarding',
account: null,
});
expect(result).toEqual({
ok: true,
value: {
start: { type: 'redirect', url: 'https://app.kapso.ai/whatsapp/setup/abc' },
externalId: null,
providerData: { customerId: 'cust-1', setupLinkId: 'link-1' },
},
});
expect(calls[0]?.body).toEqual({ customer: { name: 'Ana Profe', external_customer_id: 'user-1' } });
expect(calls[1]?.body).toMatchObject({
setup_link: {
success_redirect_url: `${kapsoConfig.callbackUrl}?returnTo=onboarding`,
meta_billing_mode: 'customer_managed',
language: 'es',
},
});
// Linking again reuses the customer.
const again = fakeFetch([
{
method: 'POST',
path: '/platform/v1/customers/cust-1/setup_links',
status: 201,
body: { data: { id: 'link-2', url: 'https://app.kapso.ai/whatsapp/setup/def' } },
},
]);
await new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: again.fn }).startConnection({
ownerId: 'user-1',
ownerName: 'Ana',
returnTo: 'settings',
account: kapsoAccount(),
});
expect(again.calls).toHaveLength(1);
});
it('does not trust the callback query', async () => {
const { fn } = fakeFetch([
{
method: 'GET',
path: '/platform/v1/whatsapp/phone_numbers/phone-1',
body: {
data: {
phone_number_id: 'phone-1',
business_account_id: 'waba-1',
display_phone_number: '+54 9 11 2345-6789',
customer_id: 'someone-else',
},
},
},
]);
const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
expect(
await provider.completeRedirect(kapsoAccount(), { setup_link_id: 'other', phone_number_id: 'phone-1' }),
).toEqual({ ok: false, error: 'invalid_setup' });
expect(
await provider.completeRedirect(kapsoAccount(), { setup_link_id: 'link-1', error_code: 'facebook_auth_failed' }),
).toEqual({ ok: false, error: 'setup_failed' });
expect(
await provider.completeRedirect(kapsoAccount(), {
setup_link_id: 'link-1',
status: 'completed',
phone_number_id: 'phone-1',
}),
).toEqual({ ok: false, error: 'invalid_setup' });
});
it('completes a setup confirmed by Kapso', async () => {
const { fn } = fakeFetch([
{
method: 'GET',
path: '/platform/v1/whatsapp/phone_numbers/phone-1',
body: {
data: {
phone_number_id: 'phone-1',
business_account_id: 'waba-1',
display_phone_number: '+54 9 11 2345-6789',
customer_id: 'cust-1',
},
},
},
]);
const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
expect(
await provider.completeRedirect(kapsoAccount(), {
setup_link_id: 'link-1',
status: 'completed',
phone_number_id: 'phone-1',
}),
).toEqual({
ok: true,
value: {
externalId: 'phone-1',
displayPhoneNumber: '+5491123456789',
providerData: { customerId: 'cust-1', setupLinkId: 'link-1', businessAccountId: 'waba-1' },
},
});
});
it('subscribes the number and submits both templates after connecting', async () => {
const { fn, calls } = fakeFetch([
{
method: 'POST',
path: '/platform/v1/whatsapp/phone_numbers/phone-1/webhooks',
status: 201,
body: { data: { id: 'wh-1' } },
},
{
method: 'POST',
path: '/meta/whatsapp/v24.0/waba-1/message_templates',
body: { id: 'tpl-1', status: 'PENDING', category: 'UTILITY' },
},
]);
const db = kapsoDb();
const provider = new KapsoProvider(kapsoConfig, { db: db as never, fetch: fn });
await provider.onConnected(
kapsoAccount({
status: 'ACTIVE',
externalId: 'phone-1',
providerData: { customerId: 'cust-1', businessAccountId: 'waba-1' },
}),
);
expect(calls[0]?.body).toMatchObject({
whatsapp_webhook: { url: kapsoConfig.webhookUrl, secret_key: kapsoConfig.webhookSecret, kind: 'kapso' },
});
const templates = calls.filter((call) => call.url.endsWith('/message_templates'));
expect(templates.map((call) => (call.body as { name: string; category: string }))).toEqual([
expect.objectContaining({ name: 'gruperly_payment_reminder', category: 'UTILITY' }),
expect.objectContaining({ name: 'gruperly_reengagement', category: 'MARKETING' }),
]);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: { providerData: { customerId: 'cust-1', businessAccountId: 'waba-1', webhookId: 'wh-1' } },
});
expect(db.whatsappTemplate.create).toHaveBeenCalledTimes(2);
});
it('is ready only once the template is approved', async () => {
const db = kapsoDb();
const provider = new KapsoProvider(kapsoConfig, { db: db as never });
const active = kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' });
db.whatsappTemplate.findUnique.mockResolvedValueOnce(null);
expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('pending');
db.whatsappTemplate.findUnique.mockResolvedValueOnce({ status: 'APPROVED' });
expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('ready');
db.whatsappTemplate.findUnique.mockResolvedValueOnce({ status: 'REJECTED' });
expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('blocked');
expect(await provider.readiness(kapsoAccount(), 'PAYMENT_REMINDER')).toBe('blocked');
});
it('sends the approved template with named parameters', async () => {
const { fn, calls } = fakeFetch([
{
method: 'POST',
path: '/meta/whatsapp/v24.0/phone-1/messages',
body: { messaging_product: 'whatsapp', messages: [{ id: 'wamid.ABC' }] },
},
]);
const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
const outcome = await provider.send(
kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' }),
'5491123456789',
{
kind: 'PAYMENT_REMINDER',
studentName: 'Ana López',
groupName: 'Yoga',
amount: '$ 25.000',
dueDate: '20/10',
paymentLink: 'https://mpago.la/x',
},
'msg-1',
);
expect(outcome).toEqual({ ok: true, providerMessageId: 'wamid.ABC' });
expect(calls[0]?.body).toMatchObject({
to: '5491123456789',
type: 'template',
template: {
name: 'gruperly_payment_reminder',
language: { code: 'es_AR' },
components: [
{
type: 'body',
parameters: expect.arrayContaining([
{ type: 'text', parameter_name: 'student_name', text: 'Ana' },
{ type: 'text', parameter_name: 'payment_link', text: 'https://mpago.la/x' },
]),
},
],
},
});
});
it('does not retry a marketing opt-out', async () => {
const { fn } = fakeFetch([
{
method: 'POST',
path: '/meta/whatsapp/v24.0/phone-1/messages',
status: 422,
body: { error: { code: 'marketing_preference_stopped' } },
},
]);
const outcome = await new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn }).send(
kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' }),
'5491123456789',
{ kind: 'REENGAGEMENT', studentName: 'Ana', groupName: 'Yoga' },
'msg-1',
);
expect(outcome).toMatchObject({ ok: false, retryable: false, code: 'marketing_preference_stopped' });
});
it('verifies the webhook and normalizes number and message events', () => {
const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never });
const created = JSON.stringify({
phone_number_id: 'phone-1',
business_account_id: 'waba-1',
display_phone_number: '+54 9 11 2345 6789',
customer: { id: 'cust-1', external_id: 'user-1' },
});
const headers = new Headers({
'X-Webhook-Signature': sign(created, kapsoConfig.webhookSecret),
'X-Webhook-Event': 'whatsapp.phone_number.created',
'X-Idempotency-Key': 'idem-1',
});
expect(provider.parseWebhook(created, headers)).toEqual({
ok: true,
value: {
dedupeKey: 'idem-1',
events: [
{
type: 'connection',
externalId: 'phone-1',
ownerId: 'user-1',
status: 'active',
displayPhoneNumber: '+5491123456789',
providerData: { businessAccountId: 'waba-1' },
},
],
},
});
const failed = JSON.stringify({
phone_number_id: 'phone-1',
message: {
id: 'wamid.ABC',
kapso: { status: 'failed', statuses: [{ status: 'failed', errors: [{ code: 131026, title: 'Undeliverable' }] }] },
},
});
const failedHeaders = new Headers({
'X-Webhook-Signature': sign(failed, kapsoConfig.webhookSecret),
'X-Webhook-Event': 'whatsapp.message.failed',
'X-Idempotency-Key': 'idem-2',
});
expect(provider.parseWebhook(failed, failedHeaders)).toEqual({
ok: true,
value: {
dedupeKey: 'idem-2',
events: [
{
type: 'message_status',
providerMessageId: 'wamid.ABC',
status: 'FAILED',
errorCode: '131026',
errorMessage: 'Undeliverable',
},
],
},
});
expect(
provider.parseWebhook(created, new Headers({ 'X-Webhook-Signature': 'deadbeef', 'X-Idempotency-Key': 'x' })),
).toEqual({ ok: false, error: 'invalid_signature' });
});
});