Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): pass the mimetype so inbound media downloads work again
Yudhi Armyndharis6a525407aa59
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 76c16a3b0..33d2379a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -56,6 +56,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The container no longer crash-loops at start when `/app/data` is a bind mount that refuses to change a symlink's owner, such as Docker Desktop file sharing: the entrypoint re-owns `/app/data` without touching or following symlinks, so a Chromium lock left by an unclean stop, under any session path, no longer stops it. Thanks @Nexiler for the report.- whatsapp-web.js: `GET /api/sessions/:sessionId/contacts`, `GET /api/sessions/:sessionId/chats` and `GET /api/sessions/:sessionId/groups` answer `503` instead of `500` when the read outruns the Puppeteer protocol timeout.- whatsapp-web.js: a forward no longer reports the id of another message sent to the same chat in the same second.+- whatsapp-web.js: inbound media downloads work again on current WhatsApp Web builds, where media the page had not downloaded before arrived as the `omitted` marker and the media route answered `404` ([#1739](https://github.com/rmyndharis/OpenWA/issues/1739)). Thanks @orezraey for the report.- whatsapp-web.js: an inbound media download whose caller already gave up is skipped, so messages that arrive after a burst keep their media.- whatsapp-web.js: a document sent from a URL without a filename is named after the percent-decoded URL basename.- whatsapp-web.js: listing chats or groups on a large account no longer blocks the page long enough for the liveness watchdog to disconnect a healthy session ([#1501](https://github.com/rmyndharis/OpenWA/issues/1501)).diff --git a/Dockerfile b/Dockerfileindex de222e22a..e4217b8fc 100644--- a/Dockerfile+++ b/Dockerfile@@ -190,7 +190,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-wwebjs-media-id.js scripts/patch-wwebjs-send-error.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-wwebjs-send-error.js scripts/patch-wwebjs-download-mimetype.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.@@ -218,6 +218,7 @@ RUN npm ci --omit=dev --ignore-scripts \&& node scripts/patch-wwebjs-group-description.js \&& node scripts/patch-wwebjs-media-id.js \&& node scripts/patch-wwebjs-send-error.js \+ && node scripts/patch-wwebjs-download-mimetype.js \&& node scripts/patch-baileys-appstate.js \&& node scripts/patch-baileys-newsletter-create.js \&& npm cache clean --forcediff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 0844486ac..22786676c 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -765,7 +765,7 @@ rm -rf node_modules/whatsapp-web.js && npm ciblock/unblock refusing every id, a status media send that never arrives, a group description thatcannot be set, an app-state resync that never settles-**Cause:** OpenWA applies eleven exact source transforms to its engine libraries at install time+**Cause:** OpenWA applies twelve exact source transforms to its engine libraries at install time(docs/29 §29.3). The Docker image runs them without `--best-effort`, so a source shape a patchercannot recognise fails the image build. A source install runs them through `scripts/postinstall.js`with `--best-effort`, where a patcher that cannot apply prints one line into a long `npm install`diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex a3e5d8ffb..29b38df1c 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-11 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.+12 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/>+ 9 OpenWA patches"]+ WA --> WLIB["whatsapp-web.js 1.34.7<br/>+ 10 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"]@@ -127,7 +127,7 @@ wrong interface method. Those three remain reader-verified.## 29.3 Install-time patches OpenWA applies to the libraries-OpenWA ships eleven exact, self-disabling source transforms over the installed engines. Each runs at+OpenWA ships twelve 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@@ -140,7 +140,7 @@ 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 eleven patches+### 29.3.1 The twelve patches| # | Patcher | Library target | What it repairs | Stand-down predicate || ---- | ---------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |@@ -155,10 +155,11 @@ reaching READY is not evidence that every patch landed. See docs/12 for the oper| 🔧⁹ | `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 built by `processMediaData` 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. || 🔧¹¹ | `scripts/patch-wwebjs-send-error.js` | whatsapp-web.js `Client.js` | A send the page refused reached OpenWA as the minified `t: t`, with nothing but Node frames: puppeteer rebuilds a page-side exception from its class name and description only, and WhatsApp Web's own error classes are minified to one letter and keep their detail in their own properties. The patch wraps the `window.WWebJS.sendMessage` call inside `Client.sendMessage`'s evaluate. A plain `Error`, which is what whatsapp-web.js's own send failures and WhatsApp Web's `No LID for user` already are, is rethrown as the same object, so its text and OpenWA's matching on it are unchanged. Anything else is rethrown as an `Error` reading `page threw {...}`, a capped JSON summary of the WhatsApp Web build actually running, the constructor name, `name`, `message`, `stack` and the value's own properties. Diagnostic only: a successful send returns what it returned before, and the dead-page classifier never reads a captured error as a transport death. | exact-shape match; unknown shape fails the build. |+| 🔧¹² | `scripts/patch-wwebjs-download-mimetype.js` | whatsapp-web.js `Message.js` | Every download of inbound media the page had not decrypted before failed on current WhatsApp Web builds, so webhooks, the chat-media archive and `history?includeMedia=true` carried the `omitted` marker and the media route answered `404`. `Message#downloadMedia()` calls `downloadAndMaybeDecrypt()` without a `mimetype`; WhatsApp Web defaults the missing value to `application/octet-stream`, rejects it as the wrong type for the media, and the `InvalidMediaFileType` it throws reaches OpenWA as `t: t`. A file the page already decrypted comes from a cache keyed by file hash and skips that check, which is why some downloads kept working. The patch passes `msg.mimetype` to the call, the fix diagnosed in whatsapp-web.js issue #201908 (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 (9 on wwjs,+This is the patch visibility the matrix cells refer to. Every patch is engine-specific (10 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 a patch@@ -178,6 +179,7 @@ class of rows (🔧⁸ and 🔧¹⁰), stated in the table instead.| 🔧⁸ block/unblock | `blockContact`, `unblockContact` on **wwjs**. Without it both answer an opaque `500` on every id, so the capability is dead rather than degraded; the blocklist read still works, which makes the failure look one-sided. || 🔧¹⁰ media send repair | Every **wwjs** media send built by `processMediaData`: `sendImageMessage`, `sendVideoMessage`, `sendAudioMessage` (voice notes included, through `ptt`), `sendDocumentMessage` and the media status posts. A sticker is built by `processStickerData`, which returns a new object rather than the media model. On the WhatsApp Web builds from 2026-09-17 the library's own id is clobbered by the media model and every such send answers a bare `500`, while text sends keep working. Not row-marked: it covers a whole class of rows rather than one. || 🔧¹¹ send error capture | No row. Every **wwjs** send that fails in the page reports what the page threw instead of `t: t`, but no cell's outcome depends on it: a send that works without the patch works the same way with it. |+| 🔧¹² download mimetype | No single row. Every **wwjs** media download goes through `Message#downloadMedia()`: inbound message media (webhook, chat-media archive, the media route), the own-send echo, `getChatHistory` with `includeMedia`, and received statuses. Without it, media the page has not decrypted before arrives as the `omitted` marker instead of its bytes; the messages themselves still arrive. |Rows that are ✅ on **both** engines where one side is patch-dependent: `initialize` (🔧⁴ wwjs),`sendTextMessage` (🔧³ wwjs), `postTextStatus` / `postImageStatus` / `postVideoStatus` /@@ -1028,7 +1030,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.-- **11** install-time patches (9 whatsapp-web.js + 2 Baileys), all exact and self-disabling.+- **12** install-time patches (10 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 27024020f..c339b668f 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-wwebjs-media-id.spec.js scripts/patch-wwebjs-send-error.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/check-sdk-coverage.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-wwebjs-send-error.spec.js scripts/patch-wwebjs-download-mimetype.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/check-sdk-coverage.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/docs-next-version.spec.ts src/common/docs-sdk-rate-limit.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/docs-27-backfill-engine.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 src/common/docs-governance.spec.ts --testPathIgnorePatterns=/node_modules/","test:watch": "jest --watch","test:cov": "jest --coverage",diff --git a/scripts/patch-wwebjs-download-mimetype.js b/scripts/patch-wwebjs-download-mimetype.jsnew file mode 100644index 000000000..d6cd80dd0--- /dev/null+++ b/scripts/patch-wwebjs-download-mimetype.js@@ -0,0 +1,91 @@+/**+ * Pass the message's mimetype to the media download whatsapp-web.js runs in the page.+ *+ * `Message#downloadMedia()` decrypts through `WAWebDownloadManager.downloadAndMaybeDecrypt()`+ * without a `mimetype`. Current WhatsApp Web builds default the missing value to+ * `application/octet-stream` and check it against the media type, so every download of media the+ * page has not decrypted before fails with `InvalidMediaFileType`, which reaches Node as the+ * minified `t: t`. Media the page already decrypted comes from a cache keyed by file hash and skips+ * that check, which is why some downloads still succeed. Diagnosed upstream in whatsapp-web.js+ * issue #201908, with no release after 1.34.7; this adds the option that issue identifies.+ *+ * 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 MESSAGE_PATH = path.join('src', 'structures', 'Message.js');+// The two options of the downloadAndMaybeDecrypt call in downloadMedia the fix goes between,+// unique in the file.+const TYPE_LINE = ' type: msg.type,\n';+const SIGNAL_LINE = ' signal: new AbortController().signal,\n';+const ANCHOR = TYPE_LINE + SIGNAL_LINE;+const FIX = TYPE_LINE + ' mimetype: msg.mimetype,\n' + SIGNAL_LINE;++function occurrences(source, needle) {+ return source.split(needle).length - 1;+}++function applyBackport(wwjsDir = DEFAULT_WWJS) {+ const messageFile = path.join(wwjsDir, MESSAGE_PATH);+ if (!fs.existsSync(messageFile)) {+ throw new Error(`whatsapp-web.js Message.js not found at ${messageFile}`);+ }++ const source = fs.readFileSync(messageFile, 'utf8');+ const anchorCount = occurrences(source, ANCHOR);+ const fixCount = occurrences(source, FIX);++ if (anchorCount === 0 && fixCount === 1) {+ return {+ skipped: true,+ reason: 'installed whatsapp-web.js already passes the mimetype to the media download',+ };+ }+ if (anchorCount !== 1 || fixCount !== 0) {+ throw new Error(+ `unsupported Message.js shape (anchors: ${anchorCount}, fixes: ${fixCount}); ` ++ 're-evaluate the media download backport against the installed whatsapp-web.js',+ );+ }++ fs.writeFileSync(messageFile, source.replace(ANCHOR, FIX));+ return { skipped: false, note: 'mimetype passed to the media download' };+}++/**+ * 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, MESSAGE_PATH), 'utf8');+ return occurrences(source, ANCHOR) === 0 && occurrences(source, FIX) === 1;+ } catch {+ return true;+ }+}++function run() {+ const bestEffort = process.argv.includes('--best-effort');+ try {+ const result = applyBackport();+ console.log(`patch-wwebjs-download-mimetype: ${result.skipped ? `skipped: ${result.reason}` : result.note}`);+ } catch (error) {+ if (bestEffort) {+ console.warn(`patch-wwebjs-download-mimetype: skipped: ${error.message}`);+ return;+ }+ console.error(`patch-wwebjs-download-mimetype: ${error.message}`);+ process.exitCode = 1;+ }+}++if (require.main === module) run();++module.exports = { applyBackport, isApplied, ANCHOR, FIX };diff --git a/scripts/patch-wwebjs-download-mimetype.spec.js b/scripts/patch-wwebjs-download-mimetype.spec.jsnew file mode 100644index 000000000..38af30529--- /dev/null+++ b/scripts/patch-wwebjs-download-mimetype.spec.js@@ -0,0 +1,76 @@+'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-download-mimetype.js');++// The real shape around the anchor: the options object of the downloadAndMaybeDecrypt call.+const BEFORE = ` mediaKeyTimestamp: msg.mediaKeyTimestamp,\n${ANCHOR} downloadQpl: mockQpl,\n`;+const AFTER = ` mediaKeyTimestamp: msg.mediaKeyTimestamp,\n${FIX} downloadQpl: mockQpl,\n`;++function makeDependency(source) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openwa-download-mimetype-'));+ const message = path.join(root, 'src', 'structures', 'Message.js');+ fs.mkdirSync(path.dirname(message), { recursive: true });+ fs.writeFileSync(message, source);+ return { root, message };+}++test('passes the mimetype to the media download', () => {+ const { root, message } = makeDependency(`head\n${BEFORE}tail\n`);++ const result = applyBackport(root);++ assert.deepEqual(result, { skipped: false, note: 'mimetype passed to the media download' });+ assert.equal(fs.readFileSync(message, 'utf8'), `head\n${AFTER}tail\n`);+});++test('is idempotent once the fix is present', () => {+ const { root, message } = makeDependency(`head\n${AFTER}tail\n`);+ const original = fs.readFileSync(message, 'utf8');++ assert.deepEqual(applyBackport(root), {+ skipped: true,+ reason: 'installed whatsapp-web.js already passes the mimetype to the media download',+ });+ assert.equal(fs.readFileSync(message, '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, message } = makeDependency('class Message {}\n');+ const original = fs.readFileSync(message, 'utf8');++ assert.throws(() => applyBackport(root), /unsupported Message\.js shape/);+ assert.equal(fs.readFileSync(message, 'utf8'), original);+});++test('rejects an ambiguous dependency shape without changing it', () => {+ const { root, message } = makeDependency(`${BEFORE}${BEFORE}`);+ const original = fs.readFileSync(message, 'utf8');++ assert.throws(() => applyBackport(root), /unsupported Message\.js shape/);+ assert.equal(fs.readFileSync(message, 'utf8'), original);+});++// The patch stands down when the fix is already there, so a shape carrying both the fix and an+// unpatched call is not one it understands either.+test('rejects a fix present alongside an unpatched call', () => {+ const { root, message } = makeDependency(`${AFTER}${BEFORE}`);+ const original = fs.readFileSync(message, 'utf8');++ assert.throws(() => applyBackport(root), /unsupported Message\.js shape/);+ assert.equal(fs.readFileSync(message, 'utf8'), original);+ assert.equal(isApplied(root), false);+});diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex 972a5d761..a6ac4a6b3 100644--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -1,7 +1,7 @@/*** Post-install hook (npm `postinstall`).*- * Twelve conditional steps, each skipped when its target is absent so the hook is a no-op where the+ * Thirteen conditional steps, each skipped when its target is absent so the hook is a no-op where the* piece is missing (the Docker builder stage copies package*.json long before any source):** 1. `npm ci` inside dashboard/ when dashboard/ exists — the dashboard carries its own lockfile and@@ -32,10 +32,13 @@* 10. `node scripts/patch-wwebjs-send-error.js --best-effort` when present, making a failed send* report what the page threw instead of `t: t`, gated the same way. It runs after the other* two Client.js patchers (steps 2 and 5), so theirs still meet the tree they were written for.- * 11. `node scripts/patch-baileys-appstate.js --best-effort` when present, the app-state resync+ * 11. `node scripts/patch-wwebjs-download-mimetype.js --best-effort` when present, passing the+ * message's mimetype to the media download so inbound media downloads work again, gated the+ * same way.+ * 12. `node scripts/patch-baileys-appstate.js --best-effort` when present, the app-state resync* bound, gated the same way.- * 12. `node scripts/patch-baileys-newsletter-create.js --best-effort` when present, the- * newsletter-create parse fix. Steps 11-12 are the Baileys patches. Every patcher runs whenever+ * 13. `node scripts/patch-baileys-newsletter-create.js --best-effort` when present, the+ * newsletter-create parse fix. Steps 12-13 are the Baileys patches. Every patcher runs whenever* its script is present, whatever ENGINE_TYPE is set to.** Structured like scripts/patch-wwebjs-201832.js: pure planning + injectable spawn, so the spec@@ -163,6 +166,15 @@ function planSteps(root, env = process.env) {options: { stdio: 'inherit', cwd: root, env: cleanEnv },});}+ const downloadMimetypePatcher = path.join(root, 'scripts', 'patch-wwebjs-download-mimetype.js');+ if (fs.existsSync(downloadMimetypePatcher)) {+ steps.push({+ name: 'whatsapp-web.js media download mimetype (scripts/patch-wwebjs-download-mimetype.js --best-effort)',+ command: process.execPath,+ args: [downloadMimetypePatcher, '--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 1a8465be4..c8dff88da 100644--- a/scripts/postinstall.spec.js+++ b/scripts/postinstall.spec.js@@ -34,6 +34,7 @@ const EXPECTED_PATCHER_ORDER = ['patch-wwebjs-group-description.js','patch-wwebjs-media-id.js','patch-wwebjs-send-error.js',+ 'patch-wwebjs-download-mimetype.js','patch-baileys-appstate.js','patch-baileys-newsletter-create.js',];diff --git a/src/engine/docs-29-counts.spec.ts b/src/engine/docs-29-counts.spec.tsindex f087096a9..e908f8c71 100644--- a/src/engine/docs-29-counts.spec.ts+++ b/src/engine/docs-29-counts.spec.ts@@ -154,6 +154,7 @@ describe('docs/29 counts match the capability matrix', () => {nine: 9,ten: 10,eleven: 11,+ twelve: 12,};const spelled = doc.match(/OpenWA ships (\w+) exact, self-disabling source transforms/);const wrongProse: string[] = [];