Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): compare an edit with the stored text in the write
Yudhi Armyndharis988040fa27a8
diff --git a/src/engine/adapters/wwebjs-message-changes.spec.ts b/src/engine/adapters/wwebjs-message-changes.spec.tsindex 0fe7be82c..198955847 100644--- a/src/engine/adapters/wwebjs-message-changes.spec.ts+++ b/src/engine/adapters/wwebjs-message-changes.spec.ts@@ -48,6 +48,10 @@ const matches = (row: Row, where: Record<string, unknown>): boolean =>if (key === 'metadata') return true;const op = want as { _type?: string; _value?: unknown } | null;if (op && typeof op === 'object' && op._type === 'not') return row[key] !== op._value;+ if (op && typeof op === 'object' && op._type === 'or') {+ return (op._value as unknown[]).some(alternative => matches(row, { [key]: alternative }));+ }+ if (op && typeof op === 'object' && op._type === 'isNull') return row[key] == null;return row[key] === want;});diff --git a/src/modules/session/message-edited-marker.spec.ts b/src/modules/session/message-edited-marker.spec.tsindex 1796da902..efd2f1b8e 100644--- a/src/modules/session/message-edited-marker.spec.ts+++ b/src/modules/session/message-edited-marker.spec.ts@@ -105,6 +105,31 @@ describe('persisted edited message marker', () => {expect(emit).toHaveBeenCalledTimes(1);});+ // The row can be inserted after the read that found none, so the write compares the text, not the read.+ it.each([+ ['before the write of a new text', 'findOne', 'new', 'new', { ...metadata, edited: true }],+ ['before the write of the same text', 'findOne', 'old', 'old', metadata],+ ['after the write of a new text', 'update', 'new', 'old', metadata],+ ['after the write of the same text', 'update', 'old', 'old', metadata],+ ] as const)(+ 'marks a row the insert lands on %s only where the write changed its text',+ async (_, after, body, stored, marked) => {+ const real = repository[after].bind(repository) as (...args: unknown[]) => Promise<unknown>;+ jest.spyOn(repository, after).mockImplementationOnce((async (...args: unknown[]) => {+ const result = await real(...args);+ await seed();+ return result;+ }) as never);+ projector.applyMessageEditQueued('s1', { ...edit, body });+ await drain();++ const row = await repository.findOneByOrFail({ waMessageId: edit.messageId });+ expect(row.body).toBe(stored);+ expect(row.metadata).toEqual(marked);+ expect(emit).toHaveBeenCalledTimes(1);+ },+ );+it('marks an edit of a row stored without a text', async () => {await seed();await repository.update({ waMessageId: edit.messageId }, { body: () => 'NULL' });diff --git a/src/modules/session/message-mutation-projector.ts b/src/modules/session/message-mutation-projector.tsindex 9da708a6a..5fba72ad9 100644--- a/src/modules/session/message-mutation-projector.ts+++ b/src/modules/session/message-mutation-projector.ts@@ -1,4 +1,4 @@-import { Not, Repository } from 'typeorm';+import { IsNull, Not, Or, Repository } from 'typeorm';import { Message } from '../message/entities/message.entity';import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';import { LoggerService } from '../../common/services/logger.service';@@ -59,23 +59,20 @@ export class MessageMutationProjector {/*** 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), with the text it holds. A row that cannot be read is reported absent with no- * reason, as before.+ * 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; body?: string }> {+ ): 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, body: true },+ select: { chatId: true, direction: true, author: true },});- return row- ? { exists: true, reason: mutationTargetsForeignRow(row, source), body: row.body }- : { exists: false, reason: null };+ return row ? { exists: true, reason: mutationTargetsForeignRow(row, source) } : { exists: false, reason: null };} catch {return { exists: false, reason: null };}@@ -149,13 +146,14 @@ export class MessageMutationProjector {return;}try {- // 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') },+ // Never onto a revoked row: a late edit must not bring back text the sender deleted. An event that repeats the+ // stored text is no edit, and the marker would label an unedited message. The write compares, not the read+ // above, as the row may be inserted between the two.+ const result = await this.messageRepository.update(+ { sessionId: id, waMessageId: message.messageId, type: Not('revoked'), body: Or(Not(message.body), IsNull()) },{ body: message.body },);- // An event that repeats the stored text is no edit, and the marker would label an unedited message.- if (verdict.body !== message.body) await this.markMessageEdited(id, message.messageId);+ if (result.affected) await this.markMessageEdited(id, message.messageId);} catch (err) {this.logger.error(`Failed to update edited message: ${message.messageId}`, String(err));}diff --git a/src/modules/session/message-projector.inbound-hold.spec.ts b/src/modules/session/message-projector.inbound-hold.spec.tsindex d90f51d56..4e4f1824e 100644--- a/src/modules/session/message-projector.inbound-hold.spec.ts+++ b/src/modules/session/message-projector.inbound-hold.spec.ts@@ -36,6 +36,10 @@ const matches = (row: Row, where: Record<string, unknown>): boolean =>const op = want as { _type?: string; _value?: unknown } | null;if (op && typeof op === 'object' && op._type === 'not') return row[key] !== op._value;if (op && typeof op === 'object' && op._type === 'in') return (op._value as unknown[]).includes(row[key]);+ if (op && typeof op === 'object' && op._type === 'or') {+ return (op._value as unknown[]).some(alternative => matches(row, { [key]: alternative }));+ }+ if (op && typeof op === 'object' && op._type === 'isNull') return row[key] == null;return row[key] === want;});diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.tsindex 38339f00f..2e55b0998 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 { Not, type Repository } from 'typeorm';+import { IsNull, Not, Or, 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';@@ -1210,7 +1210,10 @@ describe('MessageProjector (inbound projection)', () => {await flush();const guarded = { ...where, type: Not('revoked') };- expect(messageRepository.update).toHaveBeenCalledWith(guarded, { body: 'late' });+ expect(messageRepository.update).toHaveBeenCalledWith(+ { ...guarded, body: Or(Not('late'), IsNull()) },+ { body: 'late' },+ );expect(messageRepository.update).toHaveBeenCalledWith(guarded, { body: 'later' });});diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 6b44c8c5d..bb6ef533c 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -3,7 +3,7 @@ import { SessionRestrictionStore } from './session-restriction-store.service';import { PresenceStore } from './presence-store.service';import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';-import { Repository, DataSource, In, IsNull, LessThanOrEqual, Not, QueryFailedError } from 'typeorm';+import { Repository, DataSource, In, IsNull, LessThanOrEqual, Not, Or, QueryFailedError } from 'typeorm';import {NotFoundException,ConflictException,@@ -8740,7 +8740,12 @@ describe('SessionService', () => {await new Promise(resolve => setImmediate(resolve));expect(messageRepository.update).toHaveBeenCalledWith(- { sessionId: 'sess-uuid-1', waMessageId: 'WA_MSG_EDIT_1', type: Not('revoked') },+ {+ sessionId: 'sess-uuid-1',+ waMessageId: 'WA_MSG_EDIT_1',+ type: Not('revoked'),+ body: Or(Not('New edited text'), IsNull()),+ },{ body: 'New edited text' },);expect(eventsGateway.emitMessageEdited).not.toHaveBeenCalled();