Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): bound the group-metadata reads, and map a refused group create
Yudhi Armyndharis0aa264ace783
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ffb3b4fec..aaa1993b4 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+- **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.- **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.diff --git a/openapi.json b/openapi.jsonindex 268e182ab..6476c61a6 100644--- a/openapi.json+++ b/openapi.json@@ -4197,6 +4197,9 @@},"404": {"description": "No such invite — invalid, expired or revoked"+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget. Deliberately not folded into the 404 above — a query that never came back is not the same claim as a group that does not exist."}},"summary": "Preview a group from its invite code, without joining",@@ -4241,6 +4244,9 @@},"404": {"description": "Group not found"+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget. Deliberately not folded into the 404 above — a query that never came back is not the same claim as a group that does not exist."}},"summary": "Get detailed group info",diff --git a/src/engine/adapters/baileys-group-metadata.spec.ts b/src/engine/adapters/baileys-group-metadata.spec.tsnew file mode 100644index 000000000..6058b907e--- /dev/null+++ b/src/engine/adapters/baileys-group-metadata.spec.ts@@ -0,0 +1,93 @@+import { Boom } from '@hapi/boom';+import type { WASocket } from '@whiskeysockets/baileys';+import { BaileysGroups, BaileysGroupsHost } from './baileys-groups';+import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { GroupNotFoundError } from '../../common/errors/group-not-found.error';++/**+ * The three reads that resolve through Baileys' `extractGroupMetadata`. On an unanswered query it+ * throws `Boom('Invalid group metadata response: missing <group> node', { data: undefined })`, whose+ * `data` Boom normalises to null — so `refusedStatusCode` returns undefined, the raw Boom escapes,+ * and NestJS answers a bare 500 with the message discarded.+ *+ * `createGroup` is deliberately NOT given a deadline: it is the one non-idempotent site, and 503 is+ * a backpressure status the Go SDK retries three times for POST, which would risk duplicate groups.+ * Its bug is a different one — it has no refusal mapping at all.+ */++const never = (): Promise<never> => new Promise<never>(() => undefined);++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);+}++/** What extractGroupMetadata actually throws when the query went unanswered. */+const noAnswer = () => new Boom('Invalid group metadata response: missing <group> node', { data: undefined });++const META = { id: '[email protected]', subject: 'Engineering', participants: [] };++describe('getGroupInfo', () => {+ it('reports an unanswered query instead of a bare 500', async () => {+ await expect(groups({ groupMetadata: jest.fn(never) }, 15).getGroupInfo('[email protected]')).rejects.toBeInstanceOf(+ EngineTransportError,+ );+ });++ it.each([401, 403, 404])('still treats a WA %s refusal as not-found', async code => {+ const groupMetadata = jest.fn().mockRejectedValue(new Boom('refused', { data: code }));+ await expect(groups({ groupMetadata }, 500).getGroupInfo('[email protected]')).resolves.toBeNull();+ });++ it('still returns the group when WhatsApp answers inside the budget', async () => {+ const groupMetadata = jest.fn().mockResolvedValue(META);+ await expect(groups({ groupMetadata }, 500).getGroupInfo('[email protected]')).resolves.toMatchObject({+ id: '[email protected]',+ });+ });+});++describe('getGroupJoinInfo', () => {+ it('reports an unanswered query instead of a bare 500', async () => {+ await expect(groups({ groupGetInviteInfo: jest.fn(never) }, 15).getGroupJoinInfo('CODE')).rejects.toBeInstanceOf(+ EngineTransportError,+ );+ });++ it('still maps a refused invite to not-found', async () => {+ const groupGetInviteInfo = jest.fn().mockRejectedValue(new Boom('item-not-found', { data: 404 }));+ await expect(groups({ groupGetInviteInfo }, 500).getGroupJoinInfo('BAD')).rejects.toBeInstanceOf(+ GroupNotFoundError,+ );+ });+});++describe('createGroup', () => {+ it('maps a WA refusal to a refusal instead of a bare 500', async () => {+ const groupCreate = jest.fn().mockRejectedValue(new Boom('not-authorized', { data: 403 }));+ await expect(groups({ groupCreate }, 500).createGroup('G', [])).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('lets an unanswered query propagate untouched — deliberately NOT a 503', async () => {+ // 503 is a backpressure status the Go SDK retries for POST; a deadline here could create+ // duplicate WhatsApp groups. The opaque failure is preferred over a retried side effect.+ const err = noAnswer();+ const groupCreate = jest.fn().mockRejectedValue(err);+ await expect(groups({ groupCreate }, 500).createGroup('G', [])).rejects.toBe(err);+ });++ it('still returns the created group', async () => {+ const groupCreate = jest.fn().mockResolvedValue(META);+ await expect(groups({ groupCreate }, 500).createGroup('G', [])).resolves.toMatchObject({+ id: '[email protected]',+ });+ });+});diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex 504485a43..f5c777f56 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -120,7 +120,11 @@ export class BaileysGroups {async getGroupInfo(groupId: string): Promise<GroupInfo | null> {this.host.ensureReady();try {- const metadata = await this.sock().groupMetadata(groupId);+ const metadata = await withQueryDeadline(+ this.sock().groupMetadata(groupId),+ this.queryBudgetMs,+ 'WhatsApp did not answer the group metadata query in time',+ );return mapBaileysGroupInfo(metadata, jid => this.host.toNeutralJid(jid));} catch (err) {// Only a SERVER refusal may become null (→ service 404): the group does not exist or the@@ -138,9 +142,18 @@ export class BaileysGroups {}}+ /**+ * Deliberately NOT bounded by a deadline, unlike the reads either side of it. Creating a group is+ * the one non-idempotent operation here, and 503 is a backpressure status the Go SDK retries three+ * times for POST (sdk/go/retry.go) — an OpenWA deadline abandons the call without cancelling it,+ * so a slow-but-succeeding create could be issued four times and leave duplicate groups. An+ * unanswered query therefore still surfaces opaquely rather than as something retryable.+ */async createGroup(name: string, participants: string[]): Promise<Group> {this.host.ensureReady();- const metadata = await this.sock().groupCreate(name, this.toEngineParticipants(participants));+ const metadata = await mapServerRefusal('Creating the group', () =>+ this.sock().groupCreate(name, this.toEngineParticipants(participants)),+ );return mapBaileysGroup(metadata, this.host.normalizedSelfJid(), jid => this.host.toNeutralJid(jid));}@@ -250,7 +263,11 @@ export class BaileysGroups {this.host.ensureReady();let meta: Awaited<ReturnType<WASocket['groupGetInviteInfo']>>;try {- meta = await this.sock().groupGetInviteInfo(inviteCode);+ meta = await withQueryDeadline(+ this.sock().groupGetInviteInfo(inviteCode),+ this.queryBudgetMs,+ 'WhatsApp did not answer the invite-info query in time',+ );} catch (error) {// Baileys throws a Boom carrying the WA code for an invalid/expired/revoked invite — the// route's documented 404 (matching whatsapp-web.js), not a 500. Transport failures propagate.diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.tsindex e933d0339..113824464 100644--- a/src/modules/group/group.controller.ts+++ b/src/modules/group/group.controller.ts@@ -54,6 +54,12 @@ export class GroupController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiQuery({ name: 'code', description: 'Group invite code (the part after the invite link)' })@ApiResponse({ status: 200, description: 'What the invite discloses about the group', type: GroupJoinInfoDto })+ @ApiResponse({+ status: 503,+ description:+ 'WhatsApp did not answer within the request budget. Deliberately not folded into the 404 above — ' ++ 'a query that never came back is not the same claim as a group that does not exist.',+ })@ApiResponse({ status: 400, description: 'Session not started, or no code supplied' })@ApiResponse({ status: 404, description: 'No such invite — invalid, expired or revoked' })async joinInfo(@Param('sessionId') sessionId: string, @Query('code') code: string) {@@ -65,6 +71,12 @@ export class GroupController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'groupId', description: 'Group ID (e.g., [email protected])' })@ApiResponse({ status: 200, description: 'Group details with participants', type: GroupInfoDto })+ @ApiResponse({+ status: 503,+ description:+ 'WhatsApp did not answer within the request budget. Deliberately not folded into the 404 above — ' ++ 'a query that never came back is not the same claim as a group that does not exist.',+ })@ApiResponse({ status: 404, description: 'Group not found' })async findOne(@Param('sessionId') sessionId: string, @Param('groupId') groupId: string) {return this.groupService.getGroupInfo(sessionId, groupId);