Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): file a received broadcast-list message under its sender
Yudhi Armyndharisf869298b6619
diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex 98a0a30f4..ca2973c44 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -464,7 +464,9 @@ CREATE TABLE webhooks (Per-session single-message autoreply rules. `conditions` reuses the webhook filter shape verbatim(null/empty matches every inbound message except channel, broadcast-list and status messages, which-need a `kind` condition); the reply goes through the ordinary send path.+need a `kind` condition); the reply goes through the ordinary send path. On Baileys a message the+account received through a contact's broadcast list is filed under the sender's own chat (`kind`+`individual`), as WhatsApp lists it, so a rule without a `kind` condition matches it.```sqlCREATE TABLE automation_rules (diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 8493e8538..8fb34b745 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6600,7 +6600,9 @@ Omitted or empty conditions match every inbound message except channel, broadcasmessages: a rule answers those only when its conditions include a `kind` condition that matchesthem (for example `kind is channel`). A rule without one skips those chats, because a reply into achannel the account administers is published to every follower, and anywhere else WhatsApp refuses-it.+it. On Baileys a message the account received through a contact's broadcast list is filed under the+sender's own chat (`kind` `individual`), as WhatsApp lists it, so a rule without a `kind` condition+matches it.Loop safety: a rule never answers the account's own (`fromMe`) messages, messages older than5 minutes get no automated answer (so a reconnect never burst-replies the offline-queued backlog),diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 4da5ac4e0..b72b91d03 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -7,6 +7,7 @@ import { EngineTransportError } from '../../common/errors/engine-transport.errorimport { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';import { LidNotMappedError } from '../../common/errors/lid-not-mapped.error';import { parseWaId, userPart } from '../identity/wa-id';+import { storedKeyInChat } from './baileys-message-mapper';/*** Contacts/profile/chats-domain operations extracted from BaileysAdapter. The adapter keeps the@@ -410,10 +411,11 @@ export class BaileysContacts {// lid to its phone user-part through the session's lid mapping, so both spellings of one chat// still meet. Anything that still differs falls back to the synthesised key for the ADDRESSED// chat, which is exactly what every id ran on before stored keys existed.- const chatKey = this.host.toNeutralJid(chatId);const keyById = new Map(stored- .filter(msg => msg.key?.id && msg.key.remoteJid && this.host.toNeutralJid(msg.key.remoteJid) === chatKey)+ .filter(+ msg => msg.key?.id && msg.key.remoteJid && storedKeyInChat(msg.key, chatId, j => this.host.toNeutralJid(j)),+ ).map(msg => [msg.key.id as string, msg.key]),);return messageIds.map(id => keyById.get(id) ?? { remoteJid, id, fromMe: false });diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex 1cc4be29e..e6ef17fa1 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -14,6 +14,7 @@ import {} from '../interfaces/whatsapp-engine.interface';import {BAILEYS_NON_CONTENT_TYPES,+ baileysChatJid,buildIncomingMessageFromBaileys,extractBaileysBody,extractBaileysButtonReply,@@ -351,6 +352,9 @@ export class BaileysEvents {try {const b = await this.host.loadLib();const remoteJid = msg.key.remoteJid!;+ // The chat the events below report: a received broadcast-list message belongs to its sender's+ // chat. Store lookups and the foreign-message checks keep the raw key, which is what is stored.+ const chatJid = baileysChatJid(remoteJid, msg.key.participant, msg.key.fromMe === true);// Learn any lid->pn pair the key carries BEFORE canonicalizing ids below, so a fresh @lid// sender resolves to its phone in this message and for later contact lookups (#362). The pairs// also write through to the persistent lid->phone table via addLidMappings.@@ -370,22 +374,22 @@ export class BaileysEvents {if (pm?.type === b.proto.Message.ProtocolMessage.Type.REVOKE) {// A group admin may revoke anyone's message, so only the chat is checked there.if (await this.targetsForeignMessage(pm.key?.id, msg.key, !remoteJid.endsWith('@g.us'))) return;- const from = msg.key.fromMe === true ? this.host.normalizedSelfJid() : remoteJid;- const to = msg.key.fromMe === true ? remoteJid : this.host.normalizedSelfJid();+ const from = msg.key.fromMe === true ? this.host.normalizedSelfJid() : chatJid;+ const to = msg.key.fromMe === true ? chatJid : this.host.normalizedSelfJid();const revoked: RevokedMessage = {id: pm.key?.id ?? '',// The REVOKE protocolMessage's key points at the ORIGINAL deleted message,// so `id` already IS the original here. Mirror it into `revokedId` so that// field is the reliable cross-engine handle (wwebjs sets it separately).revokedId: pm.key?.id ?? undefined,- chatId: this.host.toNeutralJid(remoteJid),+ chatId: this.host.toNeutralJid(chatJid),from: this.host.toNeutralJid(from),to: this.host.toNeutralJid(to),type: 'revoked',body: '',timestamp: toUnixSeconds(msg.messageTimestamp),};- this.host.recordMessageEdit(remoteJid, revoked.id, '');+ this.host.recordMessageEdit(chatJid, revoked.id, '');// While the target is still being processed, the store change waits for it and lands after// this delete is announced, and a repeat delivery may already hold the content in the store:// record the delete now, checked against the target's own key.@@ -440,7 +444,7 @@ export class BaileysEvents {editedContentType === 'documentWithCaptionMessage' ||editedContentType === 'stickerMessage';const edited: EditedMessage = buildEditedMessage(base, hasMedia);- this.host.recordMessageEdit(remoteJid, edited.messageId, edited.body);+ this.host.recordMessageEdit(chatJid, edited.messageId, edited.body);const target = this.inboundInFlight.get(edited.messageId);if (target && this.mayChange(target.key, msg.key, false)) {this.editedWhileInFlight.delete(edited.messageId); // re-inserted as the newest@@ -469,7 +473,7 @@ export class BaileysEvents {if (await this.targetsForeignMessage(rm?.key?.id, msg.key, false, 'reaction')) return;const event: ReactionEvent = {messageId: rm?.key?.id ?? '',- chatId: this.host.toNeutralJid(remoteJid),+ chatId: this.host.toNeutralJid(chatJid),reaction: rm?.text ?? '',// A 1:1 key names the chat partner, not the author: for a reaction the account made from// its phone (fromMe) the reactor is the account itself. Group and status keys carry the@@ -574,9 +578,9 @@ export class BaileysEvents {}this.host.recordMessage(msg);if (deleted) {- this.host.recordMessageEdit(remoteJid, storedId, '');+ this.host.recordMessageEdit(chatJid, storedId, '');} else if (editedBody !== undefined && storedId !== null) {- this.host.recordMessageEdit(remoteJid, storedId, editedBody);+ this.host.recordMessageEdit(chatJid, storedId, editedBody);}} catch (err) {this.host.logger.error(diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.tsindex 6effae007..55f0a360e 100644--- a/src/engine/adapters/baileys-message-mapper.spec.ts+++ b/src/engine/adapters/baileys-message-mapper.spec.ts@@ -1,5 +1,6 @@import {BaileysIncomingFields,+ baileysChatJid,buildIncomingMessageFromBaileys,extractBaileysBody,extractBaileysButtonReply,@@ -361,19 +362,43 @@ describe('buildIncomingMessageFromBaileys', () => {expect(r.author).toBe('[email protected]');});- it('exposes the sender of a received broadcast-list message as author and keeps the list as the chat', () => {+ it("files a received broadcast-list message under the sender's chat, as Baileys does", () => {const normalize = (jid: string) => jid.replace('@s.whatsapp.net', '@c.us');const r = buildIncomingMessageFromBaileys({ ...base, remoteJid: '1700000000@broadcast', participant: '[email protected]' },normalize,);- expect(r.chatId).toBe('1700000000@broadcast');- expect(r.from).toBe('1700000000@broadcast');+ expect(r.chatId).toBe('[email protected]');+ expect(r.from).toBe('[email protected]');+ expect(r.to).toBe('[email protected]');+ expect(r.kind).toBe('individual');expect(r.isStatusBroadcast).toBe(false);expect(r.isGroup).toBe(false);expect(r.author).toBe('[email protected]');});+ it('keeps the list as the chat for a received list message with no participant', () => {+ const r = buildIncomingMessageFromBaileys({ ...base, remoteJid: '1700000000@broadcast' });+ expect(r.chatId).toBe('1700000000@broadcast');+ expect(r.kind).toBe('broadcast');+ });++ it('flags a lid sender of a received list message and files it under the lid', () => {+ const r = buildIncomingMessageFromBaileys({ ...base, remoteJid: '1700000000@broadcast', participant: '222@lid' });+ expect(r.chatId).toBe('222@lid');+ expect(r.isLidSender).toBe(true);+ });++ it('baileysChatJid mirrors Baileys getChatId without throwing', () => {+ const list = '1700000000@broadcast';+ const sender = '[email protected]';+ expect(baileysChatJid(list, sender, false)).toBe(sender);+ expect(baileysChatJid(list, sender, true)).toBe(list);+ expect(baileysChatJid(list, undefined, false)).toBe(list);+ expect(baileysChatJid('status@broadcast', sender, false)).toBe('status@broadcast');+ expect(baileysChatJid('[email protected]', sender, false)).toBe('[email protected]');+ });+it('keeps the list as the chat for a broadcast-list message the account sent', () => {const normalize = (jid: string) => jid.replace('@s.whatsapp.net', '@c.us');const r = buildIncomingMessageFromBaileys(diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.tsindex f21e0ad01..ac6d663c7 100644--- a/src/engine/adapters/baileys-message-mapper.ts+++ b/src/engine/adapters/baileys-message-mapper.ts@@ -950,11 +950,37 @@ export interface BaileysIncomingFields {}/**- * Build a neutral {@link IncomingMessage} from extracted Baileys fields. The chat is always- * `remoteJid` (Baileys reports the conversation directly); `fromMe` only flips from/to. The group- * sender, the poster of a status broadcast and the sender of a broadcast-list message all live in- * `participant` (exposed as `author`), matching the wwjs convention where `from` is the group JID or- * the broadcast id.+ * The chat a message belongs to, from its raw key: `remoteJid`, except for a broadcast-list message+ * the account received, which belongs to the 1:1 chat with its sender (`participant`). Mirrors+ * Baileys' own `getChatId` (Utils/process-message.js), which files the chat list the same way, but+ * falls back to the list instead of throwing when the key names no participant.+ */+export function baileysChatJid(remoteJid: string, participant: string | null | undefined, fromMe: boolean): string {+ const isList = remoteJid.endsWith('@broadcast') && remoteJid !== 'status@broadcast';+ return isList && !fromMe && participant ? participant : remoteJid;+}++/**+ * Whether a stored key belongs to the chat `chatId` names: the chat the message is reported under+ * ({@link baileysChatJid}), or the raw `remoteJid`, which a client may still hold for a list message.+ * Both sides go through `neutral`, so the dialects of one chat compare equal.+ */+export function storedKeyInChat(+ key: { remoteJid?: string | null; participant?: string | null; fromMe?: boolean | null },+ chatId: string,+ neutral: (jid: string) => string,+): boolean {+ const raw = key.remoteJid ?? '';+ const want = neutral(chatId);+ return neutral(raw) === want || neutral(baileysChatJid(raw, key.participant, key.fromMe === true)) === want;+}++/**+ * Build a neutral {@link IncomingMessage} from extracted Baileys fields. The chat is `remoteJid`+ * (Baileys reports the conversation directly), except that a received broadcast-list message is filed+ * under its sender's chat (see {@link baileysChatJid}); `fromMe` only flips from/to. The group sender,+ * the poster of a status broadcast and the sender of a broadcast-list message all live in+ * `participant` (exposed as `author`).*/export function buildIncomingMessageFromBaileys(fields: BaileysIncomingFields,@@ -966,7 +992,7 @@ export function buildIncomingMessageFromBaileys(const rawChatId = fields.remoteJid;const isGroup = rawChatId.endsWith('@g.us');const isStatusBroadcast = rawChatId === 'status@broadcast';- const chatId = normalizeJid(rawChatId);+ const chatId = normalizeJid(baileysChatJid(rawChatId, fields.participant, fields.fromMe));const self = normalizeJid(fields.selfJid ?? '');const incoming: IncomingMessage = {@@ -986,10 +1012,10 @@ export function buildIncomingMessageFromBaileys(};// The sender behind a group message, the poster behind a status broadcast and the sender behind a- // broadcast-list message all live in `participant` (exposed as `author`), matching the wwjs- // convention where `from` is the group JID or the `@broadcast` id. Without the status arm,+ // broadcast-list message all live in `participant` (exposed as `author`). Without the status arm,// buildIncomingStatus can only resolve the poster to the pseudo-JID itself and drops every Baileys- // status; without the list arm, a list message names only the list and loses its sender.+ // status; the list arm keeps `author` on a list message too, where it repeats the chat's sender+ // (or names the account, for a list message it sent).if ((isGroup || rawChatId.endsWith('@broadcast')) && fields.participant) {incoming.author = normalizeJid(fields.participant);}diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex 515c85499..eb8513c6f 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -24,7 +24,7 @@ import {import { toEngineParticipants } from './baileys-groups';import { findSelfParticipant } from './baileys-group-mapper';import { buildVCard } from './vcard';-import { resolveBaileysButtonClick, setBaileysText } from './baileys-message-mapper';+import { baileysChatJid, resolveBaileysButtonClick, setBaileysText, storedKeyInChat } from './baileys-message-mapper';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';import { BadRequestException, InternalServerErrorException } from '@nestjs/common';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';@@ -582,9 +582,11 @@ export class BaileysMessaging {// Whichever branch runs, the text leaves this account's view, so it must not stay the chat// preview. The echo of an own revoke is skipped as an own send, so the inbound path never clears it.const chatJid = target.key.remoteJid ?? chatId;+ // The preview of a received broadcast-list message is kept in its sender's chat.+ const previewJid = baileysChatJid(chatJid, target.key.participant, target.key.fromMe === true);if (forEveryone && (target.key.fromMe === true || (await this.selfIsGroupAdmin(target.key.remoteJid)) !== false)) {await this.send(await this.toDeliverableJid(chatId), { delete: target.key });- this.host.recordMessageEdit(chatJid, messageId, '');+ this.host.recordMessageEdit(previewJid, messageId, '');// The echo of this delete is skipped as an own send, so the stored copy is emptied here, as// processInboundMessage does for a delete made from the phone or by the other side. Recorded// first, so the message stays deleted even if the store write fails or a repeat delivery of the@@ -610,7 +612,7 @@ export class BaileysMessaging {),'the delete-for-me',);- this.host.recordMessageEdit(chatJid, messageId, '');+ this.host.recordMessageEdit(previewJid, messageId, '');}/**@@ -878,10 +880,11 @@ export class BaileysMessaging {* The stored key must belong to the requested chat β acting with another chat's key is a* not-found here, not a cross-chat write (a pin sent into chat A referencing chat B's message, or* a star indexed under the wrong conversation, would report success). Both sides are neutralized- * so @c.us/@s.whatsapp.net (and a known lid<->pn twin) compare equal.+ * so @c.us/@s.whatsapp.net (and a known lid<->pn twin) compare equal, and a received broadcast-list+ * message is found under the sender chat it is reported in.*/private assertStoredInChat(target: WAMessage, chatId: string, messageId: string): void {- if (this.host.toNeutralJid(target.key.remoteJid ?? '') !== this.host.toNeutralJid(chatId)) {+ if (!storedKeyInChat(target.key, chatId, jid => this.host.toNeutralJid(jid))) {throw new MessageNotFoundError(messageId, chatId);}}diff --git a/src/engine/adapters/baileys-send-seen.spec.ts b/src/engine/adapters/baileys-send-seen.spec.tsindex 8bc109432..06d66ed00 100644--- a/src/engine/adapters/baileys-send-seen.spec.ts+++ b/src/engine/adapters/baileys-send-seen.spec.ts@@ -136,6 +136,20 @@ describe('sendSeen', () => {expect(readMessages).toHaveBeenCalledWith([{ id: 'D1', remoteJid: '[email protected]', fromMe: true }]);});+ it('keeps the stored key of a received broadcast-list message addressed by its sender chat', async () => {+ // The message is reported under the sender's chat, but its key names the list and the sender.+ // Synthesising a key for the sender's chat dropped the participant the receipt needs.+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const key = { id: 'B1', remoteJid: '1700000000@broadcast', participant: '[email protected]', fromMe: false };+ const host = makeHost({+ getSocket: () => ({ readMessages }) as unknown as WASocket,+ getStoredMessages: () => Promise.resolve([stored(key)]),+ });++ await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', ['B1'])).resolves.toBe(true);+ expect(readMessages).toHaveBeenCalledWith([key]);+ });+it('treats a null id list as absent rather than dereferencing it', async () => {// The REST body rejects an explicit null, but this is the engine boundary; it used to throw a// TypeError here and surface as a 500.diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex 8ced7cf7b..906f35449 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -615,6 +615,39 @@ describe('BaileysSessionStore', () => {expect(store.toNeutralJid('111@lid')).toBe('[email protected]');});+ it('pairs the sender of a broadcast-list or status message with its alt, never the list id', () => {+ store.recordKeyLidMappings({+ remoteJid: '1700000000@broadcast',+ remoteJidAlt: '111@lid',+ participant: '[email protected]',+ });+ store.recordKeyLidMappings({+ remoteJid: 'status@broadcast',+ remoteJidAlt: '333@lid',+ participant: '[email protected]',+ });+ expect(store.resolvePhone('111@lid')).toBe('628222');+ expect(store.resolvePhone('333@lid')).toBe('628444');+ });++ it('ignores a pair whose phone side is not a user id', () => {+ store.recordKeyLidMappings({ remoteJid: '[email protected]', remoteJidAlt: '555@lid' });+ expect(store.resolvePhone('555@lid')).toBeNull();+ });++ it("files a received list message's preview under the sender's chat", () => {+ store.upsertChats([{ id: '[email protected]' }]);+ store.recordMessage({+ key: { remoteJid: '1700000000@broadcast', participant: '[email protected]', fromMe: false, id: 'L1' },+ message: { conversation: 'offer' },+ messageTimestamp: 100,+ });+ expect(store.listChats()).toEqual([+ expect.objectContaining({ id: '[email protected]', lastMessage: 'offer', timestamp: 100 }),+ ]);+ expect(store.lastInboundMessage('[email protected]')?.key.id).toBe('L1');+ });+it('ignores a key with no lid/pn pair', () => {store.recordKeyLidMappings({});store.recordKeyLidMappings({ remoteJid: '333@lid' }); // lid without an Alt counterpartdiff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex ff1e0433f..4e03d397a 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -4,6 +4,7 @@ import { chatKind, parseWaId, toNeutralJid as canonicalizeWaId, userPart } fromimport type { LidMappingStore } from '../identity/lid-mapping-store.service';import { mergeTwinStates, type ChatStateStore, type ChatStateValue } from './baileys-chat-state-store.service';import { resolveNonNegativeIntEnv } from '../../config/configuration';+import { baileysChatJid } from './baileys-message-mapper';interface LastMessage {key: WAMessageKey;@@ -372,24 +373,25 @@ export class BaileysSessionStore {* pairs flow through addLidMappings, so they also write through to the persistent table.*/recordKeyLidMappings(key: Pick<WAMessageKey, 'remoteJid' | 'remoteJidAlt' | 'participant' | 'participantAlt'>): void {+ // On a status or broadcast-list message `remoteJidAlt` is the SENDER's other dialect (Baileys fills+ // it for every non-group chat), so it pairs with `participant`, not with the `@broadcast` id.+ const broadcast = key.remoteJid?.endsWith('@broadcast');this.addLidMappings([- this.lidPnPair(key.remoteJid, key.remoteJidAlt),+ this.lidPnPair(broadcast ? key.participant : key.remoteJid, key.remoteJidAlt),this.lidPnPair(key.participant, key.participantAlt),]);}- /** Sorts a JID and its WhatsApp-supplied "Alt" counterpart into { lid, pn } by @lid suffix. */+ /**+ * Sorts a JID and its WhatsApp-supplied "Alt" counterpart into { lid, pn } by @lid suffix. The pn side+ * must be a user id: anything else (a group, a list) would be persisted as that lid's phone number.+ */private lidPnPair(jid?: string | null, alt?: string | null): { lid?: string; pn?: string } {if (!jid || !alt) {return {};}- if (jid.endsWith('@lid')) {- return { lid: jid, pn: alt };- }- if (alt.endsWith('@lid')) {- return { lid: alt, pn: jid };- }- return {};+ const [lid, pn] = jid.endsWith('@lid') ? [jid, alt] : alt.endsWith('@lid') ? [alt, jid] : [];+ return lid && pn && parseWaId(pn).kind === 'user' ? { lid, pn } : {};}/** Write a learned lid->phone pair through to the persistent table (bare digits, fire-and-forget). */@@ -406,7 +408,8 @@ export class BaileysSessionStore {// newest-message guard so every inbound refreshes it; the timer is cached under both the raw and// neutral JID so an outbound send addressed in either dialect (phone or @lid) finds it.this.recordEphemeralFromMessage(chatId, msg);- const key = this.chatKey(chatId);+ // A received broadcast-list message previews in its sender's chat, where Baileys lists it.+ const key = this.chatKey(baileysChatJid(chatId, msg.key.participant, msg.key.fromMe === true));const timestamp = this.toUnixSeconds(msg.messageTimestamp);if (!msg.key.fromMe) {const inbound = this.lastInbound.get(key);diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 9f83d37f9..2334def8e 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -3420,6 +3420,58 @@ describe('BaileysAdapter inbound fan-out', () => {);});+ it("files an edit, a revoke and a reaction received through a broadcast list under the sender's chat", async () => {+ baileys.getContentType.mockImplementation(realGetContentType);+ baileys.normalizeMessageContent.mockImplementation((m: unknown) => m);+ const onMessageEdited = jest.fn();+ const onMessageRevoked = jest.fn();+ const onMessageReaction = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessageEdited, onMessageRevoked, onMessageReaction });+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ const LIST = '1700000000@broadcast';+ const key = (id: string, fromMe = false) =>+ fromMe+ ? { remoteJid: LIST, fromMe, id, participant: '[email protected]' }+ : { remoteJid: LIST, fromMe, id, participant: '[email protected]' };+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: key('LIST_EDIT'),+ message: { protocolMessage: { key: { id: 'E1' }, type: 14, editedMessage: { conversation: 'fixed' } } },+ messageTimestamp: 1700000050,+ },+ {+ key: key('LIST_REVOKE'),+ message: { protocolMessage: { key: { id: 'R1' }, type: 0 } },+ messageTimestamp: 1700000051,+ },+ {+ key: key('LIST_REACTION'),+ message: { reactionMessage: { key: { id: 'X1' }, text: 'ok' } },+ messageTimestamp: 1700000052,+ },+ {+ key: key('OWN_REVOKE', true),+ message: { protocolMessage: { key: { id: 'R2' }, type: 0 } },+ messageTimestamp: 1700000053,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ await new Promise(r => setImmediate(r));++ expect(firstEditedMessage(onMessageEdited)).toMatchObject({ messageId: 'E1', chatId: '[email protected]' });+ expect(onMessageRevoked).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'R1', chatId: '[email protected]', from: '[email protected]' }),+ );+ expect(onMessageRevoked).toHaveBeenCalledWith(expect.objectContaining({ id: 'R2', chatId: LIST, to: LIST }));+ expect(onMessageReaction).toHaveBeenCalledWith(+ expect.objectContaining({ messageId: 'X1', chatId: '[email protected]', senderId: '[email protected]' }),+ );+ });+it('reactionMessage: fires onMessageReaction and NOT onMessage', async () => {// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertionconst baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };@@ -3624,6 +3676,57 @@ describe('BaileysAdapter inbound fan-out', () => {expect((await adapter.getChats())[0]?.lastMessage).toBe('');});+ describe("a received broadcast-list message previewed in its sender's chat", () => {+ const LIST = '1700000000@broadcast';+ const listKey = (id: string) => ({ remoteJid: LIST, participant: '[email protected]', fromMe: false, id });+ const original = { key: listKey('L1'), message: { conversation: 'offer' }, messageTimestamp: 1700000050 };+ const preview = async (adapter: BaileysAdapter) => (await adapter.getChats())[0]?.lastMessage;++ const receive = async (): Promise<BaileysAdapter> => {+ baileys.getContentType.mockImplementation(realGetContentType);+ baileys.normalizeMessageContent.mockImplementation((m: unknown) => m);+ const adapter = newAdapter();+ await adapter.initialize({});+ fakeSock.fire('connection.update', { connection: 'open' });+ fakeSock.fire('chats.upsert', [{ id: '[email protected]', name: 'Bob' }]);+ await deliver(original);+ expect(await preview(adapter)).toBe('offer');+ fakeStore.getMessage.mockResolvedValue(original);+ return adapter;+ };+ const deliver = async (msg: Record<string, unknown>) => {+ fakeSock.fire('messages.upsert', { type: 'notify', messages: [msg] });+ await new Promise(r => setImmediate(r));+ await new Promise(r => setImmediate(r));+ };++ it('clears the preview when the sender deletes it', async () => {+ const adapter = await receive();+ await deliver({+ key: listKey('REVOKE_L1'),+ message: { protocolMessage: { key: { id: 'L1' }, type: 0 } },+ messageTimestamp: 1700000060,+ });+ expect(await preview(adapter)).toBe('');+ });++ it('shows the edited text when the sender edits it', async () => {+ const adapter = await receive();+ await deliver({+ key: listKey('EDIT_L1'),+ message: { protocolMessage: { key: { id: 'L1' }, type: 14, editedMessage: { conversation: 'new offer' } } },+ messageTimestamp: 1700000060,+ });+ expect(await preview(adapter)).toBe('new offer');+ });++ it('clears the preview when the account deletes it for itself', async () => {+ const adapter = await receive();+ await adapter.deleteMessage('[email protected]', 'L1', false);+ expect(await preview(adapter)).toBe('');+ });+ });+describe('contentless protocol traffic on the live path (#1568)', () => {/** Push one group message through the live upsert handler with Baileys' real content-type resolution. */const fireLive = async (@@ -4119,6 +4222,35 @@ describe('BaileysAdapter store-backed ops', () => {expect(fakeSock.sendMessage).not.toHaveBeenCalled();});+ describe('a received broadcast-list message, addressed by the sender chat it is filed under', () => {+ const listMsg = {+ key: { id: 'LIST1', remoteJid: '1700000000@broadcast', participant: '[email protected]', fromMe: false },+ message: { conversation: 'to everyone on my list' },+ };++ it('can be replied to and reacted to', async () => {+ fakeStore.getMessage.mockResolvedValue(listMsg);+ const adapter = await ready();+ await adapter.replyToMessage('[email protected]', 'LIST1', 'got it');+ await adapter.reactToMessage('[email protected]', 'LIST1', 'π');+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ { text: 'got it', linkPreview: null },+ expect.objectContaining({ quoted: listMsg }),+ );+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {+ react: { text: 'π', key: listMsg.key },+ });+ });++ it('is still found through the list id, and not through another chat', async () => {+ fakeStore.getMessage.mockResolvedValue(listMsg);+ const adapter = await ready();+ await expect(adapter.reactToMessage('1700000000@broadcast', 'LIST1', 'π')).resolves.not.toThrow();+ await expect(adapter.reactToMessage('[email protected]', 'LIST1', 'π')).rejects.toBeInstanceOf(MessageNotFoundError);+ });+ });+it('forwardMessage forwards the stored message', async () => {fakeStore.getMessage.mockResolvedValue(stored);const adapter = await ready();diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex af93776f8..1988f2e9d 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -114,7 +114,12 @@ export interface IncomingMessage {* in the raw payload. 0 or undefined = no disappearing timer.* Known values: 86400 (24h), 604800 (7d), 7776000 (90d). */ephemeralDuration?: number;- /** For group, status and broadcast-list messages, the WID of the sender (`from` is the group or `@broadcast` id). */+ /**+ * For group, status and broadcast-list messages, the WID of the sender, where `from` is the group or+ * `status@broadcast`. A broadcast-list message the account received is filed under the sender's own+ * chat on Baileys, as WhatsApp lists it, so there `chatId` and `from` name the sender and `author`+ * repeats it.+ */author?: string;/** WIDs @mentioned in the message (empty/absent when none). Surfaced for command targeting. */mentionedIds?: string[];diff --git a/src/modules/automation/dto/automation-rule.dto.ts b/src/modules/automation/dto/automation-rule.dto.tsindex 3ae5f3356..32020de0e 100644--- a/src/modules/automation/dto/automation-rule.dto.ts+++ b/src/modules/automation/dto/automation-rule.dto.ts@@ -14,7 +14,9 @@ const CONDITIONS_DESCRIPTION ='Match conditions in the webhook filter format (message family: sender, recipient, chatId, body, ' +'type, isGroup, kind, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or ' +'empty means the rule matches every inbound message except channel, broadcast-list and status ' +- 'messages, which a rule answers only when it has a `kind` condition that matches them.';+ 'messages, which a rule answers only when it has a `kind` condition that matches them. On Baileys ' ++ "a message received through a contact's broadcast list is filed under the sender's chat (`kind` " ++ 'individual), so it matches.';const COOLDOWN_DESCRIPTION ='Quiet period per chat, in seconds: after the rule replies in a chat it stays silent there for ' +diff --git a/src/modules/message/dto/message-responses.dto.ts b/src/modules/message/dto/message-responses.dto.tsindex b29efb3da..f1549757c 100644--- a/src/modules/message/dto/message-responses.dto.ts+++ b/src/modules/message/dto/message-responses.dto.ts@@ -65,7 +65,8 @@ export class MessageListItemDto {@ApiPropertyOptional({type: String,nullable: true,- description: 'Sender of a group, status or broadcast-list message (`from` is the group or `@broadcast` id there).',+ description:+ 'Sender of a group, status or broadcast-list message (`from` is the group, `status@broadcast` or list id there). On Baileys a list message the account received is filed under the sender, so `from` is the sender too.',example: '[email protected]',})author?: string | null;@@ -286,7 +287,8 @@ export class ChatHistoryMessageDto {ephemeralDuration?: number;@ApiPropertyOptional({- description: 'Sender of a group, status or broadcast-list message (`from` is the group or `@broadcast` id there).',+ description:+ 'Sender of a group, status or broadcast-list message (`from` is the group, `status@broadcast` or list id there). On Baileys a list message the account received is filed under the sender, so `from` is the sender too.',example: '[email protected]',})author?: string;diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.tsindex 6ced33c7d..2093bc480 100644--- a/src/modules/message/entities/message.entity.ts+++ b/src/modules/message/entities/message.entity.ts@@ -59,8 +59,9 @@ export class Message {/*** Stable sender identity for a group, status or broadcast-list message: the JID who actually- * posted (`from` is the group or `@broadcast` id). Lets the chat view tell two same-named- * participants apart. Null on 1:1 messages, outgoing echoes, and legacy rows.+ * posted (`from` is the group, `status@broadcast` or list id; on Baileys a list message the account+ * received is filed under the sender, so `from` is the sender too). Lets the chat view tell two+ * same-named participants apart. Null on 1:1 messages, outgoing echoes, and legacy rows.*/@Column({ nullable: true })author?: string;