Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): stop classifying a dead socket as a permissions refusal
Yudhi Armyndharis7bb224f142be
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4de746ab5..1a4dd124d 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 dead socket is no longer reported as a permissions problem** — the helper that decides whether a Baileys failure was a server refusal or a transport death guarded on `data !== undefined`, but Boom's constructor defaults `data` to `null`, so the guard matched every Boom ever thrown and a `Connection Closed` (428) was classified as a 4xx refusal: twelve group and profile writes answered `403 admin rights or permissions may be missing`, joining by invite answered `400 invalid invite code`, and reading invite info answered `404`, all for a socket that was simply down. The numeric code that `assertNodeErrorFree` attaches is the only discriminator needed and every genuine refusal still maps as before, so transport failures now propagate as a 5xx instead — **a change of status code on the gateway surface for those cases**. The tests that were meant to cover this passed because their fixture was a bare `Error` rather than a real `Boom`, and now use one.- **Twelve group and profile writes no longer report success for a change WhatsApp never confirmed** — `groupLeave`, the subject/description/settings/picture/member-add-mode/disappearing-timer writes and the three profile writes all resolve through a Baileys call that awaits its query and then discards the result, and `query()` swallows its own timeout and resolves rather than throwing, so leaving a group you are still in and locking a group that stayed open both answered `200 done`; each now has a deadline of its own and answers `503` when no confirmation arrives, which does mean a genuinely slow write that lands just after the deadline is reported as unconfirmed.- **A post-connect app-state resync can no longer spin for the life of the session** — Baileys' `resyncAppState` loops until every collection reports no more patches, but every exit from that loop, including the attempt counter its own comment introduces to "ensure we don't enter a loop that cannot be exited from", sits inside a `for…in` over the decoded patches; an unanswered query decodes to an empty object, so nothing was removed, nothing was counted, and the walk re-asked every sixty seconds until the socket closed. A postinstall patch ends the walk when the decode is empty, and fails the install rather than silently skipping if the upstream shape moves.- **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`.diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex cb841a7d7..8f2a9c43c 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -33,21 +33,24 @@ export interface BaileysGroupsHost {/*** WA error code of a SERVER-refused Baileys query, or undefined for a transport/local failure.- * Baileys carries a refusal two ways: `assertNodeErrorFree` puts the numeric WA code on Boom's- * `data` (WABinary/generic-utils.js:57), and `extractGroupMetadata` puts it on `output.statusCode`- * with the error node as `data` (Socket/groups.js:280). Transport deaths ('Connection Closed',- * 'Timed Out') are LOCAL Booms with DisconnectReason statusCodes (408/428) and no server error- * node — so a numeric `data` (or an object `data` alongside a statusCode) is the discriminator.+ *+ * A numeric `data` is the whole discriminator, and it is sufficient: `query()` runs+ * `assertNodeErrorFree(result)` before it returns (Socket/socket.js:133-135), and that throws+ * `new Boom(text, { data: +errNode.attrs.code })` (WABinary/generic-utils.js:57). So every refusal+ * that can reach a caller through `query()` already carries its WA code as a number.+ *+ * There used to be a second branch reading `output.statusCode` whenever `data !== undefined`,+ * meant for `extractGroupMetadata`'s error-node throw (Socket/groups.js). It did the opposite of+ * its purpose: Boom's constructor destructures `data = null` (@hapi/boom lib/index.js:77), so NO+ * Boom ever has `data === undefined` and the guard was always true. Every transport Boom therefore+ * matched — `Boom('Connection Closed', { statusCode: 428 })` returned 428, inside the 4xx window,+ * so a dead socket was reported as `403 admin rights or permissions may be missing`. The branch was+ * also unnecessary: its target throw cannot be reached through `query()`, because a result carrying+ * an `<error>` child has already thrown from assertNodeErrorFree's identical lookup.*/export function refusedStatusCode(error: unknown): number | undefined {- const err = error as { data?: unknown; output?: { statusCode?: unknown } } | null | undefined;- if (typeof err?.data === 'number') {- return err.data;- }- if (err?.data !== undefined && typeof err.output?.statusCode === 'number') {- return err.output.statusCode;- }- return undefined;+ const err = error as { data?: unknown } | null | undefined;+ return typeof err?.data === 'number' ? err.data : undefined;}/**diff --git a/src/engine/adapters/baileys-refused-status.spec.ts b/src/engine/adapters/baileys-refused-status.spec.tsnew file mode 100644index 000000000..d4e7e97f0--- /dev/null+++ b/src/engine/adapters/baileys-refused-status.spec.ts@@ -0,0 +1,61 @@+import { Boom } from '@hapi/boom';+import { refusedStatusCode, mapServerRefusal } from './baileys-groups';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';++/**+ * `refusedStatusCode` decides whether a Baileys failure was a SERVER refusal (map to 403/404) or a+ * transport death (must propagate). Every case here is built with a real `Boom`, because that is+ * what Baileys throws and because the shape is the whole point: Boom's constructor destructures+ * `data = null`, so no Boom ever carries `data === undefined`.+ *+ * The pre-existing fixtures used `Object.assign(new Error(...), { output })` with no `data` at all,+ * which is why a transport death appeared to propagate in tests while a real one did not.+ */+describe('refusedStatusCode', () => {+ it('reads a server refusal from the numeric data assertNodeErrorFree attaches', () => {+ // query() runs assertNodeErrorFree before returning, and it throws `data: +errNode.attrs.code`.+ expect(refusedStatusCode(new Boom('forbidden', { data: 403 }))).toBe(403);+ expect(refusedStatusCode(new Boom('gone', { data: 410 }))).toBe(410);+ });++ it.each([+ ['Connection Closed', 428],+ ['Timed Out', 408],+ ])('treats a transport death (%s) as unclassified, so it propagates', (message, statusCode) => {+ // A real Boom: no server error node, and `data` defaulted to null by the constructor.+ const err = new Boom(message, { statusCode });+ expect(err.data).toBeNull();+ expect(refusedStatusCode(err)).toBeUndefined();+ });++ it('treats an unanswered query as unclassified rather than a 500-coded refusal', () => {+ // extractGroupMetadata(undefined) — `data: result` with result undefined, normalised to null.+ const err = new Boom('Invalid group metadata response: missing <group> node', { data: undefined });+ expect(refusedStatusCode(err)).toBeUndefined();+ });++ it('ignores a non-Boom failure entirely', () => {+ expect(refusedStatusCode(new TypeError('Cannot read properties of undefined'))).toBeUndefined();+ expect(refusedStatusCode(undefined)).toBeUndefined();+ });+});++describe('mapServerRefusal', () => {+ it('maps a server refusal to EngineRefusedError', async () => {+ await expect(+ mapServerRefusal('Setting the group subject', () => Promise.reject(new Boom('forbidden', { data: 403 }))),+ ).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('lets a dead socket through untouched instead of calling it a permissions problem', async () => {+ const connectionClosed = new Boom('Connection Closed', { statusCode: 428 });+ await expect(mapServerRefusal('Setting the group subject', () => Promise.reject(connectionClosed))).rejects.toBe(+ connectionClosed,+ );+ });++ it('lets an unanswered query through untouched', async () => {+ const noAnswer = new Boom('Invalid group metadata response: missing <group> node', { data: undefined });+ await expect(mapServerRefusal('Setting the group subject', () => Promise.reject(noAnswer))).rejects.toBe(noAnswer);+ });+});diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex a8cc755e2..3925c7dfd 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -142,6 +142,7 @@ import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { GroupNotFoundError } from '../../common/errors/group-not-found.error';import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';+import { Boom } from '@hapi/boom';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';@@ -2953,7 +2954,7 @@ describe('BaileysAdapter group management', () => {it('getGroupInfo does NOT fold a transport death into null — a dead socket is not "group not found"', async () => {const adapter = await ready();// Local Boom, no server error node: DisconnectReason-shaped 428 Connection Closed.- const connectionClosed = Object.assign(new Error('Connection Closed'), { output: { statusCode: 428 } });+ const connectionClosed = new Boom('Connection Closed', { statusCode: 428 });fakeSock.groupMetadata.mockRejectedValueOnce(connectionClosed);await expect(adapter.getGroupInfo('[email protected]')).rejects.toBe(connectionClosed);// A non-boom failure (programming/protocol error) propagates too.@@ -3087,7 +3088,7 @@ describe('BaileysAdapter group management', () => {it('joinGroupViaInviteCode does NOT fold a transport death into a 400 — a dead socket is not a bad invite', async () => {// Local Boom, no server error node: DisconnectReason-shaped 428 Connection Closed.- const connectionClosed = Object.assign(new Error('Connection Closed'), { output: { statusCode: 428 } });+ const connectionClosed = new Boom('Connection Closed', { statusCode: 428 });fakeSock.groupAcceptInvite.mockRejectedValue(connectionClosed);const adapter = await ready();await expect(adapter.joinGroupViaInviteCode('CODE123')).rejects.toBe(connectionClosed);@@ -3122,7 +3123,7 @@ describe('BaileysAdapter group management', () => {});it('getGroupJoinInfo lets a transport death propagate — a dead socket is not a bad invite', async () => {- const connectionClosed = Object.assign(new Error('Connection Closed'), { output: { statusCode: 428 } });+ const connectionClosed = new Boom('Connection Closed', { statusCode: 428 });fakeSock.groupGetInviteInfo.mockRejectedValue(connectionClosed);const adapter = await ready();await expect(adapter.getGroupJoinInfo('CODE123')).rejects.toBe(connectionClosed);@@ -3166,7 +3167,7 @@ describe('BaileysAdapter group management', () => {});it('a transport death on a group write propagates untouched — not folded into a 403', async () => {- const connectionClosed = Object.assign(new Error('Connection Closed'), { output: { statusCode: 428 } });+ const connectionClosed = new Boom('Connection Closed', { statusCode: 428 });fakeSock.groupUpdateSubject.mockRejectedValueOnce(connectionClosed);const adapter = await ready();await expect(adapter.setGroupSubject('[email protected]', 'X')).rejects.toBe(connectionClosed);