Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): correct HTTP status for an unknown chat and a sharp load failure
Yudhi Armyndharis8aa2a57c57e5
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex dd9ef465e..570f9ff5d 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -18,7 +18,7 @@ import {import { toEngineParticipants } from './baileys-groups';import { buildVCard } from './vcard';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';-import { BadRequestException } from '@nestjs/common';+import { BadRequestException, InternalServerErrorException } from '@nestjs/common';import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { MessageNotFoundError } from '../../common/errors/message-not-found.error';import { type createLogger } from '../../common/services/logger.service';@@ -85,6 +85,21 @@ function isWebpBuffer(data: Buffer): boolean {* `{ animated: true }` is not optional β without it sharp silently keeps only the first frame, which* would reintroduce the same quiet-corruption this function exists to remove.*/+/**+ * Load the deferred `sharp` binary, mapping a LOAD failure to a 500 rather than the decode path's 400.+ * A native-binary load failure (older CPU, stripped/musl image, missing prebuilt) is a host capability+ * gap: a valid PNG would hit it too, so reporting it as a 400 tells the caller their image is malformed.+ */+export async function loadSharp() {+ try {+ return (await import('sharp')).default;+ } catch (error) {+ throw new InternalServerErrorException(+ `Sticker conversion is unavailable: sharp could not load (${error instanceof Error ? error.message : String(error)}).`,+ );+ }+}+async function toWebpSticker(data: Buffer, mimetype: string): Promise<Buffer> {if (isWebpBuffer(data)) {return data;@@ -97,13 +112,13 @@ async function toWebpSticker(data: Buffer, mimetype: string): Promise<Buffer> {`A sticker must be a WebP image, or an image this gateway can convert to one. Received '${mimetype}'.`,);}+ // Imported lazily so an unusable `sharp` (a native binary that will not build or load on an older+ // CPU, a stripped image) degrades ONLY this one Baileys sticker route instead of killing the whole+ // gateway at boot. `sharp` sits at the top of a module the built-in engine loads unconditionally, so+ // an eager import made a single optional capability a hard boot requirement on both engines. Same+ // deferral the adapters already use for the engine libraries themselves.+ const sharp = await loadSharp();try {- // Imported lazily so an unusable `sharp` (a native binary that will not build or load on an- // older CPU, a stripped image) degrades ONLY this one Baileys sticker route instead of killing- // the whole gateway at boot. `sharp` sits at the top of a module the built-in engine loads- // unconditionally, so an eager import made a single optional capability a hard boot requirement- // on both engines. Same deferral the adapters already use for the engine libraries themselves.- const { default: sharp } = await import('sharp');return await sharp(data, { animated: true }).resize(512, 512, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } }).webp()diff --git a/src/engine/adapters/baileys-sharp-load.spec.ts b/src/engine/adapters/baileys-sharp-load.spec.tsnew file mode 100644index 000000000..221c1809c--- /dev/null+++ b/src/engine/adapters/baileys-sharp-load.spec.ts@@ -0,0 +1,16 @@+import { InternalServerErrorException } from '@nestjs/common';++// Force the deferred `sharp` binary to fail to load, the way an older CPU or a stripped/musl image+// does at runtime. The dynamic import inside loadSharp then rejects.+jest.mock('sharp', () => {+ throw new Error('ERR_DLOPEN_FAILED: sharp native binary could not be loaded');+});++import { loadSharp } from './baileys-messaging';++describe('loadSharp', () => {+ it('maps a sharp native-load failure to a 500, not the decode path 400', async () => {+ // A valid PNG would hit this same path, so a 400 would wrongly blame the caller's image.+ await expect(loadSharp()).rejects.toBeInstanceOf(InternalServerErrorException);+ });+});diff --git a/src/engine/adapters/wwebjs-messaging-unknown-chat.spec.ts b/src/engine/adapters/wwebjs-messaging-unknown-chat.spec.tsnew file mode 100644index 000000000..8693d547a--- /dev/null+++ b/src/engine/adapters/wwebjs-messaging-unknown-chat.spec.ts@@ -0,0 +1,43 @@+import type { Client } from 'whatsapp-web.js';+import { WwebjsMessaging } from './wwebjs-messaging';+import { createLogger } from '../../common/services/logger.service';+import { type WwebjsEngineHost } from './wwebjs-host';+import { MessageNotFoundError } from '../../common/errors/message-not-found.error';++/**+ * getChatById RESOLVES undefined for a chat this account cannot see (whatsapp-web.js does not throw).+ * reactToMessage/getMessageReactions/deleteMessage then dereferenced it (`chat.fetchMessages`) with no+ * guard, so an unknown chatId produced a TypeError that withPage rethrew as an opaque 500, while the+ * sibling editMessage returned the MessageNotFoundError (404) it deliberately throws for the same input.+ * getChatHistory has no message to 404 on, so a chat with no accessible history yields an empty page.+ */+const logger = createLogger('wwebjs-messaging-unknown-chat.spec');+const CHAT = '[email protected]';+const MESSAGE_ID = '[email protected]_ABC';++function makeMessaging(): WwebjsMessaging {+ const client = { getChatById: jest.fn().mockResolvedValue(undefined) };+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ isPageTransportError: () => false,+ reportIfPageTransportError: jest.fn(),+ logger,+ } as unknown as WwebjsEngineHost;+ return new WwebjsMessaging(host);+}++describe('an unknown chat resolves to 404 (or an empty history), not a 500', () => {+ it('reactToMessage throws MessageNotFoundError', async () => {+ await expect(makeMessaging().reactToMessage(CHAT, MESSAGE_ID, 'π')).rejects.toBeInstanceOf(MessageNotFoundError);+ });+ it('getMessageReactions throws MessageNotFoundError', async () => {+ await expect(makeMessaging().getMessageReactions(CHAT, MESSAGE_ID)).rejects.toBeInstanceOf(MessageNotFoundError);+ });+ it('deleteMessage throws MessageNotFoundError', async () => {+ await expect(makeMessaging().deleteMessage(CHAT, MESSAGE_ID)).rejects.toBeInstanceOf(MessageNotFoundError);+ });+ it('getChatHistory returns an empty page rather than throwing', async () => {+ await expect(makeMessaging().getChatHistory(CHAT, 10)).resolves.toEqual([]);+ });+});diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex 38f521761..50b807fa5 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -618,6 +618,11 @@ export class WwebjsMessaging {// id, not this chatId, so LID-resolving the lookup gives no send benefit and would miss a message// stored under the pre-migration @c.us chat (#583 R1 review).const chat = await this.client().getChatById(chatId);+ // getChatById RESOLVES undefined for an unknown chat (wwebjs does not throw); guard it so the+ // caller gets the 404 editMessage returns rather than a TypeError surfacing as an opaque 500.+ if (!chat) {+ throw new MessageNotFoundError(messageId, chatId);+ }const messages = await chat.fetchMessages({ limit: 100 });const message = messages.find(m => m.id._serialized === messageId);if (!message) {@@ -632,6 +637,9 @@ export class WwebjsMessaging {this.host.ensureReady();const reactions = await this.withPage('getMessageReactions', async () => {const chat = await this.client().getChatById(chatId);+ if (!chat) {+ throw new MessageNotFoundError(messageId, chatId);+ }const messages = await chat.fetchMessages({ limit: 100 });const message = messages.find(m => m.id._serialized === messageId);if (!message) {@@ -669,6 +677,12 @@ export class WwebjsMessaging {this.host.ensureReady();const messages = await this.withPage('getChatHistory', async () => {const chat = await this.client().getChatById(chatId);+ // Unknown chat: getChatById resolves undefined rather than throwing. A chat this account cannot+ // see has no history to return, so yield an empty page instead of dereferencing undefined (a+ // TypeError that would surface as a 500).+ if (!chat) {+ return [];+ }return chat.fetchMessages({ limit });});const results: IncomingMessage[] = [];@@ -754,6 +768,9 @@ export class WwebjsMessaging {// the pre-migration @c.us chat (#583 R1 review).await this.withPage('deleteMessage', async () => {const chat = await this.client().getChatById(chatId);+ if (!chat) {+ throw new MessageNotFoundError(messageId, chatId);+ }const messages = await chat.fetchMessages({ limit: 100 });const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);if (!message) {