Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): guard inbound processing + unwrap documentWithCaption media
rmyndharis3c410ae0578f
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 514eb90f6..7096cab74 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -50,6 +50,8 @@ jest.mock('@whiskeysockets/baileys', () => ({fetchLatestBaileysVersion: jest.fn().mockResolvedValue({ version: [2, 3000, 0] }),getContentType: jest.fn(() => 'conversation'),downloadMediaMessage: jest.fn().mockResolvedValue(Buffer.from('IMGDATA')),+ // Identity passthrough by default; individual tests may override to simulate unwrapping.+ normalizeMessageContent: jest.fn((c: unknown) => c),DisconnectReason: { loggedOut: 401, restartRequired: 515 },proto: {Message: {@@ -391,6 +393,53 @@ describe('BaileysAdapter inbound fan-out', () => {expect(msg.media).toEqual({ mimetype: 'image/png', data: imgBuf.toString('base64') });});+ it('inbound documentWithCaption: normalizeMessageContent unwraps wrapper, yields non-empty mimetype', async () => {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const baileys = jest.requireMock('@whiskeysockets/baileys') as {+ getContentType: jest.Mock;+ downloadMediaMessage: jest.Mock;+ normalizeMessageContent: jest.Mock;+ };+ baileys.getContentType.mockReturnValue('documentWithCaptionMessage');+ const docBuf = Buffer.from('PDFBYTES');+ baileys.downloadMediaMessage.mockResolvedValue(docBuf);+ // Simulate normalizeMessageContent unwrapping: returns the inner documentMessage.+ baileys.normalizeMessageContent.mockReturnValue({+ documentMessage: { mimetype: 'application/pdf', fileName: 'report.pdf', caption: 'Q1 report' },+ });++ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'DOC1' },+ message: {+ documentWithCaptionMessage: {+ message: {+ documentMessage: { mimetype: 'application/pdf', fileName: 'report.pdf', caption: 'Q1 report' },+ },+ },+ },+ messageTimestamp: 1700000030,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ expect(onMessage).toHaveBeenCalledTimes(1);+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const msg = onMessage.mock.calls[0][0] as {+ type: string;+ media: { mimetype: string; filename?: string; data: string };+ };+ expect(msg.type).toBe('document');+ expect(msg.media.mimetype).toBe('application/pdf');+ expect(msg.media.filename).toBe('report.pdf');+ expect(msg.media.data).toBe(docBuf.toString('base64'));+ });+it('inbound location: populates the location field with coordinates', async () => {// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertionconst baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };@@ -491,6 +540,7 @@ describe('BaileysAdapter inbound fan-out', () => {await new Promise(r => setImmediate(r));expect(onMessage).not.toHaveBeenCalled();expect(onMessageRevoked).toHaveBeenCalledTimes(1);+ expect(fakeStore.put).not.toHaveBeenCalled();// eslint-disable-next-line @typescript-eslint/no-unsafe-member-accessconst revoked = onMessageRevoked.mock.calls[0][0] as {id: string;@@ -536,6 +586,7 @@ describe('BaileysAdapter inbound fan-out', () => {await new Promise(r => setImmediate(r));expect(onMessage).not.toHaveBeenCalled();expect(onMessageReaction).toHaveBeenCalledTimes(1);+ expect(fakeStore.put).not.toHaveBeenCalled();// eslint-disable-next-line @typescript-eslint/no-unsafe-member-accessconst event = onMessageReaction.mock.calls[0][0] as {messageId: string;diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 81f946de7..a38c25cb8 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -589,58 +589,65 @@ export class BaileysAdapter implements IWhatsAppEngine {}private async processInboundMessage(msg: WAMessage): Promise<void> {- const b = await this.loadLib();- const remoteJid = msg.key.remoteJid!;- const contentType = b.getContentType(msg.message ?? undefined);-- // --- protocolMessage REVOKE: don't emit onMessage ---- if (contentType === 'protocolMessage') {- const pm = msg.message?.protocolMessage;- if (pm?.type === b.proto.Message.ProtocolMessage.Type.REVOKE) {- const from = msg.key.fromMe === true ? this.normalizedSelfJid() : remoteJid;- const to = msg.key.fromMe === true ? remoteJid : this.normalizedSelfJid();- const revoked: RevokedMessage = {- id: pm.key?.id ?? '',+ try {+ const b = await this.loadLib();+ const remoteJid = msg.key.remoteJid!;+ const contentType = b.getContentType(msg.message ?? undefined);++ // --- protocolMessage REVOKE: don't emit onMessage ---+ if (contentType === 'protocolMessage') {+ const pm = msg.message?.protocolMessage;+ if (pm?.type === b.proto.Message.ProtocolMessage.Type.REVOKE) {+ const from = msg.key.fromMe === true ? this.normalizedSelfJid() : remoteJid;+ const to = msg.key.fromMe === true ? remoteJid : this.normalizedSelfJid();+ const revoked: RevokedMessage = {+ id: pm.key?.id ?? '',+ chatId: remoteJid,+ from,+ to,+ type: 'revoked',+ body: '',+ timestamp: this.toUnixSeconds(msg.messageTimestamp),+ };+ this.callbacks.onMessageRevoked?.(revoked);+ return;+ }+ // Other protocol messages (ephemeral, history sync, etc.) — skip silently.+ return;+ }++ // --- reactionMessage: don't emit onMessage ---+ if (contentType === 'reactionMessage') {+ const rm = msg.message?.reactionMessage;+ const event: ReactionEvent = {+ messageId: rm?.key?.id ?? '',chatId: remoteJid,- from,- to,- type: 'revoked',- body: '',- timestamp: this.toUnixSeconds(msg.messageTimestamp),+ reaction: rm?.text ?? '',+ senderId: msg.key.participant ?? remoteJid,};- this.callbacks.onMessageRevoked?.(revoked);+ this.callbacks.onMessageReaction?.(event);return;}- // Other protocol messages (ephemeral, history sync, etc.) — skip silently.- return;- }-- // --- reactionMessage: don't emit onMessage ---- if (contentType === 'reactionMessage') {- const rm = msg.message?.reactionMessage;- const event: ReactionEvent = {- messageId: rm?.key?.id ?? '',- chatId: remoteJid,- reaction: rm?.text ?? '',- senderId: msg.key.participant ?? remoteJid,- };- this.callbacks.onMessageReaction?.(event);- return;- }- // --- Normal message: enrich + emit ---- const incoming = await this.mapMessage(msg, contentType);- if (msg.key.fromMe === true) {- this.callbacks.onMessageCreate?.(incoming);- } else {- this.callbacks.onMessage?.(incoming);+ // --- Normal message: enrich + emit ---+ const incoming = await this.mapMessage(msg, contentType);+ if (msg.key.fromMe === true) {+ this.callbacks.onMessageCreate?.(incoming);+ } else {+ this.callbacks.onMessage?.(incoming);+ }+ void this.config.messageStore?.put(this.config.sessionId, msg).catch(err =>+ this.logger.warn('Failed to persist message to store', {+ error: err instanceof Error ? err.message : String(err),+ }),+ );+ this.sessionStore.recordMessage(msg);+ } catch (err) {+ this.logger.error(+ `Unhandled error processing inbound message (id=${msg.key?.id ?? 'unknown'}); dropping`,+ err instanceof Error ? err.message : String(err),+ );}- void this.config.messageStore?.put(this.config.sessionId, msg).catch(err =>- this.logger.warn('Failed to persist message to store', {- error: err instanceof Error ? err.message : String(err),- }),- );- this.sessionStore.recordMessage(msg);}private handleMessagesUpdate(@@ -703,14 +710,17 @@ export class BaileysAdapter implements IWhatsAppEngine {reuploadRequest: this.sock!.updateMediaMessage,},);+ // normalizeMessageContent unwraps documentWithCaptionMessage / viewOnceMessage /+ // ephemeralMessage wrappers so we always reach the inner media sub-message.+ const normalizedContent = b.normalizeMessageContent(content) ?? content;const subMessage =- content.imageMessage ??- content.videoMessage ??- content.audioMessage ??- content.documentMessage ??- content.stickerMessage;+ normalizedContent.imageMessage ??+ normalizedContent.videoMessage ??+ normalizedContent.audioMessage ??+ normalizedContent.documentMessage ??+ normalizedContent.stickerMessage;const mimetype = subMessage?.mimetype ?? '';- const filename = content.documentMessage?.fileName ?? undefined;+ const filename = normalizedContent.documentMessage?.fileName ?? undefined;media = { mimetype, data: buf.toString('base64'), filename };} catch (err) {this.logger.debug('Failed to download inbound media; emitting message without media', {@@ -736,9 +746,15 @@ export class BaileysAdapter implements IWhatsAppEngine {| undefined)?.contextInfo;if (contextInfo?.quotedMessage && contextInfo.stanzaId) {- const qm = contextInfo.quotedMessage as Record<string, { text?: string; caption?: string } | undefined>;+ const qm = contextInfo.quotedMessage as {+ conversation?: string | null;+ extendedTextMessage?: { text?: string | null } | null;+ imageMessage?: { caption?: string | null } | null;+ videoMessage?: { caption?: string | null } | null;+ documentMessage?: { caption?: string | null } | null;+ };const qBody =- (qm.conversation as unknown as string) ??+ qm.conversation ??qm.extendedTextMessage?.text ??qm.imageMessage?.caption ??qm.videoMessage?.caption ??