Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): report an unresolvable chat as bad input on pin and mute
Yudhi Armyndharis779dfcbc7158
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e45db8fea..044699d94 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -36,6 +36,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- `POST /sessions/:id/chats/pin` and `chats/mute` answer `400` instead of an undeclared `500` on the whatsapp-web.js engine when handed a chat the session cannot resolve. Both routes are new in this release and were the only two members of their family without the resolution guard their neighbours carry, so a stale chatId reached the page and rejected there β `No LID for user` for a pin, a `TypeError` from inside `_muteUnmuteChat` for a mute. An unknown chat is reported as bad input rather than as `success: false`, which on the pin route already means the three-pin cap refused a real chat. A page-side failure on a chat that does resolve is still a `500`, since that is the only signal a renamed WhatsApp Web internal produces. The Baileys engine writes app state without resolving the chat first and still answers `success: true`.- `docs/29`'s architecture diagram counted four whatsapp-web.js patches and one Baileys patch while this release shipped a fifth and a second, and `π§β·` marked no cell, so the three whatsapp-web.js participant writes read as working against a stock library. The patch counts are now derived from `scripts/` by `docs-29-counts.spec.ts`, which bound only the interface figures before. `docs/09` Β§9.6 also omitted the two gates added to CI and described the release workflow as a lighter gate than the one it now runs.- `check:sdk-coverage` no longer passes when a client drops a route entirely: a wildcard the client built for a path parameter β `contacts/${contactId}` β was read as a one-builder family and stood in for every concrete sibling under it, so removing `contacts/blocked` from a client left the gate green. A wildcard now counts as a family only where the contract publishes no route of that shape.- The Go SDK no longer approves or rejects every pending join request when handed an empty participant list: `omitempty` dropped the empty slice, so `[]string{}` reached the gateway as the bodyless "act on every request" rather than the `400` the other four clients receive. A nil slice still means every request.diff --git a/openapi.json b/openapi.jsonindex cf9cc515a..d0a0ed802 100644--- a/openapi.json+++ b/openapi.json@@ -1393,7 +1393,7 @@"description": "Returns `{ success }`. `false` means the engine declined, and only a pin can: WhatsApp allows at most three pinned chats and the whatsapp-web.js engine reports the refusal. Unpinning always succeeds, and the Baileys engine always reports success because it cannot observe the cap."},"400": {- "description": "Session not ready"+ "description": "Session not ready, or a chatId the session cannot resolve. An unknown chat is reported here rather than as `success: false`, which on this route means only that the three-pin cap refused a real chat. The Baileys engine cannot resolve chats ahead of the write and answers `success: true` for an unknown chat."},"404": {"description": "Session not found"diff --git a/src/engine/adapters/chat-mute.spec.ts b/src/engine/adapters/chat-mute.spec.tsindex 341e255fb..309f26278 100644--- a/src/engine/adapters/chat-mute.spec.ts+++ b/src/engine/adapters/chat-mute.spec.ts@@ -33,6 +33,7 @@ describe('WwebjsChats.muteChat', () => {const client = {muteChat: jest.fn().mockResolvedValue({ isMuted: true, muteExpiration: MUTE_UNTIL }),unmuteChat: jest.fn().mockResolvedValue({ isMuted: false, muteExpiration: 0 }),+ getChatById: jest.fn().mockResolvedValue({ id: { _serialized: '[email protected]' } }),};const host = {ensureReady: jest.fn(),@@ -65,6 +66,48 @@ describe('WwebjsChats.muteChat', () => {client.muteChat.mockRejectedValue(new Error('page died'));await expect(chats.muteChat('[email protected]', MUTE_UNTIL)).rejects.toThrow('page died');});++ /**+ * Live against a real session, muting a chat the page could not resolve rejected from inside+ * `Client._muteUnmuteChat`'s evaluate with `TypeError: this.findImpl is not a function`, which+ * NestJS turns into a bare 500 β a status this route never declares, while its own 400 already+ * reads "an invalid chatId". The same call against a real chat succeeded, so the capability was+ * never the problem; only the unresolvable-chat path was.+ */+ describe.each([+ ['the page resolves no such chat', (c: { [k: string]: jest.Mock }) => c.getChatById.mockResolvedValue(undefined)],+ [+ 'the page rejects the lookup',+ (c: { [k: string]: jest.Mock }) => c.getChatById.mockRejectedValue(new Error('No LID for user')),+ ],+ ])('an unknown chat is bad input, not a server fault β %s', (_label, arrange) => {+ it('rejects with a 400 and never reaches the mute call', async () => {+ const { chats, client } = makeChats();+ arrange(client);+ await expect(chats.muteChat('[email protected]', MUTE_UNTIL)).rejects.toMatchObject({ status: 400 });+ expect(client.muteChat).not.toHaveBeenCalled();+ });++ it('guards the unmute direction too', async () => {+ const { chats, client } = makeChats();+ arrange(client);+ await expect(chats.muteChat('[email protected]', null)).rejects.toMatchObject({ status: 400 });+ expect(client.unmuteChat).not.toHaveBeenCalled();+ });+ });++ /**+ * The other half of the same fix, and the reason the guard resolves the chat instead of wrapping+ * the mute call: a page-side rejection for a chat that DOES exist is exactly what a renamed page+ * internal produces, and that is how `createGroup` was caught. Demoting it to 400 would relabel a+ * dead capability as the caller's bad input.+ */+ it('a page failure on a chat that DOES resolve stays a server error, not a 400', async () => {+ const { chats, client } = makeChats();+ client.muteChat.mockRejectedValue(new TypeError('this.findImpl is not a function'));+ await expect(chats.muteChat('[email protected]', MUTE_UNTIL)).rejects.toThrow('findImpl');+ await expect(chats.muteChat('[email protected]', MUTE_UNTIL)).rejects.not.toMatchObject({ status: 400 });+ });});describe('BaileysContacts.muteChat', () => {diff --git a/src/engine/adapters/chat-pin.spec.ts b/src/engine/adapters/chat-pin.spec.tsindex 7034ca422..8901360d0 100644--- a/src/engine/adapters/chat-pin.spec.ts+++ b/src/engine/adapters/chat-pin.spec.ts@@ -34,6 +34,7 @@ describe('WwebjsChats.pinChat', () => {const client = {pinChat: jest.fn().mockResolvedValue(true),unpinChat: jest.fn().mockResolvedValue(false),+ getChatById: jest.fn().mockResolvedValue({ id: { _serialized: '[email protected]' } }),};const host = {ensureReady: jest.fn(),@@ -65,6 +66,43 @@ describe('WwebjsChats.pinChat', () => {expect(client.unpinChat).toHaveBeenCalledWith('[email protected]');expect(client.pinChat).not.toHaveBeenCalled();});++ /**+ * Live, pinning a chat the page could not resolve rejected with `Error: No LID for user` and+ * surfaced as a bare 500 β undeclared on this route, while `chats/read` and `chats/archive`+ * answer the same unknown chat gracefully.+ *+ * `false` is deliberately NOT the answer here, unlike those two: on this route `false` already+ * means the three-pin cap refused a real chat, so reusing it would tell a caller holding a stale+ * chatId that its pin quota is full.+ */+ describe.each([+ ['the page resolves no such chat', (c: { [k: string]: jest.Mock }) => c.getChatById.mockResolvedValue(undefined)],+ [+ 'the page rejects the lookup',+ (c: { [k: string]: jest.Mock }) => c.getChatById.mockRejectedValue(new Error('No LID for user')),+ ],+ ])('an unknown chat is bad input, and must not read as the pin cap β %s', (_label, arrange) => {+ it.each([true, false])('rejects with a 400 rather than false, pin=%s', async pin => {+ const { chats, client } = makeChats();+ arrange(client);+ const call = chats.pinChat('[email protected]', pin);+ await expect(call).rejects.toMatchObject({ status: 400 });+ // The distinction the cap depends on: a refusal is `false`, an unknown chat never resolves.+ await expect(call).rejects.not.toBe(false);+ expect(client.pinChat).not.toHaveBeenCalled();+ expect(client.unpinChat).not.toHaveBeenCalled();+ });+ });++ // The guard resolves the chat rather than wrapping the pin call, so a page-side break on a chat+ // that DOES exist still reaches the caller β the signal that caught wwjs `createGroup`.+ it('a page failure on a chat that DOES resolve stays a server error, not a 400', async () => {+ const { chats, client } = makeChats();+ client.pinChat.mockRejectedValue(new TypeError('this.findImpl is not a function'));+ await expect(chats.pinChat('[email protected]', true)).rejects.toThrow('findImpl');+ await expect(chats.pinChat('[email protected]', true)).rejects.not.toMatchObject({ status: 400 });+ });});describe('BaileysContacts.pinChat', () => {diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.tsindex 61a49ff95..d95b7f34a 100644--- a/src/engine/adapters/wwebjs-chats.ts+++ b/src/engine/adapters/wwebjs-chats.ts@@ -1,3 +1,4 @@+import { BadRequestException } from '@nestjs/common';import { MessageTypes, type Client } from 'whatsapp-web.js';import { ChatSummary, ChatState } from '../interfaces/whatsapp-engine.interface';import { EngineTransportError } from '../../common/errors/engine-transport.error';@@ -119,8 +120,29 @@ export class WwebjsChats {}}+ /**+ * whatsapp-web.js signals a chat it cannot resolve by rejecting deep inside the page β `No LID for+ * user` from pin's WID lookup, a TypeError from the evaluate inside `Client._muteUnmuteChat` for+ * mute. Both surfaced as a bare 500, a status neither route declares, while every older member of+ * this family answers an unknown chat gracefully.+ *+ * Resolving the chat first turns that into the 400 the contract already promises. It deliberately+ * does NOT wrap the pin/mute call itself: a page-side rejection for a chat that DOES exist is the+ * one signal a renamed page internal produces, and demoting it to "bad input" would hide a total+ * capability failure β the shape `createGroup` turned out to have. `getChatById` is the same+ * resolution five neighbours here already trust, and it reports an unknown chat either way it can,+ * by resolving undefined or by rejecting.+ */+ private async requireResolvableChat(chatId: string): Promise<void> {+ const chat = await this.client()+ .getChatById(chatId)+ .catch(() => undefined);+ if (!chat) throw new BadRequestException(`Chat ${chatId} does not exist on this session`);+ }+async muteChat(chatId: string, muteUntil: number | null): Promise<void> {this.host.ensureReady();+ await this.requireResolvableChat(chatId);if (muteUntil === null) {await this.client().unmuteChat(chatId);return;@@ -132,6 +154,10 @@ export class WwebjsChats {async pinChat(chatId: string, pin: boolean): Promise<boolean> {this.host.ensureReady();+ // Not `return false` for an unknown chat: `false` is already taken here, and means the three-pin+ // cap refused a real chat. Conflating the two would tell a caller with a stale chatId that its+ // pin quota is full.+ await this.requireResolvableChat(chatId);if (!pin) {// unpinChat resolves the chat's NEW pin state, which is `false` for every successful unpin β// both on its early-out for an already-unpinned chat and after actually unpinningdiff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex d2c67d9ed..8d531462d 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -648,7 +648,14 @@ export class SessionController {'at most three pinned chats and the whatsapp-web.js engine reports the refusal. Unpinning always ' +'succeeds, and the Baileys engine always reports success because it cannot observe the cap.',})- @ApiResponse({ status: 400, description: 'Session not ready' })+ @ApiResponse({+ status: 400,+ description:+ 'Session not ready, or a chatId the session cannot resolve. An unknown chat is reported here ' ++ 'rather than as `success: false`, which on this route means only that the three-pin cap ' ++ 'refused a real chat. The Baileys engine cannot resolve chats ahead of the write and answers ' ++ '`success: true` for an unknown chat.',+ })@ApiResponse({ status: 404, description: 'Session not found' })@ApiResponse({status: 503,