Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): stop serving an unanswered group query as an empty group list
Yudhi Armyndharisd134a41f9173
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7e0d75603..ffb3b4fec 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 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.- **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.diff --git a/openapi.json b/openapi.jsonindex c6b5955f8..268e182ab 100644--- a/openapi.json+++ b/openapi.json@@ -853,6 +853,9 @@},"404": {"description": "Session not found"+ },+ "503": {+ "description": "WhatsApp did not answer the group-list query. Deliberately not reported as an empty list — the engine returns the same empty value for \"you are in no groups\", and a caller cannot tell those apart from the body."}},"summary": "Get all groups for a session",diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 1f44d7f88..a86efa682 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -2,7 +2,7 @@ import type { WAMessageKey, WASocket } from '@whiskeysockets/baileys';import { ChatSummary, Contact, MediaInput } from '../interfaces/whatsapp-engine.interface';import { resolveMediaBuffer } from './baileys-messaging';import { type createLogger } from '../../common/services/logger.service';-import { BAILEYS_WRITE_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';+import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';/*** Contacts/profile/chats-domain operations extracted from BaileysAdapter. The adapter keeps the@@ -28,12 +28,12 @@ export interface BaileysContactsHost {export class BaileysContacts {constructor(private readonly host: BaileysContactsHost,- private readonly writeBudgetMs: number = BAILEYS_WRITE_BUDGET_MS,+ private readonly queryBudgetMs: number = BAILEYS_QUERY_BUDGET_MS,) {}/** Bound a write whose confirmation the library discards; see baileys-query-deadline.ts. */private confirmed<T>(work: Promise<T>, operation: string): Promise<T> {- return withQueryDeadline(work, this.writeBudgetMs, `WhatsApp did not confirm ${operation} in time`);+ return withQueryDeadline(work, this.queryBudgetMs, `WhatsApp did not confirm ${operation} in time`);}/** Post-ensureReady socket handle. */diff --git a/src/engine/adapters/baileys-group-list.spec.ts b/src/engine/adapters/baileys-group-list.spec.tsnew file mode 100644index 000000000..99bfd5164--- /dev/null+++ b/src/engine/adapters/baileys-group-list.spec.ts@@ -0,0 +1,53 @@+import type { WASocket } from '@whiskeysockets/baileys';+import { BaileysGroups, BaileysGroupsHost } from './baileys-groups';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * `groupFetchAllParticipating` builds its result as `const data = {}` and only fills it behind+ * `if (groupsChild)`. On an unanswered query `getBinaryNodeChild(undefined, 'groups')` is undefined,+ * the block is skipped, and `{}` comes back — the SAME value an account with no groups produces,+ * because that answer carries a real `<groups>` node with no `<group>` children.+ *+ * So there is nothing in the return value to inspect, and the empty list is the dangerous shape: a+ * caller reading `[]` has no way to tell "you are in no groups" from "WhatsApp never answered".+ * Only a clock we own separates them.+ */++function groups(sock: Record<string, jest.Mock>, budgetMs: number): BaileysGroups {+ const host = {+ ensureReady: () => undefined,+ getSocket: () => sock as unknown as WASocket,+ logger: { warn: jest.fn(), debug: jest.fn(), info: jest.fn(), error: jest.fn() },+ toNeutralJid: (j: string) => j,+ toEngineJid: (j: string) => j,+ normalizedSelfJid: () => '[email protected]',+ } as unknown as BaileysGroupsHost;+ return new BaileysGroups(host, budgetMs);+}++describe('getGroups', () => {+ it('reports an unanswered query instead of an empty group list', async () => {+ const groupFetchAllParticipating = jest.fn(() => new Promise<never>(() => undefined));+ await expect(groups({ groupFetchAllParticipating }, 15).getGroups()).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('still returns an empty list when WhatsApp answers that there are no groups', async () => {+ // A real answer that happens to be empty: the library yields {} for this too, so the ONLY thing+ // separating it from the case above is that it arrived.+ const groupFetchAllParticipating = jest.fn().mockResolvedValue({});+ await expect(groups({ groupFetchAllParticipating }, 500).getGroups()).resolves.toEqual([]);+ });++ it('maps a populated answer unchanged', async () => {+ const groupFetchAllParticipating = jest.fn().mockResolvedValue({+ '[email protected]': {+ id: '[email protected]',+ subject: 'Engineering',+ participants: [{ id: '[email protected]', admin: 'superadmin' }],+ },+ });+ const list = await groups({ groupFetchAllParticipating }, 500).getGroups();+ expect(list).toHaveLength(1);+ expect(list[0]).toMatchObject({ id: '[email protected]', name: 'Engineering' });+ });+});diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex 8f2a9c43c..504485a43 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -14,7 +14,7 @@ import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { type createLogger } from '../../common/services/logger.service';-import { BAILEYS_WRITE_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';+import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';/*** Group-domain operations extracted from BaileysAdapter. The adapter keeps the public@@ -85,12 +85,12 @@ export function toEngineParticipants(participants: string[], toEngineJid: (jid:export class BaileysGroups {constructor(private readonly host: BaileysGroupsHost,- private readonly writeBudgetMs: number = BAILEYS_WRITE_BUDGET_MS,+ private readonly queryBudgetMs: number = BAILEYS_QUERY_BUDGET_MS,) {}/** Bound a write whose confirmation the library discards; see baileys-query-deadline.ts. */private confirmed<T>(work: Promise<T>, operation: string): Promise<T> {- return withQueryDeadline(work, this.writeBudgetMs, `WhatsApp did not confirm ${operation} in time`);+ return withQueryDeadline(work, this.queryBudgetMs, `WhatsApp did not confirm ${operation} in time`);}/** Post-ensureReady socket handle. */@@ -105,7 +105,14 @@ export class BaileysGroups {async getGroups(): Promise<Group[]> {this.host.ensureReady();- const all = await this.sock().groupFetchAllParticipating();+ // groupFetchAllParticipating yields {} for BOTH an unanswered query and an account with no+ // groups, so the empty list carries no signal — only our own clock separates them, and an+ // empty list is the shape a caller is least able to question.+ const all = await withQueryDeadline(+ this.sock().groupFetchAllParticipating(),+ this.queryBudgetMs,+ 'WhatsApp did not answer the group list query in time',+ );const self = this.host.normalizedSelfJid();return Object.values(all).map(metadata => mapBaileysGroup(metadata, self, jid => this.host.toNeutralJid(jid)));}diff --git a/src/engine/adapters/baileys-query-deadline.ts b/src/engine/adapters/baileys-query-deadline.tsindex 832371379..d181de668 100644--- a/src/engine/adapters/baileys-query-deadline.ts+++ b/src/engine/adapters/baileys-query-deadline.ts@@ -43,7 +43,7 @@ export async function withQueryDeadline<T>(work: Promise<T>, timeoutMs: number,}/**- * Budget for a single Baileys write. Anchored to MEDIA_DOWNLOAD_TIMEOUT_MS (inbound-media-cap.ts),+ * Budget for a single bounded Baileys call, read or write. Anchored to MEDIA_DOWNLOAD_TIMEOUT_MS (inbound-media-cap.ts),* this repo's existing figure for one bounded network round trip over WhatsApp. It must stay under* Baileys' 60s `defaultQueryTimeoutMs` to be observable at all, and under `session.proxyTimeoutMs`* so a multi-node deployment does not race two deadlines against each other.@@ -53,4 +53,4 @@ export async function withQueryDeadline<T>(work: Promise<T>, timeoutMs: number,* unconfirmed. That is the deliberate trade: an honest "not confirmed" beats a "done" for a change* WhatsApp never acknowledged, and every write bounded here is safe to repeat.*/-export const BAILEYS_WRITE_BUDGET_MS = 30_000;+export const BAILEYS_QUERY_BUDGET_MS = 30_000;diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 1926a3f56..1b836151a 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -368,6 +368,13 @@ export class SessionController {})@ApiResponse({ status: 400, description: 'Session not ready' })@ApiResponse({ status: 404, description: 'Session not found' })+ @ApiResponse({+ status: 503,+ description:+ 'WhatsApp did not answer the group-list query. Deliberately not reported as an empty list — ' ++ 'the engine returns the same empty value for "you are in no groups", and a caller cannot tell ' ++ 'those apart from the body.',+ })@ApiQuery({ name: 'limit', required: false, description: 'Max groups to return (1–1000, default 1000)' })@ApiQuery({ name: 'offset', required: false, description: 'Number of groups to skip (for paging)' })async getGroups(