Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): read encrypted contact edits and reactions
Yudhi Armyndharisa5cfe95a436f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bf14fb8f0..436ca3292 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -115,6 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Leave no truncated archive in `BACKUP_DIR` when the final tar step of `backup.sh` fails, for example on a full volume.- Dead-letter undispatched ingress events instead of deleting them when they age out of the dedup window.- Keep a re-sent ingress delivery redrivable when an earlier dead letter for its id was already redriven.+- Apply a contact's message edit and a member's reaction that WhatsApp sends encrypted on Baileys, which were dropped, so `message.edited` and `message.reaction` fire for them and the stored message takes the edited text.- Deliver Baileys API edit and revoke events to webhook and WebSocket consumers.- Emit Baileys API reaction updates, including reaction removal.- Apply current receiver configuration and session ownership to every webhook delivery attempt.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex b3f2832b9..4aacab40d 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -7270,6 +7270,8 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve>> WhatsApp encrypts every RSVP with a key derived from the event creation message, so only answers to events **this session received and still holds in its message store** can be reported: an event posted before the number was linked, or one evicted past `BAILEYS_MESSAGE_STORE_LIMIT`, yields no `event.response`. This covers events in groups and in 1:1 chats, with one known gap: in a 1:1 chat, an answer from the person who posted the event, whether the other person or this account answering its own event, cannot be decrypted (Baileys derives the event's creator from the chat partner's side of the chat) and is not reported. Answers given while the session was offline are reported when WhatsApp replays them on reconnect. Baileys merges the updates it receives within one short buffer window per event, so several answers to one event that arrive in the same window, even from different guests (the whole replay after a reconnect, or answers a fraction of a second apart live), arrive as the last one only. whatsapp-web.js accepts the subscription and never fires the event.+> WhatsApp also sends a contact's edit, and a reaction in some chats, encrypted under a secret carried by the message it changes. On Baileys they are read with the stored copy of that message, so `message.edited` and `message.reaction` fire for a message **this session received and still holds in its message store**; an edit or reaction of one the store no longer holds (evicted past `BAILEYS_MESSAGE_STORE_LIMIT`, or received before the number was linked) is not delivered. whatsapp-web.js gets both already decrypted from WhatsApp Web.+> There is **no** `contact.update` event. `presence.update` is emitted only for chats you have subscribed to (see the presence-subscription endpoint); call outcomes are reported as `call.accepted`, `call.rejected` and `call.missed` alongside `call.received`.> **Group-event timing caveat (Baileys).** Membership/metadata changes that occurred while a Baileys session was offline are replayed by WhatsApp on reconnect and are dispatched like live events — but the engine does not forward their original occurrence time, so they carry the **receipt time** as `timestamp`. Treat `group.*` payloads as change notifications rather than a precise clock; stale offline _calls_ are never emitted this way (they are filtered by the `offline` flag).diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 8d6d64f45..4a6a9c8f6 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -978,6 +978,11 @@ adapter boundary — none silently stubs.and is never told the outcome. So a pin refused because the account is not a group admin, or anedit refused because the target is not a text message, answers `403` on whatsapp-web.js and `200`on Baileys.+- **Inbound edits and reactions (baileys).** WhatsApp sends a contact's edit, and a reaction in some+ chats, encrypted under the secret of the message it changes, which the library does not decrypt. The+ adapter reads them with the stored copy of that message (the session's message store, bounded by+ `BAILEYS_MESSAGE_STORE_LIMIT`), so an edit or reaction of a message the store no longer holds is not+ delivered. whatsapp-web.js receives both already decrypted from WhatsApp Web.- **`muteChat` addressing.** whatsapp-web.js resolves the chat before writing and answers `400` for achatId it cannot resolve; Baileys writes the app-state patch without a lookup and answers `200` fora chat that does not exist. `pinChat` splits the same way.diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.tsindex 836122a27..1af5bb9cb 100644--- a/src/engine/adapters/baileys-events.spec.ts+++ b/src/engine/adapters/baileys-events.spec.ts@@ -1,3 +1,4 @@+import { createCipheriv, createHmac } from 'node:crypto';import { BaileysEvents, type BaileysEventsHost } from './baileys-events';import { createLogger } from '../../common/services/logger.service';import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';@@ -989,3 +990,309 @@ describe('BaileysEvents event RSVPs (event.response)', () => {expect(onEventResponse).toHaveBeenCalledWith(expect.objectContaining({ responderId: phone }));});});++/**+ * WhatsApp sends a contact's edit, and a reaction in some chats, encrypted under the secret of the message+ * it changes. These tests seal their payloads with the library's own key construction (see+ * baileys-secret-payload.spec.ts) and let the stub's protobuf decode read JSON, which is the only part+ * the real library supplies.+ */+describe('BaileysEvents encrypted edits and reactions', () => {+ const group = '[email protected]';+ const author = '39900313301142@lid';+ const reactor = '195700218425410@lid';+ const secret = Buffer.alloc(32, 0x42);+ const flush = async (): Promise<void> => {+ for (let i = 0; i < 6; i++) await new Promise(resolve => setImmediate(resolve));+ };++ const protoStub = {+ Message: {+ SecretEncryptedMessage: { SecretEncType: { UNKNOWN: 0, EVENT_EDIT: 1, MESSAGE_EDIT: 2 } },+ ProtocolMessage: { Type: { REVOKE: 0, MESSAGE_EDIT: 14 } },+ decode: (bytes: Uint8Array): unknown => JSON.parse(Buffer.from(bytes).toString()),+ ReactionMessage: { decode: (bytes: Uint8Array): unknown => JSON.parse(Buffer.from(bytes).toString()) },+ },+ };+ const lib = { ...libStub, proto: protoStub } as unknown as Awaited<ReturnType<BaileysEventsHost['loadLib']>>;++ function seal(+ label: 'Message Edit' | 'Enc Reaction',+ ids: { target: string; author: string; modifier: string },+ plain: object,+ withSecret: Buffer = secret,+ ): { encPayload: Buffer; encIv: Buffer } {+ const prk = createHmac('sha256', Buffer.alloc(32)).update(withSecret).digest();+ const info = Buffer.from(`${ids.target}${ids.author}${ids.modifier}${label}`);+ const key = createHmac('sha256', prk)+ .update(Buffer.concat([info, Buffer.from([1])]))+ .digest();+ const iv = Buffer.alloc(12, 5);+ const cipher = createCipheriv('aes-256-gcm', key, iv);+ const body = Buffer.concat([+ cipher.update(Buffer.from(JSON.stringify(plain))),+ cipher.final(),+ cipher.getAuthTag(),+ ]);+ return { encPayload: body, encIv: iv };+ }++ const original = (overrides: Record<string, unknown> = {}): WAMessage =>+ ({+ key: { id: 'ORIG1', remoteJid: group, participant: author, fromMe: false },+ messageTimestamp: 1_786_000_000,+ message: { conversation: 'old text', messageContextInfo: { messageSecret: secret.toString('base64') } },+ ...overrides,+ }) as unknown as WAMessage;++ const editPlain = {+ protocolMessage: {+ type: 14,+ key: { id: 'ORIG1' },+ editedMessage: { conversation: 'new text' },+ timestampMs: 1786000000123,+ },+ };++ function editEnvelope(+ overrides: {+ participant?: string;+ fromMe?: boolean;+ sealed?: object;+ type?: unknown;+ target?: string;+ remoteJid?: string;+ } = {},+ ): WAMessage {+ const participant = overrides.participant ?? author;+ const sealed =+ overrides.sealed ?? seal('Message Edit', { target: 'ORIG1', author, modifier: participant }, editPlain);+ return {+ key: { id: 'ENV1', remoteJid: overrides.remoteJid ?? group, participant, fromMe: overrides.fromMe ?? false },+ messageTimestamp: 1_786_000_100,+ message: {+ secretEncryptedMessage: {+ targetMessageKey: { id: overrides.target ?? 'ORIG1', remoteJid: group, fromMe: true },+ ...sealed,+ secretEncType: overrides.type ?? 2,+ },+ },+ } as unknown as WAMessage;+ }++ function reactionEnvelope(text: string, overrides: { remoteJid?: string; sealed?: object } = {}): WAMessage {+ const sealed =+ overrides.sealed ??+ seal('Enc Reaction', { target: 'ORIG1', author, modifier: reactor }, { text, senderTimestampMs: 1786000000999 });+ return {+ key: { id: 'REACT1', remoteJid: overrides.remoteJid ?? group, participant: reactor, fromMe: false },+ messageTimestamp: 1_786_000_200,+ message: {+ encReactionMessage: { targetMessageKey: { id: 'ORIG1', remoteJid: group, fromMe: false }, ...sealed },+ },+ };+ }++ function setup(extra: Partial<BaileysEventsHost> = {}, stored: WAMessage | null = original()) {+ const onMessageEdited = jest.fn();+ const onMessageReaction = jest.fn();+ const onMessage = jest.fn();+ const recordMessageEdit = jest.fn();+ const events = new BaileysEvents(+ makeHost({+ loadLib: () => Promise.resolve(lib),+ getStoredMessage: (id: string) => Promise.resolve(id === 'ORIG1' ? stored : null),+ getOnMessageEdited: () => onMessageEdited,+ getOnMessageReaction: () => onMessageReaction,+ getOnMessage: () => onMessage,+ recordMessageEdit,+ ...extra,+ }),+ );+ return { events, onMessageEdited, onMessageReaction, onMessage, recordMessageEdit };+ }++ it("applies a contact's encrypted edit of a stored message, as the plain protocol message would be", async () => {+ const { events, onMessageEdited, onMessage, recordMessageEdit } = setup();++ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope()] });+ await flush();++ expect(onMessageEdited).toHaveBeenCalledTimes(1);+ expect(onMessageEdited).toHaveBeenCalledWith(+ expect.objectContaining({ messageId: 'ORIG1', body: 'new text', chatId: group, senderId: author }),+ );+ expect(recordMessageEdit).toHaveBeenCalledWith(group, 'ORIG1', 'new text');+ expect(onMessage).not.toHaveBeenCalled();+ });++ it('reads the edit of a 1:1 message, whose key names the partner by chat and leaves the participant empty', async () => {+ const chat = '262813461250071@lid';+ const stored = original({ key: { id: 'ORIG1', remoteJid: chat, participant: '', fromMe: false } });+ const { events, onMessageEdited } = setup({}, stored);+ const sealed = seal('Message Edit', { target: 'ORIG1', author: chat, modifier: chat }, editPlain);+ const envelope = editEnvelope({ sealed, remoteJid: chat, participant: '' });++ events.handleMessagesUpsert({ type: 'notify', messages: [envelope] });+ await flush();++ expect(onMessageEdited).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'ORIG1', body: 'new text' }));+ });++ it("reads an edit the account made from its phone, under the account's own id", async () => {+ const self = '[email protected]';+ const stored = original({ key: { id: 'ORIG1', remoteJid: group, fromMe: true } });+ const { events, onMessageEdited } = setup(+ {+ getSocketOrNull: () => ({ user: { id: '6280000000000:[email protected]', lid: '5550001:12@lid' } }) as WASocket,+ },+ stored,+ );+ const sealed = seal('Message Edit', { target: 'ORIG1', author: self, modifier: self }, editPlain);++ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope({ sealed, fromMe: true })] });+ await flush();++ expect(onMessageEdited).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'ORIG1', fromMe: true }));+ });++ it('reads an edit of a message that is still being processed, with the secret that copy carries', async () => {+ // The original's repeat-delivery check never settles until released, which keeps it in flight; the+ // edit's own read of the store answers nothing.+ let release: (stored: WAMessage | null) => void = () => undefined;+ let reads = 0;+ const getStoredMessage = (id: string): Promise<WAMessage | null> => {+ if (id !== 'ORIG1') return Promise.resolve(null);+ reads += 1;+ return reads === 1 ? new Promise(resolve => (release = resolve)) : Promise.resolve(null);+ };+ const { events, onMessageEdited } = setup({ getStoredMessage });++ events.handleMessagesUpsert({ type: 'notify', messages: [original()] });+ await flush();+ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope()] });+ await flush();++ expect(onMessageEdited).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'ORIG1', body: 'new text' }));+ release(null);+ await flush();+ });++ describe('leaves an encrypted edit unapplied when', () => {+ it.each([+ ['another member sealed it for the message', () => editEnvelope({ participant: reactor })],+ [+ 'its payload was sealed under another secret',+ () =>+ editEnvelope({+ sealed: seal('Message Edit', { target: 'ORIG1', author, modifier: author }, editPlain, Buffer.alloc(32, 1)),+ }),+ ],+ ['it is an edit of an event', () => editEnvelope({ type: 1 })],+ [+ 'it names a message that is not stored',+ () =>+ editEnvelope({+ target: 'GONE',+ sealed: seal('Message Edit', { target: 'GONE', author, modifier: author }, editPlain),+ }),+ ],+ [+ 'what it decrypts to names another message than the one it targets',+ () =>+ editEnvelope({+ sealed: seal(+ 'Message Edit',+ { target: 'ORIG1', author, modifier: author },+ {+ protocolMessage: { ...editPlain.protocolMessage, key: { id: 'SOMETHING_ELSE' } },+ },+ ),+ }),+ ],+ [+ 'what it decrypts to is not an edit',+ () =>+ editEnvelope({+ sealed: seal(+ 'Message Edit',+ { target: 'ORIG1', author, modifier: author },+ {+ protocolMessage: { ...editPlain.protocolMessage, type: 0 },+ },+ ),+ }),+ ],+ ['it targets a message of another chat', () => editEnvelope({ remoteJid: '[email protected]' })],+ ])('%s', async (_name, build) => {+ const { events, onMessageEdited, onMessage, recordMessageEdit } = setup();++ events.handleMessagesUpsert({ type: 'notify', messages: [build()] });+ await flush();++ expect(onMessageEdited).not.toHaveBeenCalled();+ expect(recordMessageEdit).not.toHaveBeenCalled();+ expect(onMessage).not.toHaveBeenCalled();+ });++ it('the message store cannot be read', async () => {+ const { events, onMessageEdited } = setup({ getStoredMessage: () => Promise.reject(new Error('store down')) });++ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope()] });+ await flush();++ expect(onMessageEdited).not.toHaveBeenCalled();+ });++ it('the target carries no secret', async () => {+ const { events, onMessageEdited } = setup({}, original({ message: { conversation: 'old text' } }));++ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope()] });+ await flush();++ expect(onMessageEdited).not.toHaveBeenCalled();+ });+ });++ it('reports a reaction a member sent encrypted, and its removal', async () => {+ const { events, onMessageReaction } = setup();++ events.handleMessagesUpsert({ type: 'notify', messages: [reactionEnvelope('👍')] });+ events.handleMessagesUpsert({ type: 'notify', messages: [reactionEnvelope('')] });+ await flush();++ expect(onMessageReaction).toHaveBeenCalledTimes(2);+ expect(onMessageReaction).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({ messageId: 'ORIG1', chatId: group, reaction: '👍', senderId: reactor }),+ );+ expect(onMessageReaction).toHaveBeenNthCalledWith(2, expect.objectContaining({ reaction: '', senderId: reactor }));+ });++ it('drops an encrypted reaction that names a message of another chat, as a plain one is', async () => {+ const { events, onMessageReaction } = setup();++ events.handleMessagesUpsert({+ type: 'notify',+ messages: [reactionEnvelope('👍', { remoteJid: '[email protected]' })],+ });+ await flush();++ expect(onMessageReaction).not.toHaveBeenCalled();+ });++ it('drops an encrypted reaction sealed under another secret', async () => {+ const { events, onMessageReaction } = setup();+ const sealed = seal(+ 'Enc Reaction',+ { target: 'ORIG1', author, modifier: reactor },+ { text: '👍' },+ Buffer.alloc(32, 9),+ );++ events.handleMessagesUpsert({ type: 'notify', messages: [reactionEnvelope('👍', { sealed })] });+ await flush();++ expect(onMessageReaction).not.toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex bc55912eb..ff17ecb24 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -35,6 +35,7 @@ import {} from './baileys-message-mapper';import { buildEditedMessage } from './message-mapper';import { toUnixSeconds } from './baileys-history';+import { bytesOf, decryptSecretPayload, messageSecretOf, senderForms, withoutDevice } from './baileys-secret-payload';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { CallNotFoundError } from '../../common/errors/call-not-found.error';import {@@ -300,10 +301,14 @@ export class BaileysEvents {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.+ * Inbound messages still being processed, by id, with the key and content of the latest delivery, so+ * an edit or delete of one waits for its store write, a delete can be checked against its target+ * meanwhile, and an encrypted edit finds the secret of an original that is not stored yet.*/- private readonly inboundInFlight = new Map<string, { key: WAMessageKey; done: Promise<void> }>();+ private readonly inboundInFlight = new Map<+ string,+ { key: WAMessageKey; message: WAMessage['message']; done: Promise<void> }+ >();/*** Ids of messages deleted for everyone, oldest first. The stored copy is emptied too, but that can@@ -447,6 +452,7 @@ export class BaileysEvents {// a change waits for every delivery in flight, not only the latest.const tracked = {key: msg.key,+ message: msg.message,done: Promise.all([this.inboundInFlight.get(id)?.done, processed]).then(() => undefined),};this.inboundInFlight.set(id, tracked);@@ -549,8 +555,18 @@ export class BaileysEvents {// type drives routing here AND mapMessage. The protocol and reaction branches below read the// normalized content too: a client wraps an edit in `editedMessage`, and `ephemeralMessage` can hold// a revoke or a reaction just as well, so the raw root does not always carry them.- const normalizedRoot = b.normalizeMessageContent(msg.message ?? undefined) ?? msg.message ?? undefined;- const contentType = b.getContentType(normalizedRoot);+ let normalizedRoot = b.normalizeMessageContent(msg.message ?? undefined) ?? msg.message ?? undefined;+ let contentType = b.getContentType(normalizedRoot);+ // A contact's edit, and a reaction in some chats, arrive encrypted under the secret of the message+ // they change. Read with the stored original's secret, they are handled below as the plain+ // protocol or reaction message they stand for; one that cannot be read stays dropped as non-content.+ if (contentType === 'secretEncryptedMessage' || contentType === 'encReactionMessage') {+ const revealed = await this.revealEncryptedModification(b, msg, normalizedRoot, contentType);+ if (revealed) {+ normalizedRoot = revealed.content;+ contentType = revealed.contentType;+ }+ }// --- protocolMessage REVOKE: don't emit onMessage ---if (contentType === 'protocolMessage') {@@ -803,6 +819,106 @@ export class BaileysEvents {}}+ /**+ * Read an edit or a reaction WhatsApp sent encrypted under the secret of the message it changes (see+ * baileys-secret-payload.ts). The secret comes from the target's stored copy, or from the copy still+ * being processed, and the pair of ids it is keyed by from that target's author and this message's+ * sender, so a payload only authenticates when the sender really is who the key says. The result is+ * the plain message to route as if it had arrived that way, and every guard of that path applies to+ * it: its author and chat are checked against the stored target afterwards. Anything that cannot be+ * read (an event edit, no stored target, a payload that does not authenticate) answers undefined and+ * stays dropped. Never throws.+ */+ private async revealEncryptedModification(+ b: typeof BaileysLib,+ msg: WAMessage,+ content: WAMessage['message'],+ contentType: string,+ ): Promise<+ { content: NonNullable<WAMessage['message']>; contentType: 'protocolMessage' | 'reactionMessage' } | undefined+ > {+ try {+ const isEdit = contentType === 'secretEncryptedMessage';+ const encrypted = isEdit ? content?.secretEncryptedMessage : content?.encReactionMessage;+ const targetKey = encrypted?.targetMessageKey;+ const targetId = targetKey?.id;+ const payload = bytesOf(encrypted?.encPayload);+ const iv = bytesOf(encrypted?.encIv);+ if (!encrypted || !targetKey || !targetId || !payload || !iv) return undefined;+ if (isEdit) {+ // An edit of an event arrives the same way and is not read here. The enum is a number on a live+ // message and its name on one read back from the store.+ const type = (encrypted as { secretEncType?: unknown }).secretEncType;+ const editType = b.proto.Message.SecretEncryptedMessage.SecretEncType.MESSAGE_EDIT;+ if (type !== editType && type !== 'MESSAGE_EDIT') return undefined;+ }+ const stored = await this.readStoredMessage(+ targetId,+ 'reading the message an encrypted edit or reaction targets',+ );+ const inFlight = this.inboundInFlight.get(targetId);+ const original = stored ?? (inFlight ? { key: inFlight.key, message: inFlight.message } : undefined);+ const secret = messageSecretOf(original?.message);+ if (!original || !secret) {+ this.host.logger.debug('Cannot read an encrypted edit or reaction: the message it targets is not stored', {+ action: 'baileys_encrypted_unreadable',+ msgId: msg.key.id ?? 'unknown',+ targetId,+ });+ return undefined;+ }+ const user = this.host.getSocketOrNull()?.user;+ const own = [user?.id, user?.lid].filter((jid): jid is string => !!jid).map(withoutDevice);+ // A lid is also tried as the phone number it maps to: a message written under phone addressing can+ // be edited under lid addressing, and the key names each party the way its own client did.+ const withPhone = (forms: string[]): string[] =>+ forms.flatMap(jid => {+ const neutral = jid.endsWith('@lid') ? this.host.toNeutralJid(jid) : '';+ return neutral.endsWith('@c.us') ? [jid, `${userPart(neutral)}@s.whatsapp.net`] : [jid];+ });+ const plaintext = decryptSecretPayload({+ kind: isEdit ? 'edit' : 'reaction',+ secret,+ iv,+ payload,+ targetId,+ targetAuthors: withPhone(senderForms(original.key, own)),+ modifiers: withPhone(senderForms(msg.key, own)),+ });+ if (!plaintext) {+ this.host.logger.debug('An encrypted edit or reaction did not authenticate against its target', {+ action: 'baileys_encrypted_unauthentic',+ msgId: msg.key.id ?? 'unknown',+ targetId,+ });+ return undefined;+ }+ if (isEdit) {+ const protocolMessage = b.proto.Message.decode(plaintext).protocolMessage;+ // The decrypted message must name the target the secret was taken from, and be an edit.+ if (+ protocolMessage?.type !== b.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT ||+ protocolMessage.key?.id !== targetId+ ) {+ return undefined;+ }+ return { content: { protocolMessage }, contentType: 'protocolMessage' };+ }+ const reaction = b.proto.Message.ReactionMessage.decode(plaintext);+ return {+ content: { reactionMessage: { key: targetKey, text: reaction.text ?? '' } },+ contentType: 'reactionMessage',+ };+ } catch (error) {+ this.host.logger.debug('Could not read an encrypted edit or reaction', {+ action: 'baileys_encrypted_failed',+ msgId: msg.key.id ?? 'unknown',+ error: error instanceof Error ? error.message : String(error),+ });+ return undefined;+ }+ }+/*** 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 Baileysdiff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.tsindex 96e98d3f3..c2382a985 100644--- a/src/engine/adapters/baileys-message-mapper.ts+++ b/src/engine/adapters/baileys-message-mapper.ts@@ -10,8 +10,10 @@ import { chatKind } from '../identity/wa-id';/*** Content types that change or annotate another message and carry nothing of their own: a poll vote,* an in-chat pin, a keep-in-chat toggle, an album header (its photos arrive as their own messages), an- * encrypted reaction, an event RSVP, an encrypted edit (an event edit) and an encrypted comment. Mapped,- * they would surface as a bodyless `unknown` message, so the live and history paths drop them instead.+ * encrypted reaction, an event RSVP, an encrypted edit and an encrypted comment. Mapped, they would+ * surface as a bodyless `unknown` message, so the live and history paths drop them instead. The live+ * path first reads an encrypted edit or reaction it holds the secret for (baileys-secret-payload.ts),+ * and drops only what it cannot read.*/export const BAILEYS_NON_CONTENT_TYPES: ReadonlySet<string> = new Set(['pollUpdateMessage',diff --git a/src/engine/adapters/baileys-secret-payload.spec.ts b/src/engine/adapters/baileys-secret-payload.spec.tsnew file mode 100644index 000000000..2f1d61583--- /dev/null+++ b/src/engine/adapters/baileys-secret-payload.spec.ts@@ -0,0 +1,245 @@+import { createCipheriv, createHmac, hkdfSync } from 'node:crypto';+import { bytesOf, decryptSecretPayload, messageSecretOf, senderForms, withoutDevice } from './baileys-secret-payload';++/**+ * The key construction the library itself uses to decrypt a poll vote or an event RSVP (Utils/+ * process-message: HMAC over the secret with a zero key, then HMAC of `info || 0x01` under that), which+ * is HKDF-SHA256 with a zero salt. Written out here, not imported, so the module under test is held to+ * the library's own formula and not to a copy of itself.+ */+function referenceKey(secret: Uint8Array, info: string): Buffer {+ const prk = createHmac('sha256', Buffer.alloc(32)).update(secret).digest();+ return createHmac('sha256', prk)+ .update(Buffer.concat([Buffer.from(info), Buffer.from([1])]))+ .digest();+}++function seal(+ label: string,+ secret: Uint8Array,+ ids: { target: string; author: string; modifier: string },+ plaintext: Buffer,+ iv = Buffer.alloc(12, 9),+): { payload: Buffer; iv: Buffer } {+ const cipher = createCipheriv(+ 'aes-256-gcm',+ referenceKey(secret, `${ids.target}${ids.author}${ids.modifier}${label}`),+ iv,+ );+ return { payload: Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]), iv };+}++const secret = Buffer.alloc(32, 0x42);+const lid = '39900313301142@lid';+const phone = '[email protected]';+const ids = { target: '3EB0A1B2C3D4E5F60718', author: lid, modifier: lid };++describe('decryptSecretPayload', () => {+ it('derives the same key as the library does for a poll vote or an RSVP', () => {+ const info = 'MSGID' + lid + lid + 'Poll Vote';+ expect(Buffer.from(hkdfSync('sha256', secret, Buffer.alloc(32), Buffer.from(info), 32))).toEqual(+ referenceKey(secret, info),+ );+ });++ it.each([+ ['edit', 'Message Edit'],+ ['reaction', 'Enc Reaction'],+ ] as const)('reads a %s sealed under its label', (kind, label) => {+ const { payload, iv } = seal(label, secret, ids, Buffer.from('the plaintext'));++ const plain = decryptSecretPayload({+ kind,+ secret,+ iv,+ payload,+ targetId: ids.target,+ targetAuthors: [lid],+ modifiers: [lid],+ });++ expect(plain?.toString()).toBe('the plaintext');+ });++ it('finds the pair of ids a payload was sealed under among the forms of each party', () => {+ // Written under phone addressing by the author, edited by a sender the key names by lid.+ const { payload, iv } = seal('Message Edit', secret, { ...ids, author: phone, modifier: lid }, Buffer.from('x'));++ const plain = decryptSecretPayload({+ kind: 'edit',+ secret,+ iv,+ payload,+ targetId: ids.target,+ targetAuthors: [lid, phone],+ modifiers: ['999@lid', lid],+ });++ expect(plain?.toString()).toBe('x');+ });++ describe('answers undefined, and never throws, for', () => {+ const valid = seal('Message Edit', secret, ids, Buffer.from('payload'));+ const base = {+ kind: 'edit' as const,+ secret,+ iv: valid.iv,+ payload: valid.payload,+ targetId: ids.target,+ targetAuthors: [lid],+ modifiers: [lid],+ };++ it('a reaction label used on an edit', () => {+ expect(decryptSecretPayload({ ...base, kind: 'reaction' })).toBeUndefined();+ });++ it('a different sender of the edit than the one it was sealed for', () => {+ expect(decryptSecretPayload({ ...base, modifiers: ['111@lid'] })).toBeUndefined();+ });++ it('a different author of the target than the one it was sealed for', () => {+ expect(decryptSecretPayload({ ...base, targetAuthors: ['111@lid'] })).toBeUndefined();+ });++ it('another target id', () => {+ expect(decryptSecretPayload({ ...base, targetId: 'OTHER' })).toBeUndefined();+ });++ it('another secret', () => {+ expect(decryptSecretPayload({ ...base, secret: Buffer.alloc(32, 1) })).toBeUndefined();+ });++ it('an altered payload', () => {+ const altered = Buffer.from(valid.payload);+ altered[0] ^= 0xff;+ expect(decryptSecretPayload({ ...base, payload: altered })).toBeUndefined();+ });++ it('an altered tag', () => {+ const altered = Buffer.from(valid.payload);+ altered[altered.length - 1] ^= 0x01;+ expect(decryptSecretPayload({ ...base, payload: altered })).toBeUndefined();+ });++ it.each([+ ['a secret that is not 32 bytes', { secret: Buffer.alloc(16, 0x42) }],+ ['an iv that is not 12 bytes', { iv: Buffer.alloc(16, 9) }],+ ['a payload of only a tag', { payload: Buffer.alloc(16) }],+ ['a payload past the ceiling', { payload: Buffer.alloc(256 * 1024 + 1) }],+ ['no target id', { targetId: '' }],+ ['no candidate ids', { targetAuthors: [], modifiers: [] }],+ ])('%s', (_name, override) => {+ expect(decryptSecretPayload({ ...base, ...override })).toBeUndefined();+ });+ });++ it('tries only a few forms of each party, so a crafted key cannot multiply the work', () => {+ const { payload, iv } = seal('Message Edit', secret, ids, Buffer.from('x'));+ const many = Array.from({ length: 50 }, (_, i) => `${i}@lid`);++ // The sealing pair sits past the fourth form of the sender, so it is never tried.+ expect(+ decryptSecretPayload({+ kind: 'edit',+ secret,+ iv,+ payload,+ targetId: ids.target,+ targetAuthors: [lid],+ modifiers: [...many, lid],+ }),+ ).toBeUndefined();+ });+});++describe('bytesOf', () => {+ const bytes = Buffer.from([1, 2, 3, 250]);++ it.each([+ ['a Uint8Array', new Uint8Array(bytes)],+ ['a Buffer', bytes],+ ['base64 text', bytes.toString('base64')],+ ['a serialized Buffer with a byte array', { type: 'Buffer', data: [...bytes] }],+ ['a serialized Buffer with base64 text', { type: 'Buffer', data: bytes.toString('base64') }],+ ])('reads %s', (_name, value) => {+ expect(bytesOf(value)).toEqual(bytes);+ });++ it.each([[undefined], [null], [''], [42], [{}], [{ type: 'Buffer' }]])('answers undefined for %p', value => {+ expect(bytesOf(value)).toBeUndefined();+ });+});++describe('messageSecretOf', () => {+ const secretText = Buffer.alloc(32, 7).toString('base64');++ it('reads the secret at the top level, in either shape', () => {+ expect(messageSecretOf({ conversation: 'x', messageContextInfo: { messageSecret: secretText } })).toEqual(+ Buffer.alloc(32, 7),+ );+ expect(messageSecretOf({ messageContextInfo: { messageSecret: new Uint8Array(32).fill(7) } })).toEqual(+ Buffer.alloc(32, 7),+ );+ });++ it('finds it inside the wrappers a disappearing or view-once message adds', () => {+ const inner = { messageContextInfo: { messageSecret: secretText }, imageMessage: {} };+ expect(messageSecretOf({ ephemeralMessage: { message: { viewOnceMessageV2: { message: inner } } } })).toEqual(+ Buffer.alloc(32, 7),+ );+ });++ it.each([[undefined], [null], [{ conversation: 'x' }], [{ messageContextInfo: {} }], ['text']])(+ 'answers undefined for %p',+ message => {+ expect(messageSecretOf(message)).toBeUndefined();+ },+ );++ it('does not loop on a wrapper that holds itself', () => {+ const looped: Record<string, unknown> = {};+ looped.ephemeralMessage = { message: looped };++ expect(messageSecretOf(looped)).toBeUndefined();+ });+});++describe('senderForms', () => {+ const own = ['[email protected]', '5550001@lid'];++ it("names the account's own ids for a message it sent", () => {+ expect(senderForms({ remoteJid: '[email protected]', fromMe: true, participant: 'ignored@lid' }, own)).toEqual(own);+ });++ it("takes a group message's sender from its participant and the twin of it", () => {+ expect(senderForms({ remoteJid: '[email protected]', participant: lid, participantAlt: phone, fromMe: false }, own)).toEqual(+ [lid, phone],+ );+ });++ it('takes a 1:1 message from the chat when the participant is empty, as a live key leaves it', () => {+ expect(senderForms({ remoteJid: lid, remoteJidAlt: phone, participant: '', fromMe: false }, own)).toEqual([+ lid,+ phone,+ ]);+ });++ it('drops the device suffix, repeats and ids that name a group or a list', () => {+ expect(+ senderForms({ remoteJid: '[email protected]', participant: '39900313301142:7@lid', participantAlt: lid }, own),+ ).toEqual([lid]);+ expect(senderForms({ remoteJid: '[email protected]', fromMe: false }, own)).toEqual([]);+ expect(senderForms({ remoteJid: 'status@broadcast', fromMe: false }, own)).toEqual([]);+ });+});++describe('withoutDevice', () => {+ it.each([+ ['6281234567890:[email protected]', '[email protected]'],+ ['39900313301142:3@lid', '39900313301142@lid'],+ ['39900313301142@lid', '39900313301142@lid'],+ ])('%s -> %s', (from, to) => {+ expect(withoutDevice(from)).toBe(to);+ });+});diff --git a/src/engine/adapters/baileys-secret-payload.ts b/src/engine/adapters/baileys-secret-payload.tsnew file mode 100644index 000000000..d479f361a--- /dev/null+++ b/src/engine/adapters/baileys-secret-payload.ts@@ -0,0 +1,139 @@+import { createDecipheriv, hkdfSync } from 'node:crypto';++/**+ * WhatsApp sends a contact's message edit, and a reaction in some chats, encrypted under the secret the+ * original message carries (`messageContextInfo.messageSecret`) instead of as the plain protocol or+ * reaction message the library understands. The library decrypts poll votes and event RSVPs that way+ * and nothing else, so these two reach the adapter as an opaque `secretEncryptedMessage` and+ * `encReactionMessage`.+ *+ * The key is HKDF-SHA256 over the secret with an all-zero salt and+ * `<target id><target author><modifier><label>` as the info, and the payload is AES-256-GCM with no+ * additional data: the construction the library applies to a poll vote or an RSVP, under another label.+ * Edit and reaction payloads decrypt to a `Message` holding the protocol message and a+ * `ReactionMessage` respectively.+ */+export type SecretPayloadKind = 'edit' | 'reaction';++const LABELS: Record<SecretPayloadKind, string> = { edit: 'Message Edit', reaction: 'Enc Reaction' };+const SECRET_BYTES = 32;+const IV_BYTES = 12;+const TAG_BYTES = 16;+/** A message holds at most a text of about 64 KiB, and the largest sample payloads are a few KiB. */+const MAX_PAYLOAD_BYTES = 256 * 1024;+/** Ids one party can be written as (phone and lid, with the account's own forms); a few at most. */+const MAX_FORMS = 4;++export interface SecretPayloadInput {+ kind: SecretPayloadKind;+ /** The `messageSecret` of the message being changed. */+ secret: Uint8Array;+ iv: Uint8Array;+ /** Ciphertext followed by its 16-byte authentication tag. */+ payload: Uint8Array;+ /** Id of the message being changed. */+ targetId: string;+ /** The forms (`user@server`, no device) the target's author may be written as. */+ targetAuthors: readonly string[];+ /** The forms the sender of the edit or reaction may be written as. */+ modifiers: readonly string[];+}++/**+ * The plaintext of an edit or reaction payload, or undefined when no pair of the candidate ids+ * authenticates it. Never throws: a payload that is not for this message, or has been altered, is+ * simply not readable.+ */+export function decryptSecretPayload(input: SecretPayloadInput): Buffer | undefined {+ const { kind, secret, iv, payload, targetId } = input;+ if (!targetId || secret.length !== SECRET_BYTES || iv.length !== IV_BYTES) return undefined;+ if (payload.length <= TAG_BYTES || payload.length > MAX_PAYLOAD_BYTES) return undefined;+ const authors = [...new Set(input.targetAuthors)].slice(0, MAX_FORMS);+ const modifiers = [...new Set(input.modifiers)].slice(0, MAX_FORMS);+ const salt = Buffer.alloc(32);+ const tag = Buffer.from(payload.subarray(payload.length - TAG_BYTES));+ const body = Buffer.from(payload.subarray(0, payload.length - TAG_BYTES));+ for (const author of authors) {+ for (const modifier of modifiers) {+ const info = Buffer.from(`${targetId}${author}${modifier}${LABELS[kind]}`);+ try {+ const key = Buffer.from(hkdfSync('sha256', secret, salt, info, 32));+ const decipher = createDecipheriv('aes-256-gcm', key, iv);+ decipher.setAuthTag(tag);+ return Buffer.concat([decipher.update(body), decipher.final()]);+ } catch {+ // Not this pair of ids: the authentication tag did not verify.+ }+ }+ }+ return undefined;+}++/**+ * Bytes of a proto field in either shape the adapter meets: a live message carries a `Uint8Array`,+ * and a message read back from the store carries its base64 text (or a `{ type: 'Buffer', data }`+ * pair from an older row).+ */+export function bytesOf(value: unknown): Buffer | undefined {+ if (value instanceof Uint8Array) return Buffer.from(value);+ if (typeof value === 'string') return value ? Buffer.from(value, 'base64') : undefined;+ if (value && typeof value === 'object') {+ const { type, data } = value as { type?: unknown; data?: unknown };+ if (type === 'Buffer') {+ if (Array.isArray(data)) return Buffer.from(data as number[]);+ if (typeof data === 'string') return Buffer.from(data, 'base64');+ }+ }+ return undefined;+}++const WRAPPERS = [+ 'ephemeralMessage',+ 'viewOnceMessage',+ 'viewOnceMessageV2',+ 'viewOnceMessageV2Extension',+ 'documentWithCaptionMessage',+ 'editedMessage',+] as const;++/** The secret a message carries, at the top level or inside the wrappers a disappearing chat adds. */+export function messageSecretOf(message: unknown): Buffer | undefined {+ let current = message as Record<string, unknown> | null | undefined;+ for (let depth = 0; current && typeof current === 'object' && depth < 5; depth++) {+ const context = current.messageContextInfo as { messageSecret?: unknown } | null | undefined;+ const secret = bytesOf(context?.messageSecret);+ if (secret) return secret;+ const wrapper = WRAPPERS.find(name => current?.[name]);+ current = wrapper ? (current[wrapper] as { message?: Record<string, unknown> | null }).message : undefined;+ }+ return undefined;+}++/** `user@server` with any device suffix (`:12`) removed: the form a message secret is keyed by. */+export function withoutDevice(jid: string): string {+ return jid.replace(/:\d+(?=@)/, '');+}++/**+ * The forms a message's sender may be written as in its key: the account's own ids for a message it+ * sent, else the group participant (and its phone or lid twin), else the 1:1 chat and its twin.+ */+export function senderForms(+ key: {+ remoteJid?: string | null;+ remoteJidAlt?: string | null;+ participant?: string | null;+ participantAlt?: string | null;+ fromMe?: boolean | null;+ },+ own: readonly string[],+): string[] {+ const forms =+ key.fromMe === true+ ? [...own]+ : key.participant+ ? [key.participant, key.participantAlt]+ : [key.remoteJid, key.remoteJidAlt];+ const named = forms.filter((jid): jid is string => !!jid && !jid.endsWith('@g.us') && !jid.endsWith('@broadcast'));+ return [...new Set(named.map(withoutDevice))].slice(0, MAX_FORMS);+}