Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): drop an edit, revoke or reaction the row proves foreign
Yudhi Armyndharisecaa5cef3046
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dbaf149c4..e04a9de7e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -119,6 +119,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Preserve webhook outbox payloads until delivery or durable failure storage succeeds.- Keep one terminal webhook failure per receiver idempotency key.- Reject poll votes with no matching options while preserving explicit vote clearing.+- Drop a Baileys edit, revoke or reaction that the stored message proves foreign (another chat, or a one-to-one change by the other party), also when the engine's own message store no longer holds the original.- Name who reacted in a Baileys 1:1 reaction, whose sender id came out empty so the two parties overwrote each other's reaction, and flag a 1:1 message from a lid-only sender as `isLidSender`.- Read the duration of an outgoing Baileys audio file in a separate process and a voice note's waveform through ffmpeg, status voice notes included, so a crafted file can no longer abort or exhaust the gateway.- Bound `GET /api/search` to 1000 characters and 32 distinct words and run a repeated word once, so one request can no longer hold the event loop on SQLite for seconds.diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex b523c0a64..dda9690a5 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -594,7 +594,7 @@ export class BaileysEvents {this.changeStoredMessage(pm.key?.id, stored =>this.mayChange(stored.key, msg.key, true) ? { ...stored, message: null } : null,);- this.host.getOnMessageRevoked()?.(revoked);+ this.host.getOnMessageRevoked()?.(revoked, { fromMe: msg.key.fromMe === true });return;}if (pm?.type === b.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT) {diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex ec165fe74..edd8f0745 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -2794,6 +2794,8 @@ describe('BaileysAdapter inbound fan-out', () => {? { id: 'TARGET', revokedId: 'TARGET', body: '' }: { messageId: 'TARGET', body: 'updated' }),}),+ // A revoke also says who made it: here the account's own API delete, echoed.+ ...(operation === 'delete' ? [{ fromMe: true }] : []),);expect(operation === 'delete' ? onMessageEdited : onMessageRevoked).not.toHaveBeenCalled();expect(onMessageCreate).not.toHaveBeenCalled();@@ -3661,7 +3663,9 @@ describe('BaileysAdapter inbound fan-out', () => {await new Promise(r => setImmediate(r));expect(firstEditedMessage(onMessageEdited)).toMatchObject({ messageId: 'EDITED_ID', body: 'fixed' });- expect(onMessageRevoked).toHaveBeenCalledWith(expect.objectContaining({ id: 'REVOKED_ID' }));+ expect(onMessageRevoked).toHaveBeenCalledWith(expect.objectContaining({ id: 'REVOKED_ID' }), {+ fromMe: false,+ });expect(onMessageReaction).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'REACTED_ID', reaction: 'ok' }),);@@ -3712,8 +3716,12 @@ describe('BaileysAdapter inbound fan-out', () => {expect(firstEditedMessage(onMessageEdited)).toMatchObject({ messageId: 'E1', chatId: '[email protected]' });expect(onMessageRevoked).toHaveBeenCalledWith(expect.objectContaining({ id: 'R1', chatId: '[email protected]', from: '[email protected]' }),+ expect.anything(),+ );+ expect(onMessageRevoked).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'R2', chatId: LIST, to: LIST }),+ expect.anything(),);- expect(onMessageRevoked).toHaveBeenCalledWith(expect.objectContaining({ id: 'R2', chatId: LIST, to: LIST }));expect(onMessageReaction).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'X1', chatId: '[email protected]', senderId: '[email protected]' }),);diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 14d900795..49b09d451 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -879,7 +879,11 @@ export interface EngineEventCallbacks {* carries no chat, and the emitted payload then omits the field rather than guess.*/onMessageAck?: (messageId: string, status: DeliveryStatus, chatId?: string) => void;- onMessageRevoked?: (message: RevokedMessage) => void;+ /**+ * `actor.fromMe` says whether the account itself made the revoke (from its phone). Only an engine that+ * receives the raw protocol message can say; whatsapp-web.js leaves it out.+ */+ onMessageRevoked?: (message: RevokedMessage, actor?: { fromMe: boolean }) => void;onMessageReaction?: (event: ReactionEvent) => void;onMessageEdited?: (message: EditedMessage) => void;/**diff --git a/src/modules/session/message-mutation-guard.spec.ts b/src/modules/session/message-mutation-guard.spec.tsnew file mode 100644index 000000000..8df78512c--- /dev/null+++ b/src/modules/session/message-mutation-guard.spec.ts@@ -0,0 +1,82 @@+import { MessageDirection } from '../message/entities/message.entity';+import { mutationTargetsForeignRow } from './message-mutation-guard';++const OUT = MessageDirection.OUTGOING;+const IN = MessageDirection.INCOMING;++describe('mutationTargetsForeignRow', () => {+ const direct = '[email protected]';+ const group = '[email protected]';++ it('lets a change made by the sender of a one-to-one message through', () => {+ expect(+ mutationTargetsForeignRow({ chatId: direct, direction: IN }, { kind: 'edit', chatId: direct, fromMe: false }),+ ).toBeNull();+ expect(+ mutationTargetsForeignRow({ chatId: direct, direction: OUT }, { kind: 'revoke', chatId: direct, fromMe: true }),+ ).toBeNull();+ });++ it('refuses a one-to-one edit or revoke made by the other party', () => {+ for (const kind of ['edit', 'revoke'] as const) {+ expect(+ mutationTargetsForeignRow({ chatId: direct, direction: OUT }, { kind, chatId: direct, fromMe: false }),+ ).toBe('direction');+ expect(mutationTargetsForeignRow({ chatId: direct, direction: IN }, { kind, chatId: direct, fromMe: true })).toBe(+ 'direction',+ );+ }+ });++ it('refuses a change that names a message of another chat, whatever the kind', () => {+ for (const kind of ['edit', 'revoke', 'reaction'] as const) {+ expect(mutationTargetsForeignRow({ chatId: '[email protected]', direction: IN }, { kind, chatId: direct })).toBe(+ 'chat',+ );+ expect(mutationTargetsForeignRow({ chatId: group, direction: IN }, { kind, chatId: direct })).toBe('chat');+ }+ });++ it('does not call a lid and a phone number different, since they may be one chat', () => {+ expect(+ mutationTargetsForeignRow({ chatId: '111@lid', direction: IN }, { kind: 'edit', chatId: direct, fromMe: false }),+ ).toBeNull();+ expect(+ mutationTargetsForeignRow({ chatId: direct, direction: IN }, { kind: 'edit', chatId: '111@lid', fromMe: false }),+ ).toBeNull();+ expect(+ mutationTargetsForeignRow(+ { chatId: '111@lid', direction: IN },+ { kind: 'edit', chatId: '222@lid', fromMe: false },+ ),+ ).toBe('chat');+ });++ it('lets any participant react, and an admin delete a message the account sent', () => {+ expect(+ mutationTargetsForeignRow({ chatId: group, direction: OUT }, { kind: 'reaction', chatId: group, fromMe: false }),+ ).toBeNull();+ expect(+ mutationTargetsForeignRow({ chatId: group, direction: OUT }, { kind: 'revoke', chatId: group, fromMe: false }),+ ).toBeNull();+ });++ it('refuses a group edit by somebody other than the author, and one of the account message by a member', () => {+ const row = { chatId: group, direction: IN, author: '[email protected]' };+ expect(+ mutationTargetsForeignRow(row, { kind: 'edit', chatId: group, fromMe: false, author: '[email protected]' }),+ ).toBeNull();+ expect(mutationTargetsForeignRow(row, { kind: 'edit', chatId: group, fromMe: false, author: '[email protected]' })).toBe(+ 'author',+ );+ expect(+ mutationTargetsForeignRow({ chatId: group, direction: OUT }, { kind: 'edit', chatId: group, fromMe: false }),+ ).toBe('direction');+ });++ it('says nothing when the engine does not say who made the change', () => {+ expect(+ mutationTargetsForeignRow({ chatId: direct, direction: OUT }, { kind: 'revoke', chatId: direct }),+ ).toBeNull();+ });+});diff --git a/src/modules/session/message-mutation-guard.ts b/src/modules/session/message-mutation-guard.tsnew file mode 100644index 000000000..af2bb0cb9--- /dev/null+++ b/src/modules/session/message-mutation-guard.ts@@ -0,0 +1,59 @@+import { MessageDirection } from '../message/entities/message.entity';++/** What a stored row says about whose message it is and where it lives. */+export interface StoredMessageRef {+ chatId: string;+ direction: MessageDirection;+ author?: string | null;+}++/** What an inbound edit, revoke or reaction says about who made it and where. */+export interface MutationSource {+ kind: 'edit' | 'revoke' | 'reaction';+ chatId: string;+ /** Whether the account itself made the change, from its phone; undefined when the engine does not say. */+ fromMe?: boolean;+ /** For a group edit, the participant who wrote the message being edited. */+ author?: string;+}++const isLid = (jid: string): boolean => jid.endsWith('@lid');+const isPhone = (jid: string): boolean => jid.endsWith('@c.us');++/** Whether two neutral ids provably name different chats or people. A lid against a phone number may be one. */+function provablyDifferent(a?: string | null, b?: string | null): boolean {+ if (!a || !b || a === b) return false;+ return !((isLid(a) && isPhone(b)) || (isLid(b) && isPhone(a)));+}++/**+ * Why a change must not touch the stored row it names, or null when it may.+ *+ * Baileys applies no validation to an edit, a revoke or a reaction: it hands over whatever a participant+ * sent, naming any message id the sender knows. The engine adapter checks it against its own message+ * store, which holds the newest few thousand messages and never a history-synced one, so for an older+ * message only this row can tell. WhatsApp clients ignore a change made by somebody other than the+ * author, so applying it would make the gateway's record say what no client shows.+ *+ * - `chat`: a message id belongs to one chat.+ * - `direction`: an edit, and a revoke in a one-to-one chat, come from the author only, so a change+ * made by the counterparty cannot name a message the account sent, nor the reverse. Group revokes are+ * exempt, since an admin may delete anyone's message.+ * - `author`: a group edit comes from the participant who wrote the message.+ */+export function mutationTargetsForeignRow(+ row: StoredMessageRef,+ source: MutationSource,+): 'chat' | 'direction' | 'author' | null {+ if (provablyDifferent(row.chatId, source.chatId)) return 'chat';+ const group = source.chatId.endsWith('@g.us') || row.chatId.endsWith('@g.us');+ const authorOnly = source.kind === 'edit' || (source.kind === 'revoke' && !group);+ if (authorOnly && source.fromMe !== undefined) {+ const expected = source.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING;+ if (row.direction && row.direction !== expected) return 'direction';+ }+ if (source.kind === 'edit' && group && source.fromMe === false && provablyDifferent(row.author, source.author)) {+ return 'author';+ }+ return null;+}diff --git a/src/modules/session/message-mutation-projector.ts b/src/modules/session/message-mutation-projector.tsindex 606338773..095d0263f 100644--- a/src/modules/session/message-mutation-projector.ts+++ b/src/modules/session/message-mutation-projector.ts@@ -6,6 +6,7 @@ import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';import { ReactionEvent, EditedMessage } from '../../engine/interfaces/whatsapp-engine.interface';import { updateMessageMetadata } from '../message/message-metadata';+import { mutationTargetsForeignRow, type MutationSource } from './message-mutation-guard';/*** Applies stored-message mutations — reactions, inbound edits, REST outbound-edit echoes — behind@@ -45,6 +46,24 @@ export class MessageMutationProjector {this.messageMutations.enqueue(`${id}:${messageId}`, work);}+ /**+ * Why a change must not touch the stored row it names (see message-mutation-guard), or null: the row+ * is absent, unreadable, or the change is consistent with it. Never rejects: a read that fails lets the+ * change through, as it always went.+ */+ async foreignRowReason(sessionId: string, waMessageId: string, source: MutationSource): Promise<string | null> {+ if (!waMessageId) return null;+ try {+ const row = await this.messageRepository.findOne({+ where: { sessionId, waMessageId },+ select: { chatId: true, direction: true, author: true },+ });+ return row ? mutationTargetsForeignRow(row, source) : null;+ } catch {+ return null;+ }+ }+private async applyReaction(id: string, event: ReactionEvent): Promise<void> {try {// Guard the lookup key before it reaches TypeORM: `findOne` DROPS an undefined condition from@@ -52,6 +71,15 @@ export class MessageMutationProjector {// 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) {+ this.logger.warn('Dropping a reaction aimed at a message of another chat', {+ sessionId: id,+ messageId: event.messageId,+ reason: foreign,+ });+ return;+ }// A revoked row reads as absent, like the edit paths: a reaction that lands after the delete must// not write a reactions map back onto the cleared metadata.@@ -87,6 +115,20 @@ 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, {+ kind: 'edit',+ chatId: message.chatId,+ fromMe: message.fromMe,+ author: message.author,+ });+ if (foreign) {+ this.logger.warn('Dropping an edit aimed at a message of another chat or sender', {+ sessionId: id,+ messageId: message.messageId,+ reason: foreign,+ });+ return;+ }try {// Never onto a revoked row: a late edit must not bring back text the sender deleted.await this.messageRepository.update(diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.tsindex e732a5767..241472fff 100644--- a/src/modules/session/message-projector.service.spec.ts+++ b/src/modules/session/message-projector.service.spec.ts@@ -132,6 +132,73 @@ describe('MessageProjector', () => {});});+ describe('edits and reactions aimed at a stored row', () => {+ it('drops an edit the counterparty made of a message the account sent', async () => {+ messageRepository.findOne.mockResolvedValue({ chatId: '[email protected]', direction: 'outgoing' });++ projector.applyMessageEditQueued('s1', {+ messageId: 'M1',+ chatId: '[email protected]',+ body: 'forged',+ fromMe: false,+ } as never);+ await settle();+ await settle();++ expect(messageRepository.update).not.toHaveBeenCalled();+ expect(webhookService.dispatch).not.toHaveBeenCalled();+ });++ it("applies the counterparty's edit of its own message", async () => {+ messageRepository.findOne.mockResolvedValue({ chatId: '[email protected]', direction: 'incoming' });++ projector.applyMessageEditQueued('s1', {+ messageId: 'M1',+ chatId: '[email protected]',+ body: 'fixed typo',+ fromMe: false,+ } as never);+ await settle();+ await settle();++ expect(messageRepository.update).toHaveBeenCalledWith(+ expect.objectContaining({ sessionId: 's1', waMessageId: 'M1' }),+ { body: 'fixed typo' },+ );+ });++ it("drops a group member's edit of another member's message", async () => {+ messageRepository.findOne.mockResolvedValue({+ chatId: '[email protected]',+ direction: 'incoming',+ author: '[email protected]',+ });++ projector.applyMessageEditQueued('s1', {+ messageId: 'M1',+ chatId: '[email protected]',+ body: 'forged',+ fromMe: false,+ author: '[email protected]',+ } as never);+ await settle();+ await settle();++ expect(messageRepository.update).not.toHaveBeenCalled();+ });++ it('drops a reaction that names a message of another chat', async () => {+ messageRepository.findOne.mockResolvedValue({ chatId: '[email protected]', direction: 'incoming' });++ projector.applyReactionQueued('s1', { messageId: 'M1', chatId: '[email protected]', senderId: '[email protected]', reaction: '👍' });+ await settle();+ await settle();++ expect(messageRepository.update).not.toHaveBeenCalled();+ expect(eventsGateway.emitMessageReaction).not.toHaveBeenCalled();+ });+ });+describe('applyReactionQueued', () => {it('ignores a reaction with no target message id instead of querying for one', async () => {// findOne DROPS an undefined condition rather than matching nothing, so reaching the repository@@ -241,6 +308,71 @@ describe('MessageProjector', () => {);});+ describe('when the engine says who made the revoke', () => {+ const revoke = { id: 'M1', revokedId: 'M1', chatId: '[email protected]' } as never;+ const row = (fields: Record<string, unknown>): void => {+ messageRepository.findOne.mockResolvedValue({ chatId: '[email protected]', direction: 'incoming', ...fields });+ };++ it('drops a revoke the counterparty made of a message the account sent', async () => {+ // WhatsApp clients ignore it, and Baileys hands it over unchecked, so the stored row must not follow.+ row({ direction: 'outgoing' });++ projector.handleMessageRevoked('s1', engine, revoke, { fromMe: false });+ await settle();++ expect(messageRepository.update).not.toHaveBeenCalled();+ expect(webhookService.dispatch).not.toHaveBeenCalled();+ expect(eventsGateway.emitMessageRevoked).not.toHaveBeenCalled();+ });++ it.each([+ ['the counterparty of its own message', { direction: 'incoming' }, false],+ ['the account from its phone of its own message', { direction: 'outgoing' }, true],+ ])('applies a revoke made by %s', async (_who, fields, fromMe) => {+ row(fields);++ projector.handleMessageRevoked('s1', engine, revoke, { fromMe });+ await settle();++ expect(messageRepository.update).toHaveBeenCalledWith(+ { sessionId: 's1', waMessageId: 'M1' },+ expect.objectContaining({ type: 'revoked' }),+ );+ expect(eventsGateway.emitMessageRevoked).toHaveBeenCalledTimes(1);+ });++ it('drops a revoke that names a message of another chat', async () => {+ row({ chatId: '[email protected]' });++ projector.handleMessageRevoked('s1', engine, revoke, { fromMe: false });+ await settle();++ expect(messageRepository.update).not.toHaveBeenCalled();+ expect(eventsGateway.emitMessageRevoked).not.toHaveBeenCalled();+ });++ it('still applies a group admin deleting a message the account sent', async () => {+ row({ chatId: '[email protected]', direction: 'outgoing' });++ projector.handleMessageRevoked('s1', engine, { id: 'M1', revokedId: 'M1', chatId: '[email protected]' } as never, {+ fromMe: false,+ });+ await settle();++ expect(eventsGateway.emitMessageRevoked).toHaveBeenCalledTimes(1);+ });++ it('applies a revoke of a message nothing stored, as it always did', async () => {+ messageRepository.findOne.mockResolvedValue(null);++ projector.handleMessageRevoked('s1', engine, revoke, { fromMe: false });+ await settle();++ expect(eventsGateway.emitMessageRevoked).toHaveBeenCalledTimes(1);+ });+ });+it('ignores an event from an engine that no longer owns the session', async () => {projector.handleMessageRevoked('s1', {} as IWhatsAppEngine, { id: 'REV1' } as never);await settle();diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.tsindex 096e0392f..efff68c32 100644--- a/src/modules/session/message-projector.service.ts+++ b/src/modules/session/message-projector.service.ts@@ -1120,7 +1120,12 @@ export class MessageProjector {}/** Engine callback body, lifted out of initializeEngine so the wiring table stays readable. */- handleMessageRevoked(id: string, engine: IWhatsAppEngine, message: RevokedMessage): void {+ handleMessageRevoked(+ id: string,+ engine: IWhatsAppEngine,+ message: RevokedMessage,+ actor?: { fromMe: boolean },+ ): void {if (!this.engines.isLive(id, engine)) return;this.logger.debug(`Message revoked: ${message.id}`, {sessionId: id,@@ -1136,15 +1141,38 @@ export class MessageProjector {// `message.id` is the revocation notification, which never matches a stored row.// `revokedId` falls back to `id` (Baileys, where the two are the same).const revokedWaMessageId = message.revokedId ?? message.id;- void this.recordRevoke(id, revokedWaMessageId);- const inFlight = this.inboundInFlight.get(`${id}:${revokedWaMessageId}`);- if (inFlight) inFlight.revokeAnnounced = true;-- // Notify consumers regardless of whether the row existed: webhook (message.revoked- // is a declared event) + the real-time dashboard stream.- const revokedPayload = message as unknown as Record<string, unknown>;- void this.webhookService.dispatch(id, 'message.revoked', revokedPayload);- this.eventsGateway.emitMessageRevoked(id, revokedPayload);+ const apply = (): void => {+ void this.recordRevoke(id, revokedWaMessageId);+ const inFlight = this.inboundInFlight.get(`${id}:${revokedWaMessageId}`);+ if (inFlight) inFlight.revokeAnnounced = true;++ // Notify consumers regardless of whether the row existed: webhook (message.revoked+ // is a declared event) + the real-time dashboard stream.+ const revokedPayload = message as unknown as Record<string, unknown>;+ 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.+ if (!actor) {+ 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) {+ this.logger.warn('Dropping a revoke aimed at a message of another chat or sender', {+ sessionId: id,+ messageId: revokedWaMessageId,+ reason: foreign,+ });+ return;+ }+ apply();+ });}/** History backfill persist, extracted to message-history-projector.ts (stateless function). */diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.tsindex e807101a5..0892ea3e2 100644--- a/src/modules/session/session-engine-event-wiring.ts+++ b/src/modules/session/session-engine-event-wiring.ts@@ -248,7 +248,7 @@ export class SessionEngineEventWiring {onMessageCreate: (message, ticket): void => host.messages.handleOwnSendEcho(id, engine, message, ticket),onMessageAck: (messageId, status, chatId): void =>host.messages.handleMessageAck(id, engine, messageId, status, chatId),- onMessageRevoked: (message): void => host.messages.handleMessageRevoked(id, engine, message),+ onMessageRevoked: (message, actor): void => host.messages.handleMessageRevoked(id, engine, message, actor),onMessageReaction: (event): void => {if (!host.isLiveEngine(id, engine)) return;if (!event.messageId) {