Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): classify a w:mex refusal again, and correct the note that missed it
Yudhi Armyndharis9aa9cb3b9ec8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d75dbc007..06aa50099 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **A channel refusal answers `403` again, not a bare `500`** — narrowing the refusal classifier in the same release fixed the IQ error channel and silently de-classified the other one: WhatsApp's `w:mex` surface reports a refusal as a GraphQL error inside a _successful_ IQ, so it never carries the numeric code the classifier now reads, and deleting or muting a channel the account does not own regressed from `403` to an opaque `500`. The two error channels are decoded separately now; a dead socket and an unanswered query still do not read as refusals.- **A profile picture lookup that WhatsApp never answered no longer reads as "this contact has no picture"** — the route answered `200` with `url: null` after a silent minute, which is the same answer a contact without a picture gives, so a caller had no way to tell them apart; it now answers `503`. Passing the engine's own timeout would not have been enough on its own, because the resulting error landed in the catch that produces that same `null`. The batch lookup is unchanged: a per-id failure there is documented as `null` and stays that way.- **The last fifteen writes that reported success without confirmation now report it** — the addressbook saves, block and unblock, the archive/unread/clear/delete chat actions, delete-for-me and star, the four label writes and a call rejection all go through an engine call that discards its own result, so each answered `200` whether WhatsApp applied the change or never replied; a rejected call was the sharpest case, since the gateway also published a `rejected` outcome for a rejection nothing had acknowledged. All now share the request budget and answer `503` when no confirmation arrives.- **A dead connection is no longer reported as a bad invite code or a permissions refusal** — joining by invite and updating participants both fail without ever entering their `catch`, because the engine resolves an unanswered query rather than rejecting it: the join landed on the same "invite code may be invalid" `400` as a genuinely bad code, and a participant update on the same `403` as a missing admin right. Both now share the request budget and answer `503`; an answered-but-empty result still means what it meant.@@ -21,7 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Channel operations no longer answer a bare `500` when WhatsApp stays silent** — every one goes through a query helper that reports an absent answer as a malformed one, which the refusal classifier cannot place, so the raw error escaped with its message discarded; the channel lookup, invite lookup, subscribe, unsubscribe, delete and mute/unmute now share the same 30-second budget and answer `503`. Creating a channel is deliberately left unbounded for the same reason as creating a group — it is non-idempotent, and `503` is a status the Go SDK retries for `POST`.- **The three group-metadata reads no longer answer a bare `500` when WhatsApp stays silent** — `extractGroupMetadata` throws a Boom whose `data` is normalised to null, so the refusal classifier cannot place it and the raw error escaped with its message discarded; `GET /groups/{id}` and `GET /groups/join-info` now spend the same 30-second budget as the rest and answer `503`, and creating a group maps a genuine WhatsApp refusal to `403` instead of the same bare `500`. Group creation is deliberately left unbounded: it is the one non-idempotent call, and `503` is a status the Go SDK retries for `POST`, which could leave duplicate groups behind.- **A group list WhatsApp never answered is no longer served as "you are in no groups"** — `groupFetchAllParticipating` fills its result only behind an `if (groupsChild)`, so an unanswered query returns the same empty object an account with no groups produces, and `GET /sessions/{id}/groups` answered `200` with an empty array after a silent minute; there is nothing in the value to tell the two apart, so the read now shares the same 30-second budget as the group writes and answers `503` instead.-- **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.+- **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: the group and channel writes that go through that helper 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. Transport failures now propagate as a 5xx instead — **a change of status code on the gateway surface for those cases**. The three profile writes were never affected: they do not go through that helper. 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-channels.ts b/src/engine/adapters/baileys-channels.tsindex 9543d7362..52a4e8d75 100644--- a/src/engine/adapters/baileys-channels.ts+++ b/src/engine/adapters/baileys-channels.ts@@ -15,6 +15,31 @@ export interface BaileysChannelsHost {getSocket(): WASocket;}+/**+ * WA error code of a w:mex refusal, or undefined for anything else.+ *+ * executeWMexQuery (lib/Socket/mex.js) parses a GraphQL payload out of a SUCCESSFUL iq, so a+ * refusal never reaches assertNodeErrorFree and never carries the numeric `data` refusedStatusCode+ * reads. It throws `Boom(msg, { statusCode: errorCode, data: firstError })` instead — the code on+ * the Boom, the error node as `data`.+ *+ * A non-null OBJECT `data` is the discriminator, and it is safe here specifically: Boom defaults+ * `data` to null, so every transport failure carries null, and so does executeWMexQuery's OTHER+ * throw for an unanswered query (`data: result` with result undefined). Kept local to this file+ * rather than folded into refusedStatusCode, because promiseTimeout's Boom also carries an object+ * `data` with a 4xx code and must never be read as a refusal.+ */+export function wmexRefusalCode(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 !== null && typeof err?.data === 'object' && typeof err.output?.statusCode === 'number') {+ return err.output.statusCode;+ }+ return undefined;+}+export class BaileysChannels {constructor(private readonly host: BaileysChannelsHost,@@ -59,24 +84,33 @@ export class BaileysChannels {*/async createChannel(name: string, description?: string): Promise<Channel> {this.host.ensureReady();- const meta = await mapServerRefusal('Creating the channel', () => this.sock().newsletterCreate(name, description));+ const meta = await mapServerRefusal(+ 'Creating the channel',+ () => this.sock().newsletterCreate(name, description),+ wmexRefusalCode,+ );return this.toChannel(meta);}async deleteChannel(channelId: string): Promise<void> {this.host.ensureReady();- await mapServerRefusal('Deleting the channel', () =>- this.bounded(this.sock().newsletterDelete(channelId), 'the channel delete'),+ await mapServerRefusal(+ 'Deleting the channel',+ () => this.bounded(this.sock().newsletterDelete(channelId), 'the channel delete'),+ wmexRefusalCode,);}async muteChannel(channelId: string, mute: boolean): Promise<void> {this.host.ensureReady();- await mapServerRefusal(mute ? 'Muting the channel' : 'Unmuting the channel', () =>- this.bounded(- mute ? this.sock().newsletterMute(channelId) : this.sock().newsletterUnmute(channelId),- mute ? 'the channel mute' : 'the channel unmute',- ),+ await mapServerRefusal(+ mute ? 'Muting the channel' : 'Unmuting the channel',+ () =>+ this.bounded(+ mute ? this.sock().newsletterMute(channelId) : this.sock().newsletterUnmute(channelId),+ mute ? 'the channel mute' : 'the channel unmute',+ ),+ wmexRefusalCode,);}diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex 87430a4f6..49013bdd4 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -47,6 +47,12 @@ export interface BaileysGroupsHost {* 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.+ *+ * Only the IQ error channel is decoded here. WhatsApp's w:mex surface reports a refusal as a+ * GraphQL error inside a SUCCESSFUL iq, which never passes through assertNodeErrorFree and carries+ * an object rather than a numeric `data` — see wmexRefusalCode in baileys-channels.ts. Widening this+ * function to accept an object `data` would also swallow promiseTimeout's Boom, which carries+ * `{ stack }` alongside a 4xx DisconnectReason code, so the two channels stay separate.*/export function refusedStatusCode(error: unknown): number | undefined {const err = error as { data?: unknown } | null | undefined;@@ -60,11 +66,15 @@ export function refusedStatusCode(error: unknown): number | undefined {* failures (dropped socket, timeout) propagate untouched: folding them in would report a dead* connection as a permissions problem.*/-export async function mapServerRefusal<T>(operation: string, op: () => Promise<T>): Promise<T> {+export async function mapServerRefusal<T>(+ operation: string,+ op: () => Promise<T>,+ classify: (error: unknown) => number | undefined = refusedStatusCode,+): Promise<T> {try {return await op();} catch (error) {- const code = refusedStatusCode(error);+ const code = classify(error);if (code !== undefined && code >= 400 && code < 500) {throw new EngineRefusedError(`${operation} was refused by WhatsApp (code ${code}) — admin rights or permissions may be missing`,diff --git a/src/engine/adapters/baileys-wmex-refusal.spec.ts b/src/engine/adapters/baileys-wmex-refusal.spec.tsnew file mode 100644index 000000000..63bb9bca9--- /dev/null+++ b/src/engine/adapters/baileys-wmex-refusal.spec.ts@@ -0,0 +1,71 @@+import { Boom } from '@hapi/boom';+import type { WASocket } from '@whiskeysockets/baileys';+import { BaileysChannels, BaileysChannelsHost } from './baileys-channels';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * Channels do not fail like the rest of the adapter. executeWMexQuery reports a server refusal as a+ * GraphQL error INSIDE a successful IQ, so it never passes through assertNodeErrorFree and never+ * carries the numeric `data` that refusedStatusCode reads:+ *+ * throw new Boom(`GraphQL server error: …`, { statusCode: errorCode, data: firstError })+ *+ * `data` is the error OBJECT. Narrowing refusedStatusCode to numeric-only left these unclassified,+ * so a genuine "you do not own this channel" answered a bare 500 instead of 403.+ */+function channels(sock: Record<string, jest.Mock>, budgetMs: number): BaileysChannels {+ const host = {+ ensureReady: () => undefined,+ getSocket: () => sock as unknown as WASocket,+ } as unknown as BaileysChannelsHost;+ return new BaileysChannels(host, budgetMs);+}++/** Exactly what mex.js builds for a GraphQL refusal. */+const wmexRefusal = (code: number) =>+ new Boom('GraphQL server error: not authorized', {+ statusCode: code,+ data: { message: 'not authorized', extensions: { error_code: code } },+ });++describe('channel refusals map to 403, not a bare 500', () => {+ it.each([+ ['deleteChannel', 'newsletterDelete', (c: BaileysChannels) => c.deleteChannel('120363@newsletter')],+ ['muteChannel', 'newsletterMute', (c: BaileysChannels) => c.muteChannel('120363@newsletter', true)],+ ['createChannel', 'newsletterCreate', (c: BaileysChannels) => c.createChannel('N')],+ ])('%s', async (_n, method, call) => {+ const sock = { [method]: jest.fn().mockRejectedValue(wmexRefusal(403)) };+ await expect(call(channels(sock, 500))).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('maps any 4xx the GraphQL payload reports, not only 403', async () => {+ const newsletterDelete = jest.fn().mockRejectedValue(wmexRefusal(404));+ await expect(channels({ newsletterDelete }, 500).deleteChannel('120363@newsletter')).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });+});++describe('what must NOT be classified as a refusal', () => {+ it('a dead socket still propagates rather than becoming a 403', async () => {+ const connectionClosed = new Boom('Connection Closed', { statusCode: 428 });+ const newsletterDelete = jest.fn().mockRejectedValue(connectionClosed);+ await expect(channels({ newsletterDelete }, 500).deleteChannel('120363@newsletter')).rejects.toBe(connectionClosed);+ });++ it('an unanswered query still answers 503, not a 403', async () => {+ const newsletterDelete = jest.fn(() => new Promise<never>(() => undefined));+ await expect(channels({ newsletterDelete }, 15).deleteChannel('120363@newsletter')).rejects.toBeInstanceOf(+ EngineTransportError,+ );+ });++ it('the WMex no-answer shape is not a refusal either — its data is null', async () => {+ // executeWMexQuery's other throw: Boom(..., { statusCode: 400, data: result }) with result+ // undefined, which Boom normalises to null.+ const noAnswer = new Boom('Failed to newsletter metadata, unexpected response structure.', { statusCode: 400 });+ const newsletterDelete = jest.fn().mockRejectedValue(noAnswer);+ await expect(channels({ newsletterDelete }, 500).deleteChannel('120363@newsletter')).rejects.toBe(noAnswer);+ });+});