Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

Merge branch 'main' into fix/pre-release-0.23.7

Yudhi Armyndharisf1ac1dce644c
diff --cc docs/06-api-specification.md
index fe1510822,ef3e322c1..901f5cfae
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@@ -1699,10 -1699,10 +1699,14 @@@ One upstream gap remains on whatsapp-we
message resolves but the page decides it is not replyable, the message is sent without the quote and
the call still succeeds.
+On whatsapp-web.js a quoted send to a channel, `status@broadcast` or a broadcast list answers `501`
+and nothing is sent: the library drops a reply to those recipients without sending it, so the
+gateway refuses it before the call. The Baileys engine does not refuse it.
+
+ 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 either
engine; the id is passed through as given. `POST /messages/reply` is stricter: both engines refuse a
quoted id that does not belong to the target chat, with `404`.
diff --cc src/engine/adapters/baileys-click-button.spec.ts
index 01c6ce36e,8b11ec969..32269fd31
--- a/src/engine/adapters/baileys-click-button.spec.ts
+++ b/src/engine/adapters/baileys-click-button.spec.ts
@@@ -84,8 -84,9 +84,10 @@@ function makeMessaging(stored: unknown
getContentType: (c: unknown) => contentTypeOf(c),
} as never),
getStoredMessage,
+ wasDeletedForEveryone: () => false,
+ markDeletedForEveryone: () => undefined,
putStoredMessage,
+ recordMessage: () => undefined,
rememberOwnSend: () => undefined,
recordLidMapping: () => undefined,
getOnMessageCreate: () => undefined,
diff --cc src/engine/adapters/baileys-events.ts
index f847706dc,5c1af6be5..95b2aa8ee
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@@ -299,7 -324,18 +347,19 @@@ export class BaileysEvents
body: '',
timestamp: toUnixSeconds(msg.messageTimestamp),
};
+ this.host.recordMessageEdit(remoteJid, revoked.id, '');
+ // 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;
}
@@@ -460,49 -502,47 +528,90 @@@
}
}
+ /**
+ * Whether an edit, revoke or reaction names a stored message it cannot touch: one in another chat,
+ * or, with `checkAuthor`, one somebody else sent. WhatsApp clients ignore such a message, but Baileys
+ * emits it as-is and the projector updates the stored row by id alone, so a contact who knows an id
+ * could rewrite or erase that message. Fails open: with no stored original, or ids that cannot be
+ * compared (see {@link differentWaIds}), the event goes through as it always has.
+ *
+ * A reaction to a message the account sent to a broadcast list is exempt: Baileys files the
+ * own-device copy under the list jid (`<id>@broadcast`), while each recipient reacts from their 1:1
+ * chat, so no chat can ever match it. Edits and revokes stay strict.
+ */
+ private async targetsForeignMessage(
+ targetId: string | null | undefined,
+ key: WAMessageKey,
+ checkAuthor: boolean,
+ kind?: 'reaction',
+ ): Promise<boolean> {
+ const original = targetId
+ ? (await this.readStoredMessage(targetId, 'checking what an edit, revoke or reaction targets'))?.key
+ : undefined;
+ if (!original) return false;
+ if (kind === 'reaction' && original.fromMe === true && original.remoteJid?.endsWith('@broadcast')) return false;
+ const neutral = (jid: string): string => this.host.toNeutralJid(jid);
+ const foreign =
+ differentWaIds([original.remoteJid, original.remoteJidAlt], [key.remoteJid, key.remoteJidAlt], neutral) ||
+ (checkAuthor &&
+ ((original.fromMe === true) !== (key.fromMe === true) ||
+ (key.fromMe !== true &&
+ differentWaIds(
+ [original.participant, original.participantAlt],
+ [key.participant, key.participantAlt],
+ neutral,
+ ))));
+ if (foreign) {
+ this.host.logger.warn('Dropping an edit, revoke or reaction aimed at a message from another chat or author', {
+ msgId: key.id ?? 'unknown',
+ targetId,
+ remoteJid: key.remoteJid,
+ });
+ }
+ return foreign;
+ }
+
+ /**
+ * 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 --cc src/engine/adapters/baileys-messaging.ts
index 7dbe6cb5c,b9ecdeb43..5cd8a77bd
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@@ -16,9 -16,8 +16,9 @@@ import
Quotable,
} from '../interfaces/whatsapp-engine.interface';
import { toEngineParticipants } from './baileys-groups';
+import { findSelfParticipant } from './baileys-group-mapper';
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';
@@@ -547,18 -537,17 +553,25 @@@ 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) {
+ // Only the sender, or a group admin, can delete a message for everyone. WhatsApp ignores any other
+ // revoke, yet the send resolves, so it would report a deletion that never happened. WhatsApp Web
+ // deletes such a message for the account alone instead, and so does this. A group whose member
+ // list shows no row for the account proves nothing either way, so the revoke still goes out there.
+ // Whichever branch runs, the text leaves this account's view, so it must not stay the chat
+ // preview. The echo of an own revoke is skipped as an own send, so the inbound path never clears it.
+ const chatJid = target.key.remoteJid ?? chatId;
+ if (forEveryone && (target.key.fromMe === true || (await this.selfIsGroupAdmin(target.key.remoteJid)) !== false)) {
await this.send(await this.toDeliverableJid(chatId), { delete: target.key });
+ this.host.recordMessageEdit(chatJid, messageId, '');
+ // 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
@@@ -618,9 -591,14 +631,16 @@@
// 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));
+ // The edit's echo is skipped as an own send, so the chat preview follows it from here.
+ this.host.recordMessageEdit(target.key.remoteJid ?? chatId, messageId, body);
+ // 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
diff --cc src/engine/adapters/baileys-quoted-send.spec.ts
index f32eabb58,6aa74043d..2ece41f0e
--- a/src/engine/adapters/baileys-quoted-send.spec.ts
+++ b/src/engine/adapters/baileys-quoted-send.spec.ts
@@@ -47,8 -47,9 +47,10 @@@ function makeMessaging(stored: unknown
toUnixSeconds: () => 1,
loadLib: () => Promise.resolve({} as never),
getStoredMessage,
+ wasDeletedForEveryone: () => false,
+ markDeletedForEveryone: () => undefined,
putStoredMessage: () => undefined,
+ recordMessage: () => undefined,
rememberOwnSend: () => undefined,
recordLidMapping: () => undefined,
getOnMessageCreate: () => undefined,
diff --cc src/engine/adapters/baileys-sticker-webp.spec.ts
index d1a4b64af,e8c4b9bbb..8d8549d8f
--- a/src/engine/adapters/baileys-sticker-webp.spec.ts
+++ b/src/engine/adapters/baileys-sticker-webp.spec.ts
@@@ -58,8 -58,9 +58,10 @@@ function makeMessaging(): { messaging:
toUnixSeconds: () => 1,
loadLib: () => Promise.resolve({} as never),
getStoredMessage: () => Promise.resolve(undefined),
+ wasDeletedForEveryone: () => false,
+ markDeletedForEveryone: () => undefined,
putStoredMessage: () => undefined,
+ recordMessage: () => undefined,
rememberOwnSend: () => undefined,
recordLidMapping: () => undefined,
getOnMessageCreate: () => undefined,