Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): refuse sends the library drops for channels and broadcasts
Yudhi Armyndharisd8b1daa04bb5
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex e0d75ea8a..ac816e19d 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -13,7 +13,7 @@ import {Quotable,} from '../interfaces/whatsapp-engine.interface';import { MessageWithReactions, SerializedWid } from '../types/whatsapp-web-js.types';-import { BadRequestException } from '@nestjs/common';+import { BadRequestException, NotImplementedException } from '@nestjs/common';import { MessageNotFoundError } from '../../common/errors/message-not-found.error';import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';@@ -194,6 +194,23 @@ export function toMessageResult(msg: Message | undefined): MessageResult {return { id: id?._serialized ?? id?.$1 ?? '', timestamp: msg.timestamp };}+/**+ * whatsapp-web.js drops some sends to a channel or a status/broadcast list before it touches the page+ * (`Client.js` sendMessage returns null): a reply, a location or a contact card to any of them, and a+ * poll or a sticker to a status or broadcast list. `toMessageResult` can only read that null as a send+ * that may have gone out, a 500 the send breaker counts, so refuse it up front with a 501. The+ * recipient tests are the library's own, so the two cannot drift. A plain 501, not+ * EngineNotSupportedError: the send methods are supported, and that class marks a whole method+ * unavailable in the capability matrix.+ */+function ensureSendable(chatId: string, shape: 'reply' | 'location' | 'contact card' | 'poll' | 'sticker'): void {+ const channel = /@\w*newsletter\b/.test(chatId);+ if (/@\w*broadcast\b/.test(chatId) || (channel && shape !== 'poll' && shape !== 'sticker')) {+ const to = channel ? 'a channel' : 'a status or broadcast list';+ throw new NotImplementedException(`whatsapp-web.js cannot send a ${shape} to ${to}; nothing was sent.`);+ }+}+/*** Messaging operations extracted from WhatsAppWebJsAdapter: the send paths (with the @c.us -> @lid* resolution cache), reactions, history, delete and edit. The adapter keeps the public methods as@@ -302,6 +319,7 @@ export class WwebjsMessaging {send: (to: string) => Promise<T>,quotedMessageId?: string,): Promise<T> {+ if (quotedMessageId) ensureSendable(chatId, 'reply');const to = await this.resolveSendId(chatId);try {return await send(to);@@ -453,6 +471,7 @@ export class WwebjsMessaging {async sendLocationMessage(chatId: string, location: LocationInput): Promise<MessageResult> {this.host.ensureReady();+ ensureSendable(chatId, 'location');// Import Location class dynamically from whatsapp-web.jsconst module = await import('whatsapp-web.js');const Location = module.Location || module.default?.Location;@@ -471,6 +490,7 @@ export class WwebjsMessaging {async sendContactMessage(chatId: string, contact: ContactCard): Promise<MessageResult> {this.host.ensureReady();+ ensureSendable(chatId, 'contact card');// Shared builder sanitizes name/number (strips CR/LF, digits-only waid) so a crafted contact// can't inject extra vCard fields — the previous inline build interpolated raw values.const vcard = buildVCard(contact);@@ -493,6 +513,7 @@ export class WwebjsMessaging {// hits the same channel crash: for a channel wwjs drops the sticker form and runs processMediaData// with sendToChannel, which still ends at msg.avParams() (Utils.js:518). Guard it too (#673).this.host.ensureNotChannelRecipient(chatId);+ ensureSendable(chatId, 'sticker');// Keep the fetched content-type for a remote URL: here the mimetype selects the conversion, and// whatsapp-web.js returns the media unconverted once it reads as webp (Util.formatImageToWebpSticker).const messageMedia = await toMessageMedia(media, this.host.config.proxy?.url, { trustDeclaredType: false });@@ -514,6 +535,7 @@ export class WwebjsMessaging {async sendPollMessage(chatId: string, poll: PollInput): Promise<MessageResult> {this.host.ensureReady();+ ensureSendable(chatId, 'poll');// Import Poll dynamically like Location; the .default fallback covers builds where the// classes land on module.default (a plain `module.Poll` would be undefined there and// `new Poll` fails with "not a constructor").@@ -540,6 +562,7 @@ export class WwebjsMessaging {async replyToMessage(chatId: string, quotedMsgId: string, text: string, mentions?: string[]): Promise<MessageResult> {this.host.ensureReady();+ ensureSendable(chatId, 'reply');try {// Find the message to quoteconst chat = await this.client().getChatById(chatId);diff --git a/src/engine/adapters/wwebjs-send-shape-refusal.spec.ts b/src/engine/adapters/wwebjs-send-shape-refusal.spec.tsnew file mode 100644index 000000000..321c85c90--- /dev/null+++ b/src/engine/adapters/wwebjs-send-shape-refusal.spec.ts@@ -0,0 +1,102 @@+import { NotImplementedException } from '@nestjs/common';+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';++/**+ * whatsapp-web.js returns null from sendMessage, without touching the page, for some content shapes+ * on a channel or a status/broadcast recipient (Client.js sendMessage). Read as a result, that null+ * is a 500 saying the message may have gone out, which the send breaker counts. These pin the 501+ * the adapter answers instead, before the library is called at all. It is a plain 501 rather than+ * EngineNotSupportedError: the methods are supported, only these recipients are refused, and that+ * class marks a whole method unavailable in the capability matrix.+ */++const logger = createLogger('wwebjs-send-shape-refusal.spec');++function makeMessaging(): { messaging: WwebjsMessaging; client: { sendMessage: jest.Mock } } {+ const client = {+ sendMessage: jest.fn().mockResolvedValue({ id: { _serialized: 'M1' }, timestamp: 1 }),+ };+ const host = {+ ensureReady: jest.fn(),+ ensureNotChannelRecipient: jest.fn(),+ getClient: () => client as unknown as Client,+ logger,+ config: {},+ getNumberId: jest.fn(),+ reportIfPageTransportError: jest.fn(),+ } as unknown as WwebjsEngineHost;+ return { messaging: new WwebjsMessaging(host), client };+}++const IMAGE = {+ data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',+ mimetype: 'image/png',+};+const QUOTED = '[email protected]_3EB0ABCD';+const CHANNEL = '120363000000000000@newsletter';+const STATUS = 'status@broadcast';+const LIST = '1700000000@broadcast';++type Send = (m: WwebjsMessaging, to: string) => Promise<unknown>;+const location: Send = (m, to) => m.sendLocationMessage(to, { latitude: 1, longitude: 2 });+const contact: Send = (m, to) => m.sendContactMessage(to, { name: 'Alice', number: '628999' });+const poll: Send = (m, to) => m.sendPollMessage(to, { name: 'Q', options: ['a', 'b'] });+const sticker: Send = (m, to) => m.sendStickerMessage(to, IMAGE);+const quotedText: Send = (m, to) => m.sendTextMessage(to, 'hi', undefined, { quotedMessageId: QUOTED });+const quotedImage: Send = (m, to) => m.sendImageMessage(to, { ...IMAGE, quotedMessageId: QUOTED });++describe('WwebjsMessaging: a send whatsapp-web.js drops for the recipient', () => {+ it.each([+ ['location', CHANNEL, location],+ ['contact card', CHANNEL, contact],+ ['quoted text', CHANNEL, quotedText],+ ['quoted image', CHANNEL, quotedImage],+ ['location', STATUS, location],+ ['contact card', STATUS, contact],+ ['poll', STATUS, poll],+ ['sticker', STATUS, sticker],+ ['quoted text', STATUS, quotedText],+ ['location', LIST, location],+ ['contact card', LIST, contact],+ ['poll', LIST, poll],+ ['sticker', LIST, sticker],+ ['quoted image', LIST, quotedImage],+ ])('refuses a %s to %s with a 501 and never calls the library', async (_shape, to, send) => {+ const { messaging, client } = makeMessaging();++ const err = (await send(messaging, to).catch((e: unknown) => e)) as NotImplementedException;++ expect(err).toBeInstanceOf(NotImplementedException);+ expect(err.getStatus()).toBe(501);+ expect(err.message).toContain('nothing was sent');+ expect(client.sendMessage).not.toHaveBeenCalled();+ });++ it('refuses a reply to a channel before looking the quoted message up', async () => {+ const { messaging, client } = makeMessaging();+ const getChatById = jest.fn();+ Object.assign(client, { getChatById });++ await expect(messaging.replyToMessage(CHANNEL, QUOTED, 'hi')).rejects.toBeInstanceOf(NotImplementedException);+ expect(getChatById).not.toHaveBeenCalled();+ });++ // Known-negative control: the shapes the library does send there must still reach it, or the guard+ // would be refusing working sends.+ it.each([+ ['poll', CHANNEL, poll],+ ['plain text', STATUS, (m: WwebjsMessaging, to: string) => m.sendTextMessage(to, 'hi')],+ ['plain image', LIST, (m: WwebjsMessaging, to: string) => m.sendImageMessage(to, IMAGE)],+ ['location', '[email protected]', location],+ ['quoted text', '[email protected]', quotedText],+ ])('still sends a %s to %s', async (_shape, to, send) => {+ const { messaging, client } = makeMessaging();++ await send(messaging, to);++ expect(client.sendMessage).toHaveBeenCalledTimes(1);+ });+});