Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): leave a stored message alone when a reused id is revoked

Yudhi Armyndharis8e5e694eadc5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 381b9a6df..ed2691e50 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -75,6 +75,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Drop a Baileys edit, revoke or reaction from another chat, an edit from the wrong author, or a one-to-one revoke from the other side, aimed at a message still being downloaded, on SQLite too.
- Drop a Baileys message that reuses the id of one still being downloaded under another chat or sender, so it cannot take the id or stand in for the original when a later delete is judged.
- Drop the stored copy of a Baileys message that reuses the id of a message the gateway already holds under another chat, sender or direction, and hold an edit, delete or reaction that reads as foreign to that copy until the gateway has settled the message, so the real message's change is no longer ignored as foreign; a reusing message deleted by its sender while it downloads on SQLite, or skipped as ephemeral, is never settled and keeps its copy.
+- A Baileys revoke from the chat of a delivery that reuses the id of a message stored under another chat, or sent by the account in a one-to-one chat, no longer clears that stored message or announces `message.revoked` for it; a contact who knew the id could erase it, on SQLite and PostgreSQL.
- Warn at storage export when a file is larger than the per-entry import cap `STORAGE_IMPORT_MAX_BYTES`.
- Refuse a `PORT` with surrounding whitespace at boot instead of binding a port the image healthcheck cannot probe.
- Skip or cancel the Baileys version lookup of a session stopped while it connects, so no proxy dispatcher outlives it.
diff --git a/src/engine/adapters/inbound-hold.spec.ts b/src/engine/adapters/inbound-hold.spec.ts
index 2e78e343c..814e990f4 100644
--- a/src/engine/adapters/inbound-hold.spec.ts
+++ b/src/engine/adapters/inbound-hold.spec.ts
@@ -552,6 +552,94 @@ describe('Baileys inbound messages held for storage', () => {
expect(h.announced()).toEqual(['H']);
});
+ // An id names one message of one chat. The table refuses a delivery that reuses the id of a message it
+ // holds under another chat, and a delete from the reusing chat is the delete of that delivery, never of
+ // the stored message: its row keeps its content, and nothing announces it as deleted.
+ describe.each([
+ ['PostgreSQL', false],
+ ['SQLite', true],
+ ])('a delivery that reuses the id of a stored message of another chat, deleted by its sender on %s', (_, sqlite) => {
+ const CHAT_A = '[email protected]';
+ const CHAT_B = '[email protected]';
+ const real = (): Row => ({
+ sessionId: 's1',
+ waMessageId: 'X',
+ chatId: CHAT_A,
+ direction: 'incoming',
+ type: 'text',
+ body: 'the real one',
+ metadata: null,
+ });
+ const revokeFrom = (chat: string): WAMessage => ({
+ key: { id: 'REV', remoteJid: chat, fromMe: false },
+ messageTimestamp: 1_700_000_001,
+ message: { protocolMessage: { type: 0, key: { id: 'X', remoteJid: chat, fromMe: false } } },
+ });
+
+ it.each([
+ ['text', (): WAMessage => text('X', CHAT_B)],
+ ['media', (): WAMessage => media('X', CHAT_B)],
+ ])('leaves the stored message alone when the delivery is %s', async (_kind, reuse) => {
+ process.env.INBOUND_MEDIA_CONCURRENCY = '1';
+ const h = heldProjector({ unique: true, sqlite });
+ h.rows.push(real());
+ const download = deferred<ReturnType<typeof stream>>();
+ downloadMediaMessage.mockImplementationOnce(() => download.promise);
+ const { events } = build(4, h.callbacks);
+ upsert(events, reuse(), revokeFrom(CHAT_B));
+ await flush();
+ download.resolve(stream());
+ await flush();
+
+ expect(h.rows).toEqual([real()]);
+ expect(h.announcedAs('message.revoked')).toEqual([]);
+ expect(h.announced()).toEqual([]);
+ });
+
+ // The delivery's row waits for an earlier message of its chat: on SQLite as well, it is in flight
+ // from its emit until that commit ends, and a delete from its chat reaches it there.
+ it('leaves the stored message alone when the delivery waits for an earlier message of its chat', async () => {
+ const h = heldProjector({ unique: true, sqlite });
+ h.rows.push(real());
+ const release = h.stall('EARLIER');
+ const { events } = build(4, h.callbacks);
+ upsert(events, text('EARLIER', CHAT_B), text('X', CHAT_B));
+ await flush();
+ upsert(events, revokeFrom(CHAT_B));
+ await flush();
+ release();
+ await flush();
+
+ expect(h.rows.find(r => r.waMessageId === 'X')).toEqual(real());
+ expect(h.inserted()).toEqual(['X', 'EARLIER']);
+ expect(h.announcedAs('message.revoked')).toEqual([]);
+ expect(h.announced()).toEqual(['EARLIER']);
+ });
+
+ it('still takes a later edit from the real message chat', async () => {
+ const h = heldProjector({ unique: true, sqlite });
+ h.rows.push(real());
+ const { events } = build(4, h.callbacks);
+ upsert(events, text('X', CHAT_B), revokeFrom(CHAT_B));
+ await flush();
+ upsert(events, {
+ key: { id: 'ENV', remoteJid: CHAT_A, fromMe: false },
+ messageTimestamp: 1_700_000_002,
+ message: {
+ protocolMessage: {
+ type: 14,
+ key: { id: 'X', remoteJid: CHAT_A, fromMe: false },
+ editedMessage: { conversation: 'fixed' },
+ timestampMs: 1_700_000_002_000,
+ },
+ },
+ });
+ await flush();
+
+ expect(h.rows).toEqual([{ ...real(), body: 'fixed' }]);
+ });
+ });
+
// The session holds a change that reaches a message before its emit to the rule of the row it will
// become, which needs the direction and the sender from the arrival on.
it('names whose message it is in the arrival, and the sender behind a group message', async () => {
diff --git a/src/modules/session/message-projector.inbound-hold.spec.ts b/src/modules/session/message-projector.inbound-hold.spec.ts
index 080d307ff..f0a7e7b8d 100644
--- a/src/modules/session/message-projector.inbound-hold.spec.ts
+++ b/src/modules/session/message-projector.inbound-hold.spec.ts
@@ -456,14 +456,16 @@ describe('MessageProjector holding inbound messages (PostgreSQL)', () => {
expect(rows[0].type).not.toBe('revoked');
});
- it('is applied at once when its author made it', async () => {
+ it('is applied when its author made it, before the message is emitted', async () => {
const t = admit(arrival('A', CHAT, false, false, true));
projector.handleMessageRevoked('s1', engine, revoke(CHAT), { fromMe: true });
- expect(dispatched('message.revoked')).toHaveLength(1);
+ // Nothing waits for the row read: the emit that follows it at once announces nothing of the message.
projector.handleInboundMessage('s1', engine, message('A', CHAT, { body: 'mine', fromMe: true }), t);
await flush();
expect(rows[0]).toEqual(expect.objectContaining({ body: '', type: 'revoked' }));
+ expect(dispatched('message.revoked')).toHaveLength(1);
+ expect(dispatched('message.received')).toEqual([]);
});
it('is judged by the stored row when a repeat of the id from another chat is held', async () => {
@@ -499,6 +501,163 @@ describe('MessageProjector holding inbound messages (PostgreSQL)', () => {
});
});
+ // An id names one message of one chat. A delivery that reuses the id of a message stored under another
+ // chat is held under that id too, and a revoke from its chat agrees with it. That agreement says the
+ // delivery is taken back, not that the stored message is: only the row can say whose revoke it is.
+ describe('a revoke from the chat of a delivery that reuses the id of a stored message', () => {
+ const CHAT = '[email protected]';
+ const OTHER = '[email protected]';
+ const GROUP = '[email protected]';
+ const MEMBER = '[email protected]';
+ const stored = (over: Row = {}): Row => ({
+ sessionId: 's1',
+ waMessageId: 'A',
+ chatId: CHAT,
+ direction: 'incoming',
+ type: 'text',
+ body: 'original',
+ metadata: { keep: true },
+ ...over,
+ });
+ const revoke = (chatId: string): RevokedMessage => ({
+ id: 'A',
+ revokedId: 'A',
+ chatId,
+ from: chatId,
+ type: 'revoked',
+ body: '',
+ timestamp: 1,
+ });
+ // As the real table's unique index refuses a second row under an id.
+ const uniqueIndex = (): void => {
+ insertGate = row =>
+ rows.some(r => r.waMessageId === row.waMessageId)
+ ? Promise.reject(Object.assign(new Error('UNIQUE constraint failed'), { code: 'SQLITE_CONSTRAINT_UNIQUE' }))
+ : Promise.resolve();
+ };
+
+ it('leaves the stored row alone and announces nothing, while the delivery is held', async () => {
+ rows.push(stored());
+ uniqueIndex();
+ const t = admit(arrival('A', OTHER, false, false, false));
+ projector.handleMessageRevoked('s1', engine, revoke(OTHER), { fromMe: false });
+ await flush();
+ const receipt = projector.handleInboundMessage('s1', engine, message('A', OTHER, { body: 'repeat' }), t);
+ await flush();
+
+ expect(rows).toEqual([stored()]);
+ expect(dispatched('message.revoked')).toEqual([]);
+ expect(eventsGateway.emitMessageRevoked).not.toHaveBeenCalled();
+ expect(dispatched('message.received')).toEqual([]);
+ // The delivery was refused as another message than the one the row holds.
+ await expect(receipt?.settled).resolves.toEqual({ conflict: true });
+ });
+
+ it('leaves the stored row alone on SQLite too, while the delivery runs its hook chain', async () => {
+ build('better-sqlite3');
+ rows.push(stored());
+ uniqueIndex();
+ projector.handleInboundMessage('s1', engine, message('A', OTHER, { body: 'repeat' }));
+ projector.handleMessageRevoked('s1', engine, revoke(OTHER), { fromMe: false });
+ await flush();
+
+ expect(rows).toEqual([stored()]);
+ expect(dispatched('message.revoked')).toEqual([]);
+ expect(eventsGateway.emitMessageRevoked).not.toHaveBeenCalled();
+ });
+
+ it('keeps the revoke for the delivery itself, which is stored cleared where nothing holds the id', async () => {
+ rows.push(stored());
+ uniqueIndex();
+ const t = admit(arrival('A', OTHER, false, false, false));
+ projector.handleMessageRevoked('s1', engine, revoke(OTHER), { fromMe: false });
+ await flush();
+ // The stored message is gone (pruned, say) before the delivery commits.
+ rows.length = 0;
+ projector.handleInboundMessage('s1', engine, message('A', OTHER, { body: 'repeat' }), t);
+ await flush();
+
+ expect(rows).toEqual([expect.objectContaining({ waMessageId: 'A', chatId: OTHER, body: '', type: 'revoked' })]);
+ expect(hookStarts).toEqual([]);
+ expect(dispatched('message.received')).toEqual([]);
+ });
+
+ it('leaves the account own message alone when the other side reuses its id in the same chat', async () => {
+ rows.push(stored({ direction: 'outgoing' }));
+ uniqueIndex();
+ admit(arrival('A', CHAT, false, false, false));
+ projector.handleMessageRevoked('s1', engine, revoke(CHAT), { fromMe: false });
+ await flush();
+
+ expect(rows).toEqual([stored({ direction: 'outgoing' })]);
+ expect(dispatched('message.revoked')).toEqual([]);
+ });
+
+ it('still clears the stored message when its own chat revokes it while a repeat of it is held', async () => {
+ rows.push(stored());
+ admit(arrival('A', CHAT, false, false, false));
+ projector.handleMessageRevoked('s1', engine, revoke(CHAT), { fromMe: false });
+ await flush();
+
+ expect(rows[0]).toEqual(expect.objectContaining({ body: '', type: 'revoked', metadata: null }));
+ expect(dispatched('message.revoked')).toHaveLength(1);
+ });
+
+ it('still clears a member message a group admin revokes while a repeat of it is held', async () => {
+ rows.push(stored({ chatId: GROUP, author: MEMBER }));
+ admit(arrival('A', GROUP, false, false, false, MEMBER));
+ projector.handleMessageRevoked('s1', engine, revoke(GROUP), { fromMe: false });
+ await flush();
+
+ expect(rows[0]).toEqual(expect.objectContaining({ body: '', type: 'revoked' }));
+ expect(dispatched('message.revoked')).toHaveLength(1);
+ });
+
+ it('still clears the account own message when it revokes it from its phone while the echo is held', async () => {
+ rows.push(stored({ direction: 'outgoing' }));
+ admit(arrival('A', CHAT, false, false, true));
+ projector.handleMessageRevoked('s1', engine, revoke(CHAT), { fromMe: true });
+ await flush();
+
+ expect(rows[0]).toEqual(expect.objectContaining({ body: '', type: 'revoked' }));
+ expect(dispatched('message.revoked')).toHaveLength(1);
+ });
+
+ it('still clears a row a REST send stored under the other dialect of the chat', async () => {
+ rows.push(stored({ chatId: '[email protected]', direction: 'outgoing' }));
+ admit(arrival('A', CHAT, false, false, true));
+ projector.handleMessageRevoked('s1', engine, revoke(CHAT), { fromMe: true });
+ await flush();
+
+ expect(rows[0]).toEqual(expect.objectContaining({ body: '', type: 'revoked' }));
+ expect(dispatched('message.revoked')).toHaveLength(1);
+ });
+
+ it('takes back a message still arriving whose row nothing stores, as before', async () => {
+ const t = admit(arrival('A', CHAT, false, false, false));
+ projector.handleMessageRevoked('s1', engine, revoke(CHAT), { fromMe: false });
+ projector.handleInboundMessage('s1', engine, message('A', CHAT), t);
+ await flush();
+
+ expect(rows).toEqual([expect.objectContaining({ waMessageId: 'A', body: '', type: 'revoked' })]);
+ expect(dispatched('message.revoked')).toHaveLength(1);
+ expect(dispatched('message.received')).toEqual([]);
+ });
+
+ // A status post keeps no entry: its own table takes it. A revoke of it reaches the row of the same
+ // id, if there is one, only as a revoke of another chat.
+ it('leaves a message alone that shares its id with a deleted status post', async () => {
+ rows.push(stored());
+ admit(arrival('A', 'status@broadcast', false, true));
+ projector.handleMessageRevoked('s1', engine, revoke('status@broadcast'), { fromMe: false });
+ await flush();
+
+ expect(rows).toEqual([stored()]);
+ expect(dispatched('message.revoked')).toEqual([]);
+ });
+ });
+
it('stores a reaction and an ack that arrived before the emit once the row is written', async () => {
const t = admit(arrival('A', 'chat1'));
projector.applyReactionQueued('s1', { messageId: 'A', chatId: 'chat1', reaction: 'ok', senderId: '[email protected]' });
diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.ts
index 95936aafa..4350574c5 100644
--- a/src/modules/session/message-projector.service.ts
+++ b/src/modules/session/message-projector.service.ts
@@ -835,11 +835,7 @@ export class MessageProjector {
recordRevoke(sessionId: string, waMessageId: string): Promise<void> {
// A message not written yet takes the revoke once its row lands; the UPDATE below matches nothing.
const inFlight = this.inboundInFlight.get(`${sessionId}:${waMessageId}`);
- if (inFlight) {
- inFlight.revoked = true;
- // Media still waiting for room needs none now: wake it, so it is stored cleared at once.
- for (const t of this.tickets.get(sessionId) ?? []) if (t.entry === inFlight) t.giveUp();
- }
+ if (inFlight) this.holdRevoked(sessionId, inFlight);
return new Promise(resolve =>
this.enqueueMessageMutation(sessionId, waMessageId, () =>
this.revokeRow(sessionId, waMessageId).finally(resolve),
@@ -847,6 +843,12 @@ export class MessageProjector {
);
}
+ /** Take back a message not written yet: its row is stored cleared, and media waiting for room needs none. */
+ private holdRevoked(sessionId: string, entry: InFlightEntry): void {
+ entry.revoked = true;
+ for (const t of this.tickets.get(sessionId) ?? []) if (t.entry === entry) t.giveUp();
+ }
+
/**
* Apply {@link REVOKED_ROW_PATCH}, then hand the cleared row to `message:persisted` so a plugin index
* keyed by row id drops the content too. Must run on the message's mutation chain.
@@ -1231,20 +1233,28 @@ export class MessageProjector {
void this.webhookService.dispatch(id, 'message.revoked', revokedPayload);
this.eventsGateway.emitMessageRevoked(id, revokedPayload);
};
- // An engine that applies no validation to a revoke says who made it, and the stored row says whose
- // message it names: a revoke the row proves foreign is dropped, announcement included. whatsapp-web.js
- // reports only what WhatsApp Web itself accepted, so it passes no actor and is applied at once. So is
- // the revoke of a message still arriving, once the entry it is held under agrees with it: that message
- // has no row to be checked against, and waiting for a read would let its emit run, and announce the
- // deleted content, first.
- const source = actor && ({ kind: 'revoke', chatId: message.chatId, fromMe: actor.fromMe } as const);
- const inFlight = this.inboundInFlight.get(`${id}:${revokedWaMessageId}`);
- if (!source || (inFlight && !this.foreignToInFlight(inFlight, source))) {
+ // whatsapp-web.js reports only what WhatsApp Web itself accepted, so it passes no actor and is applied at
+ // once: its ids name the chat, so no row of another chat can hold the id. An engine that applies no
+ // validation to a revoke says who made it, and the stored row says whose message it names: a revoke the
+ // row proves foreign is dropped, announcement included.
+ if (!actor) {
apply();
return;
}
- // Judged by the stored row, which a change the entry called foreign has to find, and accept.
- const needsRow = inFlight !== undefined;
+ const source = { kind: 'revoke', chatId: message.chatId, fromMe: actor.fromMe } as const;
+ const inFlight = this.inboundInFlight.get(`${id}:${revokedWaMessageId}`);
+ // A message still arriving, once the entry it is held under agrees with the revoke, is taken back at
+ // once: waiting for a read would let its emit run, and announce the deleted content, first. That is all
+ // the entry can vouch for. A repeat of an id sent from another chat is held under it too, and the row
+ // under the id may be the other chat's message, which only the row can say: the announcement and the
+ // clearing of the row wait for it.
+ const held = inFlight !== undefined && !this.foreignToInFlight(inFlight, source);
+ if (held) {
+ this.holdRevoked(id, inFlight);
+ inFlight.revokeAnnounced = true;
+ }
+ // Otherwise judged by the stored row, which a change the entry called foreign has to find, and accept.
+ const needsRow = inFlight !== undefined && !held;
void this.mutationProjector.storedRowVerdict(id, revokedWaMessageId, source).then(verdict => {
if (!this.engines.isLive(id, engine)) return;
if (verdict.reason || (needsRow && !verdict.exists)) {