Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(message): judge a REST delete and edit by the chat they name
Yudhi Armyndharis17982ddda675
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 839f89c47..f1ceab5a5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -77,6 +77,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Drop the stored copy of a Baileys message that reuses the id of a message the gateway already holds under another chat, sender or direction, and hold an edit, delete or reaction that reads as foreign to that copy until the gateway has settled the message, so the real message's change is no longer ignored as foreign; a reusing message deleted by its sender while it downloads on SQLite, or skipped as ephemeral, is never settled and keeps its copy.- A Baileys revoke from the chat of a delivery that reuses the id of a message stored under another chat, or sent by the account in a one-to-one chat, no longer clears that stored message or announces `message.revoked` for it; a contact who knew the id could erase it, on SQLite and PostgreSQL.- A message whose insert lost to the row of another message under the same id no longer writes its pending revoke, edit, reaction or ack onto that row.+- The REST message delete and edit leave a stored row of another chat that holds the message id alone.- 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/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 02c95a511..1ed632b96 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -798,7 +798,11 @@ describe('MessageService', () => {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');+ // Naming the chat it deleted in, so the row of another chat that holds the id is left alone.+ expect(messageProjector.recordRevoke).toHaveBeenCalledWith('sess-1', 'wa-msg-1', {+ kind: 'revoke',+ chatId: '[email protected]',+ });expect(mockEngine.deleteMessage.mock.invocationCallOrder[0]).toBeLessThan(messageProjector.recordRevoke.mock.invocationCallOrder[0],);@@ -813,7 +817,11 @@ describe('MessageService', () => {expect(mockEngine.editMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', 'edited');// Persistence is delegated to the session's per-message mutation queue (serialized with the// inbound edit path) — the service no longer writes the row directly.- expect(messageProjector.recordOutboundMessageEdit).toHaveBeenCalledWith('sess-1', 'wa-msg-1', 'edited');+ expect(messageProjector.recordOutboundMessageEdit).toHaveBeenCalledWith('sess-1', 'wa-msg-1', 'edited', {+ kind: 'edit',+ chatId: '[email protected]',+ fromMe: true,+ });expect(repository.update).not.toHaveBeenCalled();expect(res).toEqual({ messageId: 'wa-msg-1', timestamp: 1706868000 });});@@ -882,7 +890,12 @@ describe('MessageService', () => {await service.editMessage('sess-1', { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'secret' });expect(mockEngine.editMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', 'redacted');- expect(messageProjector.recordOutboundMessageEdit).toHaveBeenCalledWith('sess-1', 'wa-msg-1', 'redacted');+ expect(messageProjector.recordOutboundMessageEdit).toHaveBeenCalledWith(+ 'sess-1',+ 'wa-msg-1',+ 'redacted',+ expect.objectContaining({ kind: 'edit', chatId: '[email protected]' }),+ );});it('honours a plugin that rewrites the tag list, not the list the caller sent', async () => {diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex d8d717acf..d2bd3c67e 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -693,7 +693,7 @@ export class MessageService implements PluginMessagePort {// 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);+ await this.messageProjector.recordRevoke(sessionId, dto.messageId, { kind: 'revoke', chatId: dto.chatId });}// ========== Edit Message ==========@@ -714,7 +714,11 @@ export class MessageService implements PluginMessagePort {// Best-effort: reflect the new body in the stored copy (mirrors deleteMessage's revoked flag),// serialized with the inbound edit/reaction writers through the session's per-message mutation// queue. A missing row must not fail the request — the engine edit already succeeded.- await this.messageProjector.recordOutboundMessageEdit(sessionId, finalDto.messageId, finalDto.body);+ await this.messageProjector.recordOutboundMessageEdit(sessionId, finalDto.messageId, finalDto.body, {+ kind: 'edit',+ chatId: finalDto.chatId,+ fromMe: true,+ });return { messageId: result.id, timestamp: result.timestamp };}diff --git a/src/modules/session/message-mutation-projector.ts b/src/modules/session/message-mutation-projector.tsindex 064eff43a..fb579e66a 100644--- a/src/modules/session/message-mutation-projector.ts+++ b/src/modules/session/message-mutation-projector.ts@@ -165,12 +165,27 @@ export class MessageMutationProjector {* same per-message mutation queue as the inbound edit/reaction paths so the two writers cannot* interleave (latest-write-wins holds across both directions). Same best-effort semantics as* applyMessageEdit: a missing row or a failed write must not fail the request — the engine edit- * already succeeded. Resolves once the queued write has run.+ * already succeeded. Resolves once the queued write has run. The row is the table's one under the id,+ * which another chat's message may hold: with a `source`, a row it proves foreign is left alone.*/- async recordOutboundMessageEdit(sessionId: string, messageId: string, body: string): Promise<void> {+ async recordOutboundMessageEdit(+ sessionId: string,+ messageId: string,+ body: string,+ source?: MutationSource,+ ): Promise<void> {await new Promise<void>(resolve => {this.enqueueMessageMutation(sessionId, messageId, async () => {try {+ const reason = source && (await this.foreignRowReason(sessionId, messageId, source));+ if (reason) {+ this.logger.warn('Not storing an edit aimed at a message of another chat or sender', {+ sessionId,+ messageId,+ reason,+ });+ return;+ }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) });diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.tsindex 3d492a591..8992df804 100644--- a/src/modules/session/message-projector.service.spec.ts+++ b/src/modules/session/message-projector.service.spec.ts@@ -982,6 +982,50 @@ describe('MessageProjector (inbound projection)', () => {expect(updatesAfterInsert()).toEqual([[where, revokedPatch]]);});+ // The REST delete names the chat its caller addressed: a message still arriving under another chat+ // is not the one deleted, whichever id it carries.+ it('does not take back a message arriving under another chat than the REST delete names', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ await received(engine);++ await projector.recordRevoke(SESSION_ID, 'wamid.1', { kind: 'revoke', chatId: '[email protected]' });+ releaseHook();+ await drain();++ expect(messageRepository.insert).toHaveBeenCalledWith(expect.objectContaining({ body: 'hello', type: 'text' }));+ expect(updatesAfterInsert()).toEqual([]);+ });++ it('takes back a message arriving under the chat the REST delete names', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ await received(engine);++ await projector.recordRevoke(SESSION_ID, 'wamid.1', { kind: 'revoke', chatId: '[email protected]' });+ releaseHook();+ await drain();++ expect(updatesAfterInsert()).toEqual([[where, revokedPatch]]);+ });++ it('does not give a message arriving under another chat the body of a REST edit that names a chat', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ await received(engine);++ await projector.recordOutboundMessageEdit(SESSION_ID, 'wamid.1', 'edited', {+ kind: 'edit',+ chatId: '[email protected]',+ fromMe: true,+ });+ releaseHook();+ await drain();++ expect(messageRepository.insert).toHaveBeenCalledWith(expect.objectContaining({ body: 'hello' }));+ expect(updatesAfterInsert()).toEqual([]);+ });+it('changes nothing after the insert when no revoke or edit arrived', async () => {const engine = makeEngine();engines.set(SESSION_ID, engine);@@ -1153,6 +1197,73 @@ describe('MessageProjector (inbound projection)', () => {expect(messageRepository.update).toHaveBeenCalledWith(guarded, { body: 'later' });});+ // The table holds one row per id, which may be another chat's message. The engines refuse a REST call+ // that names a chat the message is not in, but they judge their own copy, not this row.+ describe('a REST call that names a chat', () => {+ const own = '[email protected]';+ const other = '[email protected]';++ it('leaves a row of another chat alone when it deletes', async () => {+ messageRepository.findOne.mockResolvedValue({ chatId: other, direction: 'incoming' });++ await projector.recordRevoke(SESSION_ID, 'wamid.1', { kind: 'revoke', chatId: own });++ expect(messageRepository.update).not.toHaveBeenCalled();+ });++ it('clears the row of the chat it names when it deletes', async () => {+ messageRepository.findOne.mockResolvedValue({ chatId: own, direction: 'incoming' });++ await projector.recordRevoke(SESSION_ID, 'wamid.1', { kind: 'revoke', chatId: own });++ expect(messageRepository.update).toHaveBeenCalledWith(where, revokedPatch);+ });++ it('clears a row stored under the other dialect of the chat it names', async () => {+ messageRepository.findOne.mockResolvedValue({ chatId: '[email protected]', direction: 'outgoing' });++ await projector.recordRevoke(SESSION_ID, 'wamid.1', { kind: 'revoke', chatId: own });++ expect(messageRepository.update).toHaveBeenCalledWith(where, revokedPatch);+ });++ it('leaves a row of another chat alone when it edits', async () => {+ messageRepository.findOne.mockResolvedValue({ chatId: other, direction: 'outgoing' });++ await projector.recordOutboundMessageEdit(SESSION_ID, 'wamid.1', 'edited', {+ kind: 'edit',+ chatId: own,+ fromMe: true,+ });++ expect(messageRepository.update).not.toHaveBeenCalled();+ });++ it('leaves a received message alone when it edits, as only the own messages can be', async () => {+ messageRepository.findOne.mockResolvedValue({ chatId: own, direction: 'incoming' });++ await projector.recordOutboundMessageEdit(SESSION_ID, 'wamid.1', 'edited', {+ kind: 'edit',+ chatId: own,+ fromMe: true,+ });++ expect(messageRepository.update).not.toHaveBeenCalled();+ });++ it('writes the edit onto the row of the chat it names', async () => {+ messageRepository.findOne.mockResolvedValue({ chatId: own, direction: 'outgoing' });++ await projector.recordOutboundMessageEdit(SESSION_ID, 'wamid.1', 'edited', {+ kind: 'edit',+ chatId: own,+ fromMe: true,+ });++ expect(messageRepository.update).toHaveBeenCalledWith({ ...where, type: Not('revoked') }, { body: 'edited' });+ });+ });+it('clears nothing when the engine gives no message id', async () => {await projector.recordRevoke(SESSION_ID, '');diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.tsindex fff97e0be..f3cfed2b8 100644--- a/src/modules/session/message-projector.service.ts+++ b/src/modules/session/message-projector.service.ts@@ -873,14 +873,18 @@ export class MessageProjector {* 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.+ *+ * With `source`, the caller has not had the stored row judge the revoke yet: the message still arriving+ * is taken back only if the revoke agrees with it, and the row is cleared only if the revoke is not+ * foreign to it. Without one, the revoke was judged by the caller (the engine's revoke event is).*/- recordRevoke(sessionId: string, waMessageId: string): Promise<void> {+ recordRevoke(sessionId: string, waMessageId: string, source?: MutationSource): 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) this.holdRevoked(sessionId, inFlight);+ if (inFlight && !(source && this.foreignToInFlight(inFlight, source))) this.holdRevoked(sessionId, inFlight);return new Promise(resolve =>this.enqueueMessageMutation(sessionId, waMessageId, () =>- this.revokeRow(sessionId, waMessageId).finally(resolve),+ this.revokeRow(sessionId, waMessageId, true, source).finally(resolve),),);}@@ -893,12 +897,28 @@ export class MessageProjector {/*** 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.+ * keyed by row id drops the content too. Must run on the message's mutation chain. The row is the+ * table's one under the id, which another chat's message may hold: a `source` that the row proves+ * foreign leaves it alone.*/- private async revokeRow(sessionId: string, waMessageId: string, notify = true): Promise<void> {+ private async revokeRow(+ sessionId: string,+ waMessageId: string,+ notify = true,+ source?: MutationSource,+ ): Promise<void> {// An undefined condition is DROPPED from the where-clause, which would clear every row of the session.if (!waMessageId) return;try {+ const reason = source && (await this.mutationProjector.foreignRowReason(sessionId, waMessageId, source));+ if (reason) {+ this.logger.warn('Dropping a revoke aimed at a message of another chat or sender', {+ sessionId,+ messageId: waMessageId,+ reason,+ });+ return;+ }const result = await this.messageRepository.update({ sessionId, waMessageId }, REVOKED_ROW_PATCH);if (!result?.affected || !notify) return;const row = await this.messageRepository.findOne({ where: { sessionId, waMessageId } });@@ -1382,10 +1402,17 @@ 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> {+ recordOutboundMessageEdit(+ sessionId: string,+ messageId: string,+ body: string,+ source?: MutationSource,+ ): Promise<void> {+ // With a `source`, the message still arriving takes the edit only if it agrees with it, and the row+ // only if it is not foreign to it, as for recordRevoke.const inFlight = this.inboundInFlight.get(`${sessionId}:${messageId}`);- if (inFlight) inFlight.editedBody = body;- return this.mutationProjector.recordOutboundMessageEdit(sessionId, messageId, body);+ if (inFlight && !(source && this.foreignToInFlight(inFlight, source))) inFlight.editedBody = body;+ return this.mutationProjector.recordOutboundMessageEdit(sessionId, messageId, body, source);}/**