Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): match a history revoke to the chat it names
Yudhi Armyndharisbe4854a15251
diff --git a/src/modules/session/message-history-projector.spec.ts b/src/modules/session/message-history-projector.spec.tsnew file mode 100644index 000000000..3cd444c28--- /dev/null+++ b/src/modules/session/message-history-projector.spec.ts@@ -0,0 +1,76 @@+import 'reflect-metadata';+import { DataSource, Repository } from 'typeorm';+import { Message, MessageDirection } from '../message/entities/message.entity';+import { Session } from './entities/session.entity';+import type { LoggerService } from '../../common/services/logger.service';+import type { IncomingMessage } from '../../engine/interfaces/whatsapp-engine.interface';+import { persistHistoryMessages } from './message-history-projector';++// A revoke tombstone from a history sync names the chat in the neutral dialect, while a row a REST send+// wrote keeps the chat id as the caller wrote it.+describe('persistHistoryMessages revokes', () => {+ let ds: DataSource;+ let repo: Repository<Message>;+ const logger = { log: jest.fn(), warn: jest.fn(), debug: jest.fn(), error: jest.fn() } as unknown as LoggerService;++ const stored = (chatId: string, waMessageId = 'W1') =>+ repo.insert({+ sessionId: 's1',+ waMessageId,+ chatId,+ from: '[email protected]',+ to: chatId,+ body: 'secret text',+ type: 'text',+ direction: MessageDirection.OUTGOING,+ timestamp: 10,+ });++ const tombstone = (chatId: string): IncomingMessage => ({+ id: 'W1',+ chatId,+ from: '[email protected]',+ to: chatId,+ body: '',+ type: 'revoked',+ timestamp: 5,+ fromMe: true,+ isGroup: false,+ kind: 'individual',+ });++ const run = (messages: IncomingMessage[]) =>+ persistHistoryMessages(repo, undefined, 's1', messages, logger, () => true);++ beforeEach(async () => {+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [Session, Message],+ synchronize: true,+ });+ await ds.initialize();+ repo = ds.getRepository(Message);+ });+ afterEach(() => ds.destroy());++ it('clears a row stored under the other dialect of the same chat', async () => {+ await stored('[email protected]');++ const cleared = await run([tombstone('[email protected]')]);++ const row = await repo.findOneByOrFail({ sessionId: 's1', waMessageId: 'W1' });+ expect(row).toMatchObject({ type: 'revoked', body: '', chatId: '[email protected]' });+ expect(cleared.map(m => m.id)).toEqual(['W1']);+ });++ it('leaves a row of another chat alone', async () => {+ await stored('[email protected]');++ const cleared = await run([tombstone('[email protected]')]);++ const row = await repo.findOneByOrFail({ sessionId: 's1', waMessageId: 'W1' });+ expect(row).toMatchObject({ type: 'text', body: 'secret text' });+ expect(cleared).toEqual([]);+ });+});diff --git a/src/modules/session/message-history-projector.ts b/src/modules/session/message-history-projector.tsindex 3b0a4742c..3d9e62feb 100644--- a/src/modules/session/message-history-projector.ts+++ b/src/modules/session/message-history-projector.ts@@ -3,6 +3,7 @@ import { Repository, In, Raw } from 'typeorm';import { QueryDeepPartialEntity } from 'typeorm';import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';import { buildMessageMetadata, REVOKED_ROW_PATCH } from './message-row.mapper';+import { provablyDifferent } from './message-mutation-guard';import { resolveFeatureFlags } from '../../config/feature-flags';import { IncomingMessage } from '../../engine/interfaces/whatsapp-engine.interface';import { LoggerService } from '../../common/services/logger.service';@@ -51,7 +52,7 @@ export async function persistHistoryMessages(const chunkIds = ids.slice(i, i + CHUNK);const existing = await messageRepository.find({where: { sessionId: id, waMessageId: In(chunkIds) },- select: { waMessageId: true, type: true },+ select: { waMessageId: true, type: true, chatId: true },});// A delete() can retire the engine while a large batch works through its chunks; its transaction// has then already cleared this session's messages, and a row inserted after it (no FK) would@@ -111,15 +112,20 @@ export async function persistHistoryMessages(}// Insert the tombstone before clearing an existing row: concurrent content inserts then either// lose the unique-key race or are cleared here, and a later chunk cannot resurrect the payload.+ // The row keeps the chat id as its writer gave it (a REST send stores the caller's own dialect), so+ // the tombstone is matched on the chat it names, not on the string.+ const storedChats = new Map(existing.map(r => [r.waMessageId, r.chatId]));for (const messageId of chunkIds) {const m = byId.get(messageId)!;if (m.type !== 'revoked') continue;+ const storedChat = storedChats.get(messageId) ?? m.chatId;+ if (provablyDifferent(storedChat, m.chatId)) continue;if (!isLive()) break;await messageRepository.update({sessionId: id,waMessageId: messageId,- chatId: m.chatId,+ chatId: storedChat,direction: m.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING,},REVOKED_ROW_PATCH,@@ -135,13 +141,15 @@ export async function persistHistoryMessages(const m = byId.get(row.waMessageId)!;if (!isLive()) break;const direction = m.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING;- if (row.chatId !== m.chatId || row.direction !== direction || !Number.isFinite(m.timestamp)) continue;+ if (provablyDifferent(row.chatId, m.chatId) || row.direction !== direction || !Number.isFinite(m.timestamp)) {+ continue;+ }if (row.timestamp == null || row.timestamp > m.timestamp) {const result = await messageRepository.update({sessionId: id,waMessageId: m.id,- chatId: m.chatId,+ chatId: row.chatId,direction,type: 'revoked',timestamp: Raw(alias => `(${alias} IS NULL OR ${alias} > :historyTimestamp)`, {