Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): answer the typed number when the wwjs phone read fails
Yudhi Armyndharis2ce803053fed
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 363bb5fca..dc5a6e61b 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2583,6 +2583,8 @@ Check whether a phone number exists on WhatsApp and return its canonical WhatsAp`whatsappId` is the chat id WhatsApp holds for the number, in the neutral `<phone>@c.us` form on both engines (it can differ from the digits supplied), or `null` when the number is not on WhatsApp; `exists` is `whatsappId !== null`.+On whatsapp-web.js, a number WhatsApp answers under a privacy id (`@lid`) needs a second read for its phone, and when WhatsApp Web does not hold that phone locally the read sends a second query to WhatsApp, so one check can cost two outbound queries. If that second read fails, `whatsappId` is the supplied digits as `<digits>@c.us`.+> Route-order caveat: this route is two path segments (`check/:number`), so it never collides with the single-segment `GET /:contactId` — a contact id of literally `check` resolves to `GET /:contactId`.**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key lacks OPERATOR role, is not scoped to this session, is restricted to selected chats, or its IP allow-list excludes the client · `409` conflict or engine not ready (retryable) · `503` session not ready or dependency unavailable (retryable)diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 812fff64a..02d91d9e7 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -9466,19 +9466,31 @@ describe('WhatsAppWebJsAdapter raw-id extraction hardening', () => {expect(getContactLidAndPhone).not.toHaveBeenCalled();});- it('getNumberId fails with the phone read instead of answering a number that may be wrong', async () => {+ // The lookup already answered that the number exists; a failed read of its phone (a second page call that can+ // run a second WhatsApp query) must not turn that answer into a 500.+ it('getNumberId answers the typed number when the phone read fails, and logs it at debug', async () => {const getNumberId = jest.fn().mockResolvedValue({ _serialized: '159442138038327@lid' });- const failing = (error: Error): WhatsAppWebJsAdapter =>- readyAdapter({ getNumberId, getContactLidAndPhone: jest.fn().mockRejectedValue(error) });+ const adapter = readyAdapter({+ getNumberId,+ getContactLidAndPhone: jest.fn().mockRejectedValue(new Error('Evaluation failed')),+ });+ const logger = (adapter as unknown as { logger: { debug: (m: string, meta?: unknown) => void } }).logger;+ const debug = jest.spyOn(logger, 'debug').mockImplementation(() => undefined);- await expect(failing(new Error('Evaluation failed')).getNumberId('5511987654321')).rejects.toThrow(- 'Evaluation failed',- );- await expect(- failing(new Error('Protocol error: Target closed')).getNumberId('5511987654321'),- ).rejects.toBeInstanceOf(EngineTransportError);+ await expect(adapter.getNumberId('+5511987654321')).resolves.toBe('[email protected]');+ expect(debug).toHaveBeenCalledWith(expect.stringContaining('phone'), { error: 'Error: Evaluation failed' });// Existence is all checkNumberExists asks, so the phone read never reaches it.- await expect(failing(new Error('Evaluation failed')).checkNumberExists('5511987654321')).resolves.toBe(true);+ await expect(adapter.checkNumberExists('5511987654321')).resolves.toBe(true);+ });++ it('getNumberId still answers 503 when the page dies during the phone read', async () => {+ const getNumberId = jest.fn().mockResolvedValue({ _serialized: '159442138038327@lid' });+ const adapter = readyAdapter({+ getNumberId,+ getContactLidAndPhone: jest.fn().mockRejectedValue(new Error('Protocol error: Target closed')),+ });++ await expect(adapter.getNumberId('5511987654321')).rejects.toBeInstanceOf(EngineTransportError);});it('getSubscribedChannels reads $1 on a renamed build, never the literal "undefined"', async () => {@@ -9519,6 +9531,66 @@ describe('WhatsAppWebJsAdapter raw-id extraction hardening', () => {});});+/**+ * The number check of a migrated contact through the library's own page code (Client.getNumberId,+ * Client.getContactLidAndPhone and the injected WWebJS.enforceLidAndPnRetrieval) against a stand-in+ * WhatsApp Web, counting the existence queries one check sends.+ */+describe('WhatsAppWebJsAdapter number check through the library page code', () => {+ const g = globalThis as unknown as { window?: unknown };+ const LID = '159442138038327@lid';+ const PN = '[email protected]';+ afterEach(() => {+ delete g.window;+ });++ /** The typed number exists under LID; `knownLocally` is whether the page already holds that lid's phone. */+ function checkOn(page: { knownLocally: boolean; secondQuery?: 'fills' | 'throws' }) {+ const wid = (id: string) => ({ _serialized: id, server: id.split('@')[1], user: id.split('@')[0] });+ let mapped = page.knownLocally;+ const queryWidExists = jest.fn((queried: { server: string }) => {+ if (queried.server === 'lid') {+ if (page.secondQuery === 'throws') return Promise.reject(new Error('query failed'));+ mapped = true;+ }+ return Promise.resolve({ wid: wid(LID) });+ });+ const modules: Record<string, unknown> = {+ WAWebWidFactory: { createWid: wid },+ WAWebQueryExistsJob: { queryWidExists },+ WAWebApiContact: { getPhoneNumber: () => (mapped ? wid(PN) : null), getCurrentLid: () => wid(LID) },+ };+ g.window = { require: (name: string) => modules[name] };+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ (require('whatsapp-web.js/src/util/Injected/Utils.js') as { LoadUtils: () => void }).LoadUtils();+ const client = Object.assign(Object.create(Client.prototype) as object, {+ pupPage: { evaluate: (fn: (...args: unknown[]) => unknown, ...args: unknown[]) => fn(...args) },+ });+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;+ (adapter as unknown as { client: unknown }).client = client;+ return { adapter, queryWidExists };+ }++ it('sends one query when the page already holds the phone of the lid', async () => {+ const { adapter, queryWidExists } = checkOn({ knownLocally: true });+ await expect(adapter.getNumberId('5511987654321')).resolves.toBe(PN);+ expect(queryWidExists).toHaveBeenCalledTimes(1);+ });++ it('sends a second query when the page does not, and answers the phone it reads', async () => {+ const { adapter, queryWidExists } = checkOn({ knownLocally: false, secondQuery: 'fills' });+ await expect(adapter.getNumberId('5511987654321')).resolves.toBe(PN);+ expect(queryWidExists).toHaveBeenCalledTimes(2);+ });++ it('answers the typed number when that second query fails', async () => {+ const { adapter, queryWidExists } = checkOn({ knownLocally: false, secondQuery: 'throws' });+ await expect(adapter.getNumberId('5511987654321')).resolves.toBe('[email protected]');+ expect(queryWidExists).toHaveBeenCalledTimes(2);+ });+});+// A chat, contact or group id belongs to a third party, and a serialized message id embeds the chat JID:// the per-action lines keep them out of info-level output and carry them as debug metadata only.describe('WhatsAppWebJsAdapter per-action log lines', () => {diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex c2085109c..742274b80 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -1,6 +1,7 @@import { type Client } from 'whatsapp-web.js';import { InternalServerErrorException } from '@nestjs/common';import { Contact } from '../interfaces/whatsapp-engine.interface';+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { parseWaId, userPart } from '../identity/wa-id';import { readWid, type SerializedWid } from '../types/whatsapp-web-js.types';@@ -260,9 +261,20 @@ export class WwebjsContacts {// engine answers. It can differ from the digits typed (a Brazilian, Mexican or Argentine number with or// without its extra digit). A migrated contact's lookup names its `@lid`, the engine's own scheme, so the// phone is read back through it. When WhatsApp Web knows none, the typed number stands in, and a send to- // it re-resolves to the lid. A failed read propagates, as the lookup above does.- const phone = await withPage(this.host, 'getNumberId', () => this.resolveContactPhone(wid));- return `${phone ?? userPart(number).replace(/\D/g, '')}@c.us`;+ // it re-resolves to the lid. That read runs a second existence query when the page holds no phone for the+ // lid, so its failure answers the typed number too: the lookup above already settled that the number+ // exists. A session or page that died meanwhile still answers 409 or 503, as every read does.+ const typed = `${userPart(number).replace(/\D/g, '')}@c.us`;+ try {+ const phone = await withPage(this.host, 'getNumberId', () => this.resolveContactPhone(wid));+ return phone ? `${phone}@c.us` : typed;+ } catch (error) {+ if (error instanceof EngineNotReadyError || error instanceof EngineTransportError) throw error;+ this.host.logger.debug('Could not read the phone of a migrated number, answering the typed number', {+ error: String(error),+ });+ return typed;+ }}async checkNumberExists(number: string): Promise<boolean> {