Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): strip the media model id so media sends work on current WhatsApp Web
Yudhi Armyndhariscf2bf9a45268
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4be42a7ee..1ca3405d5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- whatsapp-web.js sessions send media again on the WhatsApp Web builds rolled out on 2026-09-17: the library spread the media model into the outgoing message after its id, and the model's private `__x_id` clobbered it, so every image, video, audio, document, sticker and status media send failed with `Data passed to getter must include an id property` while text kept working. An install-time patch carries upstream's one-line fix until a whatsapp-web.js release ships it ([#1643](https://github.com/rmyndharis/OpenWA/issues/1643), [#1636](https://github.com/rmyndharis/OpenWA/issues/1636)). Thanks @15874611923 and @Magnarks for the reports.- Baileys sessions record a message the account sent from its phone while the gateway was down, and dispatch `message.sent` for it, as they already did for one sent while the gateway was online. The offline replay carried the same `append` tag as the library's echo of an API send, which the upsert handler dropped wholesale; it now skips only the ids this session sent itself, and the phone's reactions, edits and revokes from that window are replayed the same way ([#1667](https://github.com/rmyndharis/OpenWA/issues/1667)).- Baileys sessions no longer drop the inbound messages WhatsApp queued while they were down. The offline replay is tagged `append`, which the upsert handler treated as history and skipped for anything older than the reconnect, so every message sent during an outage was never stored and never dispatched ([#1660](https://github.com/rmyndharis/OpenWA/issues/1660)). Thanks @fransarni for the report.- A whatsapp-web.js session that comes up without its page-side call hook says so in the log instead of silently never reporting an incoming call. The hook is installed last in the same page evaluate as the message listeners, so the session stays healthy for messages either way ([#1655](https://github.com/rmyndharis/OpenWA/issues/1655)).diff --git a/Dockerfile b/Dockerfileindex 68a9a18ef..1701db7bb 100644--- a/Dockerfile+++ b/Dockerfile@@ -184,7 +184,7 @@ COPY package*.json ./# scripts/postinstall.js rides along so a bare local `npm ci` keeps working, but the# --ignore-scripts install below skips the hook here: the explicit fatal run right# after is the sole (and stricter) applier for the image.-COPY scripts/postinstall.js scripts/patch-wwebjs-201832.js scripts/wwebjs-201832.patch scripts/patch-wwebjs-newsletter-preview.js scripts/patch-wwebjs-status.js scripts/patch-wwebjs-ready-sync.js scripts/patch-wwebjs-participant-arity.js scripts/patch-wwebjs-block.js scripts/patch-wwebjs-group-description.js scripts/patch-baileys-appstate.js scripts/patch-baileys-newsletter-create.js ./scripts/+COPY scripts/postinstall.js scripts/patch-wwebjs-201832.js scripts/wwebjs-201832.patch scripts/patch-wwebjs-newsletter-preview.js scripts/patch-wwebjs-status.js scripts/patch-wwebjs-ready-sync.js scripts/patch-wwebjs-participant-arity.js scripts/patch-wwebjs-block.js scripts/patch-wwebjs-group-description.js scripts/patch-wwebjs-media-id.js scripts/patch-baileys-appstate.js scripts/patch-baileys-newsletter-create.js ./scripts/# Install production dependencies only, then apply the backports. The status patcher runs after# the two patchers it depends on: its transforms were written against the tree they leave behind.@@ -208,6 +208,7 @@ RUN npm ci --omit=dev --ignore-scripts \&& node scripts/patch-wwebjs-participant-arity.js \&& node scripts/patch-wwebjs-block.js \&& node scripts/patch-wwebjs-group-description.js \+ && node scripts/patch-wwebjs-media-id.js \&& node scripts/patch-baileys-appstate.js \&& node scripts/patch-baileys-newsletter-create.js \&& npm cache clean --forcediff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex c8ec10e0d..ab0663462 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -5,7 +5,7 @@ Three-way comparison of every capability: the **Baileys library** (`@whiskeysockits adapter layer and REST API — including which "supported" cells only work because OpenWA patchesthe installed library. Coverage is total: all 113 `IWhatsAppEngine` methods (29.4), **all 152Baileys + 81 whatsapp-web.js library methods** (29.5), all 34 + 31 library events (29.5.4), and all-9 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.+10 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.## 29.1 How to read this matrix@@ -49,7 +49,7 @@ flowchart LRIF --> BA["BaileysAdapter"]SVC --> STORE["OpenWA-side stores"]end- WA --> WLIB["whatsapp-web.js 1.34.7<br/>+ 7 OpenWA patches"]+ WA --> WLIB["whatsapp-web.js 1.34.7<br/>+ 8 OpenWA patches"]BA --> BLIB["@whiskeysockets/baileys 7.0.0-rc14<br/>+ 2 OpenWA patches"]WLIB --> WEB["WhatsApp Web<br/>headless Chromium"]BLIB --> WAS["WhatsApp servers<br/>browser-free socket"]@@ -125,7 +125,7 @@ wrong interface method. Those three remain reader-verified.## 29.3 Install-time patches OpenWA applies to the libraries-OpenWA ships nine exact, self-disabling source transforms over the installed engines. Each runs at+OpenWA ships ten exact, self-disabling source transforms over the installed engines. Each runs at`npm install` (`scripts/postinstall.js`, `--best-effort`) and again in the Docker production stage(**without** best-effort — dependency drift fails the image build). "Self-disabling" means thepatcher no-ops once the fix is present upstream, and an unrecognized source shape fails loudly@@ -138,23 +138,24 @@ it is missing as it starts (`src/engine/adapters/engine-patch-status.ts`; 🔧¹check described below). The report is diagnostic, not preventive: startup continues, so a sessionreaching READY is not evidence that every patch landed. See docs/12 for the operator procedure.-### 29.3.1 The nine patches--| # | Patcher | Library target | What it repairs | Stand-down predicate |-| --- | ---------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| 🔧¹ | `scripts/patch-wwebjs-201832.js` (+ `wwebjs-201832.patch`) | whatsapp-web.js models | WhatsApp Web 2.3000.x renamed the serialized message-id property `id._serialized` → `id.$1`; 1.34.7 reads the old name in the `Message` constructor and ~40 downstream sites, so message ids, acks, quoted-message resolution and media downloads break. Backports upstream fix #201832 (`Base._normalizeId()`). One known harmless reject on 1.34.7 (a LID-aware `Contact.js` path that does not exist there); any other reject aborts the build. | no-ops once `_normalizeId` exists upstream. Runtime double-check: `src/engine/adapters/wwebjs-backport-check.ts` detects an unpatched install and logs an error naming the fix as the wwjs session starts (`whatsapp-web-js.adapter.ts:446`). It is diagnostic, **not** preventive — startup continues, so a session reaching READY is not evidence the patch landed. |-| 🔧² | `scripts/patch-wwebjs-status.js` | whatsapp-web.js injected status send | Two independent breakages in current WhatsApp Web builds: (1) the `canCheckStatusRankingPosterGating()` helper is gone and its call threw before any status send — now called when present, `false` (pre-gating meaning) when not; (2) `sendStatusMediaMsgAction` changed signature from positional `(msg, mediaUpdate)` to a single options object — adopted from upstream PR #201816. The two edits of the media repair are all-or-nothing. | exact-shape match; unknown shape fails the build. |-| 🔧³ | `scripts/patch-wwebjs-newsletter-preview.js` | whatsapp-web.js `Injected/Utils.js` | Link-preview generation omitted the destination chat, so WhatsApp Web could not select the newsletter preview transport: `getLinkPreview(link)` → `getLinkPreview(link, chat)`. | exact-shape match; unknown shape fails the build. |-| 🔧⁴ | `scripts/patch-wwebjs-ready-sync.js` | whatsapp-web.js readiness pipeline | Two live-observed races: on a warm profile the page can reach `hasSynced=true` before the edge listener attaches (the whole post-auth pipeline silently never runs), and a partial `attachEventListeners` failure was swallowed (message bridge dead while sends still work). Adds an `eventsAttached` completion marker and fires the handler once when the level is already true; double-fire is deduped by the adapter. | exact-shape, one group all-or-nothing; unknown shape fails the build. |-| 🔧⁵ | `scripts/patch-baileys-appstate.js` | Baileys `lib/Socket/chats.js` | `resyncAppState`'s `while (collectionsToHandle.size)` loop: `query()` resolves `undefined` on its own 60s timeout, decoding to `{}`, and every loop exit — including the library's own attempts guard — lives inside `for (const key in decoded)`, which never runs on an empty decode. The loop would burn one 60s query per pass for the life of the socket (~1000 wasted queries/day). The patch adds the missing exit: empty decode → `break`. | exact-shape match; remove once upstream bounds the loop. |-| 🔧⁶ | `scripts/patch-baileys-newsletter-create.js` | Baileys `lib/Socket/newsletter.js` | `parseNewsletterCreateResponse` reads `thread.picture.id` eagerly, but `newsletterCreate` sends only `{ name, description }` — there is no picture parameter anywhere in the chain — so `thread.picture` is null on EVERY create and the parse threw for all of them. WhatsApp creates the newsletter server-side BEFORE the response is parsed, so each call returned 500 while leaving a real channel behind, and `createChannel` is non-idempotent, so a client retrying a 5xx leaked one orphan per attempt (confirmed on the test account). `description` has the same defect whenever the caller omits one. The patch reads every nested field defensively so the response's `id` — the only place the new channel's id appears — always survives. | exact-shape match; remove once upstream tolerates a pictureless newsletter. |-| 🔧⁷ | `scripts/patch-wwebjs-participant-arity.js` | whatsapp-web.js `GroupChat.js` | `removeParticipants`/`promoteParticipants`/`demoteParticipants` resolve each requested id against the group's own member collection and drop what they cannot find, then resolve `{status: 200}` for the batch. Dropping EVERY id left the WA Web request builder an empty repeated field, whose arity assertion threw — the caller saw an unnamed `500` on removal. Promote and demote have no such assertion, so they answered `200` claiming success for people WhatsApp never touched. The patch keeps the resolved array with its holes, skips the call when nothing resolved, and returns `matched` (one boolean per REQUESTED id) so the adapter can report a per-participant outcome instead of inventing one. | exact-shape match; remove once upstream reports which participants it acted on. |-| 🔧⁸ | `scripts/patch-wwebjs-block.js` | whatsapp-web.js `Contact.js` | `Contact.block()`/`unblock()` resolved their target through `getContactToBlockOnlyUseIfNoAssociatedChat`, which WhatsApp Web removed, so both answered an opaque `500` for every id shape. The replacement helpers `handleBlock`/`handleUnblock` are modal-driven UI wrappers that block nothing when called headless, and the server now refuses a phone-keyed block outright (`trying to block a pn contact without a chat`) because individual chats are keyed by LID while wwjs folds every id back to a phone number. Resolves through `WAWebLidMigrationUtils.toUserLid` to the chat-owning identity and calls `blockContact`/`unblockContact` directly, falling back to the original contact when no LID or chat exists. | exact-shape match on both bodies; unknown shape fails the build. |-| 🔧⁹ | `scripts/patch-wwebjs-group-description.js` | whatsapp-web.js `GroupChat.js` | `GroupChat.setDescription()` calls the page's `WAWebGroupModifyInfoJob.setGroupDescription(chatWid, description, newId, descId)` positionally, but that job now takes a single options object `{desc, groupWid, newDescId, prevDescId}`. The first positional argument lands where the object is read, every field comes back undefined, and `widToGroupJid(undefined)` throws inside the page — reaching the caller as a bare `500` while the library still types the method `Promise<boolean>`. `setGroupSubject` in the same module is still positional, which is why subjects kept working and made the Wid look innocent. The patch sends the options object, takes `newDescId` from `WARandomHex.randomHex(8)` as the product does, and maps an empty description to `desc: null` so it selects the job's delete branch rather than sending an empty body element. The open upstream fix #201895 changes the same call, but keeps `WAWebMsgKey.newId()` and passes an empty description through verbatim, so this patcher will not stand down when it lands and the `desc: null` mapping has to be carried over rather than dropped with it. | exact-shape match; unknown shape fails the build. |+### 29.3.1 The ten patches++| # | Patcher | Library target | What it repairs | Stand-down predicate |+| ---- | ---------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| 🔧¹ | `scripts/patch-wwebjs-201832.js` (+ `wwebjs-201832.patch`) | whatsapp-web.js models | WhatsApp Web 2.3000.x renamed the serialized message-id property `id._serialized` → `id.$1`; 1.34.7 reads the old name in the `Message` constructor and ~40 downstream sites, so message ids, acks, quoted-message resolution and media downloads break. Backports upstream fix #201832 (`Base._normalizeId()`). One known harmless reject on 1.34.7 (a LID-aware `Contact.js` path that does not exist there); any other reject aborts the build. | no-ops once `_normalizeId` exists upstream. Runtime double-check: `src/engine/adapters/wwebjs-backport-check.ts` detects an unpatched install and logs an error naming the fix as the wwjs session starts (`whatsapp-web-js.adapter.ts:446`). It is diagnostic, **not** preventive — startup continues, so a session reaching READY is not evidence the patch landed. |+| 🔧² | `scripts/patch-wwebjs-status.js` | whatsapp-web.js injected status send | Two independent breakages in current WhatsApp Web builds: (1) the `canCheckStatusRankingPosterGating()` helper is gone and its call threw before any status send — now called when present, `false` (pre-gating meaning) when not; (2) `sendStatusMediaMsgAction` changed signature from positional `(msg, mediaUpdate)` to a single options object — adopted from upstream PR #201816. The two edits of the media repair are all-or-nothing. | exact-shape match; unknown shape fails the build. |+| 🔧³ | `scripts/patch-wwebjs-newsletter-preview.js` | whatsapp-web.js `Injected/Utils.js` | Link-preview generation omitted the destination chat, so WhatsApp Web could not select the newsletter preview transport: `getLinkPreview(link)` → `getLinkPreview(link, chat)`. | exact-shape match; unknown shape fails the build. |+| 🔧⁴ | `scripts/patch-wwebjs-ready-sync.js` | whatsapp-web.js readiness pipeline | Two live-observed races: on a warm profile the page can reach `hasSynced=true` before the edge listener attaches (the whole post-auth pipeline silently never runs), and a partial `attachEventListeners` failure was swallowed (message bridge dead while sends still work). Adds an `eventsAttached` completion marker and fires the handler once when the level is already true; double-fire is deduped by the adapter. | exact-shape, one group all-or-nothing; unknown shape fails the build. |+| 🔧⁵ | `scripts/patch-baileys-appstate.js` | Baileys `lib/Socket/chats.js` | `resyncAppState`'s `while (collectionsToHandle.size)` loop: `query()` resolves `undefined` on its own 60s timeout, decoding to `{}`, and every loop exit — including the library's own attempts guard — lives inside `for (const key in decoded)`, which never runs on an empty decode. The loop would burn one 60s query per pass for the life of the socket (~1000 wasted queries/day). The patch adds the missing exit: empty decode → `break`. | exact-shape match; remove once upstream bounds the loop. |+| 🔧⁶ | `scripts/patch-baileys-newsletter-create.js` | Baileys `lib/Socket/newsletter.js` | `parseNewsletterCreateResponse` reads `thread.picture.id` eagerly, but `newsletterCreate` sends only `{ name, description }` — there is no picture parameter anywhere in the chain — so `thread.picture` is null on EVERY create and the parse threw for all of them. WhatsApp creates the newsletter server-side BEFORE the response is parsed, so each call returned 500 while leaving a real channel behind, and `createChannel` is non-idempotent, so a client retrying a 5xx leaked one orphan per attempt (confirmed on the test account). `description` has the same defect whenever the caller omits one. The patch reads every nested field defensively so the response's `id` — the only place the new channel's id appears — always survives. | exact-shape match; remove once upstream tolerates a pictureless newsletter. |+| 🔧⁷ | `scripts/patch-wwebjs-participant-arity.js` | whatsapp-web.js `GroupChat.js` | `removeParticipants`/`promoteParticipants`/`demoteParticipants` resolve each requested id against the group's own member collection and drop what they cannot find, then resolve `{status: 200}` for the batch. Dropping EVERY id left the WA Web request builder an empty repeated field, whose arity assertion threw — the caller saw an unnamed `500` on removal. Promote and demote have no such assertion, so they answered `200` claiming success for people WhatsApp never touched. The patch keeps the resolved array with its holes, skips the call when nothing resolved, and returns `matched` (one boolean per REQUESTED id) so the adapter can report a per-participant outcome instead of inventing one. | exact-shape match; remove once upstream reports which participants it acted on. |+| 🔧⁸ | `scripts/patch-wwebjs-block.js` | whatsapp-web.js `Contact.js` | `Contact.block()`/`unblock()` resolved their target through `getContactToBlockOnlyUseIfNoAssociatedChat`, which WhatsApp Web removed, so both answered an opaque `500` for every id shape. The replacement helpers `handleBlock`/`handleUnblock` are modal-driven UI wrappers that block nothing when called headless, and the server now refuses a phone-keyed block outright (`trying to block a pn contact without a chat`) because individual chats are keyed by LID while wwjs folds every id back to a phone number. Resolves through `WAWebLidMigrationUtils.toUserLid` to the chat-owning identity and calls `blockContact`/`unblockContact` directly, falling back to the original contact when no LID or chat exists. | exact-shape match on both bodies; unknown shape fails the build. |+| 🔧⁹ | `scripts/patch-wwebjs-group-description.js` | whatsapp-web.js `GroupChat.js` | `GroupChat.setDescription()` calls the page's `WAWebGroupModifyInfoJob.setGroupDescription(chatWid, description, newId, descId)` positionally, but that job now takes a single options object `{desc, groupWid, newDescId, prevDescId}`. The first positional argument lands where the object is read, every field comes back undefined, and `widToGroupJid(undefined)` throws inside the page — reaching the caller as a bare `500` while the library still types the method `Promise<boolean>`. `setGroupSubject` in the same module is still positional, which is why subjects kept working and made the Wid look innocent. The patch sends the options object, takes `newDescId` from `WARandomHex.randomHex(8)` as the product does, and maps an empty description to `desc: null` so it selects the job's delete branch rather than sending an empty body element. The open upstream fix #201895 changes the same call, but keeps `WAWebMsgKey.newId()` and passes an empty description through verbatim, so this patcher will not stand down when it lands and the `desc: null` mapping has to be carried over rather than dropped with it. | exact-shape match; unknown shape fails the build. |+| 🔧¹⁰ | `scripts/patch-wwebjs-media-id.js` | whatsapp-web.js `Injected/Utils.js` | Every media send failed on the WhatsApp Web builds rolled out on 2026-09-17 with `Data passed to getter must include an id property`, while text still sent. `window.WWebJS.sendMessage` builds the outgoing message with `id: newMsgKey` and then spreads the media model returned by `processMediaData` into it, and on those builds that model carries an enumerable private `__x_id` that clobbers the id when the `Msg` model initialises. The patch deletes `message.__x_id` right after the object is built, which is upstream's own fix (whatsapp-web.js PR #201923, unmerged, no release after 1.34.7). It stands down once the installed tree carries that line. | exact-shape match; unknown shape fails the build. |### 29.3.2 Which matrix rows depend on which patch-This is the patch visibility the matrix cells refer to. Every patch is engine-specific (7 on wwjs,+This is the patch visibility the matrix cells refer to. Every patch is engine-specific (8 on wwjs,2 on Baileys), and **no row carries a row-level patch mark on both engines**. The two column-widepatches are a separate matter: 🔧¹ underwrites every wwjs cell and 🔧⁵ every baileys cell, so inthat sense every row does depend on a patch on each side. "Patch-dependent" below means the@@ -991,7 +992,7 @@ adapter sources — re-derive the same way when anything changes:cannot repopulate; and `rejectCall`, whose `Call.reject()` resolves while the caller's phonekeeps ringing (all in 29.6.2). Each answers 501 on wwjs. `.d.ts` presence is not capability, andonly a live call distinguishes the two.-- **9** install-time patches (7 whatsapp-web.js + 2 Baileys), all exact and self-disabling.+- **10** install-time patches (8 whatsapp-web.js + 2 Baileys), all exact and self-disabling.- **0 phantom-support rows** — every `not-available` cell throws at the adapter boundary.- Remaining adapter-gaps (fixable in this repo, ranked): **#1** `getChannelMessages` (Baileys —fetch is one line, `BinaryNode`→`ChannelMessage` parser is the work); **#2** `subscribeToChannel`diff --git a/package.json b/package.jsonindex b078fcec0..8506a7ac8 100644--- a/package.json+++ b/package.json@@ -41,7 +41,7 @@"lint": "eslint \"{src,apps,libs,test}/**/*.ts\"","lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix","test": "jest",- "test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.spec.js scripts/patch-wwebjs-ready-sync.spec.js scripts/patch-wwebjs-participant-arity.spec.js scripts/patch-wwebjs-block.spec.js scripts/patch-wwebjs-group-description.spec.js scripts/patch-baileys-appstate.spec.js scripts/patch-baileys-newsletter-create.spec.js scripts/dockerfile-patchers.spec.js scripts/check-upstream-surface.spec.mjs scripts/check-sdk-docs.spec.mjs scripts/check-audit.spec.mjs scripts/check-contract-shapes.spec.mjs scripts/cli-entrypoint-guard.spec.mjs",+ "test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.spec.js scripts/patch-wwebjs-ready-sync.spec.js scripts/patch-wwebjs-participant-arity.spec.js scripts/patch-wwebjs-block.spec.js scripts/patch-wwebjs-group-description.spec.js scripts/patch-wwebjs-media-id.spec.js scripts/patch-baileys-appstate.spec.js scripts/patch-baileys-newsletter-create.spec.js scripts/dockerfile-patchers.spec.js scripts/check-upstream-surface.spec.mjs scripts/check-sdk-docs.spec.mjs scripts/check-audit.spec.mjs scripts/check-contract-shapes.spec.mjs scripts/cli-entrypoint-guard.spec.mjs","test:docs": "jest src/common/changelog-sections.spec.ts src/common/ci-privilege-gate.spec.ts src/common/docs-ci-jobs.spec.ts src/common/docs-coverage-policy.spec.ts src/common/docs-metrics-list.spec.ts src/common/openapi/docs-06-contract.spec.ts src/common/test-lane-partition.spec.ts src/config/docs-env-example.spec.ts src/config/openapi-contract.spec.ts src/config/openapi-export-pins.spec.ts src/config/wa-web-version-example-pin.spec.ts src/engine/docs-29-counts.spec.ts src/engine/engine-inventory-parity.spec.ts src/engine/engine-parity.spec.ts src/engine/inventory-mapping-direction.spec.ts src/engine/adapters/baileys-voice-waveform.spec.ts src/engine/adapters/wwebjs-newsletter-preview.spec.ts src/modules/audit/audit-coverage.spec.ts src/modules/auth/global-route-fence-coverage.spec.ts src/modules/auth/query-session-scope-coverage.spec.ts src/modules/docker/compose-network.spec.ts src/modules/queue/bull-board-mount-coverage.spec.ts src/common/release-gate-parity.spec.ts src/database/migrations/__tests__/migration-drift.spec.ts --testPathIgnorePatterns=/node_modules/","test:watch": "jest --watch","test:cov": "jest --coverage",diff --git a/scripts/patch-wwebjs-media-id.js b/scripts/patch-wwebjs-media-id.jsnew file mode 100644index 000000000..0d378f850--- /dev/null+++ b/scripts/patch-wwebjs-media-id.js@@ -0,0 +1,88 @@+/**+ * Strip the media model's private id from the outgoing message whatsapp-web.js builds.+ *+ * `window.WWebJS.sendMessage` builds the outgoing message with `id: newMsgKey` and then spreads+ * the media model returned by `processMediaData` into it. On the WhatsApp Web builds rolled out+ * on 2026-09-17 that model carries an enumerable private `__x_id`, which lands on the plain object+ * and clobbers the id when the `Msg` model initialises: every media send fails with "Data passed+ * to getter must include an id property (it's how we memoize) but got undefined" while text keeps+ * working. Upstream carries the one-line fix in whatsapp-web.js PR #201923, unmerged, with no+ * release after 1.34.7; this applies the same line.+ *+ * The source transform is deliberately exact and self-disabling. An unknown shape fails the+ * production image build instead of silently shipping without the fix, and the patch stands down+ * once the installed tree carries the line itself.+ */+'use strict';++const fs = require('fs');+const path = require('path');++const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');+const UTILS_PATH = path.join('src', 'util', 'Injected', 'Utils.js');+// The comment that follows the outgoing message object in sendMessage, unique in the file.+const ANCHOR = " // Bot's won't reply if canonicalUrl is set (linking)\n";+const FIX = ' delete message.__x_id;\n\n';++function occurrences(source, needle) {+ return source.split(needle).length - 1;+}++function applyBackport(wwjsDir = DEFAULT_WWJS) {+ const utilsFile = path.join(wwjsDir, UTILS_PATH);+ if (!fs.existsSync(utilsFile)) {+ throw new Error(`whatsapp-web.js Utils.js not found at ${utilsFile}`);+ }++ const source = fs.readFileSync(utilsFile, 'utf8');+ const anchorCount = occurrences(source, ANCHOR);+ const fixCount = occurrences(source, FIX + ANCHOR);++ if (anchorCount === 1 && fixCount === 1) {+ return {+ skipped: true,+ reason: 'installed whatsapp-web.js already strips the media model id',+ };+ }+ if (anchorCount !== 1 || fixCount !== 0) {+ throw new Error(+ `unsupported Utils.js shape (anchors: ${anchorCount}, fixes: ${fixCount}); ` ++ 're-evaluate the media id backport against the installed whatsapp-web.js',+ );+ }++ fs.writeFileSync(utilsFile, source.replace(ANCHOR, FIX + ANCHOR));+ return { skipped: false, note: 'media model id stripped from outgoing messages' };+}++/**+ * The stand-down branch above as a predicate, for the startup guard (engine-patch-status.ts).+ * Unreadable reads as applied: a tree we cannot inspect is not evidence of a broken one.+ */+function isApplied(wwjsDir = DEFAULT_WWJS) {+ try {+ const source = fs.readFileSync(path.join(wwjsDir, UTILS_PATH), 'utf8');+ return occurrences(source, ANCHOR) === 1 && occurrences(source, FIX + ANCHOR) === 1;+ } catch {+ return true;+ }+}++function run() {+ const bestEffort = process.argv.includes('--best-effort');+ try {+ const result = applyBackport();+ console.log(`patch-wwebjs-media-id: ${result.skipped ? `skipped: ${result.reason}` : result.note}`);+ } catch (error) {+ if (bestEffort) {+ console.warn(`patch-wwebjs-media-id: skipped: ${error.message}`);+ return;+ }+ console.error(`patch-wwebjs-media-id: ${error.message}`);+ process.exitCode = 1;+ }+}++if (require.main === module) run();++module.exports = { applyBackport, isApplied, ANCHOR, FIX };diff --git a/scripts/patch-wwebjs-media-id.spec.js b/scripts/patch-wwebjs-media-id.spec.jsnew file mode 100644index 000000000..143b41c3a--- /dev/null+++ b/scripts/patch-wwebjs-media-id.spec.js@@ -0,0 +1,75 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const os = require('os');+const path = require('path');++const { applyBackport, isApplied, ANCHOR, FIX } = require('./patch-wwebjs-media-id.js');++// The real shape around the anchor: the outgoing message object closes, then the bot comment.+const BEFORE = ` ...extraOptions,\n };\n\n${ANCHOR} if (botOptions) {\n`;+const AFTER = ` ...extraOptions,\n };\n\n${FIX}${ANCHOR} if (botOptions) {\n`;++function makeDependency(source) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openwa-media-id-'));+ const utils = path.join(root, 'src', 'util', 'Injected', 'Utils.js');+ fs.mkdirSync(path.dirname(utils), { recursive: true });+ fs.writeFileSync(utils, source);+ return { root, utils };+}++test('strips the media model id from the outgoing message before it is built', () => {+ const { root, utils } = makeDependency(`head\n${BEFORE}tail\n`);++ const result = applyBackport(root);++ assert.deepEqual(result, { skipped: false, note: 'media model id stripped from outgoing messages' });+ assert.equal(fs.readFileSync(utils, 'utf8'), `head\n${AFTER}tail\n`);+});++test('is idempotent once the fix is present', () => {+ const { root, utils } = makeDependency(`head\n${AFTER}tail\n`);+ const original = fs.readFileSync(utils, 'utf8');++ assert.deepEqual(applyBackport(root), {+ skipped: true,+ reason: 'installed whatsapp-web.js already strips the media model id',+ });+ assert.equal(fs.readFileSync(utils, 'utf8'), original);+});++test('reports the patch as applied only once the transform has run', () => {+ const { root } = makeDependency(`head\n${BEFORE}tail\n`);++ assert.equal(isApplied(root), false);+ applyBackport(root);+ assert.equal(isApplied(root), true);+});++test('rejects an unknown dependency shape without changing it', () => {+ const { root, utils } = makeDependency('window.WWebJS.sendMessage = async () => {};\n');+ const original = fs.readFileSync(utils, 'utf8');++ assert.throws(() => applyBackport(root), /unsupported Utils\.js shape/);+ assert.equal(fs.readFileSync(utils, 'utf8'), original);+});++test('rejects an ambiguous dependency shape without changing it', () => {+ const { root, utils } = makeDependency(`${BEFORE}${BEFORE}`);+ const original = fs.readFileSync(utils, 'utf8');++ assert.throws(() => applyBackport(root), /unsupported Utils\.js shape/);+ assert.equal(fs.readFileSync(utils, 'utf8'), original);+});++// The patch stands down when the fix is already there, so a shape carrying both the fix and a+// second anchor is not one it understands either.+test('rejects a fix present alongside a second anchor', () => {+ const { root, utils } = makeDependency(`${AFTER}${BEFORE}`);+ const original = fs.readFileSync(utils, 'utf8');++ assert.throws(() => applyBackport(root), /unsupported Utils\.js shape/);+ assert.equal(fs.readFileSync(utils, 'utf8'), original);+});diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex 938d6e301..6a9d772e7 100644--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -27,11 +27,13 @@* unblock after WhatsApp Web removed the contact resolver they used.* 8. `node scripts/patch-wwebjs-group-description.js --best-effort` when present, realigning the* group-description job call with the options object the page now takes, gated the same way.- * 9. `node scripts/patch-baileys-appstate.js --best-effort` when present, the app-state resync+ * 9. `node scripts/patch-wwebjs-media-id.js --best-effort` when present, stripping the media+ * model's private id from the outgoing message so media sends work again, gated the same way.+ * 10. `node scripts/patch-baileys-appstate.js --best-effort` when present, the app-state resync* bound, gated the same way.- * 10. `node scripts/patch-baileys-newsletter-create.js --best-effort` when present, the- * newsletter-create parse fix. Steps 9-10 are the Baileys patches, so a Baileys-only install- * runs those and skips 2-8.+ * 11. `node scripts/patch-baileys-newsletter-create.js --best-effort` when present, the+ * newsletter-create parse fix. Steps 10-11 are the Baileys patches, so a Baileys-only install+ * runs those and skips 2-9.** Structured like scripts/patch-wwebjs-201832.js: pure planning + injectable spawn, so the spec* (scripts/postinstall.spec.js, node:test) exercises every branch without a real npm run.@@ -140,6 +142,15 @@ function planSteps(root, env = process.env) {options: { stdio: 'inherit', cwd: root, env: cleanEnv },});}+ const mediaIdPatcher = path.join(root, 'scripts', 'patch-wwebjs-media-id.js');+ if (fs.existsSync(mediaIdPatcher)) {+ steps.push({+ name: 'whatsapp-web.js media send repair (scripts/patch-wwebjs-media-id.js --best-effort)',+ command: process.execPath,+ args: [mediaIdPatcher, '--best-effort'],+ options: { stdio: 'inherit', cwd: root, env: cleanEnv },+ });+ }const baileysAppStatePatcher = path.join(root, 'scripts', 'patch-baileys-appstate.js');if (fs.existsSync(baileysAppStatePatcher)) {steps.push({diff --git a/scripts/postinstall.spec.js b/scripts/postinstall.spec.jsindex 58fce40db..bb2878df3 100644--- a/scripts/postinstall.spec.js+++ b/scripts/postinstall.spec.js@@ -32,6 +32,7 @@ const EXPECTED_PATCHER_ORDER = ['patch-wwebjs-participant-arity.js','patch-wwebjs-block.js','patch-wwebjs-group-description.js',+ 'patch-wwebjs-media-id.js','patch-baileys-appstate.js','patch-baileys-newsletter-create.js',];