Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): verify message-action targets, resolve LID recipients, fold label-chat ids
Yudhi Armyndharis540051f212e0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c23e25044..8f3b550b1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- A media-storage root the app cannot write to is caught at boot with a clear error, instead of failing on the first write (#1066).- The bundled `docker-compose.yml` now forwards the `SEND_PACING_*`, `MEDIA_CONVERSION_*`/`FFMPEG_PATH` and session-ownership (`NODE_ID`, `NODE_URL`, lease/sweep) variables — previously these features could not be enabled from `.env` in a compose deployment at all.- The four label write tools (`LabelUpsert`, `LabelDelete`, `LabelAddToChat`, `LabelRemoveFromChat`) answered `Internal error` over MCP even though the write had succeeded on WhatsApp, prompting agents to retry a completed operation; they now return `{ success: true }`.+- **Baileys message-action targeting:** star/pin/unpin/react/delete now verify the stored message belongs to the requested chat (a mismatched pair answered success while writing under the wrong conversation), pin/unpin/react/delete resolve LID-migrated contacts like every other send, and tagging/untagging a chat's label folds the neutral id to the engine form so the write lands on the real chat instead of a phantom index.- **whatsapp-web.js raw-id extraction hardening:** listing a label's chats no longer 500s when a labelled chat was deleted, and the channel list, channel creation and group-invite preview now read the `$1` fallback for the WA Web property rename — previously a renamed build returned channel ids as the literal string `"undefined"` and turned every valid invite preview into a false 404.- **Baileys refusals now answer their documented statuses instead of 500:** an invalid/expired group invite previews as 404, admin-refused group writes (subject, description, announce/locked, picture, member-add mode) and refused channel writes (create/delete/mute) answer 403 — matching the whatsapp-web.js engine. Transport failures still propagate unchanged.- **Multi-node request routing hardening:** forwarded requests now carry the client address in `x-forwarded-for` (so `allowedIps` keys and per-IP throttling see the real client once peer nodes are listed in `TRUSTED_PROXIES`), a malformed session id no longer 500s on Postgres in routed mode, and the client-settable forwarded marker is verified — a marked request landing on a live non-owner answers 409 instead of executing there.diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex ebccb9cf9..e42f50acc 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -292,14 +292,17 @@ export class BaileysMessaging {async reactToMessage(chatId: string, messageId: string, emoji: string): Promise<void> {this.host.ensureReady();const target = await this.requireStored(messageId);- await this.sock().sendMessage(chatId, { react: { text: emoji, key: target.key } });+ this.assertStoredInChat(target, chatId, messageId);+ // Resolved like any other send: a lid-migrated contact rejects PN-addressed sends (ack 463).+ await this.sock().sendMessage(await this.toDeliverableJid(chatId), { react: { text: emoji, key: target.key } });}async deleteMessage(chatId: string, messageId: string, forEveryone = true): Promise<void> {this.host.ensureReady();const target = await this.requireStored(messageId);+ this.assertStoredInChat(target, chatId, messageId);if (forEveryone) {- await this.sock().sendMessage(chatId, { delete: target.key });+ await this.sock().sendMessage(await this.toDeliverableJid(chatId), { delete: target.key });return;}// Delete-for-me (revoke on this device only): Baileys exposes it as a chat modification, not a@@ -327,12 +330,7 @@ export class BaileysMessaging {`the edit of message ${messageId} was rejected — only the account's own messages can be edited`,);}- // The stored key must belong to the requested chat — editing with another chat's key is a- // not-found here, not a cross-chat write. Both sides are neutralized so @c.us/@s.whatsapp.net- // (and a known lid<->pn twin) compare equal.- if (this.host.toNeutralJid(target.key.remoteJid ?? '') !== this.host.toNeutralJid(chatId)) {- throw new MessageNotFoundError(messageId, chatId);- }+ this.assertStoredInChat(target, chatId, messageId);// An edit keeps the original message id, so it is neither re-persisted nor echoed as a new send.// The destination is resolved like any other send: a lid-migrated contact rejects PN-addressed// sends with ack error 463 (see toDeliverableJid).@@ -449,9 +447,22 @@ export class BaileysMessaging {return found;}+ /**+ * 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.+ */+ private assertStoredInChat(target: WAMessage, chatId: string, messageId: string): void {+ if (this.host.toNeutralJid(target.key.remoteJid ?? '') !== this.host.toNeutralJid(chatId)) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ }+async starMessage(chatId: string, messageId: string, star: boolean): Promise<void> {this.host.ensureReady();const target = await this.requireStored(messageId);+ this.assertStoredInChat(target, chatId, messageId);// fromMe is load-bearing: the same message id addresses a different message depending on// direction, so omitting it would star the wrong side of the conversation.// Fold @c.us -> @s.whatsapp.net: chatModify keys the star app-state index by the raw jid (no@@ -470,11 +481,12 @@ export class BaileysMessaging {async pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {this.host.ensureReady();const target = await this.requireStored(messageId);+ this.assertStoredInChat(target, chatId, messageId);// Read the enum through the LAZY loader rather than a static import. @whiskeysockets/baileys is// pure ESM and every other site in this codebase defers it to first connect; a module-scope// require would drag ~590 modules into boot even for whatsapp-web.js-only processes.const { proto } = await this.host.loadLib();- await this.sock().sendMessage(chatId, {+ await this.sock().sendMessage(await this.toDeliverableJid(chatId), {pin: target.key,type: proto.PinInChat.Type.PIN_FOR_ALL,// WhatsApp recognises only these three windows; the DTO rejects anything else before we@@ -486,8 +498,12 @@ export class BaileysMessaging {async unpinMessage(chatId: string, messageId: string): Promise<void> {this.host.ensureReady();const target = await this.requireStored(messageId);+ this.assertStoredInChat(target, chatId, messageId);const { proto } = await this.host.loadLib();// `time` is meaningless for an unpin and is omitted rather than sent as a dummy value.- await this.sock().sendMessage(chatId, { pin: target.key, type: proto.PinInChat.Type.UNPIN_FOR_ALL });+ await this.sock().sendMessage(await this.toDeliverableJid(chatId), {+ pin: target.key,+ type: proto.PinInChat.Type.UNPIN_FOR_ALL,+ });}}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 35e772342..b51219dc7 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -2731,6 +2731,46 @@ describe('BaileysAdapter store-backed ops', () => {expect(fakeSock.removeChatLabel).toHaveBeenCalledWith('[email protected]', 'LABEL8');});+ // chatModify keys the label app-state index by the RAW jid, so a neutral @c.us would label a+ // phantom chat the phone never reads — reported as success. Same fold the deleteForMe/star+ // writes carry.+ it('addLabelToChat folds the neutral @c.us id to the engine form', async () => {+ const adapter = await ready();+ await adapter.addLabelToChat('[email protected]', 'LABEL8');+ expect(fakeSock.addChatLabel).toHaveBeenCalledWith('[email protected]', 'LABEL8');+ });++ it('removeLabelFromChat folds the neutral @c.us id to the engine form', async () => {+ const adapter = await ready();+ await adapter.removeLabelFromChat('[email protected]', 'LABEL8');+ expect(fakeSock.removeChatLabel).toHaveBeenCalledWith('[email protected]', 'LABEL8');+ });++ // A stored key must belong to the requested chat: the pin/star/react/delete would otherwise land+ // in whatever chat the caller named while referencing another conversation's message — and+ // report success. editMessage has carried this guard from the start; these are its siblings.+ it.each([+ ['starMessage', (a: BaileysAdapter) => a.starMessage('[email protected]', 'TARGET', true)],+ ['pinMessage', (a: BaileysAdapter) => a.pinMessage('[email protected]', 'TARGET', 86400)],+ ['unpinMessage', (a: BaileysAdapter) => a.unpinMessage('[email protected]', 'TARGET')],+ ['reactToMessage', (a: BaileysAdapter) => a.reactToMessage('[email protected]', 'TARGET', '👍')],+ ['deleteMessage', (a: BaileysAdapter) => a.deleteMessage('[email protected]', 'TARGET', true)],+ ])('%s refuses a chat/message pair mismatch as not-found', async (_name, call) => {+ fakeStore.getMessage.mockResolvedValue(stored); // stored under 628111, requested for 628999+ const adapter = await ready();+ await expect(call(adapter)).rejects.toBeInstanceOf(MessageNotFoundError);+ expect(fakeSock.sendMessage).not.toHaveBeenCalled();+ expect(fakeSock.chatModify).not.toHaveBeenCalled();+ });++ it('pinMessage resolves the LID deliverable jid like the send path', async () => {+ fakeStore.getMessage.mockResolvedValue(stored);+ fakeSock.signalRepository = { lidMapping: { getLIDForPN: jest.fn().mockResolvedValue('484848@lid') } };+ const adapter = await ready();+ await adapter.pinMessage('[email protected]', 'TARGET', 86400);+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('484848@lid', expect.objectContaining({ pin: stored.key }));+ });+it('getChannelById maps newsletterMetadata(jid) → Channel (optionals only when present)', async () => {fakeSock.newsletterMetadata.mockResolvedValue({id: '120363N@newsletter',diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 0a96e4aad..d5002aaf7 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -568,13 +568,16 @@ export class BaileysAdapter implements IWhatsAppEngine {// WhatsApp Business only — Baileys rejects these on personal accounts. The label must already// exist (use getLabels on an engine that lists them); addChatLabel/removeChatLabel associate it// with a chat, they do not create/edit the label definition.+ // Fold @c.us -> @s.whatsapp.net first: chatModify (which both calls wrap) keys the label+ // app-state index by the RAW jid, so a neutral @c.us would label a phantom chat the phone never+ // reads — reported as success. Same class of no-op the deleteForMe/star folds fixed.async addLabelToChat(chatId: string, labelId: string): Promise<void> {this.ensureReady();- await this.sock!.addChatLabel(chatId, labelId);+ await this.sock!.addChatLabel(this.sessionStore.toEngineJid(chatId), labelId);}async removeLabelFromChat(chatId: string, labelId: string): Promise<void> {this.ensureReady();- await this.sock!.removeChatLabel(chatId, labelId);+ await this.sock!.removeChatLabel(this.sessionStore.toEngineJid(chatId), labelId);}/*** Create or update a label.