Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(message): clear a revoked message's stored content
Yudhi Armyndharis1d3619b9f4d1
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 32bf4c2ea..a7de3c06f 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1507,6 +1507,9 @@ The inline fallback also keeps an inbound message's media downloadable after`CHAT_MEDIA_ARCHIVE_TTL_DAYS` retention purges the archived file, since retention leaves the inlinecopy in place.+A revoked message (deleted for everyone, or through `POST /messages/delete`) has no media: its row is+cleared on revoke, and this route answers `404` for it.+**Auth:** API key**Path parameters**@@ -2192,7 +2195,7 @@ The controller hardcodes the result after the engine call. Note the `200` status#### POST /api/sessions/:sessionId/messages/delete-Delete a message (for everyone by default); also flags the stored record as `revoked`.+Delete a message (for everyone by default); also clears the stored record and flags it `revoked`.**Auth:** API key (OPERATOR)@@ -2216,7 +2219,7 @@ Delete a message (for everyone by default); also flags the stored record as `rev**Response** `200`-After the engine delete, the stored message body is cleared and its `type` set to `revoked`. Note the `200` status (via `@HttpCode`).+After the engine delete, the stored message's body and `metadata` (inline media, quote, reactions) are cleared, its archived-media pointer is removed, and its `type` is set to `revoked`, the same as when the engine reports a revoke (`message.revoked`). The archived file itself is deleted later by the chat-media orphan sweep, once it has stayed unreferenced for the sweep's grace window. Note the `200` status (via `@HttpCode`).```json{ "success": true }diff --git a/docs/26-global-search.md b/docs/26-global-search.mdindex 65a3ea84e..26fa024f0 100644--- a/docs/26-global-search.md+++ b/docs/26-global-search.md@@ -176,11 +176,12 @@ Because the route and the response shape are identical across providers, dashboakeep working unchanged when you switch backends.> **Backfill is the plugin's responsibility.** The `message:persisted` hook fires only for **live**-> traffic — outbound on send, inbound on receive — never for history-backfill persistence. So a plugin-> provider installed on a deployment that already has message history must perform its own one-time-> backfill (read `messages` and index) at enablement; its index will otherwise miss pre-installation-> rows. The built-in DB-FTS provider is unaffected — its index is DB-synced via triggers on every-> insert, including backfill.+> traffic — outbound on send, inbound on receive, and again when a stored message is revoked (see+> [27.3](./27-plugin-search-providers.md#273-indexing-via-the-messagepersisted-hook)) — never for+> history-backfill persistence. So a plugin provider installed on a deployment that already has message+> history must perform its own one-time backfill (read `messages` and index) at enablement; its index+> will otherwise miss pre-installation rows. The built-in DB-FTS provider is+> unaffected — its index is DB-synced via triggers on every insert, including backfill.## 26.8 Migration and backfilldiff --git a/docs/27-plugin-search-providers.md b/docs/27-plugin-search-providers.mdindex b3d78a22f..7dc1901d8 100644--- a/docs/27-plugin-search-providers.md+++ b/docs/27-plugin-search-providers.md@@ -88,8 +88,9 @@ text (escape-then-highlight), never as HTML. Do not inject HTML.## 27.3 Indexing via the `message:persisted` hook-The core fires `message:persisted` for every live message (outbound on send, inbound on receive) — never-for history backfill. Register a handler to keep your index in sync:+The core fires `message:persisted` for every live message (outbound on send, inbound on receive, and again+when a stored message is revoked) — never for history backfill. Register a handler to keep your index in+sync:```tsctx.registerHook('message:persisted', async hookCtx => {@@ -104,6 +105,12 @@ as `PENDING` (usually with `waMessageId` still null), then emits it **again** wireaches its terminal state (`SENT` with the engine id, or `FAILED`). Key your documents by the row `id`and treat every emission as an upsert, and your index always converges to the finalized state.+**A revoke re-emits the row too.** When a message of either direction is revoked (an engine+`message.revoked`, or `POST /messages/delete`, whether or not `forEveryone` is set), the core clears the+stored row and emits `message:persisted` again with the same `id`, an empty `body`, `type: 'revoked'` and+null `metadata`. An upsert keyed by `id` therefore drops the deleted content from your index; do not count+the emission as a new message.+One race remains visible by design: when the engine's own-send echo wins, the redundant PENDING row ismerged into the echo's row and then dropped. The core emits `message:persisted` for the surviving row(upsert it) followed by `message:deleted` for the dropped one — delete that document by its `id`:diff --git a/src/database/migrations/1786900000000-ScrubRevokedMessageContent.ts b/src/database/migrations/1786900000000-ScrubRevokedMessageContent.tsnew file mode 100644index 000000000..668914ff6--- /dev/null+++ b/src/database/migrations/1786900000000-ScrubRevokedMessageContent.ts@@ -0,0 +1,27 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Clear what earlier releases kept on a revoked message's row.+ *+ * A revoke used to empty only `body`, leaving the inline media, quote and reactions in `metadata` and+ * the archived-media pointer in `mediaPath`/`mediaMimetype`, so the list and media endpoints kept+ * serving content the sender deleted. New revokes clear all of it; this brings the rows revoked+ * before that in line. The archived files those pointers referenced become unreferenced, and the+ * chat-media orphan sweep reaps them after its grace window.+ *+ * Idempotent, and `down` is a no-op: the cleared content is not recoverable.+ */+export class ScrubRevokedMessageContent1786900000000 implements MigrationInterface {+ name = 'ScrubRevokedMessageContent1786900000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (!(await queryRunner.hasTable('messages'))) return;+ await queryRunner.query(+ `UPDATE "messages" SET "body" = '', "metadata" = NULL, "mediaPath" = NULL, "mediaMimetype" = NULL WHERE "type" = 'revoked'`,+ );+ }++ public async down(): Promise<void> {+ // Nothing to restore.+ }+}diff --git a/src/database/migrations/__tests__/1786900000000-ScrubRevokedMessageContent.spec.ts b/src/database/migrations/__tests__/1786900000000-ScrubRevokedMessageContent.spec.tsnew file mode 100644index 000000000..3a1953dce--- /dev/null+++ b/src/database/migrations/__tests__/1786900000000-ScrubRevokedMessageContent.spec.ts@@ -0,0 +1,75 @@+import { DataSource, Repository } from 'typeorm';+import { Message, MessageDirection, MessageStatus } from '../../../modules/message/entities/message.entity';+import { ScrubRevokedMessageContent1786900000000 } from '../1786900000000-ScrubRevokedMessageContent';++// A real SQLite database: the statement itself is what is under test.+describe('ScrubRevokedMessageContent migration', () => {+ const migration = new ScrubRevokedMessageContent1786900000000();+ let ds: DataSource;+ let repository: Repository<Message>;++ beforeEach(async () => {+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [Message], synchronize: true });+ await ds.initialize();+ repository = ds.getRepository(Message);+ });++ afterEach(async () => {+ await ds.destroy();+ });++ const row = (waMessageId: string, type: string, body: string): Promise<Message> =>+ repository.save(+ repository.create({+ sessionId: 's1',+ chatId: '[email protected]',+ waMessageId,+ from: '[email protected]',+ to: '[email protected]',+ body,+ type,+ direction: MessageDirection.INCOMING,+ status: MessageStatus.SENT,+ timestamp: 1,+ metadata: { media: { mimetype: 'image/png', data: 'AAAA' }, reactions: { '[email protected]': 'ok' } },+ mediaPath: `chat-media/s1/${waMessageId}.png`,+ mediaMimetype: 'image/png',+ }),+ );++ it('clears the content of revoked rows and leaves every other row alone', async () => {+ const revoked = await row('wa-revoked', 'revoked', 'This message was deleted');+ const kept = await row('wa-kept', 'image', 'caption');++ const runner = ds.createQueryRunner();+ await migration.up(runner);+ await migration.up(runner); // idempotent+ await runner.release();++ expect(await repository.findOneByOrFail({ id: revoked.id })).toMatchObject({+ body: '',+ type: 'revoked',+ metadata: null,+ mediaPath: null,+ mediaMimetype: null,+ });+ expect(await repository.findOneByOrFail({ id: kept.id })).toMatchObject({+ body: 'caption',+ metadata: kept.metadata,+ mediaPath: kept.mediaPath,+ mediaMimetype: 'image/png',+ });+ });++ it('skips a database without a messages table', async () => {+ const empty = new DataSource({ type: 'better-sqlite3', database: ':memory:' });+ await empty.initialize();+ const runner = empty.createQueryRunner();++ await expect(migration.up(runner)).resolves.toBeUndefined();+ await expect(migration.down()).resolves.toBeUndefined();++ await runner.release();+ await empty.destroy();+ });+});diff --git a/src/modules/chat-media/chat-media-archive.service.spec.ts b/src/modules/chat-media/chat-media-archive.service.spec.tsindex 09462c966..3dd9b873b 100644--- a/src/modules/chat-media/chat-media-archive.service.spec.ts+++ b/src/modules/chat-media/chat-media-archive.service.spec.ts@@ -180,6 +180,19 @@ describe('ChatMediaArchiveService', () => {expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeNull();update.mockRestore();});++ it('does not point a row revoked while its file was written back at the media', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ // The archive works from the in-memory row the projector inserted; the revoke lands meanwhile.+ await repository.update({ id: row.id }, { type: 'revoked', body: '' });++ await expect(enabled().archive(row)).resolves.toBeNull();++ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeNull();+ const files = [];+ for await (const f of storageService.iterateFiles(CHAT_MEDIA_PREFIX)) files.push(f);+ expect(files).toEqual([]);+ });});describe('getMedia', () => {@@ -193,6 +206,14 @@ describe('ChatMediaArchiveService', () => {});});+ it('returns null for a revoked message that still points at a file', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ await enabled().archive(row);+ await repository.update({ id: row.id }, { type: 'revoked' });++ expect(await enabled().getMedia('sess-1', [row.chatId], row.waMessageId)).toBeNull();+ });+it('returns null for a message with nothing archived', async () => {const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });expect(await enabled().getMedia('sess-1', [row.chatId], row.waMessageId)).toBeNull();diff --git a/src/modules/chat-media/chat-media-archive.service.ts b/src/modules/chat-media/chat-media-archive.service.tsindex d670f8c30..0a06598d6 100644--- a/src/modules/chat-media/chat-media-archive.service.ts+++ b/src/modules/chat-media/chat-media-archive.service.ts@@ -158,7 +158,16 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {}try {- await this.repository.update({ id: row.id }, { mediaPath: key, mediaMimetype: media.mimetype });+ // Conditional on the row not being revoked: a revoke that landed while the file was written+ // cleared the row, and pointing it at the file would bring the deleted media back.+ const result = await this.repository.update(+ { id: row.id, type: Not('revoked') },+ { mediaPath: key, mediaMimetype: media.mimetype },+ );+ if (result.affected === 0) {+ await this.storageService.deleteFile(key).catch(() => undefined); // else the orphan sweep reaps it+ return null;+ }} catch (error) {// The file exists but no row references it — an orphan the sweep reaps after its grace// window. The row itself stays consistent (mediaPath still null), so nothing else to undo.@@ -183,7 +192,8 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {// engine-neutral form depending on which writer won the persist race. The caller owns the// dialect resolution (it holds the lid table), so this only has to match any of them.const row = await this.repository.findOne({ where: { sessionId, chatId: In(chatIds), waMessageId } });- if (!row?.mediaPath || !row.mediaMimetype) return null;+ // A revoked row serves nothing, whatever pointer it still holds.+ if (!row?.mediaPath || !row.mediaMimetype || row.type === 'revoked') return null;return { path: row.mediaPath, mimetype: row.mediaMimetype };}diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 5e6fb2e25..f2508cf90 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -67,7 +67,7 @@ describe('MessageService', () => {let service: MessageService;let repository: jest.Mocked<Partial<Repository<Message>>>;let engines: EngineRegistry;- let messageProjector: { recordOutboundMessageEdit: jest.Mock };+ let messageProjector: { recordOutboundMessageEdit: jest.Mock; recordRevoke: jest.Mock };let hookManager: jest.Mocked<Partial<HookManager>>;let lidMappingStore: { findLidsForPhone: jest.Mock; findPhoneForLid: jest.Mock };let mockEngine: ReturnType<typeof createMockEngine>;@@ -84,7 +84,10 @@ describe('MessageService', () => {mockEngine = createMockEngine();- messageProjector = { recordOutboundMessageEdit: jest.fn().mockResolvedValue(undefined) };+ messageProjector = {+ recordOutboundMessageEdit: jest.fn().mockResolvedValue(undefined),+ recordRevoke: jest.fn().mockResolvedValue(undefined),+ };engines = new EngineRegistry();engines.set('sess-1', mockEngine as unknown as IWhatsAppEngine);@@ -809,6 +812,16 @@ describe('MessageService', () => {expect(mockEngine.deleteMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', false);});++ it('clears the stored row through the same revoke as an engine revoke, after the engine delete', async () => {+ await service.deleteMessage('sess-1', { chatId: '[email protected]', messageId: 'wa-msg-1' });++ expect(messageProjector.recordRevoke).toHaveBeenCalledWith('sess-1', 'wa-msg-1');+ expect(mockEngine.deleteMessage.mock.invocationCallOrder[0]).toBeLessThan(+ messageProjector.recordRevoke.mock.invocationCallOrder[0],+ );+ expect(repository.update).not.toHaveBeenCalled();+ });});describe('editMessage', () => {@@ -1045,6 +1058,15 @@ describe('MessageService', () => {});});+ it('404s for a revoked row that still carries an inline copy', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue({+ ...inlineRow({ mimetype: 'image/jpeg', data: Buffer.from('GONE').toString('base64') }),+ type: 'revoked',+ });+ const svc = build(noArchive(), storage());+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).rejects.toThrow(NotFoundException);+ });+it('prefers the archived file over the inline copy when both exist', async () => {(repository.findOne as jest.Mock).mockResolvedValue(inlineRow({ mimetype: 'image/png', data: Buffer.from('INLINE').toString('base64') }),@@ -1270,4 +1292,17 @@ describe('spendInlineMediaBudget', () => {expect(mediaOf(rows[0]).data).toBeUndefined();expect(mediaOf(rows[0]).omitted).toBe(true);});+ // A revoked message has no media. A row restored from an older backup, or merged onto after its+ // revoke was cleared, can still carry a payload; the list must not return it, and it must not+ // spend the newest-payload allowance the next real media is owed.+ it('drops the media of a revoked row and still inlines the media after it', () => {+ const revoked = row('revoked', 5000);+ revoked.type = 'revoked';+ const rows = [revoked, row('image', 3000)];+ spendInlineMediaBudget(rows, 1000);++ expect(rows[0].metadata.media).toBeUndefined();+ expect(mediaOf(rows[1]).data).toHaveLength(3000);+ expect(mediaOf(rows[1]).omitted).toBeUndefined();+ });});diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex f0839bd81..6da6331ab 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -95,6 +95,11 @@ export function createInlineMediaSpender(budgetBytes: number): (message: Messagereturn message => {const metadata = message.metadata as Record<string, unknown> | null | undefined;if (!metadata || typeof metadata !== 'object') return;+ // A revoked message has no media, even on a row restored or merged after its revoke was cleared.+ if (message.type === 'revoked') {+ delete metadata.media;+ return;+ }const media = metadata.media as { data?: unknown; sizeBytes?: number } | null | undefined;if (!media || typeof media.data !== 'string' || MEDIA_URL_POINTER.test(media.data)) return;@@ -546,6 +551,8 @@ export class MessageService implements PluginMessagePort {});const inline = (row?.metadata as { media?: { data?: unknown; mimetype?: unknown; omitted?: unknown } })?.media;if (+ // A revoked message's media is gone, even on a row cleared before revokes dropped it.+ row?.type === 'revoked' ||!inline ||inline.omitted ||typeof inline.data !== 'string' ||@@ -648,13 +655,10 @@ export class MessageService implements PluginMessagePort {const engine = this.getEngine(sessionId);await engine.deleteMessage(dto.chatId, dto.messageId, dto.forEveryone ?? true);- // Flag the stored message as revoked. No localized display string is persisted here;- // the dashboard renders the localized "message deleted" text.- try {- await this.messageRepository.update({ sessionId, waMessageId: dto.messageId }, { body: '', type: 'revoked' });- } catch (err) {- this.logger.warn(`Failed to flag deleted message ${dto.messageId} as revoked`, { error: String(err) });- }+ // Clear the stored message the same way an engine revoke does (body, media and metadata), on+ // its mutation chain. Best-effort: never rejects. No localized display string is persisted+ // here; the dashboard renders the localized "message deleted" text.+ await this.messageProjector.recordRevoke(sessionId, dto.messageId);}// ========== Edit Message ==========diff --git a/src/modules/session/message-mutation-projector.ts b/src/modules/session/message-mutation-projector.tsindex 1f0481393..aa72a6db2 100644--- a/src/modules/session/message-mutation-projector.ts+++ b/src/modules/session/message-mutation-projector.ts@@ -1,4 +1,4 @@-import { Repository } from 'typeorm';+import { Not, Repository } from 'typeorm';import { QueryDeepPartialEntity } from 'typeorm';import { Message } from '../message/entities/message.entity';import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';@@ -96,7 +96,11 @@ 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> {try {- await this.messageRepository.update({ sessionId: id, waMessageId: message.messageId }, { body: message.body });+ // Never onto a revoked row: a late edit must not bring back text the sender deleted.+ await this.messageRepository.update(+ { sessionId: id, waMessageId: message.messageId, type: Not('revoked') },+ { body: message.body },+ );} catch (err) {this.logger.error(`Failed to update edited message: ${message.messageId}`, String(err));}@@ -117,7 +121,7 @@ export class MessageMutationProjector {await new Promise<void>(resolve => {this.enqueueMessageMutation(sessionId, messageId, async () => {try {- await this.messageRepository.update({ sessionId, waMessageId: messageId }, { body });+ await this.messageRepository.update({ sessionId, waMessageId: messageId, type: Not('revoked') }, { body });} catch (err) {this.logger.warn(`Failed to update stored body of edited message ${messageId}`, { error: String(err) });} finally {diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.tsindex 49da49c32..5d5e14487 100644--- a/src/modules/session/message-projector.service.spec.ts+++ b/src/modules/session/message-projector.service.spec.ts@@ -3,7 +3,7 @@ import { getRepositoryToken } from '@nestjs/typeorm';import { ConfigService } from '@nestjs/config';import { MessageProjector, PERSIST_RETRY_DELAY_MS } from './message-projector.service';import { EngineRegistry } from '../../engine/engine-registry.service';-import type { Repository } from 'typeorm';+import { Not, type Repository } from 'typeorm';import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';import { Session } from './entities/session.entity';import { EventsGateway } from '../events/events.gateway';@@ -551,6 +551,17 @@ describe('MessageProjector (inbound projection)', () => {expect(projector.inFlightInbound('other-session', 'wamid.1')).toBeUndefined();});+ it('lends no text to a quote once the message is revoked before its row is written', () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ hookManager.execute.mockImplementationOnce(() => new Promise(() => undefined));++ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming());+ projector.handleMessageRevoked(SESSION_ID, engine, { id: 'wamid.1' } as never);++ expect(projector.inFlightInbound(SESSION_ID, 'wamid.1')).toEqual({ chatId: '[email protected]', body: '' });+ });+// The row is inserted only after the message:received chain, so a revoke or edit landing while// it runs updates nothing, and the insert would then write the content the sender took back.describe('a revoke or edit that lands while message:received is still running', () => {@@ -575,6 +586,7 @@ describe('MessageProjector (inbound projection)', () => {);};const where = { sessionId: SESSION_ID, waMessageId: 'wamid.1' };+ const revokedPatch = { body: '', type: 'revoked', metadata: null, mediaPath: null, mediaMimetype: null };beforeEach(() => {Object.assign(eventsGateway, { emitMessageEdited: jest.fn() });@@ -586,13 +598,14 @@ describe('MessageProjector (inbound projection)', () => {await received(engine);projector.handleMessageRevoked(SESSION_ID, engine, { id: 'wamid.1', body: '', type: 'revoked' } as never);- expect(messageRepository.update).toHaveBeenCalledWith(where, { body: '', type: 'revoked' });+ await drain();+ expect(messageRepository.update).toHaveBeenCalledWith(where, revokedPatch);expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.revoked', expect.anything());releaseHook();await drain();expect(messageRepository.insert).toHaveBeenCalledTimes(1);- expect(updatesAfterInsert()).toEqual([[where, { body: '', type: 'revoked' }]]);+ expect(updatesAfterInsert()).toEqual([[where, revokedPatch]]);});it('writes the latest edit onto the row once it is written', async () => {@@ -621,7 +634,7 @@ describe('MessageProjector (inbound projection)', () => {releaseHook();await drain();- expect(updatesAfterInsert()).toEqual([[where, { body: '', type: 'revoked' }]]);+ expect(updatesAfterInsert()).toEqual([[where, revokedPatch]]);});it('changes nothing after the insert when no revoke or edit arrived', async () => {@@ -719,6 +732,82 @@ describe('MessageProjector (inbound projection)', () => {});});+ describe('a revoked message', () => {+ const where = { sessionId: SESSION_ID, waMessageId: 'wamid.1' };+ const revokedPatch = { body: '', type: 'revoked', metadata: null, mediaPath: null, mediaMimetype: null };+ const flush = async (): Promise<void> => {+ for (let i = 0; i < 5; i++) await new Promise(resolve => setImmediate(resolve));+ };++ beforeEach(() => {+ Object.assign(eventsGateway, { emitMessageReaction: jest.fn(), emitMessageEdited: jest.fn() });+ });++ it('keeps nothing of the content and hands the cleared row to message:persisted', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ const cleared = { id: 7, ...where, ...revokedPatch };+ messageRepository.update.mockResolvedValueOnce({ affected: 1 });+ messageRepository.findOne.mockResolvedValueOnce(cleared);++ projector.handleMessageRevoked(SESSION_ID, engine, { id: 'NOTIF', revokedId: 'wamid.1' } as never);+ await flush();++ expect(messageRepository.update).toHaveBeenCalledWith(where, revokedPatch);+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:persisted',+ { sessionId: SESSION_ID, message: cleared },+ expect.anything(),+ );+ expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.revoked', expect.anything());+ });++ it('does not announce a row that was never stored', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ messageRepository.update.mockResolvedValueOnce({ affected: 0 });++ projector.handleMessageRevoked(SESSION_ID, engine, { id: 'wamid.1' } as never);+ await flush();++ expect(hookManager.execute).not.toHaveBeenCalledWith('message:persisted', expect.anything(), expect.anything());+ });++ it('lands after a reaction queued before it, so the reaction cannot write content back', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ messageRepository.findOne.mockResolvedValue({ ...where, metadata: { media: { data: 'AAAA' } } });++ projector.applyReactionQueued(SESSION_ID, { messageId: 'wamid.1', senderId: '[email protected]', reaction: 'ok' } as never);+ projector.handleMessageRevoked(SESSION_ID, engine, { id: 'wamid.1' } as never);+ await flush();++ expect(messageRepository.update.mock.calls.at(-1)).toEqual([where, revokedPatch]);+ });++ it('never takes an edit, inbound or outbound', async () => {+ projector.applyMessageEditQueued(SESSION_ID, { messageId: 'wamid.1', body: 'late' } as never);+ await projector.recordOutboundMessageEdit(SESSION_ID, 'wamid.1', 'later');+ await flush();++ const guarded = { ...where, type: Not('revoked') };+ expect(messageRepository.update).toHaveBeenCalledWith(guarded, { body: 'late' });+ expect(messageRepository.update).toHaveBeenCalledWith(guarded, { body: 'later' });+ });++ it('clears nothing when the engine gives no message id', async () => {+ await projector.recordRevoke(SESSION_ID, '');++ expect(messageRepository.update).not.toHaveBeenCalled();+ });++ it('resolves the REST revoke even when the write fails', async () => {+ messageRepository.update.mockRejectedValueOnce(new Error('db down'));++ await expect(projector.recordRevoke(SESSION_ID, 'wamid.1')).resolves.toBeUndefined();+ });+ });+// Hook chains for different messages finish in any order. A slow chain for one message must not let// a later message of the same chat be stored and announced first.describe('commit order within a chat', () => {@@ -902,6 +991,24 @@ describe('MessageProjector (inbound projection)', () => {expect(updatesAfterS()).toEqual([[expect.objectContaining(whereS), { status: MessageStatus.READ }]]);});+ it('empties the echo row when the REST delete lands before it is written', async () => {+ const { releaseA } = await echoWaitingBehindA();+ void projector.recordRevoke(SESSION_ID, 'S');+ releaseA();+ await flush();++ expect(updatesAfterS()).toEqual([[whereS, expect.objectContaining({ body: '', type: 'revoked' })]]);+ });++ it('writes a REST edit onto the echo row once it is written', async () => {+ const { releaseA } = await echoWaitingBehindA();+ void projector.recordOutboundMessageEdit(SESSION_ID, 'S', 'fixed');+ releaseA();+ await flush();++ expect(updatesAfterS()).toEqual([[whereS, { body: 'fixed' }]]);+ });+it('stores reactions that arrived before the row, without announcing them again', async () => {const emitMessageReaction = jest.fn();Object.assign(eventsGateway, { emitMessageReaction });diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.tsindex 85a9988ee..848582b97 100644--- a/src/modules/session/message-projector.service.ts+++ b/src/modules/session/message-projector.service.ts@@ -58,6 +58,20 @@ import { isMessagePayload } from '../../core/hooks/hook-results';*/export const ACK_RECONCILE_DELAY_MS = 750;+/**+ * What a revoke leaves of a stored message: the placeholder WhatsApp itself shows. Body, archived-media+ * pointers and metadata (inline media, quote, reactions, buttons) are all cleared, so the row carries+ * nothing of what the sender took back. The archived file, now unreferenced, is reaped by the chat-media+ * orphan sweep.+ */+const REVOKED_ROW_PATCH = {+ body: '',+ type: 'revoked',+ metadata: null,+ mediaPath: null,+ mediaMimetype: null,+} as unknown as QueryDeepPartialEntity<Message>;+/*** Delay before the single retry of a message insert that failed transiently (lock contention, a* dropped connection, a pool timeout). The engine delivers each message once, so without the retry@@ -242,7 +256,9 @@ export class MessageProjector {* table.*/inFlightInbound(sessionId: string, waMessageId: string): Pick<IncomingMessage, 'chatId' | 'body'> | undefined {- return waMessageId ? this.inboundInFlight.get(`${sessionId}:${waMessageId}`)?.message : undefined;+ const entry = waMessageId ? this.inboundInFlight.get(`${sessionId}:${waMessageId}`) : undefined;+ // A revoked message lends no text, as its cleared row would not; the chatId still scopes the quote.+ return entry && (entry.revoked ? { chatId: entry.message.chatId, body: '' } : entry.message);}/**@@ -483,11 +499,8 @@ export class MessageProjector {}if (!pending?.revoked && pending?.editedBody === undefined && !pending?.reactions) return;this.enqueueMessageMutation(id, waMessageId, async () => {+ if (pending.revoked) return this.revokeRow(id, waMessageId);try {- if (pending.revoked) {- await this.messageRepository.update({ sessionId: id, waMessageId }, { body: '', type: 'revoked' });- return;- }if (pending.editedBody !== undefined) {await this.messageRepository.update({ sessionId: id, waMessageId }, { body: pending.editedBody });}@@ -512,6 +525,43 @@ export class MessageProjector {await this.messageRepository.update({ sessionId: id, waMessageId }, { metadata: { ...metadata, reactions } });}+ /**+ * Clear a revoked message's stored row, on the message's mutation chain so a reaction or edit queued+ * before it cannot write content back afterwards. Used by the engine's revoke event and by the REST+ * delete. Best-effort like every stored-message mutation: never rejects, and resolves once the write+ * has run.+ */+ 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;+ return new Promise(resolve =>+ this.enqueueMessageMutation(sessionId, waMessageId, () =>+ this.revokeRow(sessionId, waMessageId).finally(resolve),+ ),+ );+ }++ /**+ * 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.+ */+ private async revokeRow(sessionId: string, waMessageId: string): Promise<void> {+ // An undefined condition is DROPPED from the where-clause, which would clear every row of the session.+ if (!waMessageId) return;+ try {+ const result = await this.messageRepository.update({ sessionId, waMessageId }, REVOKED_ROW_PATCH);+ if (!result?.affected) return;+ const row = await this.messageRepository.findOne({ where: { sessionId, waMessageId } });+ if (!row) return;+ void this.hookManager+ .execute('message:persisted', { sessionId, message: row }, { sessionId, source: 'SessionService' })+ .catch(() => undefined);+ } catch (err) {+ this.logger.error(`Failed to clear revoked message ${waMessageId}`, String(err));+ }+ }+/** Fan an accepted inbound message out: `message:persisted` plugin hook, webhook, websocket emit. */private dispatchInboundMessage(id: string, finalMessage: InboundMessageData, outcome: InboundPersistOutcome): void {const { dbMessage, persisted } = outcome;@@ -793,21 +843,15 @@ export class MessageProjector {action: 'message_revoked',});- // Flag the stored message as revoked (best-effort; the message may not be in the- // DB). The dashboard renders the localized "message deleted" text, so no display- // string is persisted here.+ // Clear the stored message (best-effort; the message may not be in the DB). The+ // dashboard renders the localized "message deleted" text, so no display string is+ // persisted here.//// Match on `revokedId` (the ORIGINAL deleted message's id) when present: on wwebjs// `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;- const inFlight = this.inboundInFlight.get(`${id}:${revokedWaMessageId}`);- if (inFlight) inFlight.revoked = true;- void this.messageRepository- .update({ sessionId: id, waMessageId: revokedWaMessageId }, { body: '', type: 'revoked' })- .catch(err => {- this.logger.error(`Failed to update revoked message: ${revokedWaMessageId}`, String(err));- });+ void this.recordRevoke(id, revokedWaMessageId);// Notify consumers regardless of whether the row existed: webhook (message.revoked// is a declared event) + the real-time dashboard stream.@@ -845,6 +889,8 @@ export class MessageProjector {/** Stored-row update for a REST outbound edit, on the same mutation chain — see MessageMutationProjector. */recordOutboundMessageEdit(sessionId: string, messageId: string, body: string): Promise<void> {+ const inFlight = this.inboundInFlight.get(`${sessionId}:${messageId}`);+ if (inFlight) inFlight.editedBody = body;return this.mutationProjector.recordOutboundMessageEdit(sessionId, messageId, body);}diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex b009f17d1..a6a75f133 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -5970,7 +5970,7 @@ describe('SessionService', () => {expect(messageRepository.update as jest.Mock).toHaveBeenCalledWith({ sessionId: 'sess-uuid-1', waMessageId: 'ORIGINAL_MSG' },- { body: '', type: 'revoked' },+ { body: '', type: 'revoked', metadata: null, mediaPath: null, mediaMimetype: null },);// The DB flag is an internal side effect; the delivered payload is the public contract@@ -6001,7 +6001,7 @@ describe('SessionService', () => {expect(messageRepository.update as jest.Mock).toHaveBeenCalledWith({ sessionId: 'sess-uuid-1', waMessageId: 'ORIGINAL_MSG' },- { body: '', type: 'revoked' },+ { body: '', type: 'revoked', metadata: null, mediaPath: null, mediaMimetype: null },);});@@ -7477,14 +7477,13 @@ describe('SessionService', () => {};callbacks.onMessageRevoked(revoked);- // Allow the queued microtask (repository.update().then()) to resolve.- await Promise.resolve();- await Promise.resolve();+ // Allow the queued revoke on the message's mutation chain to run.+ await new Promise(resolve => setImmediate(resolve));// The stored update must carry an EMPTY body and the 'revoked' type — no display string.expect(messageRepository.update).toHaveBeenCalledWith({ sessionId: 'sess-uuid-1', waMessageId: 'WA_MSG_1' },- { body: '', type: 'revoked' },+ { body: '', type: 'revoked', metadata: null, mediaPath: null, mediaMimetype: null },);// The structured payload emitted to clients must not contain any localized text.@@ -7543,7 +7542,7 @@ describe('SessionService', () => {await new Promise(resolve => setImmediate(resolve));expect(messageRepository.update).toHaveBeenCalledWith(- { sessionId: 'sess-uuid-1', waMessageId: 'WA_MSG_EDIT_1' },+ { sessionId: 'sess-uuid-1', waMessageId: 'WA_MSG_EDIT_1', type: Not('revoked') },{ body: 'New edited text' },);expect(eventsGateway.emitMessageEdited).not.toHaveBeenCalled();