Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwjs): backport upstream #201832 to restore id._serialized access (#747)
Yudhi Armyndharis3e3c167387ec
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 46f277f35..3539f9cd6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **Inbound media download, message ids, acks, and reply quoting restored**+ (whatsapp-web.js `id._serialized` → `id.$1` rename). WhatsApp Web build 2.3000.x+ (rolled out ~2026-07-14) renamed the internal serialized message-id property+ from `id._serialized` to `id.$1`, which broke whatsapp-web.js 1.34.7's+ `downloadMedia()`, message-id extraction, ack tracking, and quoted-message+ resolution for every bot at once. The production Docker image now backports+ upstream fix [#201832](https://github.com/wwebjs/whatsapp-web.js/pull/201832)+ (`Base._normalizeId`) into the installed dependency at build time via+ `scripts/patch-wwebjs-201832.js`. The patcher applies the real upstream diff+ (with a loud-fail guard against version skew) and auto-disables the moment a+ future whatsapp-web.js release ships the fix, so it is a stopgap, not a fork.+ Fixes #747.++- **Source installs get the whatsapp-web.js backport too, not just the Docker image.**+ `npm install` now applies it from `postinstall`, so the local-development setup in+ the README is no longer stuck with broken media downloads. It is best-effort+ there: a machine without a `patch` binary (Windows outside WSL) or a+ Baileys-only setup gets a warning rather than a failed install. The image build+ still treats the same failure as fatal.++- **Reactions stay attributable on the renamed-id builds too.** `Reaction` assigns+ its keys straight through, so it is the one structure upstream's normalization+ doesn't reach; the adapter now reads the renamed field directly and falls back to+ the empty no-id sentinel instead of passing `undefined` on.++- **A reaction with no message id no longer updates an arbitrary message.**+ `applyReaction` looked the message up by an id that could be `undefined`, and+ TypeORM drops an undefined condition from the where-clause rather than matching+ nothing — so the lookup found an unrelated row and emitted its reactions under+ the incoming event. The id is now checked before the query. Latent since+ reactions were added; only reachable when an engine can't resolve the id.+- **Engine start timeouts now return a diagnostic 504 instead of a bare 500.** Two`POST /api/sessions/:id/start` failure modes previously escaped to NestJS's default handler as ameaningless `500 Internal Server Error`: (1) the **auth-timeout** — whatsapp-web.js throws thediff --git a/Dockerfile b/Dockerfileindex a7091e356..98f35606b 100644--- a/Dockerfile+++ b/Dockerfile@@ -72,6 +72,7 @@ RUN apt-get update && apt-get install -y \xdg-utils \dumb-init \gosu \+ patch \curl \procps \&& rm -rf /var/lib/apt/lists/*@@ -87,8 +88,13 @@ WORKDIR /app# Copy package filesCOPY package*.json ./-# Install production dependencies only-RUN npm ci --omit=dev && npm cache clean --force+# Backport upstream whatsapp-web.js#201832 (id._serialized -> id.$1 normalization,+# broken by WA Web 2.3000.x ~2026-07-14) into the installed dep at build time.+# The patcher self-disables once whatsapp-web.js ships the fix upstream.+COPY scripts/patch-wwebjs-201832.js scripts/wwebjs-201832.patch ./scripts/++# Install production dependencies only, then apply the backport patcher (needs `patch`).+RUN npm ci --omit=dev && node scripts/patch-wwebjs-201832.js && npm cache clean --force# amd64: download Chrome for Testing via Puppeteer and symlink it.# arm64: use Debian's chromium installed above (CfT has no linux-arm64 build).diff --git a/package.json b/package.jsonindex 85c09eaf5..b8e92337a 100644--- a/package.json+++ b/package.json@@ -25,7 +25,7 @@"dashboard:ci": "cd dashboard && npm ci","dashboard:dev": "cd dashboard && npm run dev","dashboard:build": "cd dashboard && npm run build",- "postinstall": "node -e \"if (require('fs').existsSync('dashboard')) require('child_process').spawnSync('npm run dashboard:install', { stdio: 'inherit', shell: true });\"",+ "postinstall": "node -e \"const fs=require('fs'),cp=require('child_process'); if (fs.existsSync('dashboard')) cp.spawnSync('npm run dashboard:install', { stdio: 'inherit', shell: true }); if (fs.existsSync('scripts/patch-wwebjs-201832.js')) cp.spawnSync(process.execPath, ['scripts/patch-wwebjs-201832.js', '--best-effort'], { stdio: 'inherit' });\"","check:versions": "node scripts/check-doc-versions.mjs","openapi:export": "ts-node scripts/export-openapi.ts openapi.json","openapi:check": "ts-node scripts/export-openapi.ts /tmp/openapi.generated.json && diff -u openapi.json /tmp/openapi.generated.json",diff --git a/scripts/patch-wwebjs-201832.js b/scripts/patch-wwebjs-201832.jsnew file mode 100644index 000000000..0c805e01b--- /dev/null+++ b/scripts/patch-wwebjs-201832.js@@ -0,0 +1,209 @@+/**+ * Build-time backport of upstream whatsapp-web.js#201832 into the installed+ * whatsapp-web.js. Run after `npm ci` in the Docker production stage.+ *+ * Background: WhatsApp Web build 2.3000.x (rolled out ~2026-07-14) renamed the+ * serialized message-id property `id._serialized` to `id.$1` (a minifier-mangled+ * name). whatsapp-web.js 1.34.7 (what OpenWA pins) reads `_serialized` in the+ * Message constructor and ~40 downstream sites, so message ids, acks, quoted-+ * message resolution, and media downloads all break. Upstream fix #201832 adds a+ * `Base._normalizeId()` helper and reapplies it across the model constructors.+ * This script backports that fix into node_modules at image build time.+ *+ * Self-removing: it no-ops once the installed whatsapp-web.js already defines+ * `Base._normalizeId` (i.e. upstream shipped #201832 and OpenWA bumped its dep).+ *+ * Why `patch` and not `git apply`: a bare `git -C node_modules/whatsapp-web.js+ * apply` silently no-ops ("Skipped / 0 files changed") because the parent repo's+ * .git interferes with the diff's blob-SHA index lines. `patch` has no repo+ * discovery and applies cleanly.+ *+ * Known reject on 1.34.7: Contact.js hunk #2 targets a LID-aware block()/+ * unblock() path that does not exist in 1.34.7 (the PR's base is ahead there).+ * It is harmless — the rename cannot break absent code — so it is intentionally+ * dropped. Any OTHER reject means the installed shape drifted from the backport's+ * expected base; we abort the build loudly rather than ship a silently partial+ * patch.+ */+'use strict';++const fs = require('fs');+const path = require('path');+const { execFileSync } = require('child_process');++const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');+const DEFAULT_PATCH = path.join(__dirname, 'wwebjs-201832.patch');+// The single hunk expected to reject on 1.34.7 (targets absent LID-block code).+const EXPECTED_REJECTS = new Set(['src/structures/Contact.js.rej']);++// Every normalization site the backport must land, so a hunk that fails to apply can never pass+// unnoticed. `patch` always writes a .rej for a hunk it couldn't place, but a hunk placed at the+// WRONG offset would be silent — these assertions are what close that gap.+const REQUIRED_SITES = [+ ['src/structures/Base.js', /static _normalizeId\(id\)/],+ ['src/structures/Message.js', /this\.id = Base\._normalizeId\(data\.id\)/],+ ['src/structures/Chat.js', /this\.id = Base\._normalizeId\(data\.id\)/],+ ['src/structures/Contact.js', /this\.id = Base\._normalizeId\(data\.id\)/],+ ['src/structures/Channel.js', /this\.id = Base\._normalizeId\(data\.id\)/],+ ['src/structures/Broadcast.js', /this\.id = Base\._normalizeId\(data\.id\)/],+ ['src/structures/GroupNotification.js', /this\.id = Base\._normalizeId\(data\.id\)/],+ ['src/structures/ClientInfo.js', /this\.wid = Base\._normalizeId\(data\.wid\)/],+];++/** Artifacts `patch` can leave behind. `.~N~` are GNU's backup-if-mismatch copies of pre-patch source. */+const ARTIFACT_RE = /(\.rej|\.orig|~)$/;++/** True once `rel`'s REQUIRED_SITES marker is present in the installed tree. */+function siteLanded(wwjsDir, rel) {+ const marker = REQUIRED_SITES.find(([r]) => r === rel)[1];+ return marker.test(fs.readFileSync(path.join(wwjsDir, rel), 'utf8'));+}++/**+ * Flag an error raised once `patch` has started writing. `--best-effort` degrades on a pre-flight failure+ * (no `patch` binary — nothing ran, tree untouched) but must never swallow one of these: `patch` applies+ * hunks as it goes, so failing mid-apply leaves whatsapp-web.js half-patched — which the self-disable+ * check above reads as healthy, latching the broken tree in on every later run.+ */+function partialTree(err) {+ err.leftPartialTree = true;+ return err;+}++function findArtifacts(root, dir = root) {+ const out = [];+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ if (entry.name === 'node_modules' || entry.name === '.git') continue;+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ out.push(...findArtifacts(root, full));+ } else if (ARTIFACT_RE.test(entry.name)) {+ out.push(path.relative(root, full));+ }+ }+ return out;+}++function applyBackport(wwjsDir = DEFAULT_WWJS, patchFile = DEFAULT_PATCH) {+ const baseJs = path.join(wwjsDir, 'src', 'structures', 'Base.js');+ if (!fs.existsSync(baseJs)) {+ throw new Error(`whatsapp-web.js not found at ${wwjsDir}`);+ }+ // Self-removal: once the installed whatsapp-web.js normalizes ids itself, this backport steps+ // aside. Detect on the id-normalizing READ in the Message constructor rather than on Base.js's+ // helper: Message.js is the load-bearing site (OpenWA reads `msg.id._serialized` in ~40 places),+ // and keying off Base.js alone would treat a half-patched tree — helper present, constructor not —+ // as "already fixed" and ship it. Matched loosely (`Base._normalizeId(` OR an inline `$1` fallback)+ // so a future upstream release that fixes this differently still stands the patcher down.+ const msgJs = path.join(wwjsDir, 'src', 'structures', 'Message.js');+ const msgSrc = fs.readFileSync(msgJs, 'utf8');+ if (/_normalizeId\(|\.\$1/.test(msgSrc)) {+ // Message.js normalizing is necessary but NOT sufficient to stand down. `patch` writes as it goes and+ // Message.js is patched early, so a run that died part-way through lands here too — and skipping would+ // latch that half-patched tree in permanently, because every later run takes this same branch and never+ // reaches the assertions below. An upstream release that fixes this lands every site at once; a crashed+ // run does not. Proving the tree is whole is what tells the two apart.+ const missing = REQUIRED_SITES.filter(([rel]) => !siteLanded(wwjsDir, rel));+ if (missing.length) {+ throw new Error(+ 'whatsapp-web.js is PARTIALLY patched — Message.js normalizes ids but ' ++ `${missing.map(([rel]) => rel).join(', ')} did not land. A previous run left the tree half-patched; ` ++ 'it cannot repair itself. Reinstall the dependency (`rm -rf node_modules/whatsapp-web.js && npm ci`) ' ++ 'and re-run. If the installed version genuinely ships its own fix, drop this backport instead.',+ );+ }+ return { skipped: true, reason: 'installed whatsapp-web.js already normalizes message ids' };+ }++ // Apply the real upstream diff via `patch` (no git-discovery interference).+ // Flags, each load-bearing:+ // --no-backup-if-mismatch GNU patch defaults to writing `<file>.~1~` backups for every file+ // whose hunks needed an offset or rejected — 328K of pre-patch source+ // that would otherwise ship in the image. (`-V none` does NOT do this;+ // it only picks the backup *style*.) BSD patch has no such default,+ // which is why this is invisible on macOS and only bites in Debian CI.+ // -F0 No fuzz: a hunk must match exactly, never slide onto a similar-looking+ // neighbouring block. Fuzzed application would be silent — invisible to+ // both the reject-set check and the assertions below.+ // --ignore-whitespace Absorbs a trivial context-indent mismatch in GroupChat.js.+ // -f -N Never prompt; `-f` also forces already-applied hunks to reject loudly+ // rather than be skipped silently.+ // With these, GNU and BSD patch produce byte-identical trees, so a local macOS run faithfully+ // reproduces the Debian image build.+ try {+ execFileSync(+ 'patch',+ ['-p1', '-d', wwjsDir, '--no-backup-if-mismatch', '-N', '-f', '-F0', '--ignore-whitespace', '-i', patchFile],+ { stdio: 'pipe' },+ );+ } catch (e) {+ // `patch` exits 1 when hunks reject — expected here (Contact.js hunk #2), and the reject set is+ // verified below. Anything else (2 = serious trouble, ENOENT = `patch` not installed) is a real+ // failure: rethrow it rather than let the assertions below misreport it as version skew.+ if (e.status !== 1) {+ const detail = e.stderr ? String(e.stderr).trim() : e.message;+ const err = new Error(`\`patch\` failed (${e.code ?? `exit ${e.status}`}): ${detail}`);+ // ENOENT means `patch` never executed, so the tree is untouched and degrading is still safe.+ throw e.code === 'ENOENT' ? err : partialTree(err);+ }+ }++ const artifacts = findArtifacts(wwjsDir);+ const unexpected = artifacts.filter(a => !EXPECTED_REJECTS.has(a));+ if (unexpected.length) {+ throw partialTree(+ new Error(+ `unexpected patch artifact(s) — version skew vs the backport base: ${unexpected.join(', ')}. ` ++ 'Re-evaluate scripts/wwebjs-201832.patch against the installed whatsapp-web.js.',+ ),+ );+ }++ // Verify EVERY normalization site landed — a hunk placed at a wrong offset leaves no .rej.+ for (const [rel, marker] of REQUIRED_SITES) {+ if (!siteLanded(wwjsDir, rel)) {+ throw partialTree(+ new Error(`${rel} was not patched (missing ${marker}) — aborting rather than ship a partial backport.`),+ );+ }+ }++ // Clean up the expected .rej (Contact.js hunk #2 intentionally dropped).+ for (const a of artifacts) fs.unlinkSync(path.join(wwjsDir, a));++ return {+ skipped: false,+ note: 'applied (Contact.js LID-block hunk intentionally skipped — absent in 1.34.7)',+ };+}++if (require.main === module) {+ // `--best-effort` (used by the postinstall hook) warns instead of failing. The image build runs+ // without it: there, an unpatched whatsapp-web.js must abort the build rather than ship broken.+ // Locally the same failure is only a degraded dev install — `patch` may not exist at all (Windows+ // without WSL), and a Baileys-only user has no reason to care — so breaking `npm install` over it+ // would be worse than the bug.+ const bestEffort = process.argv.includes('--best-effort');+ const target = process.argv.find(a => !a.startsWith('--') && a !== process.argv[0] && a !== process.argv[1]);+ try {+ const res = applyBackport(target || DEFAULT_WWJS);+ console.log(`patch-wwebjs-201832: ${res.skipped ? `skipped — ${res.reason}` : res.note}`);+ } catch (e) {+ // `--best-effort` degrades only while the tree is still pristine — an unpatched whatsapp-web.js is a+ // known-degraded dev install, which is the trade this flag exists to make. A HALF-patched one is not+ // that trade: it is undetectable afterwards (the self-disable check reads it as healthy) and would+ // ship silently. Fail on it regardless of the flag.+ if (bestEffort && !e.leftPartialTree) {+ console.warn(+ `patch-wwebjs-201832: skipped — ${e.message}\n` ++ ' Inbound media/message ids may be broken on current WhatsApp Web builds (#747).\n' ++ ' The published Docker image applies this automatically; see scripts/patch-wwebjs-201832.js.',+ );+ return;+ }+ console.error(`patch-wwebjs-201832: ${e.message}`);+ process.exit(1);+ }+}++module.exports = { applyBackport, DEFAULT_WWJS, DEFAULT_PATCH, EXPECTED_REJECTS };diff --git a/scripts/wwebjs-201832.patch b/scripts/wwebjs-201832.patchnew file mode 100644index 000000000..1f842c4cf--- /dev/null+++ b/scripts/wwebjs-201832.patch@@ -0,0 +1,513 @@+diff --git a/index.d.ts b/index.d.ts+index 8127770492b..b155be8391d 100644+--- a/index.d.ts++++ b/index.d.ts+@@ -212,10 +212,7 @@ declare namespace WAWebJS {+ ): Promise<Message>;++ /** Send a reaction to a specific messageId */+- sendReaction(+- messageId: string,+- reaction: string,+- ): Promise<void>;++ sendReaction(messageId: string, reaction: string): Promise<void>;++ /** Sends a channel admin invitation to a user, allowing them to become an admin of the channel */+ sendChannelAdminInvite(+diff --git a/src/Client.js b/src/Client.js+index a122a8f336b..62de5395407 100644+--- a/src/Client.js++++ b/src/Client.js+@@ -1234,7 +1234,8 @@ class Client extends EventEmitter {+ const parentMsgKey = reaction.reactionParentKey;+ const timestamp = reaction.reactionTimestamp / 1000;+ const sender = reaction.author ?? reaction.from;+- const senderUserJid = sender._serialized;++ const senderUserJid =++ sender._serialized || sender.$1;++ return {+ ...reaction,+@@ -1262,14 +1263,15 @@ class Client extends EventEmitter {+ const parentMsgKey = vote.pollUpdateParentKey;+ const timestamp = vote.t / 1000;+ const sender = vote.author ?? vote.from;+- const senderUserJid = sender._serialized;++ const senderUserJid =++ sender._serialized || sender.$1;++ let parentMessage = Msg.get(+- parentMsgKey._serialized,++ parentMsgKey._serialized || parentMsgKey.$1,+ );+ if (!parentMessage) {+ const fetched = await Msg.getMessagesById([+- parentMsgKey._serialized,++ parentMsgKey._serialized || parentMsgKey.$1,+ ]);+ parentMessage = fetched?.messages?.[0] || null;+ }+@@ -1898,7 +1900,7 @@ class Client extends EventEmitter {+ .joinGroupViaInvite(inviteCode);+ }, inviteCode);++- return res.gid._serialized;++ return res.gid._serialized || res.gid.$1;+ }++ /**+@@ -2442,7 +2444,8 @@ class Client extends EventEmitter {+ (participant.wid = window+ .require('WAWebApiContact')+ .getPhoneNumber(participant.wid));+- const participantId = participant.wid._serialized;++ const participantId =++ participant.wid._serialized || participant.wid.$1;+ const statusCode = participant.error || 200;++ if (autoSendInviteV4 && statusCode === 403) {+@@ -2458,7 +2461,8 @@ class Client extends EventEmitter {+ (await window+ .require('WAWebCollections')+ .Chat.find(participant.wid)),+- createGroupResult.wid._serialized,++ createGroupResult.wid._serialized ||++ createGroupResult.wid.$1,+ createGroupResult.subject,+ participant.invite_code,+ participant.invite_code_exp,+@@ -2932,7 +2936,7 @@ class Client extends EventEmitter {+ let chatIds = window+ .require('WAWebCollections')+ .Blocklist.getModelsArray()+- .map((a) => a.id._serialized);++ .map((a) => a.id._serialized || a.id.$1);+ return Promise.all(+ chatIds.map((id) => window.WWebJS.getContact(id)),+ );+@@ -2993,7 +2997,9 @@ class Client extends EventEmitter {+ );+ const chats = window+ .require('WAWebCollections')+- .Chat.filter((e) => chatIds.includes(e.id._serialized));++ .Chat.filter((e) =>++ chatIds.includes(e.id._serialized || e.id.$1),++ );++ let actions = labels.map((label) => ({+ id: label.id,+@@ -3374,8 +3380,8 @@ class Client extends EventEmitter {+ await window.WWebJS.enforceLidAndPnRetrieval(userId);++ return {+- lid: lid?._serialized,+- pn: phone?._serialized,++ lid: lid?._serialized || lid?.$1,++ pn: phone?._serialized || phone?.$1,+ };+ }),+ );+@@ -3446,9 +3452,12 @@ class Client extends EventEmitter {++ if (!serialized) return null;++- serialized.chatId = window+- .require('WAWebJidToWid')+- .userJidToUserWid(serialized.chatJid)._serialized;++ serialized.chatId = (() => {++ const _w = window++ .require('WAWebJidToWid')++ .userJidToUserWid(serialized.chatJid);++ return _w._serialized || _w.$1;++ })();+ delete serialized.chatJid;++ return serialized;+diff --git a/src/structures/Base.js b/src/structures/Base.js+index ed1d83c09e6..a22afdf817a 100644+--- a/src/structures/Base.js++++ b/src/structures/Base.js+@@ -19,6 +19,20 @@ class Base {+ _patch(data) {+ return data;+ }++++ /**++ * Normalizes a WhatsApp ID object so that `_serialized` is always defined.++ * WhatsApp Web changed `_serialized` to `$1` in July 2026. This ensures++ * backward compatibility so all downstream code can continue using `_serialized`.++ * @param {object} id++ * @returns {object}++ */++ static _normalizeId(id) {++ if (id && id._serialized == null && id.$1 != null) {++ return Object.assign({}, id, { _serialized: id.$1 });++ }++ return id;++ }+ }++ module.exports = Base;+diff --git a/src/structures/Broadcast.js b/src/structures/Broadcast.js+index ce03dfaf5fc..f0bbb8ed330 100644+--- a/src/structures/Broadcast.js++++ b/src/structures/Broadcast.js+@@ -19,7 +19,7 @@ class Broadcast extends Base {+ * ID that represents the chat+ * @type {object}+ */+- this.id = data.id;++ this.id = Base._normalizeId(data.id);++ /**+ * Unix timestamp of last status+diff --git a/src/structures/Channel.js b/src/structures/Channel.js+index cd3e08786fe..25181de6b86 100644+--- a/src/structures/Channel.js++++ b/src/structures/Channel.js+@@ -29,7 +29,7 @@ class Channel extends Base {+ * ID that represents the channel+ * @type {ChannelId}+ */+- this.id = data.id;++ this.id = Base._normalizeId(data.id);++ /**+ * Title of the channel+diff --git a/src/structures/Chat.js b/src/structures/Chat.js+index 40211bf04d4..79624e34430 100644+--- a/src/structures/Chat.js++++ b/src/structures/Chat.js+@@ -19,7 +19,7 @@ class Chat extends Base {+ * ID that represents the chat+ * @type {object}+ */+- this.id = data.id;++ this.id = Base._normalizeId(data.id);++ /**+ * Title of the chat+diff --git a/src/structures/ClientInfo.js b/src/structures/ClientInfo.js+index 8e273c16a8d..de3dece19d9 100644+--- a/src/structures/ClientInfo.js++++ b/src/structures/ClientInfo.js+@@ -24,7 +24,7 @@ class ClientInfo extends Base {+ * Current user ID+ * @type {object}+ */+- this.wid = data.wid;++ this.wid = Base._normalizeId(data.wid);++ /**+ * @type {object}+diff --git a/src/structures/Contact.js b/src/structures/Contact.js+index 339fa5c9e51..b56c967aa94 100644+--- a/src/structures/Contact.js++++ b/src/structures/Contact.js+@@ -26,7 +26,7 @@ class Contact extends Base {+ * ID that represents the contact+ * @type {ContactId}+ */+- this.id = data.id;++ this.id = Base._normalizeId(data.id);++ /**+ * Contact's phone number+@@ -196,7 +196,7 @@ class Contact extends Base {++ contact = await window+ .require('WAWebCollections')+- .Contact.find(lid._serialized);++ .Contact.find(lid._serialized || lid.$1);+ }+ await window+ .require('WAWebBlockContactAction')+diff --git a/src/structures/GroupChat.js b/src/structures/GroupChat.js+index 3cecc82845b..b9049d472cc 100644+--- a/src/structures/GroupChat.js++++ b/src/structures/GroupChat.js+@@ -156,7 +156,7 @@ class GroupChat extends Chat {+ };++ for (let pWid of participantWids) {+- const pId = pWid._serialized;++ const pId = pWid._serialized || pWid.$1;+ pWid =+ pWid.server === 'lid'+ ? window+@@ -170,7 +170,11 @@ class GroupChat extends Chat {+ isInviteV4Sent: false,+ };++- if (groupParticipants.some((p) => p._serialized === pId)) {++ if (++ groupParticipants.some(++ (p) => (p._serialized || p.$1) === pId,++ )++ ) {+ participantData[pId].code = 409;+ participantData[pId].message = errorCodes[409];+ continue;+@@ -223,7 +227,7 @@ class GroupChat extends Chat {+ .require('WAWebChatSendMessages')+ .sendGroupInviteMessage(+ userChat,+- group.id._serialized,++ group.id._serialized || group.id.$1,+ groupName,+ rpcResult.inviteV4Code,+ rpcResult.inviteV4CodeExp,+@@ -274,10 +278,10 @@ class GroupChat extends Chat {++ return (+ chat.groupMetadata.participants.get(+- lid?._serialized,++ lid?._serialized || lid?.$1,+ ) ||+ chat.groupMetadata.participants.get(+- phone?._serialized,++ phone?._serialized || phone?.$1,+ )+ );+ }),+@@ -312,10 +316,10 @@ class GroupChat extends Chat {++ return (+ chat.groupMetadata.participants.get(+- lid?._serialized,++ lid?._serialized || lid?.$1,+ ) ||+ chat.groupMetadata.participants.get(+- phone?._serialized,++ phone?._serialized || phone?.$1,+ )+ );+ }),+@@ -350,10 +354,10 @@ class GroupChat extends Chat {++ return (+ chat.groupMetadata.participants.get(+- lid?._serialized,++ lid?._serialized || lid?.$1,+ ) ||+ chat.groupMetadata.participants.get(+- phone?._serialized,++ phone?._serialized || phone?.$1,+ )+ );+ }),+diff --git a/src/structures/GroupNotification.js b/src/structures/GroupNotification.js+index a723639f4ef..61d597851aa 100644+--- a/src/structures/GroupNotification.js++++ b/src/structures/GroupNotification.js+@@ -18,7 +18,7 @@ class GroupNotification extends Base {+ * ID that represents the groupNotification+ * @type {object}+ */+- this.id = data.id;++ this.id = Base._normalizeId(data.id);++ /**+ * Extra content+@@ -45,7 +45,7 @@ class GroupNotification extends Base {+ */+ this.chatId =+ typeof data.id.remote === 'object'+- ? data.id.remote._serialized++ ? data.id.remote._serialized || data.id.remote.$1+ : data.id.remote;++ /**+@@ -54,7 +54,7 @@ class GroupNotification extends Base {+ */+ this.author =+ typeof data.author === 'object'+- ? data.author._serialized++ ? data.author._serialized || data.author.$1+ : data.author;++ /**+diff --git a/src/structures/Message.js b/src/structures/Message.js+index 51e9062dbc0..ed7991352d7 100644+--- a/src/structures/Message.js++++ b/src/structures/Message.js+@@ -35,7 +35,9 @@ class Message extends Base {+ * ID that represents the message+ * @type {object}+ */+- this.id = data.id;++ // Normalize id: WhatsApp Web changed _serialized to $1 in 2026-07 update.++ // Keep _serialized always populated for backward compatibility.++ this.id = Base._normalizeId(data.id);++ /**+ * ACK status for the message+@@ -75,7 +77,7 @@ class Message extends Base {+ */+ this.from =+ typeof data.from === 'object' && data.from !== null+- ? data.from._serialized++ ? data.from._serialized || data.from.$1+ : data.from;++ /**+@@ -87,7 +89,7 @@ class Message extends Base {+ */+ this.to =+ typeof data.to === 'object' && data.to !== null+- ? data.to._serialized++ ? data.to._serialized || data.to.$1+ : data.to;++ /**+@@ -96,7 +98,7 @@ class Message extends Base {+ */+ this.author =+ typeof data.author === 'object' && data.author !== null+- ? data.author._serialized++ ? data.author._serialized || data.author.$1+ : data.author;++ /**+@@ -211,13 +213,13 @@ class Message extends Base {+ groupName: data.inviteGrpName,+ fromId:+ typeof data.from === 'object' &&+- '_serialized' in data.from+- ? data.from._serialized++ (data.from._serialized || data.from.$1)++ ? data.from._serialized || data.from.$1+ : data.from,+ toId:+ typeof data.to === 'object' &&+- '_serialized' in data.to+- ? data.to._serialized++ (data.to._serialized || data.to.$1)++ ? data.to._serialized || data.to.$1+ : data.to,+ }+ : undefined;+diff --git a/src/util/Injected/Utils.js b/src/util/Injected/Utils.js+index dfa30a579de..b7e23bc7fe7 100644+--- a/src/util/Injected/Utils.js++++ b/src/util/Injected/Utils.js+@@ -582,7 +582,7 @@ exports.LoadUtils = () => {++ return window+ .require('WAWebCollections')+- .Msg.get(newMsgKey._serialized);++ .Msg.get(newMsgKey._serialized || newMsgKey.$1);+ };++ window.WWebJS.editMessage = async (msg, content, options = {}) => {+@@ -625,7 +625,9 @@ exports.LoadUtils = () => {+ await window+ .require('WAWebSendMessageEditAction')+ .sendMessageEdit(msg, content, internalOptions);+- return window.require('WAWebCollections').Msg.get(msg.id._serialized);++ return window++ .require('WAWebCollections')++ .Msg.get(msg.id._serialized || msg.id.$1);+ };++ window.WWebJS.toStickerData = async (mediaInfo) => {+@@ -830,10 +832,16 @@ exports.LoadUtils = () => {++ if (typeof msg.id.remote === 'object') {+ msg.id = Object.assign({}, msg.id, {+- remote: msg.id.remote._serialized,++ remote: msg.id.remote._serialized || msg.id.remote.$1,+ });+ }+++ // WhatsApp Web changed _serialized to $1 in message IDs (2026-07 update).++ // Normalize here so all downstream Node.js code can keep using _serialized.++ if (msg.id && msg.id._serialized == null && msg.id.$1 != null) {++ msg.id = Object.assign({}, msg.id, { _serialized: msg.id.$1 });++ }+++ delete msg.pendingAckUpdate;++ return msg;+@@ -953,7 +961,7 @@ exports.LoadUtils = () => {+ model.isGroup = true;+ const chatWid = window+ .require('WAWebWidFactory')+- .createWid(chat.id._serialized);++ .createWid(chat.id._serialized || chat.id.$1);+ const groupMetadata =+ window.require('WAWebCollections').GroupMetadata ||+ window.require('WAWebCollections').WAWebGroupMetadataCollection;+@@ -981,16 +989,17 @@ exports.LoadUtils = () => {++ model.lastMessage = null;+ if (model.msgs && model.msgs.length) {+- const lastMessage = chat.lastReceivedKey++ const _lastReceivedKeyId = chat.lastReceivedKey++ ? chat.lastReceivedKey._serialized || chat.lastReceivedKey.$1++ : null;++ const lastMessage = _lastReceivedKeyId+ ? window+ .require('WAWebCollections')+- .Msg.get(chat.lastReceivedKey._serialized) ||++ .Msg.get(_lastReceivedKeyId) ||+ (+ await window+ .require('WAWebCollections')+- .Msg.getMessagesById([+- chat.lastReceivedKey._serialized,+- ])++ .Msg.getMessagesById([_lastReceivedKeyId])+ )?.messages?.[0]+ : null;+ lastMessage &&+@@ -1320,9 +1329,10 @@ exports.LoadUtils = () => {+ };++ window.WWebJS.rejectCall = async (peerJid, id) => {+- let userId = window++ const _meUser = window+ .require('WAWebUserPrefsMeUser')+- .getMaybeMePnUser()._serialized;++ .getMaybeMePnUser();++ let userId = _meUser._serialized || _meUser.$1;++ const stanza = window.require('WAWap').wap(+ 'call',+@@ -1632,9 +1642,12 @@ exports.LoadUtils = () => {+ .membershipRequestsActionRejectParticipantMixins+ ?.value.error;+ return {+- requesterId: window+- .require('WAWebWidFactory')+- .createWid(p.jid)._serialized,++ requesterId: (() => {++ const _w = window++ .require('WAWebWidFactory')++ .createWid(p.jid);++ return _w._serialized || _w.$1;++ })(),+ ...(error+ ? {+ error: +error,+@@ -1651,11 +1664,15 @@ exports.LoadUtils = () => {+ }+ } else {+ result.push({+- requesterId: window+- .require('WAWebJidToWid')+- .userJidToUserWid(+- participant.participantArgs[0].participantJid,+- )._serialized,++ requesterId: (() => {++ const _w = window++ .require('WAWebJidToWid')++ .userJidToUserWid(++ participant.participantArgs[0]++ .participantJid,++ );++ return _w._serialized || _w.$1;++ })(),+ message: 'ServerStatusCodeError',+ });+ }diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 7cad42f2c..102d750c3 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -1452,6 +1452,68 @@ describe('WhatsAppWebJsAdapter inbound media (MEDIA_DOWNLOAD_ENABLED=false)', ()});});+describe('WhatsAppWebJsAdapter message_reaction (id resolution across WA Web builds)', () => {+ const wireReactionHandler = (): { onMessageReaction: jest.Mock; client: EventEmitter } => {+ const adapter = new WhatsAppWebJsAdapter({+ sessionId: 'sess-reaction-test',+ sessionDataPath: './data/sessions',+ puppeteer: {},+ });+ const client = Object.assign(new EventEmitter(), {+ info: { wid: { _serialized: '[email protected]', user: '628123' }, pushname: 'Tester' },+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),+ pupPage: { evaluate: jest.fn().mockResolvedValue(true) },+ });+ (adapter as unknown as { client: unknown }).client = client;+ const onMessageReaction = jest.fn();+ (adapter as unknown as { callbacks: unknown }).callbacks = { onMessageReaction };+ (adapter as unknown as { setupEventHandlers: () => void }).setupEventHandlers();+ return { onMessageReaction, client };+ };++ const reactionArg = (mock: jest.Mock): { messageId: string; chatId: string } => {+ const calls = mock.mock.calls as Array<[{ messageId: string; chatId: string }]>;+ return calls[0][0];+ };++ const emitReaction = (client: EventEmitter, msgId: unknown): void => {+ client.emit('message_reaction', {+ msgId,+ id: { remote: '[email protected]' },+ reaction: '👍',+ senderId: '[email protected]',+ });+ };++ it('reads _serialized on a healthy WA Web build', () => {+ const { onMessageReaction, client } = wireReactionHandler();++ emitReaction(client, { _serialized: 'REACTED_MSG' });++ expect(reactionArg(onMessageReaction).messageId).toBe('REACTED_MSG');+ });++ it('falls back to $1 on a build that renamed _serialized (#747)', () => {+ const { onMessageReaction, client } = wireReactionHandler();++ // `Reaction` passes its keys straight through, so upstream's id normalization never reaches it —+ // this fallback is the only thing keeping reactions attributable on an affected build.+ emitReaction(client, { $1: 'REACTED_MSG_RENAMED' });++ expect(reactionArg(onMessageReaction).messageId).toBe('REACTED_MSG_RENAMED');+ });++ it('emits the empty no-id sentinel rather than undefined when neither field resolves', () => {+ const { onMessageReaction, client } = wireReactionHandler();++ emitReaction(client, {});++ // Never undefined: downstream looks the message up by this id, and TypeORM drops an undefined+ // condition from the where-clause — which would match an unrelated row.+ expect(reactionArg(onMessageReaction).messageId).toBe('');+ });+});+describe('WhatsAppWebJsAdapter message_revoke_everyone (forwards the original deleted id as revokedId)', () => {const wireRevokeHandler = (): { onMessageRevoked: jest.Mock; client: EventEmitter } => {const adapter = new WhatsAppWebJsAdapter({diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex d32260096..99fe2ddd1 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -52,6 +52,7 @@ import {BusinessClient,WwjsChannelData,GroupCreateResult,+ SerializedWid,} from '../types/whatsapp-web-js.types';import { buildIncomingMessageBase, mapContactFields } from './message-mapper';import { buildVCard } from './vcard';@@ -628,8 +629,16 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginthis.client.on('message_reaction', reaction => {try {+ // `Reaction` assigns its keys straight through (`this.msgId = data.parentMsgKey`), so it is the+ // one structure upstream's id normalization doesn't reach — on a WA Web build that renamed+ // `_serialized` to `$1` (#747), `msgId._serialized` is undefined even with the backport applied.+ // Read `$1` as a fallback, and fall back again to `''` (the same no-id sentinel Baileys uses)+ // rather than pass undefined on: `applyReaction` looks the message up by this id, and TypeORM+ // DROPS an undefined condition from the where-clause — which would match an arbitrary row and+ // emit another message's reactions. Empty string finds nothing and returns cleanly.+ const msgId = reaction.msgId as unknown as SerializedWid;const event: ReactionEvent = {- messageId: reaction.msgId._serialized,+ messageId: msgId?._serialized ?? msgId?.$1 ?? '',chatId: reaction.id.remote,reaction: reaction.reaction,senderId: reaction.senderId,diff --git a/src/engine/adapters/wwebjs-backport-201832.spec.ts b/src/engine/adapters/wwebjs-backport-201832.spec.tsnew file mode 100644index 000000000..24b06e248--- /dev/null+++ b/src/engine/adapters/wwebjs-backport-201832.spec.ts@@ -0,0 +1,207 @@+import { execFileSync, spawnSync } from 'child_process';+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';++// The patcher is a CommonJS build script (scripts/*.js); import it with a typed+// shape so the spec stays under the strict lint rules.+// eslint-disable-next-line @typescript-eslint/no-require-imports+const { applyBackport, DEFAULT_PATCH: PATCH_FILE } = require('../../../scripts/patch-wwebjs-201832') as {+ applyBackport: (wwjsDir: string, patchFile?: string) => { skipped: boolean; reason?: string; note?: string };+ DEFAULT_PATCH: string;+};++const WWJS_SRC = path.join(__dirname, '..', '..', '..', 'node_modules', 'whatsapp-web.js');+/** The patcher's CLI entrypoint — the `--best-effort` cases exercise the process, not just applyBackport. */+const SCRIPT = path.join(__dirname, '..', '..', '..', 'scripts', 'patch-wwebjs-201832.js');++/**+ * Guards the build-time backport of upstream whatsapp-web.js#201832+ * (`id._serialized` -> `id.$1` normalization, broken by WA Web 2.3000.x). Each+ * case runs the patcher against a temp COPY of the installed whatsapp-web.js so+ * the real node_modules install is never mutated. This covers the boot-smoke+ * blind spot (boot-smoke only curls /api/health/live and never exercises the+ * patched paths): if the patcher ever fails to restore the normalization sites,+ * or drifts on a future whatsapp-web.js bump, these tests fail loudly.+ */+describe('patch-wwebjs-201832 (build-time backport of upstream #201832)', () => {+ const tmpDirs: string[] = [];++ /**+ * A pristine (unpatched) copy of the installed whatsapp-web.js.+ *+ * The install itself is not a reliable fixture: `postinstall` applies this same backport, so+ * node_modules is patched on a normal `npm install` but pristine in the Docker builder stage+ * (which installs before `scripts/` is copied). Reverse the constructor rewrites on the copy so+ * every case starts from the same known-unpatched shape either way.+ */+ function copyWwjs(): string {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-backport-'));+ tmpDirs.push(tmp);+ const copy = path.join(tmp, 'whatsapp-web.js');+ fs.cpSync(WWJS_SRC, copy, { recursive: true });++ const baseJs = path.join(copy, 'src', 'structures', 'Base.js');+ if (!/static _normalizeId/.test(fs.readFileSync(baseJs, 'utf8'))) return copy; // already pristine++ // Reverse-apply the same diff rather than hand-unpicking it: symmetric with the forward path, and+ // it stays correct by construction if the patch file changes. Exits 1 on the Contact.js hunk that+ // was never applied in the first place — expected, hence the ignored status.+ try {+ execFileSync(+ 'patch',+ ['-p1', '-d', copy, '-R', '--no-backup-if-mismatch', '-f', '-F0', '--ignore-whitespace', '-i', PATCH_FILE],+ { stdio: 'pipe' },+ );+ } catch (e) {+ if ((e as { status?: number }).status !== 1) throw e;+ }+ for (const rej of ['src/structures/Contact.js.rej']) {+ fs.rmSync(path.join(copy, rej), { force: true });+ }+ return copy;+ }++ afterAll(() => {+ for (const dir of tmpDirs) fs.rmSync(dir, { recursive: true, force: true });+ });++ it('self-removes (no-ops) once the installed dep normalizes ids itself', () => {+ const dir = copyWwjs();+ // Land the fix the way an upstream release would — every site at once. Normalizing only SOME sites+ // is a half-patched tree, not a fixed one, and must not be used to simulate this (see below).+ applyBackport(dir);+ const injected = path.join(dir, 'src', 'util', 'Injected', 'Utils.js');+ const before = fs.readFileSync(injected, 'utf8');++ const res = applyBackport(dir);++ expect(res.skipped).toBe(true);+ // Injected/Utils.js carries no REQUIRED_SITES marker, so it stays byte-identical only if the patcher+ // truly stood down. Re-applying would reject every already-applied hunk and leave artifacts behind.+ expect(fs.readFileSync(injected, 'utf8')).toBe(before);+ });++ it('refuses to stand down on a half-patched tree', () => {+ const dir = copyWwjs();+ // Exactly what a run that died mid-apply leaves: `patch` writes as it goes and Message.js is patched+ // early, so the load-bearing constructor normalizes while its siblings never did. Standing down here+ // latches the broken tree in for good — every later run reads Message.js and takes the same branch —+ // and ships a whatsapp-web.js whose ids work in some paths and not others.+ const msgJs = path.join(dir, 'src', 'structures', 'Message.js');+ fs.writeFileSync(+ msgJs,+ fs.readFileSync(msgJs, 'utf8').replace('this.id = data.id', 'this.id = Base._normalizeId(data.id)'),+ );++ expect(() => applyBackport(dir)).toThrow(/PARTIALLY patched/);+ });++ it('applies the backport across every id-normalization site', () => {+ const dir = copyWwjs();++ const res = applyBackport(dir);++ expect(res.skipped).toBe(false);+ const read = (rel: string): string => fs.readFileSync(path.join(dir, rel), 'utf8');+ // Root helper + the load-bearing Message constructor that OpenWA's ~40+ // `msg.id._serialized` reads depend on, plus every sibling structure.+ expect(read('src/structures/Base.js')).toContain('static _normalizeId');+ expect(read('src/structures/Message.js')).toContain('this.id = Base._normalizeId(data.id)');+ for (const f of ['Chat', 'Contact', 'Channel', 'Broadcast', 'GroupNotification']) {+ expect(read(`src/structures/${f}.js`)).toContain('this.id = Base._normalizeId(data.id)');+ }+ expect(read('src/structures/ClientInfo.js')).toContain('this.wid = Base._normalizeId(data.wid)');+ // from/to/author fallbacks (OpenWA reads these as chat/sender strings).+ expect(read('src/structures/Message.js')).toMatch(/data\.from\._serialized \|\| data\.from\.\$1/);+ });++ it('leaves no patch artifacts in the image', () => {+ const dir = copyWwjs();++ applyBackport(dir);++ // GNU patch writes `<file>.~1~` backups of pre-patch source on any offset/reject+ // (BSD patch does not — which is why this must be asserted, not eyeballed on macOS).+ // Rejects are cleaned too. Anything left here would ship in the production image.+ const leftovers: string[] = [];+ const walk = (d: string): void => {+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {+ if (e.name === 'node_modules') continue;+ const full = path.join(d, e.name);+ if (e.isDirectory()) walk(full);+ else if (/(\.rej|\.orig|~)$/.test(e.name)) leftovers.push(path.relative(dir, full));+ }+ };+ walk(dir);+ expect(leftovers).toEqual([]);+ });++ it('normalizes a $1-only id while leaving a healthy id untouched', () => {+ const dir = copyWwjs();+ applyBackport(dir);++ // The load-bearing invariant, exercised rather than grepped: on an affected+ // build `_serialized` is synthesized from `$1`; on a healthy build the id must+ // pass through byte-for-byte (identity), so unaffected users see no change.+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const Base = require(path.join(dir, 'src', 'structures', 'Base.js')) as {+ _normalizeId: (id: unknown) => { _serialized?: string };+ };++ const affected = { $1: '[email protected]_ABC', remote: '[email protected]', fromMe: true, id: 'ABC' };+ expect(Base._normalizeId(affected)._serialized).toBe('[email protected]_ABC');+ // Sibling fields survive the copy — OpenWA reads id.remote / id.id downstream.+ expect(Base._normalizeId(affected)).toMatchObject({ remote: '[email protected]', fromMe: true, id: 'ABC' });++ const healthy = { _serialized: '[email protected]_XYZ', remote: '[email protected]' };+ expect(Base._normalizeId(healthy)).toBe(healthy); // identity — same reference, not a copy+ });++ it('aborts loudly on unexpected version skew', () => {+ const dir = copyWwjs();+ // Break the exact line the Message hunk targets -> that hunk rejects, which+ // is NOT in the expected-reject set -> the patcher must throw rather than+ // ship a partially patched whatsapp-web.js.+ const msgJs = path.join(dir, 'src', 'structures', 'Message.js');+ fs.writeFileSync(msgJs, fs.readFileSync(msgJs, 'utf8').replace('this.id = data.id', 'this.id = DATA_ID_MOVED'));++ expect(() => applyBackport(dir)).toThrow(/version skew/);+ });++ // `npm ci` fires the postinstall hook (--best-effort) BEFORE the image build's strict run, so+ // --best-effort decides what the strict run inherits. Both directions are load-bearing.+ describe('--best-effort', () => {+ it('still fails when the tree was already written', () => {+ const dir = copyWwjs();+ // Skew a hunk so `patch` mutates the tree and only THEN rejects. Degrading here would leave a+ // half-patched tree that the strict run reads as healthy and waves through — a green build+ // shipping broken ids. An unpatched dep is the trade this flag exists to make; this is not.+ const chatJs = path.join(dir, 'src', 'structures', 'Chat.js');+ fs.writeFileSync(chatJs, fs.readFileSync(chatJs, 'utf8').replace('this.id = data.id', 'this.id = MOVED'));++ const res = spawnSync(process.execPath, [SCRIPT, '--best-effort', dir], { encoding: 'utf8' });++ expect(res.status).toBe(1);+ expect(res.stderr).toMatch(/version skew/);+ });++ it('degrades when `patch` is not installed, leaving the tree pristine', () => {+ const dir = copyWwjs();+ // The case the flag exists for (Windows outside WSL, Baileys-only setups): `patch` never runs, so+ // nothing was written and a warning beats breaking `npm install`. Emptying PATH is what makes the+ // lookup fail; node itself is invoked by absolute path and is unaffected.+ const emptyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-nopath-'));+ tmpDirs.push(emptyDir);++ const res = spawnSync(process.execPath, [SCRIPT, '--best-effort', dir], {+ encoding: 'utf8',+ env: { ...process.env, PATH: emptyDir },+ });++ expect(res.status).toBe(0);+ expect(res.stderr).toMatch(/skipped/);+ expect(fs.readFileSync(path.join(dir, 'src', 'structures', 'Message.js'), 'utf8')).toContain('this.id = data.id');+ });+ });+});diff --git a/src/engine/types/whatsapp-web-js.types.ts b/src/engine/types/whatsapp-web-js.types.tsindex e505722e5..171dea7ad 100644--- a/src/engine/types/whatsapp-web-js.types.ts+++ b/src/engine/types/whatsapp-web-js.types.ts@@ -6,9 +6,16 @@ import { Chat, Client, Message } from 'whatsapp-web.js';/*** A WhatsApp ID (Wid) as serialized by whatsapp-web.js, e.g. `{ _serialized: '[email protected]' }`.+ *+ * WA Web build 2.3000.x (~2026-07-14) renamed this property to the minifier-mangled `$1`, breaking+ * every `_serialized` read at once (#747). The image build backports upstream's id normalization+ * (`scripts/patch-wwebjs-201832.js`), which restores `_serialized` on the structures it covers — but+ * `Reaction` is not one of them, so `$1` is declared here for the callsites that must read it+ * directly. Both are optional: exactly one is present depending on the WA Web build.*/export interface SerializedWid {_serialized?: string;+ $1?: string;}/**diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 6655a739d..2dc59f80d 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1451,6 +1451,21 @@ describe('SessionService', () => {expect(stored.metadata?.reactions).toEqual({ alice: '👍', bob: '🎉' });});+ it('drops a reaction with no message id instead of letting it match an arbitrary row', async () => {+ const callbacks = await startAndCaptureCallbacks();+ // An engine that can't resolve the reacted message's id passes `''` (the no-id sentinel). It must+ // never reach findOne: TypeORM drops an empty/undefined condition from the where-clause, so the+ // lookup would match some other message and emit ITS reactions under this event.+ (messageRepository.findOne as jest.Mock).mockClear();+ (messageRepository.update as jest.Mock).mockClear();++ callbacks.onMessageReaction!({ messageId: '', chatId: 'c', senderId: 'alice', reaction: '👍' });+ for (let i = 0; i < 3; i++) await flush();++ expect(messageRepository.findOne).not.toHaveBeenCalled();+ expect(messageRepository.update).not.toHaveBeenCalled();+ });+it('persists a reaction via a scoped metadata update, never a full-row save (protects ack status)', async () => {const callbacks = await startAndCaptureCallbacks();// The row was already advanced to DELIVERED by a concurrent ack. A full-row save(msg) woulddiff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 308484deb..e48068ff1 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -1255,6 +1255,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat*/private async applyReaction(id: string, event: ReactionEvent): Promise<void> {try {+ // Guard the lookup key before it reaches TypeORM: `findOne` DROPS an undefined condition from+ // the where-clause rather than matching nothing, so an engine that couldn't resolve the reacted+ // message's id would silently match an arbitrary row and clobber/emit its reactions. `!msg` is+ // no protection against that — the row it finds is real, just the wrong one.+ if (!event.messageId) return;+const msg = await this.messageRepository.findOne({ where: { sessionId: id, waMessageId: event.messageId } });if (!msg) return;