Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): answer a chat-label write on an unknown chat with 404
Yudhi Armyndharis4960a1d4425d
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex c8d798daf..8ff7c7e2c 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4100,7 +4100,7 @@ Add a label to a chat.The handler always returns the literal `{ "success": true }`.-**Errors:** `400` validation failure (missing/empty/non-string `labelId`, or any unknown body field — strict whitelist), or session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `409` conflict or engine not ready (retryable) · `422` labels require a WhatsApp Business account, or the chat type has no labels · `503` session not ready or dependency unavailable (retryable)+**Errors:** `400` validation failure (missing/empty/non-string `labelId`, or any unknown body field — strict whitelist), or session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` (whatsapp-web.js) the chat does not exist on this session, so nothing was written · `409` conflict or engine not ready (retryable) · `422` labels require a WhatsApp Business account, or the chat type has no labels · `503` session not ready or dependency unavailable (retryable)#### DELETE /api/sessions/:sessionId/labels/chat/:chatId/:labelId@@ -4124,7 +4124,7 @@ Remove a label from a chat.The handler always returns `{ "success": true }`. DELETE default status is `200` (no `@HttpCode` override).-**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `409` conflict or engine not ready (retryable) · `422` labels require a WhatsApp Business account, or the chat type has no labels · `503` session not ready or dependency unavailable (retryable)+**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` (whatsapp-web.js) the chat does not exist on this session, so nothing was written · `409` conflict or engine not ready (retryable) · `422` labels require a WhatsApp Business account, or the chat type has no labels · `503` session not ready or dependency unavailable (retryable)#### GET /api/sessions/:sessionId/statusdiff --git a/openapi.json b/openapi.jsonindex 9de99af4a..db4e827fd 100644--- a/openapi.json+++ b/openapi.json@@ -6898,6 +6898,9 @@}}},+ "404": {+ "description": "The chat does not exist on this session, so nothing was written (whatsapp-web.js)"+ },"409": {"description": "The session is not connected: an engine exists for it but is not `ready`, meaning disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it, and for those few seconds the answer is a `409` naming the reload; retry shortly."},@@ -6957,6 +6960,9 @@}}},+ "404": {+ "description": "The chat does not exist on this session, so nothing was written (whatsapp-web.js)"+ },"409": {"description": "The session is not connected: an engine exists for it but is not `ready`, meaning disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it, and for those few seconds the answer is a `409` naming the reload; retry shortly."},diff --git a/src/engine/adapters/wwebjs-label-transport-death.spec.ts b/src/engine/adapters/wwebjs-label-transport-death.spec.tsindex 2e835b6cf..f4b685c91 100644--- a/src/engine/adapters/wwebjs-label-transport-death.spec.ts+++ b/src/engine/adapters/wwebjs-label-transport-death.spec.ts@@ -1,3 +1,4 @@+import { NotFoundException } from '@nestjs/common';import type { Client } from 'whatsapp-web.js';import { WwebjsLabels } from './wwebjs-labels';import { createLogger } from '../../common/services/logger.service';@@ -96,8 +97,9 @@ describe('label operations distinguish a dead page from an ordinary failure', ()});// Client.getChatById resolves undefined for a chat the page cannot resolve; dereferencing it was a- // TypeError, a 500 on GET and on both chat-label writes that read the current set first.- it('treats an unresolved chat as carrying no labels', async () => {+ // TypeError, a 500 on GET and on both chat-label writes that read the current set first. The read+ // answers an empty set, but a write must not: upstream resolves it as a silent no-op.+ it('reads an unresolved chat as unlabelled and refuses to write to it', async () => {const client = {getChatById: jest.fn().mockResolvedValue(undefined),addOrRemoveLabels: jest.fn().mockResolvedValue(undefined),@@ -112,7 +114,8 @@ describe('label operations distinguish a dead page from an ordinary failure', ()const labels = new WwebjsLabels(host);await expect(labels.getChatLabels('[email protected]')).resolves.toEqual([]);- await expect(labels.addLabelToChat('[email protected]', '7')).resolves.toBeUndefined();- expect(client.addOrRemoveLabels).toHaveBeenCalledWith(['7'], ['[email protected]']);+ await expect(labels.addLabelToChat('[email protected]', '7')).rejects.toBeInstanceOf(NotFoundException);+ await expect(labels.removeLabelFromChat('[email protected]', '7')).rejects.toBeInstanceOf(NotFoundException);+ expect(client.addOrRemoveLabels).not.toHaveBeenCalled();});});diff --git a/src/engine/adapters/wwebjs-labels.ts b/src/engine/adapters/wwebjs-labels.tsindex 53d5d0f52..e1f27c2ba 100644--- a/src/engine/adapters/wwebjs-labels.ts+++ b/src/engine/adapters/wwebjs-labels.ts@@ -1,3 +1,4 @@+import { NotFoundException } from '@nestjs/common';import { type Client } from 'whatsapp-web.js';import { Label, ChatSummary } from '../interfaces/whatsapp-engine.interface';import { GroupChat, BusinessClient } from '../types/whatsapp-web-js.types';@@ -121,14 +122,18 @@ export class WwebjsLabels {// Return empty instead of letting the unguarded call throw a TypeError (HTTP 500).return [];}+ // An unknown chat carries no labels, which is an honest answer for a read.+ return (await this.readChatLabels(chatId)) ?? [];+ }++ /** The chat's labels, or null when the page cannot resolve the chat (getChatById resolves undefined). */+ private async readChatLabels(chatId: string): Promise<Label[] | null> {const labels = await withPage(this.host, 'getChatLabels', async () => {const chat = await this.client().getChatById(chatId);- // getChatById resolves undefined for a chat the page cannot resolve; an unknown chat carries no- // labels, and the label write then matches no chat page-side, the same no-op upstream makes.- return chat ? (chat as unknown as GroupChat).getLabels() : [];+ return chat ? ((await (chat as unknown as GroupChat).getLabels()) ?? []) : null;});if (!labels) {- return [];+ return null;}return labels.map(label => ({@@ -163,7 +168,13 @@ export class WwebjsLabels {if (isChannelJid(chatId)) {throw new ChatLabelsUnsupportedError('Channels do not support chat labels.');}- const ids = new Set((await this.getChatLabels(chatId)).map(label => label.id));+ // Not the read's empty answer: addOrRemoveLabels matches no chat page-side for an unknown id and+ // resolves without writing anything, which the route would report as success.+ const current = await this.readChatLabels(chatId);+ if (!current) {+ throw new NotFoundException(`Chat ${chatId} does not exist on this session`);+ }+ const ids = new Set(current.map(label => label.id));if (add) {ids.add(labelId);} else {diff --git a/src/modules/label/label.controller.ts b/src/modules/label/label.controller.tsindex 8053b32df..6ac7c334f 100644--- a/src/modules/label/label.controller.ts+++ b/src/modules/label/label.controller.ts@@ -175,6 +175,10 @@ export class LabelController {},})@ApiResponse({ status: 200, description: 'Label added to chat', type: LabelAckResponseDto })+ @ApiResponse({+ status: 404,+ description: 'The chat does not exist on this session, so nothing was written (whatsapp-web.js)',+ })@ApiResponse({status: 422,description: 'Labels require a WhatsApp Business account, or the chat type has no labels',@@ -202,6 +206,10 @@ export class LabelController {@ApiParam({ name: 'chatId', description: 'Chat ID' })@ApiParam({ name: 'labelId', description: 'Label ID to remove' })@ApiResponse({ status: 200, description: 'Label removed from chat', type: LabelAckResponseDto })+ @ApiResponse({+ status: 404,+ description: 'The chat does not exist on this session, so nothing was written (whatsapp-web.js)',+ })@ApiResponse({status: 422,description: 'Labels require a WhatsApp Business account, or the chat type has no labels',