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>
This commit is contained in:
Jose Selesan
2026-10-22 19:15:02 -03:00
parent bef4056f8e
commit f4d2c26e29
23 changed files with 619 additions and 82 deletions

View File

@@ -139,6 +139,29 @@ export function whatsappNumberInUseProblem(): ProblemDetails {
});
}
export function whatsappLinkingNotStartedProblem(): ProblemDetails {
return conflictProblem({
detail: 'Empezá la vinculación de WhatsApp antes de pedir el código.',
code: 'whatsapp_linking_not_started',
});
}
/** The provider links by QR or redirect only (Kapso). */
export function whatsappPairingUnsupportedProblem(): ProblemDetails {
return conflictProblem({
detail: 'Este proveedor de WhatsApp no permite vincular con el número de teléfono.',
code: 'whatsapp_pairing_unsupported',
});
}
/** The session is not ready to hand out a code yet; retryable in seconds. */
export function whatsappPairingNotReadyProblem(): ProblemDetails {
return conflictProblem({
detail: 'WhatsApp todavía está preparando la vinculación. Intentá de nuevo en unos segundos.',
code: 'whatsapp_pairing_not_ready',
});
}
/** The WhatsApp gateway refused the request, or could not be reached. */
export function whatsappProviderErrorProblem(): ProblemDetails {
return {

View File

@@ -0,0 +1,21 @@
import type { WhatsappPairingCode } from '@gruperly/shared';
import { WhatsappPairingCodeSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { RequestWhatsappPairingCode } from './use-case';
const route = new Hono();
route.post('/', validate.json(WhatsappPairingCodeSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const { phoneNumber } = c.req.valid('json') as WhatsappPairingCode;
const useCase = new RequestWhatsappPairingCode();
const result = await useCase.execute(user.id, phoneNumber);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,63 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, WhatsappPairingCodeDto } from '@gruperly/shared';
import { countryCodeSchema, err, ok, toWhatsappE164 } from '@gruperly/shared';
import {
validationProblem,
whatsappLinkingNotStartedProblem,
whatsappPairingUnsupportedProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { getMessagingProvider } from '../../providers';
import type { MessagingProvider } from '../../providers/messaging-provider';
type RequestWhatsappPairingCodeDeps = {
db?: Pick<PrismaClient, 'whatsappAccount' | 'user'>;
provider?: MessagingProvider;
};
/**
* Links the teacher's WhatsApp by phone number instead of QR: WhatsApp shows a
* prompt on that phone and the teacher types the code we return. It is what
* makes linking possible from the phone the app is running on.
*
* The linking must have been started with `POST /whatsapp/connect` (the account
* is PENDING with a live session); the code completes that same linking, so the
* status polling and the webhook finish it as with a QR.
*/
export class RequestWhatsappPairingCode {
constructor(private readonly deps: RequestWhatsappPairingCodeDeps = {}) {}
async execute(
ownerId: string,
phoneNumber: string,
): Promise<Result<WhatsappPairingCodeDto, ProblemDetails>> {
const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider();
if (!providerResult.ok) return providerResult;
const provider = providerResult.value;
if (!provider.requestPairingCode) return err(whatsappPairingUnsupportedProblem());
const db = this.deps.db ?? prisma;
const account = await db.whatsappAccount.findUnique({ where: { ownerId } });
if (!account || account.provider !== provider.id || account.status !== 'PENDING') {
return err(whatsappLinkingNotStartedProblem());
}
// Typed the way people write their own number (`11 2345-6789`): the
// teacher's country settles the calling code, as for the attendees.
const owner = await db.user.findUnique({ where: { id: ownerId }, select: { country: true } });
const country = countryCodeSchema.safeParse(owner?.country);
const e164 = toWhatsappE164(phoneNumber, country.success ? country.data : null);
if (!e164) {
return err(
validationProblem({
detail: 'Revisá el número: escribilo con el código de área.',
errors: { phoneNumber: ['Número inválido'] },
}),
);
}
const code = await provider.requestPairingCode(account, e164.slice(1));
if (!code.ok) return code;
return ok({ pairingCode: code.value });
}
}

View File

@@ -129,6 +129,17 @@ export interface MessagingProvider {
account: WhatsappAccountRecord,
): Promise<Result<ConnectionSnapshot, ProblemDetails>>;
/**
* Asks for a code to link by phone number instead of scanning the QR, for a
* linking already started with `startConnection`. `phoneDigits` is the
* teacher's number in international format, digits only. Only providers that
* link a WhatsApp Web session (OpenWA) implement it.
*/
requestPairingCode?(
account: WhatsappAccountRecord,
phoneDigits: string,
): Promise<Result<string, ProblemDetails>>;
/**
* Finishes a redirect-based linking from the callback query. Only providers
* whose `startConnection` answers `redirect` implement it.

View File

@@ -83,6 +83,15 @@ export class OpenWaClient {
return response.qrCode ?? null;
}
requestPairingCode(
sessionId: string,
phoneNumber: string,
): Promise<{ pairingCode: string; status?: string }> {
return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/pairing-code`, {
phoneNumber,
});
}
createWebhook(
sessionId: string,
body: { url: string; events: string[]; secret: string; retryCount: number },

View File

@@ -1,7 +1,8 @@
import type { ProblemDetails, Result, WhatsappReadiness } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { whatsappProviderErrorProblem } from '@/http/problem-builders';
import { whatsappPairingNotReadyProblem, whatsappProviderErrorProblem } from '@/http/problem-builders';
import { logger } from '@/logger';
import { sleep } from '../../lib/dispatch';
import { verifyHmacSha256 } from '../../lib/hmac';
import { renderMessage } from '../../lib/render-message';
import type {
@@ -34,6 +35,14 @@ const WEBHOOK_RETRY_COUNT = 3;
/** The global throttler's 429 carries no `retryAfterSeconds`; it clears in seconds. */
const DEFAULT_RATE_LIMIT_MS = 60_000;
/**
* Right after `start` the session is still `initializing` and OpenWA answers a
* pairing-code request with 409 until it reads `qr_ready` (on Baileys also for
* up to 30 s while a socket closes). Retried here so the teacher's click works.
*/
const PAIRING_ATTEMPTS = 6;
const PAIRING_RETRY_MS = 2_000;
const PENDING_STATUSES = new Set(['created', 'initializing', 'qr_ready', 'authenticating']);
/** One OpenWA session per teacher. Names allow letters, digits and hyphens (3-50). */
@@ -41,7 +50,7 @@ export function openWaSessionName(ownerId: string): string {
return `gruperly-${ownerId.replace(/[^a-zA-Z0-9-]/g, '')}`.slice(0, 50);
}
type OpenWaProviderDeps = { fetch?: OpenWaFetch };
type OpenWaProviderDeps = { fetch?: OpenWaFetch; sleep?: (ms: number) => Promise<void> };
/**
* OpenWA (self-hosted, unofficial WhatsApp Web gateway) for the MVP.
@@ -54,12 +63,14 @@ type OpenWaProviderDeps = { fetch?: OpenWaFetch };
export class OpenWaProvider implements MessagingProvider {
readonly id = 'OPENWA' as const;
private readonly client: OpenWaClient;
private readonly sleep: (ms: number) => Promise<void>;
constructor(
private readonly config: OpenWaConfig,
deps: OpenWaProviderDeps = {},
) {
this.client = new OpenWaClient(config, deps.fetch);
this.sleep = deps.sleep ?? sleep;
}
async startConnection(
@@ -138,6 +149,29 @@ export class OpenWaProvider implements MessagingProvider {
}
}
async requestPairingCode(
account: WhatsappAccountRecord,
phoneDigits: string,
): Promise<Result<string, ProblemDetails>> {
if (!account.externalId) return err(whatsappProviderErrorProblem());
for (let attempt = 1; ; attempt++) {
try {
const response = await this.client.requestPairingCode(account.externalId, phoneDigits);
return ok(response.pairingCode);
} catch (error) {
const notReady = error instanceof OpenWaApiError && error.status === 409;
if (notReady && attempt < PAIRING_ATTEMPTS) {
await this.sleep(PAIRING_RETRY_MS);
continue;
}
if (notReady) return err(whatsappPairingNotReadyProblem());
logger.warn({ err: describe(error) }, 'OpenWA pairing code request failed');
return err(whatsappProviderErrorProblem());
}
}
}
async disconnect(account: WhatsappAccountRecord): Promise<Result<void, ProblemDetails>> {
if (!account.externalId) return ok(undefined);
const sessionId = account.externalId;

View File

@@ -2,6 +2,7 @@ import { Hono } from 'hono';
import callbackRoute from './features/callback/route';
import connectRoute from './features/connect/route';
import disconnectRoute from './features/disconnect/route';
import pairingCodeRoute from './features/pairing-code/route';
import statusRoute from './features/status/route';
import webhookRoute from './features/webhook/route';
@@ -11,6 +12,7 @@ const routes = new Hono();
// it on `/connect` gives the RESTful `DELETE /whatsapp/connect`.
routes.route('/connect', connectRoute);
routes.route('/connect', disconnectRoute);
routes.route('/connect/pairing-code', pairingCodeRoute);
routes.route('/status', statusRoute);
routes.route('/callback', callbackRoute);
routes.route('/webhooks', webhookRoute);