Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): keep stored messages in step with edits and deletes
Yudhi Armyndharisf771692edaa8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5a1c30426..37d9d28ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- A reply, button click or quoting send made from a `message:received` plugin hook stores the text of the message it quotes, so the dashboard shows that quote instead of an empty box.+- Baileys: replies to and forwards of an edited message carry the edited text instead of the original.+- Baileys: a message deleted for everyone answers `404` on reply, quoted send, forward, react, edit, star, pin, unpin and click-button; a reply or forward of it sent the deleted content back to the chat.- The dashboard dev server proxies only `/api/` paths, so a full reload of the API Keys page (`/api-keys`) loads the dashboard instead of being forwarded to the backend.- The dashboard Chats thread renders an `@<digits>` mention as `@FirstName` when that participant has posted in the loaded thread and their id matches the digits in the body. This covers whatsapp-web.js, where the author id and the mention carry the same digits. On Baileys the author is normalized to the phone number when the lid mapping is known while the body keeps the lid digits, so those mentions stay as WhatsApp sent them, as does any mention of someone who has not posted. The resolved name renders inside its own `<bdi>` element, outside Linkify's `ignoreTags`-respected walk, so a push name can never become a clickable link, however it's spelled. Thanks @TanmayChachra.- The dashboard Plugins page shows a plugin's status and type in the selected language; they rendered as raw English values (`installed`, `extension`) in every locale.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 5311f789f..ef3e322c1 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1699,6 +1699,10 @@ One upstream gap remains on whatsapp-web.js and cannot be switched off from heremessage resolves but the page decides it is not replyable, the message is sent without the quote andthe call still succeeds.+On Baileys a message deleted for everyone is not found (`404`): the store drops its content, so the+deleted text or media is never quoted back into the chat. An edited message is quoted with its edited+text.+Quoting a message from a **different chat** is not validated on these `send-*` routes on eitherengine; the id is passed through as given. `POST /messages/reply` is stricter: both engines refuse aquoted id that does not belong to the target chat, with `404`.diff --git a/src/engine/adapters/baileys-click-button.spec.ts b/src/engine/adapters/baileys-click-button.spec.tsindex d422ca45c..8b11ec969 100644--- a/src/engine/adapters/baileys-click-button.spec.ts+++ b/src/engine/adapters/baileys-click-button.spec.ts@@ -84,6 +84,8 @@ function makeMessaging(stored: unknown = PROMPT, opts: { ephemeralExpiration?: ngetContentType: (c: unknown) => contentTypeOf(c),} as never),getStoredMessage,+ wasDeletedForEveryone: () => false,+ markDeletedForEveryone: () => undefined,putStoredMessage,rememberOwnSend: () => undefined,recordLidMapping: () => undefined,diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.tsindex b83b21701..9fca72e56 100644--- a/src/engine/adapters/baileys-events.spec.ts+++ b/src/engine/adapters/baileys-events.spec.ts@@ -102,6 +102,7 @@ function makeHost(overrides: Partial<BaileysEventsHost> = {}): BaileysEventsHostconsumeOwnSend: () => false,getStoredMessage: () => undefined,putStoredMessage: () => undefined,+ updateStoredMessage: () => undefined,getOnMessage: () => undefined,getOnMessageCreate: () => undefined,getOnMessageRevoked: () => undefined,@@ -487,3 +488,15 @@ describe('BaileysEvents.mapMessage', () => {expect(downloadMediaMessage).toHaveBeenCalledTimes(1);});});++describe('BaileysEvents record of messages deleted for everyone', () => {+ it('forgets the oldest id once it holds its limit', () => {+ const events = new BaileysEvents(makeHost());+ const limit = BaileysEvents.DELETED_FOR_EVERYONE_LIMIT;+ for (let i = 0; i <= limit; i++) events.markDeletedForEveryone(`M${i}`);++ expect(events.wasDeletedForEveryone('M0')).toBe(false);+ expect(events.wasDeletedForEveryone('M1')).toBe(true);+ expect(events.wasDeletedForEveryone(`M${limit}`)).toBe(true);+ });+});diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex ae38b0e02..5c1af6be5 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -22,6 +22,7 @@ import {extractBaileysLocation,isBaileysCatalogShare,mapBaileysStatus,+ setBaileysText,} from './baileys-message-mapper';import { buildEditedMessage } from './message-mapper';import { toUnixSeconds } from './baileys-history';@@ -114,6 +115,8 @@ export interface BaileysEventsHost {recordMessageEdit(chatId: string, messageId: string, text: string): void;/** Persist an inbound message to the store; undefined when no store is configured. */putStoredMessage(msg: WAMessage): Promise<void> | undefined;+ /** Rewrite a stored message in place (see BaileysMessageStore.update); undefined without a store. */+ updateStoredMessage(messageId: string, change: (stored: WAMessage) => WAMessage | null): Promise<void> | undefined;/*** True exactly once for the id of a message this session sent through the API, whose library echo* is arriving; false for anything the session did not send (see OwnSendRegistry).@@ -156,8 +159,40 @@ export class BaileysEvents {{ callFrom: string; expiresAt: number; from: string; isVideo: boolean; isGroup: boolean }>();+ /** How many ids the record of deletes for everyone keeps before it forgets the oldest. */+ static readonly DELETED_FOR_EVERYONE_LIMIT = 5_000;++ /**+ * Inbound messages still being processed, by id, with the key of the latest delivery, so an edit or+ * delete of one waits for its store write and a delete can be checked against its target meanwhile.+ */+ private readonly inboundInFlight = new Map<string, { key: WAMessageKey; done: Promise<void> }>();++ /**+ * Ids of messages deleted for everyone, oldest first. The stored copy is emptied too, but that can+ * land late: a delete can overtake the original while it downloads its media, and a repeat delivery+ * can be stored after the delete was applied. Whatever the store holds meanwhile, a message named+ * here is never quoted, forwarded or reacted to, nor stored with its content. Bounded, because the+ * windows it covers close once the original's processing settles, and the store has caught up then.+ */+ private readonly deletedForEveryone = new Set<string>();+constructor(private readonly host: BaileysEventsHost) {}+ /** Whether a delete for everyone of this message was accepted (see deletedForEveryone). */+ wasDeletedForEveryone(messageId: string): boolean {+ return this.deletedForEveryone.has(messageId);+ }++ /** Record an accepted delete for everyone of this message (see deletedForEveryone). */+ markDeletedForEveryone(messageId: string): void {+ this.deletedForEveryone.add(messageId);+ if (this.deletedForEveryone.size > BaileysEvents.DELETED_FOR_EVERYONE_LIMIT) {+ const [oldest] = this.deletedForEveryone;+ this.deletedForEveryone.delete(oldest);+ }+ }+handleMessagesUpsert(event: { messages: WAMessage[]; type: string }): void {for (const msg of event.messages) {if (!msg.message || !msg.key?.remoteJid) {@@ -197,7 +232,7 @@ export class BaileysEvents {// and the message keeps its media either way. The catch below is the teardown path: the// limiter rejects only when it has been closed, since processInboundMessage handles its own// failures (a media download that fails emits the omitted marker rather than throwing).- void this.host.inboundLimiter+ const processed = this.host.inboundLimiter.run(() => this.processInboundMessage(msg)).catch((error: unknown) => {// Only one failure can actually land here today: the limiter closing, an orderly teardown.@@ -215,6 +250,19 @@ export class BaileysEvents {);return this.processInboundMessage(msg, { skipMedia: true });});+ const id = msg.key.id;+ if (id) {+ // A repeat delivery can arrive while the first is still downloading and finish before it, so+ // a change waits for every delivery in flight, not only the latest.+ const tracked = {+ key: msg.key,+ done: Promise.all([this.inboundInFlight.get(id)?.done, processed]).then(() => undefined),+ };+ this.inboundInFlight.set(id, tracked);+ void tracked.done.finally(() => {+ if (this.inboundInFlight.get(id) === tracked) this.inboundInFlight.delete(id);+ });+ }}}@@ -276,6 +324,18 @@ export class BaileysEvents {body: '',timestamp: toUnixSeconds(msg.messageTimestamp),};+ // While the target is still being processed, the store change waits for it and lands after+ // this delete is announced, and a repeat delivery may already hold the content in the store:+ // record the delete now, checked against the target's own key.+ const target = this.inboundInFlight.get(revoked.id);+ if (target && this.mayChange(target.key, msg.key, true)) {+ this.markDeletedForEveryone(revoked.id);+ }+ // The stored copy keeps its key, so a late re-delivery is still recognised and a delete+ // for me can still address it, but loses its content, so nothing can quote or resend it.+ this.changeStoredMessage(pm.key?.id, stored =>+ this.mayChange(stored.key, msg.key, true) ? { ...stored, message: null } : null,+ );this.host.getOnMessageRevoked()?.(revoked);return;}@@ -318,6 +378,12 @@ export class BaileysEvents {editedContentType === 'stickerMessage';const edited: EditedMessage = buildEditedMessage(base, hasMedia);this.host.recordMessageEdit(remoteJid, edited.messageId, edited.body);+ this.changeStoredMessage(edited.messageId, stored => {+ const content = this.mayChange(stored.key, msg.key, false)+ ? b.normalizeMessageContent(stored.message ?? undefined)+ : undefined;+ return content && setBaileysText(content, edited.body) ? stored : null;+ });this.host.getOnMessageEdited()?.(edited);return;}@@ -392,7 +458,9 @@ export class BaileysEvents {});// Stored before it is announced: whoever hears about this message may act on it at once (a quoted// reply, a reaction, a read receipt), and the store holds a read of an id until its write lands.- void this.host.putStoredMessage(msg)?.catch(err =>+ // A message deleted for everyone while it was being processed is stored as the delete leaves it.+ const deleted = storedId !== null && this.deletedForEveryone.has(storedId);+ void this.host.putStoredMessage(deleted ? { ...msg, message: null } : msg)?.catch(err =>this.host.logger.warn('Failed to persist message to store', {error: err instanceof Error ? err.message : String(err),}),@@ -434,6 +502,47 @@ export class BaileysEvents {}}+ /**+ * Apply an edit or a delete for everyone to the stored copy of the message it targets, which is+ * what a later quote or forward reads and what a retry resend falls back to. WhatsApp delivers the+ * change after the message, but the message can still be downloading its media, or waiting for a+ * limiter slot, when the change is processed, and a change written first would be overwritten by+ * the original. So the write waits for the original's own processing, which has called put() by+ * the time it settles, and the store queues the change behind that put. With nothing in flight the+ * change reaches the store at once: this is called before the change is announced, so a read by+ * whoever hears of it waits for the write, as a read of a just-announced message waits for its put.+ * Detached and best-effort, like the put.+ */+ private changeStoredMessage(+ messageId: string | null | undefined,+ change: (stored: WAMessage) => WAMessage | null,+ ): void {+ if (!messageId) return;+ const apply = async (): Promise<void> => this.host.updateStoredMessage(messageId, change);+ const inFlight = this.inboundInFlight.get(messageId)?.done;+ void (inFlight ? inFlight.then(apply) : apply()).catch(err =>+ this.host.logger.warn('Failed to apply an edit or delete to the message store', {+ msgId: messageId,+ error: err instanceof Error ? err.message : String(err),+ }),+ );+ }++ /**+ * Whether an edit or delete sent under `envelope` may change the stored message `target`. Baileys+ * checks neither the chat nor the sender of either (Utils/process-message.js), so the stored copy+ * changes only for one from the same chat and from the message's author. A group admin may delete+ * anyone's message, which nothing here can verify, so a group delete skips the author check.+ * Compared in the neutral dialect, so a chat or sender seen by lid once and by phone once matches.+ */+ private mayChange(target: WAMessageKey, envelope: WAMessageKey, isDelete: boolean): boolean {+ const chat = (key: WAMessageKey): string => this.host.toNeutralJid(key.remoteJid ?? '');+ const author = (key: WAMessageKey): string =>+ key.fromMe === true ? 'fromMe' : this.host.toNeutralJid(key.participant || key.remoteJid || '');+ if (chat(target) !== chat(envelope)) return false;+ return (isDelete && parseWaId(chat(target)).kind === 'group') || author(target) === author(envelope);+ }+handleMessagesUpdate(updates: Array<{ key?: { id?: string | null }; update?: { status?: number | null } }>): void {for (const u of updates) {const status = mapBaileysStatus(u.update?.status);diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.tsindex e197d574f..90f08609d 100644--- a/src/engine/adapters/baileys-message-mapper.spec.ts+++ b/src/engine/adapters/baileys-message-mapper.spec.ts@@ -14,6 +14,7 @@ import {isBaileysCatalogShare,mapBaileysMessageType,mapBaileysStatus,+ setBaileysText,} from './baileys-message-mapper';describe('mapBaileysMessageType (baileys content-type -> neutral MessageType)', () => {@@ -188,6 +189,29 @@ describe('extractBaileysBody (inbound text/caption + interactive shapes)', () =>});});+describe('setBaileysText (an edit written back where extractBaileysBody reads it)', () => {+ it.each([+ ['a plain text', { conversation: 'before' }],+ ['an extended text', { extendedTextMessage: { text: 'before', matchedText: 'https://example.com' } }],+ ['a photo caption', { imageMessage: { caption: 'before', url: 'https://mmg.example/x' } }],+ ['a video caption', { videoMessage: { caption: 'before' } }],+ ['a document caption', { documentMessage: { caption: 'before', fileName: 'a.pdf' } }],+ ])('rewrites %s and keeps the rest of the content', (_kind, content) => {+ const copy = structuredClone(content);+ expect(setBaileysText(copy, 'after')).toBe(true);+ expect(extractBaileysBody(copy)).toBe('after');+ // Only the text slot moved: the same object with the new text is what remains.+ expect(setBaileysText(copy, 'before')).toBe(true);+ expect(copy).toEqual(content);+ });++ it('changes nothing on content with no text slot', () => {+ const content = { locationMessage: { degreesLatitude: 1 } } as Record<string, unknown>;+ expect(setBaileysText(content, 'after')).toBe(false);+ expect(content).toEqual({ locationMessage: { degreesLatitude: 1 } });+ });+});+describe('extractBaileysContext (quoted body shares the live body extractor)', () => {const quoted = (quotedMessage: object) =>extractBaileysContext({diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.tsindex e4047caa6..2dfb35047 100644--- a/src/engine/adapters/baileys-message-mapper.ts+++ b/src/engine/adapters/baileys-message-mapper.ts@@ -165,6 +165,38 @@ export function extractBaileysBody(content: BaileysBodyContent): string {);}+/**+ * Write edited text into the slot a message carries its text in, which is where+ * {@link extractBaileysBody} reads it back: the text itself, or the caption of a photo, video or+ * document. Everything else the content holds (media keys, thumbnail, link preview) is kept, as+ * WhatsApp Web keeps it (an edit changes the message's body or caption in place), so the edited+ * message is still a valid message of its original type when it is quoted or forwarded. Returns+ * false, changing nothing, when the content has no such slot.+ * Pass the NORMALIZED content: it is a reference into the message, so the write lands there.+ */+export function setBaileysText(+ content: Pick<+ BaileysBodyContent,+ 'conversation' | 'extendedTextMessage' | 'imageMessage' | 'videoMessage' | 'documentMessage'+ >,+ text: string,+): boolean {+ if (typeof content.conversation === 'string') {+ content.conversation = text;+ return true;+ }+ if (content.extendedTextMessage) {+ content.extendedTextMessage.text = text;+ return true;+ }+ const media = content.imageMessage ?? content.videoMessage ?? content.documentMessage;+ if (media) {+ media.caption = text;+ return true;+ }+ return false;+}+/*** Joins the vCards of a `contactsArrayMessage` into one string, in the order they were shared.* Returns `undefined` (not `''`) when there are no vCards to join, so it composes with `??` indiff --git a/src/engine/adapters/baileys-message-store.service.spec.ts b/src/engine/adapters/baileys-message-store.service.spec.tsindex 81e62833f..3bb1df340 100644--- a/src/engine/adapters/baileys-message-store.service.spec.ts+++ b/src/engine/adapters/baileys-message-store.service.spec.ts@@ -1,3 +1,4 @@+import type { WAMessage } from '@whiskeysockets/baileys';import { DataSource, Repository } from 'typeorm';import { BaileysStoredMessage } from './baileys-stored-message.entity';import { BaileysMessageStoreService } from './baileys-message-store.service';@@ -56,6 +57,25 @@ describe('BaileysMessageStoreService', () => {mediaKey: Buffer.from([0x01, 0x02, 0x03, 0xff]),}) as unknown as Parameters<BaileysMessageStoreService['put']>[1];+ /** Hold the next upsert until released: the database round trip a reader can land inside. */+ const holdNextUpsert = (): { release: () => void; fail: (err: Error) => void } => {+ let release!: () => void;+ let fail!: (err: Error) => void;+ const gate = new Promise<void>((resolve, reject) => {+ release = resolve;+ fail = reject;+ });+ const real = repo.upsert.bind(repo);+ jest.spyOn(repo, 'upsert').mockImplementationOnce(async (...args: Parameters<typeof real>) => {+ await gate;+ return real(...args);+ });+ return { release, fail };+ };+ const ticks = async (): Promise<void> => {+ for (let i = 0; i < 20; i++) await new Promise<void>(resolve => setImmediate(resolve));+ };+it('round-trips a WAMessage through BufferJSON', async () => {await seedSession('s1');await service.put('s1', msg('M1'));@@ -215,25 +235,6 @@ describe('BaileysMessageStoreService', () => {});describe('a read issued while the write is in flight', () => {- /** Hold the next upsert until released: the database round trip a reader can land inside. */- const holdNextUpsert = (): { release: () => void; fail: (err: Error) => void } => {- let release!: () => void;- let fail!: (err: Error) => void;- const gate = new Promise<void>((resolve, reject) => {- release = resolve;- fail = reject;- });- const real = repo.upsert.bind(repo);- jest.spyOn(repo, 'upsert').mockImplementationOnce(async (...args: Parameters<typeof real>) => {- await gate;- return real(...args);- });- return { release, fail };- };- const ticks = async (): Promise<void> => {- for (let i = 0; i < 20; i++) await new Promise<void>(resolve => setImmediate(resolve));- };-beforeEach(() => seedSession('s1'));it('getMessage waits for the write', async () => {@@ -266,6 +267,16 @@ describe('BaileysMessageStoreService', () => {expect(await read).toBeNull();});+ it('a write that throws before it starts rejects put and releases the read', async () => {+ jest.spyOn(service as unknown as { write: () => Promise<void> }, 'write').mockImplementationOnce(() => {+ throw new Error('no library');+ });+ const write = service.put('s1', msg('M1'));+ const read = service.getMessage('s1', 'M1');+ await expect(write).rejects.toThrow('no library');+ expect(await read).toBeNull();+ }, 1_000);+it('a read waits for the latest write of an id, not an earlier failed one', async () => {const first = holdNextUpsert();const firstWrite = service.put('s1', msg('M1'));@@ -282,6 +293,86 @@ describe('BaileysMessageStoreService', () => {});});+ describe('update', () => {+ it('rewrites the stored message in place and keeps its eviction age', async () => {+ await seedSession('s1');+ await service.put('s1', msg('M1'));+ const before = await repo.findOneByOrFail({ sessionId: 's1', waMessageId: 'M1' });++ await service.update('s1', 'M1', stored => ({ ...stored, message: { conversation: 'edited' } }));++ expect((await service.getMessage('s1', 'M1'))?.message?.conversation).toBe('edited');+ const after = await repo.findOneByOrFail({ sessionId: 's1', waMessageId: 'M1' });+ // An edit is not a new message: refreshing createdAt would push it to the back of the eviction queue.+ expect(after.createdAt).toEqual(before.createdAt);+ expect(await repo.count({ where: { sessionId: 's1' } })).toBe(1);+ });++ it('keeps the binary fields through the rewrite', async () => {+ await seedSession('s1');+ await service.put('s1', msg('M1'));+ await service.update('s1', 'M1', stored => ({ ...stored, message: null }));+ const got = await service.getMessage('s1', 'M1');+ expect(got?.message).toBeNull();+ expect(Buffer.isBuffer((got as unknown as { mediaKey: unknown }).mediaKey)).toBe(true);+ });++ it('leaves an id the store does not hold absent, and a row the change declines untouched', async () => {+ await seedSession('s1');+ await service.put('s1', msg('M1'));+ const change = jest.fn(() => null);++ await service.update('s1', 'NOPE', change);+ await service.update('s1', 'M1', change);++ expect(change).toHaveBeenCalledTimes(1); // only for the row that exists+ expect(await service.getMessage('s1', 'NOPE')).toBeNull();+ expect((await service.getMessage('s1', 'M1'))?.message?.conversation).toBe('M1');+ });++ it('applies after a put of the same id that has not finished yet', async () => {+ await seedSession('s1');+ // The change is asked for while the original's write is still in flight (its first await is+ // the library import), which is how the inbound path and a delete for everyone meet.+ await Promise.all([+ service.put('s1', msg('M1')),+ Promise.resolve().then(() => service.update('s1', 'M1', stored => ({ ...stored, message: null }))),+ ]);+ expect((await service.getMessage('s1', 'M1'))?.message).toBeNull();+ });++ it('a read issued while an update is in flight sees the change', async () => {+ await seedSession('s1');+ await service.put('s1', msg('M1'));+ let release!: () => void;+ const gate = new Promise<void>(resolve => (release = resolve));+ const real = repo.update.bind(repo);+ jest.spyOn(repo, 'update').mockImplementationOnce(async (...args: Parameters<typeof real>) => {+ await gate;+ return real(...args);+ });++ const change = service.update('s1', 'M1', stored => ({ ...stored, message: { conversation: 'edited' } }));+ const read = service.getMessage('s1', 'M1');+ for (let i = 0; i < 20; i++) await new Promise<void>(resolve => setImmediate(resolve));+ release();+ await change;++ expect((await read)?.message?.conversation).toBe('edited');+ });++ it('an update asked for before the put of the same id settles instead of waiting on it', async () => {+ await seedSession('s1');+ const change = jest.fn((stored: WAMessage) => ({ ...stored, message: null }));++ await Promise.all([service.update('s1', 'M1', change), service.put('s1', msg('M1'))]);++ // Queued first, the update found nothing to change; the put that followed it still landed.+ expect(change).not.toHaveBeenCalled();+ expect((await service.getMessage('s1', 'M1'))?.message?.conversation).toBe('M1');+ });+ });+it('clearSession removes only that session', async () => {await seedSession('s1');await seedSession('s2');@@ -291,4 +382,22 @@ describe('BaileysMessageStoreService', () => {expect(await service.getMessage('s1', 'M1')).toBeNull();expect(await service.getMessage('s2', 'M2')).not.toBeNull();});++ it('clearSession waits for a write of that session still in flight, so it cannot recreate the row', async () => {+ await seedSession('s1');+ await seedSession('s2');+ await service.put('s2', msg('M2'));+ const held = holdNextUpsert();+ const write = service.put('s1', msg('M1'));+ await ticks();++ const clearing = service.clearSession('s1');+ await ticks();+ held.release();+ await clearing;+ await write;++ expect(await repo.count({ where: { sessionId: 's1' } })).toBe(0);+ expect(await repo.count({ where: { sessionId: 's2' } })).toBe(1);+ });});diff --git a/src/engine/adapters/baileys-message-store.service.ts b/src/engine/adapters/baileys-message-store.service.tsindex 9eb397194..b95a77b18 100644--- a/src/engine/adapters/baileys-message-store.service.ts+++ b/src/engine/adapters/baileys-message-store.service.ts@@ -6,6 +6,7 @@ import type { WAMessage } from '@whiskeysockets/baileys';import { BaileysStoredMessage } from './baileys-stored-message.entity';import { BaileysMessageStore } from '../types/baileys.types';import { createLogger } from '../../common/services/logger.service';+import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';function positiveIntFromEnv(name: string, fallback: number): number {const parsed = Number.parseInt(process.env[name] ?? '', 10);@@ -41,8 +42,12 @@ export class BaileysMessageStoreService implements BaileysMessageStore {* is still running, and whoever hears about it may look it up at once (a quoted reply, a reaction,* a read receipt). A read of an id held here waits for that write instead of reporting the message* missing. An entry lives exactly as long as its write, so the map only ever holds writes in flight.+ * A later write of the same id replaces the entry: it is queued behind every earlier one, so waiting+ * for it covers them too.*/private readonly pendingWrites = new Map<string, Promise<void>>();+ /** One write chain per stored message, so a put and a later update of the same id land in call order. */+ private readonly writes = new KeyedMutationQueue();/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first use, not at boot). */private baileysLib?: typeof BaileysLib;@@ -56,21 +61,58 @@ export class BaileysMessageStoreService implements BaileysMessageStore {private readonly repo: Repository<BaileysStoredMessage>,) {}- async put(sessionId: string, msg: WAMessage): Promise<void> {+ put(sessionId: string, msg: WAMessage): Promise<void> {const waMessageId = msg.key?.id;if (!waMessageId) {- return;+ return Promise.resolve();}- // Registered before the first await, so a read issued any time after put() is called sees this write.- const key = `${sessionId}:${waMessageId}`;- const write = this.write(sessionId, waMessageId, msg);+ return this.track(sessionId, waMessageId, () => this.write(sessionId, waMessageId, msg));+ }++ /**+ * Rewrite a stored message in place: `change` receives the stored copy and returns its replacement,+ * or null to leave the row as it is. An id the store does not hold stays absent, since there is no+ * original to change. Queued behind any put() of the same id already called, so a change that+ * arrives while the original's write is still in flight lands on top of it rather than under it.+ * createdAt is left alone: an edit or a delete is not a new message, and must not reset its age.+ */+ update(sessionId: string, messageId: string, change: (stored: WAMessage) => WAMessage | null): Promise<void> {+ if (!messageId) {+ return Promise.resolve();+ }+ return this.track(sessionId, messageId, async () => {+ // Read the row itself: this runs on the id's write chain, after every earlier write of the id, so+ // waiting on pendingWrites here would wait on this very write.+ const stored = await this.readStored(sessionId, messageId);+ const next = stored && change(stored);+ if (!next) {+ return;+ }+ const { BufferJSON } = await this.loadLib();+ await this.repo.update(+ { sessionId, waMessageId: messageId },+ { serializedMessage: JSON.stringify(next, BufferJSON.replacer) },+ );+ });+ }++ /**+ * Queue `work` on the id's write chain and register it as the id's in-flight write before returning,+ * so a read issued any time after put() or update() is called waits for it. `work` is called inside a+ * promise chain, so one that throws before returning its promise still settles the write.+ */+ private track(sessionId: string, messageId: string, work: () => Promise<void>): Promise<void> {+ const key = `${sessionId}:${messageId}`;+ const write = new Promise<void>((resolve, reject) =>+ this.writes.enqueue(key, () => Promise.resolve().then(work).then(resolve, reject)),+ );this.pendingWrites.set(key, write);- try {- await write;- } finally {- // A later put of the same id replaced the entry and owns it now.+ // A later write of the same id replaced the entry and owns it now.+ const release = (): void => {if (this.pendingWrites.get(key) === write) this.pendingWrites.delete(key);- }+ };+ write.then(release, release);+ return write;}private async write(sessionId: string, waMessageId: string, msg: WAMessage): Promise<void> {@@ -112,6 +154,10 @@ export class BaileysMessageStoreService implements BaileysMessageStore {// letting an undefined criterion reach the ORM (TypeORM 1.x throws; 0.3 matched an arbitrary row).if (!messageId) return null;await this.settled(sessionId, messageId);+ return this.readStored(sessionId, messageId);+ }++ private async readStored(sessionId: string, messageId: string): Promise<WAMessage | null> {const row = await this.repo.findOne({ where: { sessionId, waMessageId: messageId } });if (!row) {return null;@@ -142,6 +188,13 @@ export class BaileysMessageStoreService implements BaileysMessageStore {}async clearSession(sessionId: string): Promise<void> {+ // A write already in flight would recreate its row after the delete. Its failure is the writer's to report.+ const prefix = `${sessionId}:`;+ await Promise.all(+ [...this.pendingWrites]+ .filter(([key]) => key.startsWith(prefix))+ .map(([, write]) => write.catch(() => undefined)),+ );await this.repo.delete({ sessionId });}diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex d16bc69c6..b9ecdeb43 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -17,7 +17,7 @@ import {} from '../interfaces/whatsapp-engine.interface';import { toEngineParticipants } from './baileys-groups';import { buildVCard } from './vcard';-import { resolveBaileysButtonClick } from './baileys-message-mapper';+import { resolveBaileysButtonClick, setBaileysText } from './baileys-message-mapper';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';import { BadRequestException, InternalServerErrorException } from '@nestjs/common';import { EngineRefusedError } from '../../common/errors/engine-refused.error';@@ -53,6 +53,12 @@ export interface BaileysMessagingHost {rememberOwnSend(id: string | null | undefined): void;/** Look up a previously-seen message from the store (the reply/forward/react/delete handle). */getStoredMessage(messageId: string): Promise<WAMessage | null> | undefined;+ /** Rewrite a stored message in place (see BaileysMessageStore.update); undefined without a store. */+ updateStoredMessage(messageId: string, change: (stored: WAMessage) => WAMessage | null): Promise<void> | undefined;+ /** Whether this message was deleted for everyone, even where the stored copy does not show it yet. */+ wasDeletedForEveryone(messageId: string): boolean;+ /** Record a delete for everyone this session just made (see wasDeletedForEveryone). */+ markDeletedForEveryone(messageId: string): void;/** Remember a lid<->phone pair the socket resolved, so later reads do not have to ask again. */recordLidMapping(lid: string, pn: string): void;/** The currently-registered onMessageCreate callback, if any (assigned at initialize()). */@@ -531,10 +537,17 @@ export class BaileysMessaging {async deleteMessage(chatId: string, messageId: string, forEveryone = true): Promise<void> {this.host.ensureReady();- const target = await this.requireStored(messageId);+ // A message already deleted for everyone can still be deleted for me: that clears its placeholder.+ const target = await this.requireStored(messageId, true);this.assertStoredInChat(target, chatId, messageId);if (forEveryone) {await this.send(await this.toDeliverableJid(chatId), { delete: target.key });+ // The echo of this delete is skipped as an own send, so the stored copy is emptied here, as+ // processInboundMessage does for a delete made from the phone or by the other side. Recorded+ // first, so the message stays deleted even if the store write fails or a repeat delivery of the+ // original is stored after it.+ this.host.markDeletedForEveryone(messageId);+ await this.changeStored(messageId, stored => ({ ...stored, message: null }));return;}// Delete-for-me (revoke on this device only): Baileys exposes it as a chat modification, not a@@ -578,7 +591,14 @@ export class BaileysMessaging {// protocolMessage edit envelope, so an edit can re-tag participants. An edit REPLACES the// content, so omitting mentions drops whatever tags the original carried.const editContent = { text: body, ...this.withMentions(mentions), edit: target.key };+ const b = await this.host.loadLib();await this.send(jid, this.previewSafe(editContent), this.previewSafeOptions(editContent));+ // Same reason as deleteMessage: the stored copy is what a later quote carries, and this edit's+ // echo never reaches processInboundMessage.+ await this.changeStored(messageId, stored => {+ const content = b.normalizeMessageContent(stored.message ?? undefined);+ return content && setBaileysText(content, body) ? stored : null;+ });// Both fields describe the EDITED MESSAGE, not the protocol envelope that carried the edit.// That envelope has an id and a send time of its own; answering with either would name something// no route can address and no stored row is keyed by, and would disagree with the@@ -753,15 +773,36 @@ export class BaileysMessaging {return { quoted: await this.requireStored(quotedMessageId) };}- /** Resolve a previously-seen message from the store, or throw a clear not-found error. */- private async requireStored(messageId: string): Promise<WAMessage> {+ /**+ * Resolve a previously-seen message from the store, or throw a clear not-found error.+ *+ * A message deleted for everyone is kept with its content removed, and is not found here unless+ * `allowDeleted`: quoting it would hand WhatsApp the deleted content again (Baileys copies the+ * quoted message into the reply's contextInfo), and there is nothing left to forward, react to or+ * edit. A message the session knows was deleted is treated the same while its stored copy still+ * holds the content, as it can when the delete overtook the original's own store write.+ */+ private async requireStored(messageId: string, allowDeleted = false): Promise<WAMessage> {const found = await this.host.getStoredMessage(messageId);- if (!found?.key) {+ const deleted = !found?.message || this.host.wasDeletedForEveryone(messageId);+ if (!found?.key || (deleted && !allowDeleted)) {throw new MessageNotFoundError(messageId);}return found;}+ /** Apply a change this session just made to the stored copy. Best-effort: the change already went out. */+ private async changeStored(messageId: string, change: (stored: WAMessage) => WAMessage | null): Promise<void> {+ try {+ await this.host.updateStoredMessage(messageId, change);+ } catch (err) {+ this.host.logger.warn('Failed to apply an edit or delete to the message store', {+ msgId: messageId,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+/*** The stored key must belong to the requested chat — acting with another chat's key is a* not-found here, not a cross-chat write (a pin sent into chat A referencing chat B's message, ordiff --git a/src/engine/adapters/baileys-quote-on-receipt.spec.ts b/src/engine/adapters/baileys-quote-on-receipt.spec.tsindex 386ed705e..187e05c3c 100644--- a/src/engine/adapters/baileys-quote-on-receipt.spec.ts+++ b/src/engine/adapters/baileys-quote-on-receipt.spec.ts@@ -5,6 +5,7 @@ import { BaileysMessaging } from './baileys-messaging';import { BaileysMessageStoreService } from './baileys-message-store.service';import { BaileysStoredMessage } from './baileys-stored-message.entity';import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';+import { MessageNotFoundError } from '../../common/errors/message-not-found.error';import { createLogger } from '../../common/services/logger.service';import { Session, SessionStatus } from '../../modules/session/entities/session.entity';import type { IncomingMessage } from '../interfaces/whatsapp-engine.interface';@@ -16,6 +17,12 @@ const inbound = (id: string): WAMessage => ({message: { conversation: 'hi' },});+const photo = (id: string): WAMessage => ({+ key: { id, remoteJid: CHAT, fromMe: false },+ messageTimestamp: 1_700_000_000,+ message: { imageMessage: { mimetype: 'image/jpeg', caption: 'about to be deleted' } },+});+/*** Real events, real messaging, real store on in-memory SQLite. A consumer that quotes a message the* moment it is announced (a quick-reply plugin on message:received) used to lose the race against the@@ -26,6 +33,9 @@ describe('quoting a Baileys message the moment it is announced', () => {let repo: Repository<BaileysStoredMessage>;let store: BaileysMessageStoreService;let release: () => void;+ let upsert: jest.SpyInstance;+ /** One release per media download started, in call order: each download is held until released. */+ let downloads: Array<() => void>;const ticks = async (): Promise<void> => {for (let i = 0; i < 20; i++) await new Promise<void>(resolve => setImmediate(resolve));};@@ -40,13 +50,14 @@ describe('quoting a Baileys message the moment it is announced', () => {await ds.initialize();repo = ds.getRepository(BaileysStoredMessage);store = new BaileysMessageStoreService(repo);+ downloads = [];await ds.getRepository(Session).save(ds.getRepository(Session).create({ id: 's1', name: 's1', status: SessionStatus.READY, config: {} }));// Hold the first upsert: the database round trip the consumer lands inside.const gate = new Promise<void>(resolve => (release = resolve));const real = repo.upsert.bind(repo);- jest.spyOn(repo, 'upsert').mockImplementationOnce(async (...args: Parameters<typeof real>) => {+ upsert = jest.spyOn(repo, 'upsert').mockImplementationOnce(async (...args: Parameters<typeof real>) => {await gate;return real(...args);});@@ -60,6 +71,7 @@ describe('quoting a Baileys message the moment it is announced', () => {const build = (onMessage: (m: IncomingMessage) => void,+ on: { edited?: () => void; revoked?: () => void } = {},): { events: BaileysEvents; messaging: BaileysMessaging; sock: { sendMessage: jest.Mock } } => {const sock = {sendMessage: jest@@ -78,6 +90,17 @@ describe('quoting a Baileys message the moment it is announced', () => {normalizeMessageContent: (c: unknown) => c,getContentType: (c: Record<string, unknown> | undefined) => Object.keys(c ?? {})[0],proto: { Message: { ProtocolMessage: { Type: { REVOKE: 0, MESSAGE_EDIT: 14 } } } },+ downloadMediaMessage: () =>+ new Promise(resolve =>+ downloads.push(() =>+ resolve({+ // eslint-disable-next-line @typescript-eslint/require-await+ async *[Symbol.asyncIterator]() {+ yield Buffer.from('JPEG');+ },+ }),+ ),+ ),} as never),getFetchDispatcher: () => undefined,inboundLimiter: new ConcurrencyLimiter(4),@@ -86,11 +109,15 @@ describe('quoting a Baileys message the moment it is announced', () => {recordMessageEdit: () => undefined,putStoredMessage: (m: WAMessage) => store.put('s1', m),getStoredMessage: (id: string) => store.getMessage('s1', id),+ updateStoredMessage: (id: string, change: (stored: WAMessage) => WAMessage | null) =>+ store.update('s1', id, change),consumeOwnSend: () => false,rememberOwnSend: () => undefined,recordLidMapping: () => undefined,getOnMessage: () => onMessage,getOnMessageCreate: () => undefined,+ getOnMessageEdited: () => on.edited,+ getOnMessageRevoked: () => on.revoked,ensureReady: () => undefined,sessionProxyUrl: () => undefined,getEphemeralExpiration: () => undefined,@@ -100,10 +127,24 @@ describe('quoting a Baileys message the moment it is announced', () => {const messaging = new BaileysMessaging({...host,mapMessage: (...a: Parameters<BaileysEvents['mapMessage']>) => events.mapMessage(...a),+ wasDeletedForEveryone: (id: string) => events.wasDeletedForEveryone(id),+ markDeletedForEveryone: (id: string) => events.markDeletedForEveryone(id),});return { events, messaging, sock };};+ const change = (protocolMessage: Record<string, unknown>, chat = CHAT): WAMessage => ({+ key: { id: 'CHANGE', remoteJid: chat, fromMe: false },+ messageTimestamp: 1_700_000_100,+ message: { protocolMessage: { key: { id: 'TARGET' }, ...protocolMessage } },+ });++ /** The content of every row the store was asked to write for `id`, in order. */+ const writtenContents = (id: string): unknown[] =>+ (upsert.mock.calls as Array<[{ waMessageId: string; serializedMessage: string }]>)+ .filter(([row]) => row.waMessageId === id)+ .map(([row]) => (JSON.parse(row.serializedMessage) as WAMessage).message);+it('lets an onMessage consumer quote the message it was just handed', async () => {let reply: Promise<unknown> | undefined;const { events, messaging, sock } = build(m => {@@ -129,4 +170,133 @@ describe('quoting a Baileys message the moment it is announced', () => {await ticks();expect(heard).toHaveBeenCalledTimes(1);});++ describe('an edit or a delete for everyone of a stored message', () => {+ const stored = async (events: BaileysEvents): Promise<void> => {+ events.handleMessagesUpsert({ messages: [inbound('TARGET')], type: 'notify' });+ await ticks();+ release();+ await ticks();+ };++ it('lets a consumer of the edit quote the edited text at once', async () => {+ let reply: Promise<unknown> | undefined;+ const { events, messaging, sock } = build(() => undefined, {+ edited: () => {+ reply = messaging.replyToMessage(CHAT, 'TARGET', 'ok');+ },+ });+ await stored(events);++ events.handleMessagesUpsert({+ messages: [change({ type: 14, editedMessage: { conversation: 'after the edit' } })],+ type: 'notify',+ });+ await ticks();++ await expect(reply).resolves.toMatchObject({ id: 'R1' });+ const [, , options] = sock.sendMessage.mock.calls[0] as [unknown, unknown, { quoted?: WAMessage }];+ expect(options.quoted?.message?.conversation).toBe('after the edit');+ });++ it('refuses a consumer of the delete that quotes the deleted message at once', async () => {+ let reply: Promise<unknown> | undefined;+ const { events, messaging, sock } = build(() => undefined, {+ revoked: () => {+ reply = messaging.replyToMessage(CHAT, 'TARGET', 'ok').catch((err: unknown) => err);+ },+ });+ await stored(events);++ events.handleMessagesUpsert({ messages: [change({ type: 0 })], type: 'notify' });+ await ticks();++ expect(await reply).toBeInstanceOf(MessageNotFoundError);+ expect(sock.sendMessage).not.toHaveBeenCalled();+ });+ });++ describe('a delete for everyone that arrives while the original is still downloading its media', () => {+ beforeEach(() => release()); // the held step here is the download, not the store write++ it('keeps the content out of the store and out of a quote of the original announced after it', async () => {+ let reply: Promise<unknown> | undefined;+ const { events, messaging, sock } = build(m => {+ reply = messaging.replyToMessage(CHAT, m.id, 'ok').catch((err: unknown) => err);+ });+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });+ await ticks();+ events.handleMessagesUpsert({ messages: [change({ type: 0 })], type: 'notify' });+ await ticks();++ downloads[0]();+ await ticks();++ expect(await reply).toBeInstanceOf(MessageNotFoundError);+ expect(sock.sendMessage).not.toHaveBeenCalled();+ expect(writtenContents('TARGET')).toEqual([null]);+ });++ it('keeps a repeat delivery that passed the repeat check from restoring the content', async () => {+ const { events, messaging } = build(() => undefined);+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });+ await ticks();+ events.handleMessagesUpsert({ messages: [change({ type: 0 })], type: 'notify' });+ await ticks();+ // Nothing is stored yet, so the repeat is not recognised as one and downloads too.+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });+ await ticks();++ downloads[0](); // the first delivery is stored, and the delete lands on top of it+ await ticks();+ downloads[1](); // then the repeat is stored+ await ticks();++ expect((await store.getMessage('s1', 'TARGET'))?.message).toBeNull();+ expect(writtenContents('TARGET')).toEqual([null, null]);+ await expect(messaging.forwardMessage(CHAT, '[email protected]', 'TARGET')).rejects.toBeInstanceOf(+ MessageNotFoundError,+ );+ });++ it('refuses a consumer of the delete while a repeat of the original is already stored', async () => {+ let reply: Promise<unknown> | undefined;+ const { events, messaging, sock } = build(() => undefined, {+ revoked: () => {+ reply = messaging.replyToMessage(CHAT, 'TARGET', 'ok').catch((err: unknown) => err);+ },+ });+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });+ await ticks();+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });+ await ticks();+ downloads[1](); // the repeat is stored with its content; the first delivery still downloads+ await ticks();++ events.handleMessagesUpsert({ messages: [change({ type: 0 })], type: 'notify' });+ await ticks();++ expect(await reply).toBeInstanceOf(MessageNotFoundError);+ expect(sock.sendMessage).not.toHaveBeenCalled();+ downloads[0]();+ await ticks();+ });++ it('ignores a delete of the same id sent from another chat', async () => {+ let reply: Promise<unknown> | undefined;+ const { events, messaging } = build(m => {+ reply = messaging.replyToMessage(CHAT, m.id, 'ok');+ });+ events.handleMessagesUpsert({ messages: [photo('TARGET')], type: 'notify' });+ await ticks();+ events.handleMessagesUpsert({ messages: [change({ type: 0 }, '[email protected]')], type: 'notify' });+ await ticks();++ downloads[0]();+ await ticks();++ await expect(reply).resolves.toMatchObject({ id: 'R1' });+ expect(writtenContents('TARGET')).toEqual([photo('TARGET').message]);+ });+ });});diff --git a/src/engine/adapters/baileys-quoted-send.spec.ts b/src/engine/adapters/baileys-quoted-send.spec.tsindex 1c6597ccf..6aa74043d 100644--- a/src/engine/adapters/baileys-quoted-send.spec.ts+++ b/src/engine/adapters/baileys-quoted-send.spec.ts@@ -47,6 +47,8 @@ function makeMessaging(stored: unknown = STORED): {toUnixSeconds: () => 1,loadLib: () => Promise.resolve({} as never),getStoredMessage,+ wasDeletedForEveryone: () => false,+ markDeletedForEveryone: () => undefined,putStoredMessage: () => undefined,rememberOwnSend: () => undefined,recordLidMapping: () => undefined,@@ -132,4 +134,15 @@ describe('BaileysMessaging — a quote rides along with every content kind', ()// the send would not fix it.expect(sock.sendMessage).not.toHaveBeenCalled();});++ it('refuses a message deleted for everyone instead of quoting what was deleted', async () => {+ // The store keeps a deleted message with `message: null`. Baileys copies the quoted message into+ // the reply's contextInfo, so quoting the pre-delete copy would send the deleted content again.+ const { messaging, sock } = makeMessaging({ ...STORED, message: null });++ await expect(+ messaging.sendTextMessage(CHAT, 'hi', undefined, { quotedMessageId: 'QUOTED-1' }),+ ).rejects.toBeInstanceOf(MessageNotFoundError);+ expect(sock.sendMessage).not.toHaveBeenCalled();+ });});diff --git a/src/engine/adapters/baileys-remaining-writes.spec.ts b/src/engine/adapters/baileys-remaining-writes.spec.tsindex c5d6cd3e7..078051b34 100644--- a/src/engine/adapters/baileys-remaining-writes.spec.ts+++ b/src/engine/adapters/baileys-remaining-writes.spec.ts@@ -41,6 +41,8 @@ function messaging(sock: Record<string, jest.Mock>, budgetMs: number): BaileysMetoUnixSeconds: () => 1,loadLib: () => Promise.resolve({} as never),getStoredMessage: () => Promise.resolve({ key: { ...LAST.key, fromMe: true }, message: {}, messageTimestamp: 1 }),+ wasDeletedForEveryone: () => false,+ markDeletedForEveryone: () => undefined,putStoredMessage: () => undefined,recordLidMapping: () => undefined,getOnMessageCreate: () => undefined,diff --git a/src/engine/adapters/baileys-sticker-webp.spec.ts b/src/engine/adapters/baileys-sticker-webp.spec.tsindex fad9a72dc..e8c4b9bbb 100644--- a/src/engine/adapters/baileys-sticker-webp.spec.ts+++ b/src/engine/adapters/baileys-sticker-webp.spec.ts@@ -58,6 +58,8 @@ function makeMessaging(): { messaging: BaileysMessaging; sock: { sendMessage: jetoUnixSeconds: () => 1,loadLib: () => Promise.resolve({} as never),getStoredMessage: () => Promise.resolve(undefined),+ wasDeletedForEveryone: () => false,+ markDeletedForEveryone: () => undefined,putStoredMessage: () => undefined,rememberOwnSend: () => undefined,recordLidMapping: () => undefined,diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex d9959a02b..6cd2d5270 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -172,6 +172,7 @@ const fakeStore = {getMessage: jest.fn(),getMessages: jest.fn().mockResolvedValue([]),clearSession: jest.fn().mockResolvedValue(undefined),+ update: jest.fn().mockResolvedValue(undefined),};// clearAllMocks keeps implementations: a store lookup one test taught to return a message must not@@ -6774,3 +6775,301 @@ describe('BaileysAdapter voice status', () => {).rejects.toThrow(/recipients is required/);});});++describe('BaileysAdapter keeps the message store in step with edits and deletes', () => {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const baileys = jest.requireMock('@whiskeysockets/baileys') as {+ getContentType: jest.Mock;+ normalizeMessageContent: jest.Mock;+ downloadMediaMessage: jest.Mock;+ };++ type StoredShape = { key: Record<string, unknown>; message: Record<string, unknown> | null };+ const PEER = '[email protected]';+ const GROUP = '[email protected]';++ beforeEach(() => {+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.resetEmitter();+ jest.clearAllMocks();+ baileys.getContentType.mockImplementation(realGetContentType);+ baileys.normalizeMessageContent.mockImplementation((c: unknown) => c);+ fakeSock.sendMessage.mockResolvedValue({ key: { id: 'ENVELOPE', remoteJid: PEER, fromMe: true } });+ });++ const settle = () => new Promise(r => setImmediate(r));++ /** The change the adapter handed the store for `id`, applied to `stored`. */+ const changed = (id: string, stored: StoredShape): StoredShape | null => {+ const call = (fakeStore.update.mock.calls as Array<[string, string, (m: StoredShape) => StoredShape | null]>).find(+ c => c[1] === id,+ );+ if (!call) throw new Error(`no store update for ${id}`);+ expect(call[0]).toBe('db-uuid-1');+ return call[2](structuredClone(stored));+ };++ const fireProtocol = (key: Record<string, unknown>, protocolMessage: Record<string, unknown>) =>+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [{ key: { id: 'ENVELOPE_IN', ...key }, message: { protocolMessage }, messageTimestamp: 1700000100 }],+ });++ const loggerOf = (adapter: BaileysAdapter) =>+ (adapter as unknown as { logger: { warn: (m: string, ctx?: unknown) => void } }).logger;++ const started = async (): Promise<BaileysAdapter> => {+ const adapter = newAdapter();+ await adapter.initialize({});+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };++ it('writes an inbound edit into the stored copy, so a later quote carries the new text', async () => {+ await started();+ fireProtocol(+ { remoteJid: PEER, fromMe: false },+ { key: { id: 'ORIG' }, type: 14, editedMessage: { conversation: 'after the edit' } },+ );+ await settle();++ const stored = {+ key: { remoteJid: PEER, fromMe: false, id: 'ORIG' },+ message: { extendedTextMessage: { text: 'before the edit', matchedText: 'https://example.com' } },+ };+ expect(changed('ORIG', stored)?.message).toEqual({+ extendedTextMessage: { text: 'after the edit', matchedText: 'https://example.com' },+ });+ });++ it('edits only the caption of a stored photo, keeping the media', async () => {+ await started();+ fireProtocol(+ { remoteJid: PEER, fromMe: false },+ { key: { id: 'PHOTO' }, type: 14, editedMessage: { imageMessage: { caption: 'new caption' } } },+ );+ await settle();++ const stored = {+ key: { remoteJid: PEER, fromMe: false, id: 'PHOTO' },+ message: { imageMessage: { caption: 'old caption', url: 'https://mmg.example/x', mimetype: 'image/jpeg' } },+ };+ expect(changed('PHOTO', stored)?.message).toEqual({+ imageMessage: { caption: 'new caption', url: 'https://mmg.example/x', mimetype: 'image/jpeg' },+ });+ });++ it('ignores an edit from anyone but the author', async () => {+ await started();+ fireProtocol(+ { remoteJid: GROUP, participant: '[email protected]', fromMe: false },+ { key: { id: 'THEIRS' }, type: 14, editedMessage: { conversation: 'spoofed' } },+ );+ await settle();++ const stored = {+ key: { remoteJid: GROUP, participant: '[email protected]', fromMe: false, id: 'THEIRS' },+ message: { conversation: 'original' },+ };+ expect(changed('THEIRS', stored)).toBeNull();+ });++ it('empties the stored copy of a message deleted for everyone, keeping its key', async () => {+ await started();+ fireProtocol({ remoteJid: PEER, fromMe: false }, { key: { id: 'GONE' }, type: 0 });+ await settle();++ const stored = { key: { remoteJid: PEER, fromMe: false, id: 'GONE' }, message: { conversation: 'secret' } };+ expect(changed('GONE', stored)).toEqual({ key: stored.key, message: null });+ });++ it('empties an own message deleted from the phone', async () => {+ await started();+ fireProtocol({ remoteJid: PEER, fromMe: true }, { key: { id: 'MINE' }, type: 0 });+ await settle();++ const stored = { key: { remoteJid: PEER, fromMe: true, id: 'MINE' }, message: { conversation: 'oops' } };+ expect(changed('MINE', stored)?.message).toBeNull();+ });++ it('applies a group admin deleting another member message', async () => {+ await started();+ fireProtocol(+ { remoteJid: GROUP, participant: '[email protected]', fromMe: false },+ { key: { id: 'G1' }, type: 0 },+ );+ await settle();++ const stored = {+ key: { remoteJid: GROUP, participant: '[email protected]', fromMe: false, id: 'G1' },+ message: { conversation: 'removed by an admin' },+ };+ expect(changed('G1', stored)?.message).toBeNull();+ });++ it('ignores a 1:1 delete of an own message sent by the other side, and one from another chat', async () => {+ await started();+ fireProtocol({ remoteJid: PEER, fromMe: false }, { key: { id: 'MINE' }, type: 0 });+ // The same author, from another group: the author check and the group-delete allowance both pass,+ // so only the chat check refuses it.+ fireProtocol({ remoteJid: '[email protected]', participant: PEER, fromMe: false }, { key: { id: 'OTHER' }, type: 0 });+ await settle();++ expect(+ changed('MINE', { key: { remoteJid: PEER, fromMe: true, id: 'MINE' }, message: { conversation: 'x' } }),+ ).toBeNull();+ expect(+ changed('OTHER', {+ key: { remoteJid: GROUP, participant: PEER, fromMe: false, id: 'OTHER' },+ message: { conversation: 'y' },+ }),+ ).toBeNull();+ });++ it('applies a delete only after the original, still downloading its media, has been stored', async () => {+ let release!: () => void;+ baileys.downloadMediaMessage.mockReturnValueOnce(+ new Promise(resolve => {+ release = () => resolve(streamOf(Buffer.from('JPEG')));+ }),+ );+ await started();+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: PEER, fromMe: false, id: 'SLOW' },+ message: { imageMessage: { mimetype: 'image/jpeg', caption: 'about to be deleted' } },+ messageTimestamp: 1700000099,+ },+ ],+ });+ fireProtocol({ remoteJid: PEER, fromMe: false }, { key: { id: 'SLOW' }, type: 0 });+ await settle();+ // The delete has been seen, but writing it now would put it under the original's own write.+ expect(fakeStore.update).not.toHaveBeenCalled();++ release();+ for (let i = 0; i < 5; i++) await settle();++ expect(fakeStore.put).toHaveBeenCalledTimes(1);+ expect(fakeStore.update).toHaveBeenCalledTimes(1);+ expect(fakeStore.put.mock.invocationCallOrder[0]).toBeLessThan(fakeStore.update.mock.invocationCallOrder[0]);+ });++ it('waits for a first delivery still downloading when its repeat was stored first', async () => {+ let release!: () => void;+ baileys.downloadMediaMessage+ .mockReturnValueOnce(+ new Promise(resolve => {+ release = () => resolve(streamOf(Buffer.from('JPEG')));+ }),+ )+ .mockReturnValueOnce(Promise.resolve(streamOf(Buffer.from('JPEG'))));+ await started();+ const delivery = () => ({+ key: { remoteJid: PEER, fromMe: false, id: 'TWICE' },+ message: { imageMessage: { mimetype: 'image/jpeg', caption: 'about to be deleted' } },+ messageTimestamp: 1700000099,+ });+ fakeSock.fire('messages.upsert', { type: 'notify', messages: [delivery()] });+ fakeSock.fire('messages.upsert', { type: 'notify', messages: [delivery()] });+ for (let i = 0; i < 5; i++) await settle();+ expect(fakeStore.put).toHaveBeenCalledTimes(1); // the repeat, while the first is still downloading++ fireProtocol({ remoteJid: PEER, fromMe: false }, { key: { id: 'TWICE' }, type: 0 });+ await settle();+ expect(fakeStore.update).not.toHaveBeenCalled();++ release();+ for (let i = 0; i < 5; i++) await settle();+ expect(fakeStore.put).toHaveBeenCalledTimes(2);+ expect(fakeStore.update).toHaveBeenCalledTimes(1);+ expect(fakeStore.put.mock.invocationCallOrder[1]).toBeLessThan(fakeStore.update.mock.invocationCallOrder[0]);+ });++ const ownStored = {+ key: { id: 'TARGET', remoteJid: PEER, fromMe: true },+ message: { conversation: 'as sent' },+ messageTimestamp: '1700000000',+ };++ it('empties the stored copy when the API deletes a message for everyone', async () => {+ fakeStore.getMessage.mockResolvedValue(ownStored);+ const adapter = await started();+ await adapter.deleteMessage(PEER, 'TARGET', true);+ expect(changed('TARGET', ownStored)).toEqual({ ...ownStored, message: null });+ });++ it('still answers a delete for everyone when the store cannot record it', async () => {+ // The delete already reached WhatsApp; failing the request now would invite a retry of it.+ fakeStore.getMessage.mockResolvedValue(ownStored);+ fakeStore.update.mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));+ const adapter = await started();+ const warn = jest.spyOn(loggerOf(adapter), 'warn').mockImplementation(() => undefined);+ await expect(adapter.deleteMessage(PEER, 'TARGET', true)).resolves.toBeUndefined();+ expect(warn).toHaveBeenCalledWith(+ 'Failed to apply an edit or delete to the message store',+ expect.objectContaining({ msgId: 'TARGET', error: 'SQLITE_BUSY: database is locked' }),+ );+ });++ it('refuses a message the API deleted for everyone even when the store could not record the delete', async () => {+ fakeStore.getMessage.mockResolvedValue(ownStored);+ fakeStore.update.mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));+ const adapter = await started();+ jest.spyOn(loggerOf(adapter), 'warn').mockImplementation(() => undefined);+ await adapter.deleteMessage(PEER, 'TARGET', true);+ fakeSock.sendMessage.mockClear();++ await expect(adapter.replyToMessage(PEER, 'TARGET', 'quoting it')).rejects.toBeInstanceOf(MessageNotFoundError);+ expect(fakeSock.sendMessage).not.toHaveBeenCalled();+ });++ it('logs rather than drops an inbound delete the store cannot record', async () => {+ fakeStore.update.mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));+ const adapter = await started();+ const warn = jest.spyOn(loggerOf(adapter), 'warn').mockImplementation(() => undefined);+ fireProtocol({ remoteJid: PEER, fromMe: false }, { key: { id: 'GONE' }, type: 0 });+ await settle();+ expect(fakeStore.update).toHaveBeenCalledTimes(1);+ expect(warn).toHaveBeenCalledWith(+ 'Failed to apply an edit or delete to the message store',+ expect.objectContaining({ msgId: 'GONE', error: 'SQLITE_BUSY: database is locked' }),+ );+ });++ it('writes an API edit into the stored copy before answering', async () => {+ fakeStore.getMessage.mockResolvedValue(ownStored);+ const adapter = await started();+ await adapter.editMessage(PEER, 'TARGET', 'edited body');+ expect(changed('TARGET', ownStored)?.message).toEqual({ conversation: 'edited body' });+ });++ it.each([+ ['replyToMessage', (a: BaileysAdapter) => a.replyToMessage(PEER, 'TARGET', 'quoting it')],+ [+ 'a quoted send',+ (a: BaileysAdapter) =>+ a.sendImageMessage(PEER, { mimetype: 'image/png', data: Buffer.from([1]), quotedMessageId: 'TARGET' }),+ ],+ ['forwardMessage', (a: BaileysAdapter) => a.forwardMessage(PEER, '[email protected]', 'TARGET')],+ ['reactToMessage', (a: BaileysAdapter) => a.reactToMessage(PEER, 'TARGET', '👍')],+ ['editMessage', (a: BaileysAdapter) => a.editMessage(PEER, 'TARGET', 'x')],+ ])('%s refuses a message deleted for everyone as not found', async (_name, call) => {+ fakeStore.getMessage.mockResolvedValue({ ...ownStored, message: null });+ const adapter = await started();+ await expect(call(adapter)).rejects.toBeInstanceOf(MessageNotFoundError);+ expect(fakeSock.sendMessage).not.toHaveBeenCalled();+ });++ it('still deletes for me a message already deleted for everyone', async () => {+ fakeStore.getMessage.mockResolvedValue({ ...ownStored, message: null });+ const adapter = await started();+ await adapter.deleteMessage(PEER, 'TARGET', false);+ expect(fakeSock.chatModify).toHaveBeenCalledWith(+ { deleteForMe: { deleteMedia: true, key: ownStored.key, timestamp: 1700000000 } },+ PEER,+ );+ });+});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex b5103dfd3..c7301562f 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -134,6 +134,10 @@ export class BaileysAdapter implements IWhatsAppEngine {recordMessage: msg => this.sessionStore.recordMessage(msg),recordMessageEdit: (chatId, messageId, text) => this.sessionStore.recordMessageEdit(chatId, messageId, text),putStoredMessage: msg => this.config.messageStore?.put(this.config.dbSessionId, msg),+ updateStoredMessage: (messageId, change) =>+ this.config.messageStore?.update(this.config.dbSessionId, messageId, change),+ wasDeletedForEveryone: messageId => this.events.wasDeletedForEveryone(messageId),+ markDeletedForEveryone: messageId => this.events.markDeletedForEveryone(messageId),rememberOwnSend: id => this.ownSends.remember(id),consumeOwnSend: id => this.ownSends.consume(id),getOnMessage: () => this.callbacks.onMessage,diff --git a/src/engine/adapters/create-call-link.spec.ts b/src/engine/adapters/create-call-link.spec.tsindex 12a419459..245e63c23 100644--- a/src/engine/adapters/create-call-link.spec.ts+++ b/src/engine/adapters/create-call-link.spec.ts@@ -46,6 +46,8 @@ describe('BaileysMessaging.createCallLink', () => {CALL_AUDIO_PREFIX: 'https://call.whatsapp.com/voice/',} as never),getStoredMessage: () => Promise.resolve(undefined),+ wasDeletedForEveryone: () => false,+ markDeletedForEveryone: () => undefined,putStoredMessage: () => undefined,recordLidMapping: () => undefined,getOnMessageCreate: () => undefined,diff --git a/src/engine/builtin/baileys/index.spec.ts b/src/engine/builtin/baileys/index.spec.tsindex f4c6bd450..59b5c66a5 100644--- a/src/engine/builtin/baileys/index.spec.ts+++ b/src/engine/builtin/baileys/index.spec.ts@@ -59,7 +59,13 @@ describe('BaileysPlugin.createEngine (opaque config)', () => {});it('passes the message store to the adapter', () => {- const store = { put: jest.fn(), getMessage: jest.fn(), getMessages: jest.fn(), clearSession: jest.fn() };+ const store = {+ put: jest.fn(),+ getMessage: jest.fn(),+ getMessages: jest.fn(),+ update: jest.fn(),+ clearSession: jest.fn(),+ };const plugin = new BaileysPlugin(store);plugin.createEngine({ sessionId: 'sess-1' });expect(BaileysAdapter).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'sess-1', messageStore: store }));diff --git a/src/engine/types/baileys.types.ts b/src/engine/types/baileys.types.tsindex 0c3f08dbb..ec3923e76 100644--- a/src/engine/types/baileys.types.ts+++ b/src/engine/types/baileys.types.ts@@ -20,6 +20,11 @@ export interface BaileysMessageStore {* result, so the caller cannot assume the order or the length matches its input.*/getMessages(sessionId: string, messageIds: string[]): Promise<WAMessage[]>;+ /**+ * Rewrite a stored message in place, for an edit or a delete for everyone. `change` returns the+ * replacement, or null to leave it untouched; an id the store does not hold stays absent.+ */+ update(sessionId: string, messageId: string, change: (stored: WAMessage) => WAMessage | null): Promise<void>;/** Remove all stored messages for a session (called on logout). */clearSession(sessionId: string): Promise<void>;}