Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): drop poll votes, pins and album headers
Yudhi Armyndharisaf85907a78d1
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex 149d9bfa2..7db2732e7 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -13,6 +13,7 @@ import {RevokedMessage,} from '../interfaces/whatsapp-engine.interface';import {+ BAILEYS_NON_CONTENT_TYPES,buildIncomingMessageFromBaileys,extractBaileysBody,extractBaileysButtonReply,@@ -480,6 +481,19 @@ export class BaileysEvents {return;}+ // --- a vote, a pin, an album header and the like: don't emit onMessage ---+ // They only point at another message, so mapped they would reach consumers, in either+ // direction, as a bodyless `unknown` message (see BAILEYS_NON_CONTENT_TYPES).+ if (contentType && BAILEYS_NON_CONTENT_TYPES.has(contentType)) {+ this.host.logger.debug('Dropping a message that carries no content of its own', {+ action: 'baileys_drop_non_content',+ msgId: msg.key.id,+ remoteJid,+ contentType,+ });+ return;+ }+// --- contentless protocol traffic: don't emit onMessage ---// A sender-key distribution (Signal traffic every group participant emits on first write or key// rotation) or a history-sync notice carries no user content, yet reached consumers as a bodylessdiff --git a/src/engine/adapters/baileys-history.ts b/src/engine/adapters/baileys-history.tsindex 15f5f3bfd..c7794be23 100644--- a/src/engine/adapters/baileys-history.ts+++ b/src/engine/adapters/baileys-history.ts@@ -2,6 +2,7 @@ import type * as BaileysLib from '@whiskeysockets/baileys';import type { Chat, Contact as BaileysContact, WAMessage, WASocket } from '@whiskeysockets/baileys';import { EngineEventCallbacks, IncomingMessage } from '../interfaces/whatsapp-engine.interface';import {+ BAILEYS_NON_CONTENT_TYPES,buildIncomingMessageFromBaileys,extractBaileysBody,extractBaileysButtonReply,@@ -229,7 +230,8 @@ export class BaileysHistory {/*** Media-free WAMessage -> IncomingMessage map for bulk history (downloading media for thousands of* messages would be ruinous; the type is kept, the payload dropped). Returns null for protocol /- * reaction / key / empty messages, which carry nothing for the chat view.+ * reaction / key / empty messages and for BAILEYS_NON_CONTENT_TYPES, which carry nothing for the+ * chat view.*/private mapHistoryMessage(b: typeof BaileysLib, msg: WAMessage): IncomingMessage | null {const raw = msg.message;@@ -246,7 +248,8 @@ export class BaileysHistory {!contentType ||contentType === 'protocolMessage' ||contentType === 'reactionMessage' ||- contentType === 'senderKeyDistributionMessage'+ contentType === 'senderKeyDistributionMessage' ||+ BAILEYS_NON_CONTENT_TYPES.has(contentType)) {return null;}diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.tsindex 2dfb35047..2c0defe39 100644--- a/src/engine/adapters/baileys-message-mapper.ts+++ b/src/engine/adapters/baileys-message-mapper.ts@@ -1,6 +1,21 @@import { DeliveryStatus, IncomingMessage, MessageType } from '../interfaces/whatsapp-engine.interface';import { chatKind } from '../identity/wa-id';+/**+ * Content types that change or annotate another message and carry nothing of their own: a poll vote,+ * an in-chat pin, a keep-in-chat toggle, an album header (its photos arrive as their own messages), an+ * encrypted reaction and an event RSVP. Mapped, they would surface as a bodyless `unknown` message, so+ * the live and history paths drop them instead.+ */+export const BAILEYS_NON_CONTENT_TYPES: ReadonlySet<string> = new Set([+ 'pollUpdateMessage',+ 'pinInChatMessage',+ 'keepInChatMessage',+ 'albumMessage',+ 'encReactionMessage',+ 'encEventResponseMessage',+]);+/*** Map a Baileys message content-type token (from `getContentType`) to the engine-neutral* {@link MessageType}. `audioMessage` splits on the `ptt` flag into `voice` vs `audio`,diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 31b86522c..b77c4e8e1 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -2189,6 +2189,83 @@ describe('BaileysAdapter inbound fan-out', () => {});});+ describe('messages with no content of their own are dropped on the live and history paths', () => {+ // A poll vote rides with its messageContextInfo, which protobuf decodes first (field 35 before 50);+ // it must not decide the type. A vote in a disappearing chat arrives wrapped.+ const nonContent: Array<[string, Record<string, unknown>]> = [+ [+ 'VOTE',+ {+ messageContextInfo: { messageSecret: 'cw==' },+ pollUpdateMessage: { pollCreationMessageKey: { id: 'POLL1' }, vote: { encPayload: 'eA==', encIv: 'eA==' } },+ },+ ],+ [+ 'VOTE_EPHEMERAL',+ { ephemeralMessage: { message: { pollUpdateMessage: { pollCreationMessageKey: { id: 'POLL1' } } } } },+ ],+ ['PIN', { pinInChatMessage: { key: { id: 'M1' }, type: 1 } }],+ ['KEEP', { keepInChatMessage: { key: { id: 'M1' }, keepType: 1 } }],+ ['ALBUM', { albumMessage: { expectedImageCount: 2 } }],+ ['ENC_REACTION', { encReactionMessage: { targetMessageKey: { id: 'M1' } } }],+ ['EVENT_RSVP', { encEventResponseMessage: { eventCreationMessageKey: { id: 'EV1' } } }],+ ];+ const batch = (fromMe: boolean) => [+ ...nonContent.map(([id, message]) => ({+ key: { remoteJid: '[email protected]', fromMe, id },+ message,+ messageTimestamp: 1700000060,+ })),+ {+ key: { remoteJid: '[email protected]', fromMe, id: 'TEXT' },+ message: { conversation: 'a real message' },+ messageTimestamp: 1700000061,+ },+ ];++ beforeEach(() => {+ baileys.getContentType.mockImplementation(realGetContentType);+ baileys.normalizeMessageContent.mockImplementation(+ (m?: { ephemeralMessage?: { message?: unknown } }) => m?.ephemeralMessage?.message ?? m,+ );+ });++ it.each([+ ['received', false, 'onMessage'],+ ['sent from the phone', true, 'onMessageCreate'],+ ] as const)('live, %s: emits and stores only the real message', async (_label, fromMe, callback) => {+ const emitted = jest.fn();+ const adapter = newAdapter();+ const logger = (adapter as unknown as { logger: { debug: (m: string, meta?: unknown) => void } }).logger;+ const debug = jest.spyOn(logger, 'debug').mockImplementation(() => undefined);+ await adapter.initialize({ [callback]: emitted });+ fakeSock.fire('messages.upsert', { type: 'notify', messages: batch(fromMe) });+ await new Promise(r => setImmediate(r));+ await new Promise(r => setImmediate(r));++ expect(emitted).toHaveBeenCalledTimes(1);+ expect(emitted).toHaveBeenCalledWith(expect.objectContaining({ id: 'TEXT', type: 'text' }));+ const stored = fakeStore.put.mock.calls as Array<[string, { key: { id: string } }]>;+ expect(stored.map(([, m]) => m.key.id)).toEqual(['TEXT']);+ expect(debug).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ msgId: 'VOTE', contentType: 'pollUpdateMessage' }),+ );+ });++ it('history sync: keeps only the real message', async () => {+ const onHistoryMessages = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onHistoryMessages });+ fakeSock.fire('messaging-history.set', { contacts: [], chats: [], messages: batch(false) });+ await new Promise(r => setImmediate(r));+ await new Promise(r => setImmediate(r));+ expect(onHistoryMessages).toHaveBeenCalledTimes(1);+ const mapped = (onHistoryMessages.mock.calls as Array<[IncomingMessage[]]>)[0][0];+ expect(mapped.map(m => m.id)).toEqual(['TEXT']);+ });+ });+it('surfaces inbound @mentions as neutral mentionedIds (contextInfo.mentionedJid)', async () => {const onMessage = jest.fn();const adapter = newAdapter();