Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): drop a re-delivered inbound message before dispatch
Yudhi Armyndharisba7fac01e732
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex 817f541a8..711a1ab5d 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -171,11 +171,10 @@ export class BaileysEvents {// apart except the id, which the adapter recorded when it sent: skip only what we sent, so// the echo cannot fire onMessageCreate twice and the phone's outage-window sends still land// as outgoing messages. Real history never reaches this handler; it arrives on- // messaging-history.set and is captured dispatch-free. A re-delivered inbound message is- // harmless, since the insert oracle dedupes on the WhatsApp message id and does not dispatch- // a stored message again. That oracle does NOT gate dispatch on the own-send path, which is- // why the echo has to be caught here, and why a fromMe message the store already holds is- // dropped in processInboundMessage before it can be reported a second time.+ // messaging-history.set and is captured dispatch-free. A re-delivered message of either+ // direction the store already holds is dropped in processInboundMessage: the projector's insert+ // oracle dedupes the inbound fan-out but runs after the message:received plugin hook, and it+ // does not gate dispatch on the own-send path at all, which is also why the echo is caught here.//// Only ids this session SENT are consumed here. Claiming every inbound fromMe id instead, to// close the window where two deliveries of one id arrive before the store write commits, costs@@ -369,15 +368,17 @@ export class BaileysEvents {}// --- Normal message: enrich + emit ---- // A fromMe message the store already holds was delivered or sent before: WhatsApp re-delivers- // a node whose ack was lost on a drop, and the own-send path downstream dispatches message.sent- // whatever its insert did, so the second copy has to stop here. The store is written by both- // the inbound path below and the send path, and it survives a restart, which the registry- // consulted in handleMessagesUpsert does not. The read fails open (see readStoredMessage).- const ownMessageId = msg.key.fromMe === true ? (msg.key.id ?? null) : null;- if (ownMessageId !== null && (await this.readStoredMessage(ownMessageId))) {+ // A message the store already holds was delivered or sent before: WhatsApp re-delivers a node+ // whose ack was lost on a drop, so the second copy has to stop here. Downstream would not catch+ // it: the own-send path dispatches message.sent whatever its insert did, and the inbound path+ // runs the message:received plugin hook before its insert oracle dedupes. The store is written+ // by the inbound path below, only after dispatch, and by the send path, and it survives a+ // restart, which the registry consulted in handleMessagesUpsert does not. The read fails open+ // (see readStoredMessage).+ const storedId = msg.key.id ?? null;+ if (storedId !== null && (await this.readStoredMessage(storedId))) {this.host.logger.debug('Skipping a re-delivered message this session already recorded', {- msgId: ownMessageId,+ msgId: storedId,});return;}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 914032f5a..7e181e07d 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -2419,6 +2419,48 @@ describe('BaileysAdapter inbound fan-out', () => {expect(onMessageCreate).toHaveBeenCalledTimes(1);});+ // The inbound insert oracle dedupes the webhook and WS fan-out, but the message:received plugin+ // hook runs before it, so a re-delivered inbound message has to stop here too.+ it('does not dispatch a received message twice when WhatsApp re-delivers it', async () => {+ const received = {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'INBOUND_REDELIVERED' },+ message: { conversation: 'hello' },+ messageTimestamp: Math.floor(Date.now() / 1000) - 60,+ };+ fakeStore.getMessage.mockResolvedValueOnce(null).mockResolvedValueOnce(received);+ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('connection.update', { connection: 'open' });++ fakeSock.fire('messages.upsert', { type: 'notify', messages: [received] });+ await new Promise(r => setImmediate(r));+ fakeSock.fire('messages.upsert', { type: 'append', messages: [received] }); // the unacked re-delivery+ await new Promise(r => setImmediate(r));+ expect(onMessage).toHaveBeenCalledTimes(1);+ });++ it('still dispatches a received message when the store cannot be read', async () => {+ fakeStore.getMessage.mockRejectedValueOnce(new Error('SQLITE_BUSY'));+ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('connection.update', { connection: 'open' });++ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'INBOUND_STORE_DOWN' },+ message: { conversation: 'hello' },+ messageTimestamp: Math.floor(Date.now() / 1000),+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ expect(onMessage).toHaveBeenCalledTimes(1);+ });+// A story is not a conversation: the projector drops an own status post rather than reporting it,// so downloading its media first is work nothing consumes, and a story is a full-size photo.it('does not download the media of a status the account posted from its phone', async () => {