Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): stop reporting an unanswered number check as "not on WhatsApp"

Yudhi Armyndharisf6eca8598d70
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b2e1d9cf4..d7c517fe2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A number check no longer answers "not on WhatsApp" when WhatsApp simply did not answer** — Baileys' `onWhatsApp` has no else branch after its result check, so an unanswered lookup resolved `undefined`, which the adapter folded into the same `null` a genuine miss produces; `GET /contacts/check/{number}` then reported `exists: false` and `checkNumberExists` returned false — a confident verdict about a number the gateway had heard nothing about, on the one route the send documentation tells callers to trust before sending. An empty result is still a real answer and still reports `false`; only the absent one now raises `503`.
- **A group invite code now says why it could not be read** — fetching one is admin-only, but the groups list returns every group the account belongs to whatever its role, so the request lands on ids the caller was just handed: Baileys let WhatsApp's refusal escape as a bare `500` (13 of 16 groups on the test account) while whatsapp-web.js stringified its missing result into `{"inviteCode":"undefined"}` and the link `https://chat.whatsapp.com/undefined` behind a `200` (53 of 101). Both engines now answer `403`, the same status the group writes have answered since they were fixed, and an unanswered query answers `503` instead of the codeless link `https://chat.whatsapp.com/`.
- **A catalog read no longer stalls for a minute and then reports an empty catalog** — Baileys answers an unanswered query with `undefined` rather than an error and its catalog parsers are null-safe, so a request WhatsApp never replied to was indistinguishable from a business with no products: `GET /catalog` and `/catalog/products` returned `200` with nothing in them after a silent 60 seconds, and `send-product` reported `404 Product not found` for a product it had simply never heard about. The walk now spends one 30-second budget across every page and answers `503`, and a server that repeats a page cursor instead of advancing no longer spins the walk until the process exhausts its heap.
- **A benign whatsapp-web.js rejection no longer reads like a crash** — the same un-awaited `framenavigated` re-injection that already logs at `WARN` when the page goes away was logged at `ERROR` in its other shape, where the navigation lands before WhatsApp Web has defined its module registry; it appears at the first boot after the pinned WhatsApp Web build moves under a warm profile, and the session reaches ready unaided.
diff --git a/openapi.json b/openapi.json
index 10154deb5..f0a02a3ca 100644
--- a/openapi.json
+++ b/openapi.json
@@ -3898,6 +3898,9 @@
}
}
}
+ },
+ "503": {
+ "description": "WhatsApp did not answer the lookup. Deliberately not reported as `exists: false` — that would be a claim about the number rather than about the query, and this route exists to be trusted before a send."
}
},
"summary": "Check if a phone number exists on WhatsApp",
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index 1d829a7bd..0c4aa8ad5 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -20,6 +20,7 @@ import { BadRequestException } from '@nestjs/common';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { MessageNotFoundError } from '../../common/errors/message-not-found.error';
import { type createLogger } from '../../common/services/logger.service';
+import { EngineTransportError } from '../../common/errors/engine-transport.error';
/**
* Messaging-domain operations extracted from BaileysAdapter. The adapter keeps the public
@@ -146,7 +147,15 @@ export class BaileysMessaging {
async getNumberId(number: string): Promise<string | null> {
this.host.ensureReady();
const results = await this.sock().onWhatsApp(number);
- const hit = results?.[0];
+ // onWhatsApp has no else branch after `if (results)`, so it resolves undefined when the usync
+ // query goes unanswered — and Baileys' query() swallows its own timeout rather than throwing.
+ // An empty ARRAY is a real answer; undefined is the absence of one, and coalescing the two
+ // turns "we never heard back" into "this number is not on WhatsApp", which the caller then
+ // acts on. The two are distinguishable here, so they are distinguished.
+ if (results === undefined) {
+ throw new EngineTransportError('WhatsApp did not answer the number-check query');
+ }
+ const hit = results[0];
// Baileys returns a raw `<phone>@s.whatsapp.net`; neutralize it before it crosses the engine
// boundary so the value matches whatsapp-web.js (`<phone>@c.us`) and the IWhatsAppEngine contract
// (no raw `@s.whatsapp.net` in a neutral field). It also round-trips back to a send on either engine.
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index b761da619..a8cc755e2 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -1307,6 +1307,23 @@ describe('BaileysAdapter messaging', () => {
await expect(adapter.checkNumberExists('628111')).resolves.toBe(false);
});
+ // Baileys' onWhatsApp resolves undefined when the usync query goes unanswered — it has no else
+ // branch after `if (results)`. Coalescing that to null reports "this number is not on WhatsApp",
+ // which is a claim about the number rather than about the query that never came back.
+ it('getNumberId reports an unanswered lookup instead of claiming the number is not on WhatsApp', async () => {
+ fakeSock.onWhatsApp.mockResolvedValue(undefined);
+ const adapter = await readyAdapter();
+ await expect(adapter.getNumberId('628111')).rejects.toBeInstanceOf(EngineTransportError);
+ await expect(adapter.checkNumberExists('628111')).rejects.toBeInstanceOf(EngineTransportError);
+ });
+
+ // An empty array is a real answer: Baileys returns [] when there is nothing to query.
+ it('getNumberId still returns null for an empty result, which is an answer and not a failure', async () => {
+ fakeSock.onWhatsApp.mockResolvedValue([]);
+ const adapter = await readyAdapter();
+ await expect(adapter.getNumberId('628111')).resolves.toBeNull();
+ });
+
it('sendChatState maps typing -> composing presence', async () => {
const adapter = await readyAdapter();
await adapter.sendChatState('[email protected]', 'typing');
diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.ts
index 09d408215..75719bc0c 100644
--- a/src/modules/contact/contact.controller.ts
+++ b/src/modules/contact/contact.controller.ts
@@ -91,6 +91,13 @@ export class ContactController {
description: 'Number existence check result',
type: NumberCheckResponseDto,
})
+ @ApiResponse({
+ status: 503,
+ description:
+ 'WhatsApp did not answer the lookup. Deliberately not reported as `exists: false` — that ' +
+ 'would be a claim about the number rather than about the query, and this route exists to be ' +
+ 'trusted before a send.',
+ })
async checkNumber(@Param('sessionId') sessionId: string, @Param('number') number: string) {
// The engine returns the canonical chat id in its native format; we don't build the JID here
// (decoupled from the whatsapp-web.js `@c.us` scheme).