Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): read an empty key participant as none
Yudhi Armyndharisd97672913a8c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 99cd74e57..891f448af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -112,6 +112,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Preserve webhook outbox payloads until delivery or durable failure storage succeeds.- Keep one terminal webhook failure per receiver idempotency key.- Reject poll votes with no matching options while preserving explicit vote clearing.+- Name who reacted in a Baileys 1:1 reaction, whose sender id came out empty so the two parties overwrote each other's reaction, and flag a 1:1 message from a lid-only sender as `isLidSender`.- Read the duration of an outgoing Baileys audio file in a separate process and a voice note's waveform through ffmpeg, status voice notes included, so a crafted file can no longer abort or exhaust the gateway.- Bound `GET /api/search` to 1000 characters and 32 distinct words and run a repeated word once, so one request can no longer hold the event loop on SQLite for seconds.- Print the startup banner's API Docs URL only when Swagger is served, so a production boot no longer points at a `404`.diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.tsindex 1283ca7e2..836122a27 100644--- a/src/engine/adapters/baileys-events.spec.ts+++ b/src/engine/adapters/baileys-events.spec.ts@@ -634,6 +634,76 @@ describe('BaileysEvents record of messages deleted for everyone', () => {});});+describe('BaileysEvents live keys of a 1:1 chat', () => {+ // Baileys runs every live key through cleanMessage, which leaves '' where a 1:1 key has no participant.+ const partner = '[email protected]';+ const self = '[email protected]';+ const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));++ it.each([+ ['the chat partner', false, partner],+ ['the account', true, self],+ ])('names %s as the reactor of a reaction whose participant is empty', async (_who, fromMe, expected) => {+ const onMessageReaction = jest.fn();+ const events = new BaileysEvents(makeHost({ getOnMessageReaction: () => onMessageReaction }));++ events.handleMessagesUpsert({+ type: 'notify',+ messages: [+ {+ key: { id: 'R1', remoteJid: partner, fromMe, participant: '' },+ messageTimestamp: 1_700_000_000,+ message: { reactionMessage: { key: { id: 'M1', remoteJid: partner }, text: '👍' } },+ },+ ],+ });+ for (let i = 0; i < 5; i++) await flush();++ expect(onMessageReaction).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'M1', senderId: expected }));+ });++ it('flags a sender known only by lid when the participant is empty', async () => {+ const events = new BaileysEvents(makeHost());++ const incoming = await events.mapMessage(+ {+ key: { id: 'L1', remoteJid: '111222333@lid', fromMe: false, participant: '' },+ messageTimestamp: 1_700_000_000,+ message: { conversation: 'hi' },+ },+ 'conversation',+ );++ expect(incoming.isLidSender).toBe(true);+ });++ it.each([+ ['the guest', false, partner],+ ['the account', true, self],+ ])('reports an answer from %s whose RSVP key has an empty participant', async (_who, fromMe, expected) => {+ const onEventResponse = jest.fn();+ const events = new BaileysEvents(makeHost({ getOnEventResponse: () => onEventResponse }));++ events.handleMessagesUpdate([+ {+ key: { id: 'EVT9', remoteJid: self },+ update: {+ eventResponses: [+ {+ eventResponseMessageKey: { id: 'RSVP9', remoteJid: partner, fromMe, participant: '' },+ senderTimestampMs: 1786000000123,+ response: { response: 1 },+ },+ ],+ },+ },+ ] as never);+ await flush();++ expect(onEventResponse).toHaveBeenCalledWith(expect.objectContaining({ responderId: expected, fromMe }));+ });+});+describe('BaileysEvents event RSVPs (event.response)', () => {const group = '[email protected]';const eventKey = { id: 'EVT1', remoteJid: group };diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex 23b7a2312..b523c0a64 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -103,6 +103,15 @@ const PROTOCOL_NOISE_KEYS: ReadonlySet<string> = new Set(['messageHistoryBundle',]);+/**+ * The participant a live key names, or undefined when it names none. Baileys passes every live key+ * through cleanMessage, which writes jidNormalizedUser(participant) back, and that is '' for the absent+ * participant of a 1:1 chat. `??` keeps the empty string, which then reads as a sender that is nobody.+ */+export function keyParticipant(key: { participant?: string | null }): string | undefined {+ return key.participant ? key.participant : undefined;+}+/*** Whether two ids provably name different chats or people. Each side is a jid plus the other-dialect* twin WhatsApp may send beside it (`remoteJidAlt`, `participantAlt`), compared neutralised, so a lid@@ -609,7 +618,7 @@ export class BaileysEvents {id: pm.key?.id ?? '',remoteJid,fromMe: msg.key.fromMe === true,- participant: msg.key.participant ?? undefined,+ participant: keyParticipant(msg.key),body: extractBaileysBody(normalizedEdited),contentType: editedContentType,isPtt: normalizedEdited.audioMessage?.ptt === true,@@ -662,7 +671,7 @@ export class BaileysEvents {// its phone (fromMe) the reactor is the account itself. Group and status keys carry the// author as `participant`, own reactions included, which the edit branch reads the same way.senderId: this.host.toNeutralJid(- msg.key.participant ?? (msg.key.fromMe === true ? this.host.normalizedSelfJid() : remoteJid),+ keyParticipant(msg.key) ?? (msg.key.fromMe === true ? this.host.normalizedSelfJid() : remoteJid),),};this.host.getOnMessageReaction()?.(event);@@ -963,7 +972,7 @@ export class BaileysEvents {const chatJid = envelope.remoteJid ?? eventKey.remoteJid;// Same rule as a reaction: a 1:1 key names the chat partner, so the account's own answer is// attributed to the account; group keys carry the responder as `participant`.- const responder = envelope.participant ?? (fromMe ? this.host.normalizedSelfJid() : chatJid);+ const responder = keyParticipant(envelope) ?? (fromMe ? this.host.normalizedSelfJid() : chatJid);if (!responder) return;const event: EventResponseEvent = {eventMessageId: eventKey.id,@@ -1678,7 +1687,7 @@ export class BaileysEvents {id: msg.key.id ?? '',remoteJid: msg.key.remoteJid!,fromMe: msg.key.fromMe === true,- participant: msg.key.participant ?? undefined,+ participant: keyParticipant(msg.key),body,contentType,isPtt: normalized.audioMessage?.ptt === true,diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.tsindex c147bc069..ad1b05208 100644--- a/src/engine/adapters/baileys-message-mapper.ts+++ b/src/engine/adapters/baileys-message-mapper.ts@@ -1065,7 +1065,7 @@ export function buildIncomingMessageFromBaileys(}// The lid check uses the RAW sender (participant in a group, else the chat JID) before normalization.- const senderJid = fields.participant ?? rawChatId;+ const senderJid = fields.participant ? fields.participant : rawChatId;if (senderJid.endsWith('@lid')) {incoming.isLidSender = true;}