Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): report an unreachable recipient as 400, not 500
Yudhi Armyndharis04291108c62f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8f5645e24..2653cd1f5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- **Swagger "Try it out" called `http://localhost:2785` instead of the host that served the docs**, failing with `Failed to fetch` anywhere else — a relative server is now listed first, so it resolves to the serving origin.+- **Sending to a number WhatsApp cannot resolve returned `500`** on the whatsapp-web.js engine — it now answers `400` naming the recipient and both possible causes. Callers that retried the old 500 should treat this as terminal.## [0.14.0] - 2026-08-05diff --git a/src/common/errors/recipient-unreachable.error.ts b/src/common/errors/recipient-unreachable.error.tsnew file mode 100644index 000000000..c8d8d7880--- /dev/null+++ b/src/common/errors/recipient-unreachable.error.ts@@ -0,0 +1,30 @@+import { BadRequestException } from '@nestjs/common';++/**+ * Thrown when WhatsApp Web cannot resolve an individual recipient to an addressable id, so the send+ * can never leave the gateway. Since WhatsApp's LID migration the page reports this as a bare+ * `Error: No LID for user` raised inside its own bundle — with no status, no recipient, and nothing+ * that identifies it as a caller problem — which reached the client as `500 Internal server error`+ * and left nothing to act on (#1068, and #156/#573 before it).+ *+ * The gateway already knows better by then: `getNumberId` returned null, which is exactly how+ * whatsapp-web.js reports "this number is not reachable on WhatsApp". That verdict is now surfaced+ * instead of discarded.+ *+ * Extends NestJS `BadRequestException` so it maps to **HTTP 400** through the built-in exception+ * handler — no custom global filter required. 400 rather than 404: on these routes a 404 already+ * means the *session* was not found, and reusing it for the recipient would be ambiguous. Mirrors+ * how {@link EngineNotSupportedError} maps to 501 and {@link EngineRefusedError} to 403.+ *+ * Two distinct situations produce it, and the message names both because the gateway cannot tell+ * them apart: the number genuinely is not on WhatsApp, or this account has never had a chat with it+ * (the upstream whatsapp-web.js LID limitation, whatsapp-web.js#3834).+ */+export class RecipientUnreachableError extends BadRequestException {+ constructor(chatId: string) {+ super(+ `WhatsApp could not resolve the recipient ${chatId}. Either the number is not on WhatsApp, or ` ++ 'this session has no existing chat with it — message it once from the phone, then retry.',+ );+ }+}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex f75ac1913..e955f16e6 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -23,6 +23,7 @@ import { MessageNotFoundError } from '../../common/errors/message-not-found.erroimport { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';import { ChannelMediaNotSupportedError } from '../../common/errors/channel-media-not-supported.error';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';import { EditedMessage, EngineStatus, GroupEvent, IncomingCallEvent } from '../interfaces/whatsapp-engine.interface';import { CallNotFoundError } from '../../common/errors/call-not-found.error';import { EngineRefusedError } from '../../common/errors/engine-refused.error';@@ -3658,12 +3659,29 @@ describe('LID resolution for individual sends (#573 — WhatsApp @c.us → @lidexpect(res.id).toBe('OUT1');});- it('does not retry when re-resolution yields the same id (no pointless second send)', async () => {+ // An unreachable recipient is a caller-visible fact, not a server fault: getNumberId already+ // returned null. The bare page-side `No LID for user` carries no status, so letting it through+ // surfaced as `500 Internal server error` with nothing to act on (#1068).+ it('does not retry when re-resolution yields the same id, and reports a 400 (no pointless second send)', async () => {const getNumberId = jest.fn().mockResolvedValue(null); // unresolvable → fallback stays @c.usconst sendMessage = jest.fn().mockRejectedValue(new Error('No LID for user'));const adapter = ready({ getNumberId, sendMessage });- await expect(adapter.sendTextMessage('[email protected]', 'x')).rejects.toThrow('No LID for user');- expect(sendMessage).toHaveBeenCalledTimes(1);+ await expect(adapter.sendTextMessage('[email protected]', 'x')).rejects.toBeInstanceOf(RecipientUnreachableError);+ await expect(adapter.sendTextMessage('[email protected]', 'x')).rejects.toMatchObject({ status: 400 });+ // The raw engine wording must not reach the caller — it named neither the recipient nor the cause.+ await expect(adapter.sendTextMessage('[email protected]', 'x')).rejects.not.toThrow('No LID for user');+ expect(sendMessage).toHaveBeenCalledTimes(3); // one per attempt above, never a retry within one+ });++ it('reports a 400 when the RETRY against a re-resolved id is also unreachable', async () => {+ const getNumberId = jest+ .fn()+ .mockResolvedValueOnce({ _serialized: '[email protected]' })+ .mockResolvedValueOnce({ _serialized: '999@lid' });+ const sendMessage = jest.fn().mockRejectedValue(new Error('No LID for user'));+ const adapter = ready({ getNumberId, sendMessage });+ await expect(adapter.sendTextMessage('[email protected]', 'x')).rejects.toBeInstanceOf(RecipientUnreachableError);+ expect(sendMessage).toHaveBeenCalledTimes(2); // original + the one re-resolved retry});it('does not retry on a non-LID send error', async () => {diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex a44dd179e..2a25b7f22 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -20,6 +20,7 @@ import { chatHistoryMediaBudgetBytes, coerceDeclaredSize, ingestMediaBudgetBytesimport { buildIncomingMessageBase } from './message-mapper';import { buildVCard } from './vcard';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';import { type WwebjsEngineHost } from './wwebjs-host';/**@@ -240,6 +241,11 @@ export class WwebjsMessaging {* — the signature of a contact whose cached/resolved id is stale (typically a `@c.us` for a contact* that has since migrated to `@lid`) — drop the mapping, re-resolve once, and retry only if the* fresh id differs, so a genuinely unreachable recipient surfaces its error instead of looping.+ *+ * When re-resolution cannot help, the recipient is unreachable rather than stale, and the raw+ * `No LID for user` is replaced with {@link RecipientUnreachableError} (400). The bare page-side+ * Error carries no status and no recipient, so letting it through produced an opaque 500 for what+ * is really a caller-visible fact the gateway already established: `getNumberId` returned null.*/private async sendResolved<T>(chatId: string, send: (to: string) => Promise<T>): Promise<T> {const to = await this.resolveSendId(chatId);@@ -255,7 +261,7 @@ export class WwebjsMessaging {this.resolvedSendIds.delete(chatId);const fresh = await this.resolveSendId(chatId);if (fresh === to) {- throw err;+ throw new RecipientUnreachableError(chatId);}// The first send threw, but wwjs can throw after the message is already on the wire — so this// retry may produce a duplicate. Log it: without this the second copy is invisible.@@ -264,7 +270,16 @@ export class WwebjsMessaging {staleId: to,freshId: fresh,});- return send(fresh);+ try {+ return await send(fresh);+ } catch (retryErr) {+ // The re-resolved id is no better than the stale one — same unreachable recipient, and the+ // raw error would 500 exactly as the first one did.+ if (isNoLidForUserError(retryErr)) {+ throw new RecipientUnreachableError(chatId);+ }+ throw retryErr;+ }}}