Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): keep a repeated message id from steering a change
Yudhi Armyndharis20f56cd7b686
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 475cd1dc1..fc41ad67d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -68,7 +68,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Keep the sessions of a plugin's other enabled instances active when creating, disabling or deleting a session-scoped instance retires an operator-set `*`.- Omit the name, push name, caption, background colour and font of a received status that has none from `GET /status` instead of returning `null`, as the schema declares.- Bound the inbound media a PostgreSQL session holds before storing it to `INBOUND_MEDIA_CONCURRENCY` payloads, keeping each chat's arrival order.-- Drop a Baileys edit, revoke or reaction from another chat, or an edit or revoke from the wrong author, aimed at a message still being downloaded, on SQLite too.+- 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.- 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/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex 35a3825e9..607553d8f 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -415,6 +415,17 @@ export class BaileysEvents {});continue;}+ // An id names one message of one chat and one sender. A delivery that reuses the id of a message+ // still being processed under another chat or sender is not a repeat of it: let through, it would+ // take the id first (the row, the stored copy, and the key a delete of the first is judged by).+ const firstKey = msg.key.id ? this.inboundInFlight.get(msg.key.id)?.key : undefined;+ if (firstKey && this.namesAnotherMessage(firstKey, msg.key)) {+ this.host.logger.warn('Dropping a message that reuses the id of one still being processed', {+ msgId: msg.key.id ?? 'unknown',+ remoteJid: msg.key.remoteJid,+ });+ continue;+ }// Throttle through the limiter so a burst of media messages can't run unbounded parallel// downloads (each a full decrypted buffer in heap). Ordering stays correct — the message store// keeps the newest by timestamp. The queue is unbounded, so a burst parks rather than shedding@@ -466,6 +477,21 @@ export class BaileysEvents {}}+ /**+ * Whether two keys of one id provably name different messages: another chat, another side of the+ * conversation, or (outside the account's own messages) another sender. Fails open, like+ * {@link differentWaIds}: ids that cannot be compared are the same message.+ */+ private namesAnotherMessage(first: WAMessageKey, key: WAMessageKey): boolean {+ const neutral = (jid: string): string => this.host.toNeutralJid(jid);+ return (+ (first.fromMe === true) !== (key.fromMe === true) ||+ differentWaIds([first.remoteJid, first.remoteJidAlt], [key.remoteJid, key.remoteJidAlt], neutral) ||+ (key.fromMe !== true &&+ differentWaIds([first.participant, first.participantAlt], [key.participant, key.participantAlt], neutral))+ );+ }+/** Admit a live message (see EngineEventCallbacks.admitInbound); undefined where nothing is held. */private admitInbound(msg: WAMessage): InboundTicket | undefined {const admit = this.host.getAdmitInbound?.();diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex edd8f0745..748cc4618 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -8689,7 +8689,11 @@ describe('BaileysAdapter keeps the message store in step with edits and deletes'fireProtocol({ remoteJid: PEER, fromMe: false }, { key: { id: 'MINE' }, type: 0 });// The same author, from another group: the author check and the group-delete allowance both pass,// so only the chat check refuses it.- fireProtocol({ remoteJid: '[email protected]', participant: PEER, fromMe: false }, { key: { id: 'OTHER' }, type: 0 });+ // An envelope has an id of its own, and two of them in flight never share one.+ fireProtocol(+ { id: 'ENVELOPE_OTHER', remoteJid: '[email protected]', participant: PEER, fromMe: false },+ { key: { id: 'OTHER' }, type: 0 },+ );await settle();expect(@@ -8765,6 +8769,87 @@ describe('BaileysAdapter keeps the message store in step with edits and deletes'expect(fakeStore.put.mock.invocationCallOrder[1]).toBeLessThan(fakeStore.update.mock.invocationCallOrder[0]);});+ // A message id names one message of one chat and one sender. A contact who knows the id of a message+ // the account is still downloading can send a text under it, and a delete after it: neither may take+ // the id from the first, nor have the delete judged against the key of the second.+ it('drops a delivery that reuses the id of a message still downloading under another sender', async () => {+ let release!: () => void;+ baileys.downloadMediaMessage.mockReturnValueOnce(+ new Promise(resolve => {+ release = () => resolve(streamOf(Buffer.from('JPEG')));+ }),+ );+ const onMessage = jest.fn();+ const onMessageCreate = jest.fn();+ const onMessageRevoked = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage, onMessageCreate, onMessageRevoked });+ fakeSock.fire('connection.update', { connection: 'open' });+ const warn = jest.spyOn(loggerOf(adapter), 'warn').mockImplementation(() => undefined);+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: PEER, fromMe: true, id: 'REUSED' },+ message: { imageMessage: { mimetype: 'image/jpeg', caption: 'sent from the phone' } },+ messageTimestamp: 1700000099,+ },+ ],+ });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: PEER, fromMe: false, id: 'REUSED' },+ message: { conversation: 'theirs' },+ messageTimestamp: 1700000100,+ },+ ],+ });+ fireProtocol({ remoteJid: PEER, fromMe: false }, { key: { id: 'REUSED' }, type: 0 });+ for (let i = 0; i < 5; i++) await settle();++ expect(onMessage).not.toHaveBeenCalled();+ expect(onMessageRevoked).not.toHaveBeenCalled();+ expect(warn).toHaveBeenCalledWith(+ 'Dropping a message that reuses the id of one still being processed',+ expect.objectContaining({ msgId: 'REUSED' }),+ );++ release();+ for (let i = 0; i < 5; i++) await settle();+ expect(onMessageCreate).toHaveBeenCalledTimes(1);+ expect(onMessageCreate).toHaveBeenCalledWith(expect.objectContaining({ id: 'REUSED', fromMe: true }));+ });++ it('still takes a repeat delivery of a message still downloading from the same chat and sender', async () => {+ let release!: () => void;+ baileys.downloadMediaMessage+ .mockReturnValueOnce(+ new Promise(resolve => {+ release = () => resolve(streamOf(Buffer.from('JPEG')));+ }),+ )+ .mockReturnValueOnce(Promise.resolve(streamOf(Buffer.from('JPEG'))));+ const warn = jest.spyOn(loggerOf(await started()), 'warn').mockImplementation(() => undefined);+ const delivery = () => ({+ key: { remoteJid: PEER, fromMe: false, id: 'SAME' },+ message: { imageMessage: { mimetype: 'image/jpeg', caption: 'twice' } },+ messageTimestamp: 1700000099,+ });+ fakeSock.fire('messages.upsert', { type: 'notify', messages: [delivery()] });+ fakeSock.fire('messages.upsert', { type: 'notify', messages: [delivery()] });+ for (let i = 0; i < 5; i++) await settle();+ release();+ for (let i = 0; i < 5; i++) await settle();++ expect(warn).not.toHaveBeenCalledWith(+ 'Dropping a message that reuses the id of one still being processed',+ expect.anything(),+ );+ expect(fakeStore.put).toHaveBeenCalledTimes(2);+ });+const ownStored = {key: { id: 'TARGET', remoteJid: PEER, fromMe: true },message: { conversation: 'as sent' },diff --git a/src/engine/adapters/inbound-hold.spec.ts b/src/engine/adapters/inbound-hold.spec.tsindex 9e1187a84..bd934edac 100644--- a/src/engine/adapters/inbound-hold.spec.ts+++ b/src/engine/adapters/inbound-hold.spec.ts@@ -532,6 +532,29 @@ describe('Baileys inbound messages held for storage', () => {]);});+ it('names the sender behind a broadcast-list or status message too, and none behind a one-to-one chat', async () => {+ const h = heldProjector();+ const admitInbound = jest.fn(h.callbacks.admitInbound);+ const { events } = build(4, { ...h.callbacks, admitInbound });+ const key = (id: string, remoteJid: string, fromMe: boolean, participant?: string) => ({+ ...text(id, remoteJid),+ key: { id, remoteJid, fromMe, ...(participant ? { participant } : {}) },+ });+ upsert(+ events,+ key('L', '1700000002@broadcast', false, '[email protected]'),+ key('S', 'status@broadcast', false, '[email protected]'),+ key('M', '[email protected]', false, '[email protected]'),+ );+ await flush();++ expect(admitInbound.mock.calls.map(([a]) => [a.id, a.author])).toEqual([+ ['L', '[email protected]'],+ ['S', '[email protected]'],+ ['M', undefined],+ ]);+ });+it('still processes a message, and the rest of its batch, when its admission throws', async () => {const h = heldProjector();let calls = 0;@@ -993,6 +1016,20 @@ describe('whatsapp-web.js inbound messages held for storage', () => {]);});+ it('names the sender behind a group message in the arrival', async () => {+ const h = heldProjector();+ const admitInbound = jest.fn(h.callbacks.admitInbound);+ const { client } = build({ ...h.callbacks, admitInbound });+ client.emit('message', { ...incoming('grp', '[email protected]', undefined, 'hi'), author: '[email protected]' });+ client.emit('message', incoming('one', '[email protected]', undefined, 'hello'));+ await flush();++ expect(admitInbound.mock.calls.map(([a]) => [a.id, a.fromMe, a.author])).toEqual([+ ['grp', false, '[email protected]'],+ ['one', false, undefined],+ ]);+ });+it('settles the ticket of an own echo its handler never takes, so the chat is not held up', async () => {const h = heldProjector();// The handler ignores the ticket it is handed: only the adapter's own settle can release it.diff --git a/src/modules/session/message-mutation-projector.ts b/src/modules/session/message-mutation-projector.tsindex 095d0263f..064eff43a 100644--- a/src/modules/session/message-mutation-projector.ts+++ b/src/modules/session/message-mutation-projector.ts@@ -27,18 +27,20 @@ export class MessageMutationProjector {/*** Queue a reaction apply. Reactions read-modify-write the metadata column, so they must be- * serialized per message; the caller only knows it has an event to apply.+ * serialized per message; the caller only knows it has an event to apply. `needsRow` is for a change+ * the message still arriving under the same id judged foreign: it is applied only to a stored row that+ * accepts it, and announced only then, so a change nothing stored vouches for goes no further.*/- applyReactionQueued(id: string, event: ReactionEvent): void {- this.enqueueMessageMutation(id, event.messageId, () => this.applyReaction(id, event));+ applyReactionQueued(id: string, event: ReactionEvent, needsRow = false): void {+ this.enqueueMessageMutation(id, event.messageId, () => this.applyReaction(id, event, needsRow));}/*** Queue an edit apply. Shares the reaction chain so rapid edit-vs-reaction on the same message* stays ordered rather than racing.*/- applyMessageEditQueued(id: string, message: EditedMessage): void {- this.enqueueMessageMutation(id, message.messageId, () => this.applyMessageEdit(id, message));+ applyMessageEditQueued(id: string, message: EditedMessage, needsRow = false): void {+ this.enqueueMessageMutation(id, message.messageId, () => this.applyMessageEdit(id, message, needsRow));}/** Queue a message-scoped mutation. A failed operation is isolated so later events still run. */@@ -52,31 +54,44 @@ export class MessageMutationProjector {* change through, as it always went.*/async foreignRowReason(sessionId: string, waMessageId: string, source: MutationSource): Promise<string | null> {- if (!waMessageId) return null;+ return (await this.storedRowVerdict(sessionId, waMessageId, source)).reason;+ }++ /**+ * What the stored row says of a change: whether there is one to ask, and why the change must not touch+ * it (null when it may). A row that cannot be read is reported absent with no reason, as before.+ */+ async storedRowVerdict(+ sessionId: string,+ waMessageId: string,+ source: MutationSource,+ ): Promise<{ exists: boolean; reason: string | null }> {+ if (!waMessageId) return { exists: false, reason: null };try {const row = await this.messageRepository.findOne({where: { sessionId, waMessageId },select: { chatId: true, direction: true, author: true },});- return row ? mutationTargetsForeignRow(row, source) : null;+ return row ? { exists: true, reason: mutationTargetsForeignRow(row, source) } : { exists: false, reason: null };} catch {- return null;+ return { exists: false, reason: null };}}- private async applyReaction(id: string, event: ReactionEvent): Promise<void> {+ private async applyReaction(id: string, event: ReactionEvent, needsRow: boolean): Promise<void> {try {// Guard the lookup key before it reaches TypeORM: `findOne` DROPS an undefined condition from// the where-clause rather than matching nothing, so an engine that couldn't resolve the reacted// message's id would silently match an arbitrary row and clobber/emit its reactions. `!msg` is// no protection against that — the row it finds is real, just the wrong one.if (!event.messageId) return;- const foreign = await this.foreignRowReason(id, event.messageId, { kind: 'reaction', chatId: event.chatId });- if (foreign) {+ const verdict = await this.storedRowVerdict(id, event.messageId, { kind: 'reaction', chatId: event.chatId });+ if (needsRow && !verdict.exists) return;+ if (verdict.reason) {this.logger.warn('Dropping a reaction aimed at a message of another chat', {sessionId: id,messageId: event.messageId,- reason: foreign,+ reason: verdict.reason,});return;}@@ -114,18 +129,19 @@ export class MessageMutationProjector {}/** Persist an edit before notifying consumers, while still surfacing the occurrence if storage fails. */- private async applyMessageEdit(id: string, message: EditedMessage): Promise<void> {- const foreign = await this.foreignRowReason(id, message.messageId, {+ private async applyMessageEdit(id: string, message: EditedMessage, needsRow: boolean): Promise<void> {+ const verdict = await this.storedRowVerdict(id, message.messageId, {kind: 'edit',chatId: message.chatId,fromMe: message.fromMe,author: message.author,});- if (foreign) {+ if (needsRow && !verdict.exists) return;+ if (verdict.reason) {this.logger.warn('Dropping an edit aimed at a message of another chat or sender', {sessionId: id,messageId: message.messageId,- reason: foreign,+ reason: verdict.reason,});return;}diff --git a/src/modules/session/message-projector.inbound-hold.spec.ts b/src/modules/session/message-projector.inbound-hold.spec.tsindex d607d5ed1..2c761369a 100644--- a/src/modules/session/message-projector.inbound-hold.spec.ts+++ b/src/modules/session/message-projector.inbound-hold.spec.ts@@ -13,6 +13,7 @@ import type {IncomingMessage,InboundTicket,IWhatsAppEngine,+ RevokedMessage,} from '../../engine/interfaces/whatsapp-engine.interface';/**@@ -52,12 +53,13 @@ const message = (id: string, chatId: string, over: Partial<IncomingMessage> = {}...over,});-const arrival = (id: string, chatId: string, needsRoom = false, status = false, fromMe?: boolean) => ({+const arrival = (id: string, chatId: string, needsRoom = false, status = false, fromMe?: boolean, author?: string) => ({id,chatId,needsRoom,status,fromMe,+ author,});describe('MessageProjector holding inbound messages (PostgreSQL)', () => {@@ -315,6 +317,151 @@ describe('MessageProjector holding inbound messages (PostgreSQL)', () => {expect(rows[0]).toEqual(expect.objectContaining({ body: 'edited' }));});+ // An id names one message. A repeat of it sent from another chat is held under the same entry, and+ // must not take the entry over: a change aimed through the repeat would be judged by its chat.+ // In a group the edit comes from the participant who wrote the message, which the arrival names.+ it('keeps a group edit by another participant out of the message, and takes the one by its author', async () => {+ const GROUP = '[email protected]';+ const author = '[email protected]';+ const t = admit(arrival('A', GROUP, false, false, false, author));+ projector.applyMessageEditQueued('s1', {+ messageId: 'A',+ body: 'FORGED',+ chatId: GROUP,+ fromMe: false,+ author: '[email protected]',+ } as never);+ projector.handleInboundMessage('s1', engine, message('A', GROUP, { body: 'original', author }), t);+ await flush();+ expect(rows[0]).toEqual(expect.objectContaining({ body: 'original' }));++ const u = admit(arrival('B', GROUP, false, false, false, author));+ projector.applyMessageEditQueued('s1', {+ messageId: 'B',+ body: 'edited',+ chatId: GROUP,+ fromMe: false,+ author,+ } as never);+ projector.handleInboundMessage('s1', engine, message('B', GROUP, { body: 'original', author }), u);+ await flush();+ expect(rows[1]).toEqual(expect.objectContaining({ body: 'edited' }));+ });++ it('keeps the chat of the first arrival when a repeat of the id names another chat', async () => {+ const first = admit(arrival('A', CHAT, false, false, false));+ const repeat = admit(arrival('A', OTHER, false, false, false));+ // The repeat is emitted first and its insert is out; the changes that follow name its chat.+ const gate = deferred<void>();+ insertGate = row => (row.chatId === OTHER ? gate.promise : Promise.resolve());+ projector.handleInboundMessage('s1', engine, message('A', OTHER, { body: 'repeat' }), repeat);+ await flush();+ projector.applyMessageEditQueued('s1', {+ messageId: 'A',+ body: 'FORGED',+ chatId: OTHER,+ fromMe: false,+ } as never);+ projector.applyReactionQueued('s1', { messageId: 'A', chatId: OTHER, reaction: 'X', senderId: '[email protected]' });+ projector.handleInboundMessage('s1', engine, message('A', CHAT, { body: 'original' }), first);+ await flush();+ gate.resolve();+ await flush();++ const original = rows.find(r => r.chatId === CHAT);+ expect(original).toEqual(expect.objectContaining({ body: 'original' }));+ expect((original?.metadata as Row | undefined)?.reactions).toBeUndefined();+ expect(dispatched('message.received').map(p => p.body)).not.toContain('FORGED');+ });++ // The entry of a repeat that the engine will drop is no judge of a stored message: its row is.+ it('lets a change through to the stored row while a repeat of its id from another chat is held', async () => {+ rows.push({ sessionId: 's1', waMessageId: 'A', chatId: CHAT, direction: 'incoming', body: 'original' });+ admit(arrival('A', OTHER, false, false, false));+ projector.applyMessageEditQueued('s1', {+ messageId: 'A',+ body: 'edited',+ chatId: CHAT,+ fromMe: false,+ } as never);+ projector.applyReactionQueued('s1', { messageId: 'A', chatId: CHAT, reaction: 'ok', senderId: '[email protected]' });+ await flush();++ expect(rows[0].body).toBe('edited');+ expect(dispatched('message.edited')).toHaveLength(1);+ expect((rows[0].metadata as Row).reactions).toEqual({ '[email protected]': 'ok' });+ });++ it('still drops a change from the repeat chat aimed at the stored row, and announces nothing', async () => {+ rows.push({ sessionId: 's1', waMessageId: 'A', chatId: CHAT, direction: 'incoming', body: 'original' });+ admit(arrival('A', OTHER, false, false, false));+ projector.applyMessageEditQueued('s1', {+ messageId: 'A',+ body: 'FORGED',+ chatId: OTHER,+ fromMe: false,+ } as never);+ await flush();++ expect(rows[0].body).toBe('original');+ expect(dispatched('message.edited')).toEqual([]);+ });++ // The revoke of a message that has no row yet is applied at once, but only when the entry it names+ // agrees with who made it: the other side of a one-to-one chat cannot clear the account's message.+ describe('a revoke of a message still arriving', () => {+ const revoke = (chatId: string): RevokedMessage => ({+ id: 'A',+ revokedId: 'A',+ chatId,+ from: chatId,+ to: '[email protected]',+ type: 'revoked',+ body: '',+ timestamp: 1,+ });++ it('is dropped when the other side of a one-to-one chat made it, and nothing is announced', async () => {+ const t = admit(arrival('A', CHAT, false, false, true));+ projector.handleMessageRevoked('s1', engine, revoke(CHAT), { fromMe: false });+ await flush();+ projector.handleInboundMessage('s1', engine, message('A', CHAT, { body: 'mine', fromMe: true }), t);+ await flush();++ expect(dispatched('message.revoked')).toEqual([]);+ expect(eventsGateway.emitMessageRevoked).not.toHaveBeenCalled();+ expect(rows[0]).toEqual(expect.objectContaining({ body: 'mine' }));+ expect(rows[0].type).not.toBe('revoked');+ });++ it('is applied at once when its author made it', async () => {+ const t = admit(arrival('A', CHAT, false, false, true));+ projector.handleMessageRevoked('s1', engine, revoke(CHAT), { fromMe: true });+ expect(dispatched('message.revoked')).toHaveLength(1);+ projector.handleInboundMessage('s1', engine, message('A', CHAT, { body: 'mine', fromMe: true }), t);+ await flush();++ expect(rows[0]).toEqual(expect.objectContaining({ body: '', type: 'revoked' }));+ });++ it('is judged by the stored row when a repeat of the id from another chat is held', async () => {+ rows.push({ sessionId: 's1', waMessageId: 'A', chatId: CHAT, direction: 'incoming', body: 'original' });+ admit(arrival('A', OTHER, false, false, false));+ projector.handleMessageRevoked('s1', engine, revoke(CHAT), { fromMe: false });+ await flush();++ expect(dispatched('message.revoked')).toHaveLength(1);+ });++ it('is dropped when the held entry calls it foreign and no row exists', async () => {+ admit(arrival('A', OTHER, false, false, false));+ projector.handleMessageRevoked('s1', engine, revoke(CHAT), { fromMe: false });+ await flush();++ expect(dispatched('message.revoked')).toEqual([]);+ });+ });+it('does not guess a direction when the engine did not say whose message it is', async () => {const t = admit(arrival('A', CHAT));projector.applyMessageEditQueued('s1', {diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.tsindex b00c65d00..8170fecde 100644--- a/src/modules/session/message-projector.service.ts+++ b/src/modules/session/message-projector.service.ts@@ -375,7 +375,7 @@ export class MessageProjector {// handler's rewrite.const inFlightKey = `${id}:${message.id}`;const inFlight = turn- ? Object.assign(turn.entry, { quote: quoteOf(messageData), ref: refOf(messageData) })+ ? Object.assign(turn.entry, { quote: quoteOf(messageData), ref: turn.entry.ref ?? refOf(messageData) }): this.trackInFlight(inFlightKey, messageData);const onFailure = (err: unknown): null => {@@ -447,10 +447,12 @@ export class MessageProjector {/** Record a message as not yet written; a re-fire of the same id keeps the changes recorded so far. */private trackInFlight(key: string, message: InboundMessageData) {- const { revoked, revokeAnnounced, editedBody, ackStatus, reactions } = this.inboundInFlight.get(key) ?? {};+ const { ref, revoked, revokeAnnounced, editedBody, ackStatus, reactions } = this.inboundInFlight.get(key) ?? {};const inFlight = {quote: quoteOf(message),- ref: refOf(message),+ // The first delivery of an id says whose message it is: a repeat sent from another chat must not+ // take that over from it, or a change aimed through the repeat would be judged by the wrong rule.+ ref: ref ?? refOf(message),revoked,revokeAnnounced,editedBody,@@ -915,7 +917,7 @@ export class MessageProjector {// path, the entry follows the chain's rewrites, so a quote carries what the row will hold.const inFlightKey = `${id}:${message.id}`;const inFlight = turn- ? Object.assign(turn.entry, { quote: quoteOf(messageData), ref: refOf(messageData) })+ ? Object.assign(turn.entry, { quote: quoteOf(messageData), ref: turn.entry.ref ?? refOf(messageData) }): this.trackInFlight(inFlightKey, messageData);// Execute hook for message sent - plugins can modify or stop processing. Like the inbound path,// the hook chain runs concurrently and the commit waits its turn on the chat's queue.@@ -1178,26 +1180,31 @@ export class MessageProjector {// 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: it has no row to be checked against, and waiting for a read- // would let its emit run, and announce the deleted content, first.- if (!actor || this.inboundInFlight.has(`${id}:${revokedWaMessageId}`)) {+ // 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))) {apply();return;}- void this.mutationProjector- .foreignRowReason(id, revokedWaMessageId, { kind: 'revoke', chatId: message.chatId, fromMe: actor.fromMe })- .then(foreign => {- if (!this.engines.isLive(id, engine)) return;- if (foreign) {+ // Judged by the stored row, which a change the entry called foreign has to find, and accept.+ const needsRow = inFlight !== undefined;+ void this.mutationProjector.storedRowVerdict(id, revokedWaMessageId, source).then(verdict => {+ if (!this.engines.isLive(id, engine)) return;+ if (verdict.reason || (needsRow && !verdict.exists)) {+ if (verdict.reason) {this.logger.warn('Dropping a revoke aimed at a message of another chat or sender', {sessionId: id,messageId: revokedWaMessageId,- reason: foreign,+ reason: verdict.reason,});- return;}- apply();- });+ return;+ }+ apply();+ });}/** History backfill persist, extracted to message-history-projector.ts (stateless function). */@@ -1222,25 +1229,28 @@ export class MessageProjector {applyReactionQueued(id: string, event: ReactionEvent): void {// A message not written yet keeps the reaction for its row; the live event still goes out now.const inFlight = event.messageId ? this.inboundInFlight.get(`${id}:${event.messageId}`) : undefined;+ let needsRow = false;if (inFlight) {- // The row it will become would drop the change, and no row exists yet to say so: it is neither- // kept for the row nor announced.- if (this.foreignToInFlight(inFlight, { kind: 'reaction', chatId: event.chatId })) return;- (inFlight.reactions ??= {})[event.senderId] = event.reaction ?? '';+ // The row it will become would drop the change, so it is not kept for it. Nothing is announced on+ // that word alone either: a stored row of the same id (a repeat sent from another chat reached the+ // entry, not the message it repeats) is the one to ask, and without one the change goes no further.+ if (this.foreignToInFlight(inFlight, { kind: 'reaction', chatId: event.chatId })) needsRow = true;+ else (inFlight.reactions ??= {})[event.senderId] = event.reaction ?? '';}- this.mutationProjector.applyReactionQueued(id, event);+ this.mutationProjector.applyReactionQueued(id, event, needsRow);}/** Edit apply, queued on the per-message mutation chain — see MessageMutationProjector. */applyMessageEditQueued(id: string, message: EditedMessage): void {const inFlight = this.inboundInFlight.get(`${id}:${message.messageId}`);+ let needsRow = false;if (inFlight) {- // See applyReactionQueued: judged foreign, it is neither kept for the row nor announced.+ // See applyReactionQueued: judged foreign, it is not kept for the row, and a stored row decides.const source = { kind: 'edit', chatId: message.chatId, fromMe: message.fromMe, author: message.author } as const;- if (this.foreignToInFlight(inFlight, source)) return;- inFlight.editedBody = message.body;+ if (this.foreignToInFlight(inFlight, source)) needsRow = true;+ else inFlight.editedBody = message.body;}- this.mutationProjector.applyMessageEditQueued(id, message);+ this.mutationProjector.applyMessageEditQueued(id, message, needsRow);}/**