Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): refresh pairing credentials
Yudhi Armyndharis1d46f11e20d7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9a0d4c80f..8f772681e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Refresh Baileys pairing secrets and prevent stale QR renders during linking.- Upgrade proxy-addr to 2.0.8 to correct IPv4-mapped IPv6 proxy trust matching.- Upgrade source-map-js to 1.2.2 to validate indexed source-map offsets.- Fix Baileys first-contact addresses and reject phone numbers reported as unregistered before sending.diff --git a/Dockerfile b/Dockerfileindex ffd403327..d508425a2 100644--- a/Dockerfile+++ b/Dockerfile@@ -191,7 +191,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-wwebjs-download-mimetype.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/patch-baileys-pairing.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.@@ -222,6 +222,7 @@ RUN npm ci --omit=dev --ignore-scripts \&& node scripts/patch-wwebjs-download-mimetype.js \&& node scripts/patch-baileys-appstate.js \&& node scripts/patch-baileys-newsletter-create.js \+ && node scripts/patch-baileys-pairing.js \&& npm cache clean --force# Replace the npm the base image bundles. npm is not on the request path — the entrypoint runsdiff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex f74747958..ee43e58e8 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-12 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.+13 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.## 29.1 How to read this matrix@@ -51,7 +51,7 @@ flowchart LRSVC --> STORE["OpenWA-side stores"]endWA --> WLIB["whatsapp-web.js 1.34.7<br/>+ 10 OpenWA patches"]- BA --> BLIB["@whiskeysockets/baileys 7.0.0-rc14<br/>+ 2 OpenWA patches"]+ BA --> BLIB["@whiskeysockets/baileys 7.0.0-rc14<br/>+ 3 OpenWA patches"]WLIB --> WEB["WhatsApp Web<br/>headless Chromium"]BLIB --> WAS["WhatsApp servers<br/>browser-free socket"]WA -.->|"not-available"| E["EngineNotSupportedError<br/>HTTP 501"]@@ -128,11 +128,11 @@ wrong interface method. Those three remain reader-verified.## 29.3 Install-time patches OpenWA applies to the libraries-OpenWA ships twelve exact, self-disabling source transforms over the installed engines. Each runs at+OpenWA ships thirteen 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 the-patcher no-ops once the fix is present upstream, and an unrecognized source shape fails loudly-rather than shipping a silently partial patch.+(**without** best-effort — dependency drift fails the image build). A recognized repaired source shape makes the+patcher no-op; an unrecognized source shape fails loudly rather than shipping a silently partial+patch. Retire the rc14 pairing backport once an upstream release includes both fixes."Fails loudly" holds for the image build, not for `npm install`, where `--best-effort` turns arefusal into one line of a long transcript. So each patcher also exports an `isApplied()` predicate,@@ -141,27 +141,28 @@ 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 twelve 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, in `WwebjsLifecycle.initialize()`. 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 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.1 The thirteen 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, in `WwebjsLifecycle.initialize()`. 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. |+| Repair | `scripts/patch-baileys-pairing.js` | Baileys `lib/Socket/socket.js`, `messages-recv.js` | Send notification ACKs before login. Rotate retired registration secrets, persist them and refresh the current QR without consuming another reference. | Exact rc14 backport; remove once an upstream release includes both fixes. |+| 🔧⁷ | `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 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 patchThis 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-wide+3 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 patchthis row needs specifically, which is usually marked in the row and, for the two that cover a whole@@ -1033,7 +1034,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.-- **12** install-time patches (10 whatsapp-web.js + 2 Baileys), all exact and self-disabling.+- **13** install-time patches (10 whatsapp-web.js + 3 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 26bbb6b69..d08b65f60 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/proxy-addr.spec.js 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/smoke-test-docker-proxy.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/proxy-addr.spec.js 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/patch-baileys-pairing.spec.js scripts/baileys-pairing.integration.spec.mjs scripts/dockerfile-patchers.spec.js scripts/smoke-test-docker-proxy.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/baileys-pairing.integration.spec.mjs b/scripts/baileys-pairing.integration.spec.mjsnew file mode 100644index 000000000..c30ec2dd2--- /dev/null+++ b/scripts/baileys-pairing.integration.spec.mjs@@ -0,0 +1,185 @@+// Exercise the pinned Baileys socket over loopback WebSocket.+// Loopback WebSocket transport; no WhatsApp traffic, account or persisted auth.+import test from 'node:test';+import assert from 'node:assert/strict';+import { createRequire } from 'node:module';+import { pathToFileURL } from 'node:url';+import path from 'node:path';+import { once } from 'node:events';+const require = createRequire(process.env.BAILEYS_TEST_PROVIDER_PACKAGE || import.meta.url);+const root = path.dirname(require.resolve('@whiskeysockets/baileys/package.json'));+const load = relative => import(pathToFileURL(path.join(root, relative)));+const { default: makeWASocket } = await load('lib/Socket/index.js');+const { initAuthCreds } = await load('lib/Utils/auth-utils.js');+const { DEF_CALLBACK_PREFIX } = await load('lib/Defaults/index.js');+const { decodeBinaryNode } = await load('lib/WABinary/index.js');+const { WebSocketServer } = require('ws');+function deliver(ws, node) {+ const child = Array.isArray(node.content) ? node.content[0]?.tag : '';+ for (const [attr, value] of Object.entries(node.attrs)) {+ ws.emit(`${DEF_CALLBACK_PREFIX}${node.tag},${attr}:${value},${child}`, node);+ ws.emit(`${DEF_CALLBACK_PREFIX}${node.tag},${attr}:${value}`, node);+ ws.emit(`${DEF_CALLBACK_PREFIX}${node.tag},${attr}`, node);+ }+ ws.emit(`${DEF_CALLBACK_PREFIX}${node.tag},,${child}`, node);+ ws.emit(`${DEF_CALLBACK_PREFIX}${node.tag}`, node);+}+function nextQr(sock) {+ return new Promise(resolve => {+ const listener = update => {+ if (update.qr) {+ sock.ev.off('connection.update', listener);+ resolve(update.qr);+ }+ };+ sock.ev.on('connection.update', listener);+ });+}+const refresh = child => ({+ tag: 'notification',+ attrs: { id: 'fixture-refresh', from: 's.whatsapp.net', type: 'companion_reg_refresh' },+ content: child ? [{ tag: child, attrs: {} }] : [],+});+async function boot(t) {+ const server = new WebSocketServer({ host: '127.0.0.1', port: 0 });+ await once(server, 'listening');+ server.on('connection', client =>+ client.on('message', data => {+ const frame = Buffer.from(data);+ server.emit('fixture-frame', frame);+ }),+ );+ const errors = [],+ logger = {+ level: 'silent',+ child: () => logger,+ trace() {},+ debug() {},+ info() {},+ warn() {},+ error() {+ errors.push(true);+ },+ };+ const creds = initAuthCreds();+ let sock;+ t.after(async () => {+ await sock?.end(new Error('fixture complete'));+ for (const client of server.clients) client.terminate();+ await new Promise(resolve => server.close(resolve));+ });+ sock = makeWASocket({+ auth: { creds, keys: { get: async () => ({}), set: async () => {} } },+ logger,+ waWebSocketUrl: `ws://127.0.0.1:${server.address().port}`,+ connectTimeoutMs: 5000,+ qrTimeout: 10000,+ });+ if (!sock.ws.isOpen) await once(sock.ws, 'open');+ const qrs = [],+ updates = [];+ sock.ev.on('connection.update', update => {+ if (update.qr) qrs.push(update.qr);+ });+ sock.ev.on('creds.update', update => updates.push(update));+ return { sock, creds, qrs, updates, errors, server };+}+const pairDevice = () => ({+ tag: 'iq',+ attrs: { from: 's.whatsapp.net', type: 'set', id: 'fixture-pair' },+ content: [+ {+ tag: 'pair-device',+ attrs: {},+ content: ['fixture-ref-1', 'fixture-ref-2'].map(ref => ({ tag: 'ref', attrs: {}, content: Buffer.from(ref) })),+ },+ ],+});+for (const child of ['companion_reg_refresh', 'pair-device-rotate-qr'])+ test('real socket emits fresh credentials and renders same ref for ' + child, { timeout: 10000 }, async t => {+ const { sock, creds, qrs, updates, errors } = await boot(t);+ let qr = nextQr(sock);+ deliver(sock.ws, pairDevice());+ await qr;+ const initial = qrs[0].split('#')[1].split(','),+ secret = creds.advSecretKey;+ qr = nextQr(sock);+ deliver(sock.ws, refresh(child));+ await qr;+ const current = qrs[1].split('#')[1].split(',');+ assert.equal(current[0], initial[0]);+ assert.deepEqual(current.slice(1, 3), initial.slice(1, 3));+ assert.notEqual(current[3], secret);+ assert.equal(current[3], creds.advSecretKey);+ assert.equal(Buffer.from(current[3], 'base64').length, 32);+ assert.ok(updates.some(update => update.advSecretKey === current[3]));+ for (let n = 0; n < 50; n++) deliver(sock.ws, refresh(child));+ assert.equal(qrs.length, 52);+ assert.ok(qrs.every(value => value.split('#')[1].split(',')[0] === initial[0]));+ // Generic notification handler still runs concurrently and must not throw.+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(errors.length, 0);+ });+test('real ACK succeeds before login and writes the expected notification stanza', { timeout: 10000 }, async t => {+ const { sock, creds, server, errors } = await boot(t);+ const receiveAck = () =>+ new Promise(resolve =>+ server.on('fixture-frame', async frame => {+ try {+ const offset = frame.subarray(0, 2).toString() === 'WA' ? 7 : 3;+ const node = await decodeBinaryNode(frame.subarray(offset));+ if (node.tag === 'ack') resolve(node);+ } catch {}+ }),+ );+ const received = receiveAck();+ await sock.sendMessageAck(refresh('companion_reg_refresh'));+ const ack = await received;+ assert.deepEqual(ack.attrs, {+ id: 'fixture-refresh',+ to: 's.whatsapp.net',+ class: 'notification',+ type: 'companion_reg_refresh',+ });+ creds.me = { id: '[email protected]' };+ const registeredAck = receiveAck();+ await sock.sendMessageAck(+ {+ tag: 'message',+ attrs: {+ id: 'registered-message',+ from: '[email protected]',+ participant: '[email protected]',+ type: 'text',+ },+ },+ 42,+ );+ assert.deepEqual((await registeredAck).attrs, {+ id: 'registered-message',+ to: '[email protected]',+ class: 'message',+ error: '42',+ participant: '[email protected]',+ type: 'text',+ from: creds.me.id,+ });+ assert.equal(errors.length, 0);+});+test('malformed refresh and established identity leave credentials and QR intact', { timeout: 10000 }, async t => {+ const { sock, creds, qrs, updates } = await boot(t);+ let qr = nextQr(sock);+ deliver(sock.ws, pairDevice());+ await qr;+ const secret = creds.advSecretKey;+ deliver(sock.ws, refresh());+ deliver(sock.ws, refresh('wrong-child'));+ assert.equal(qrs.length, 1);+ assert.equal(creds.advSecretKey, secret);+ assert.equal(updates.length, 0);+ creds.me = { id: '[email protected]', name: 'fixture' };+ deliver(sock.ws, refresh('companion_reg_refresh'));+ assert.equal(qrs.length, 1);+ assert.equal(creds.advSecretKey, secret);+ assert.equal(updates.length, 0);+});diff --git a/scripts/patch-baileys-pairing.js b/scripts/patch-baileys-pairing.jsnew file mode 100644index 000000000..018241586--- /dev/null+++ b/scripts/patch-baileys-pairing.js@@ -0,0 +1,174 @@+/**+ * Exact rc14 backports of WhiskeySockets/Baileys #2749 and #2765.+ * Pre-login notifications have no creds.me; ACKs must still be sent. When WA+ * retires unpaired registration material, rotate only its advertisement secret,+ * persist it through creds.update and re-render the current QR without spending+ * another ref. Registered/pairing-code sessions and malformed nodes stay intact.+ * Sources: https://github.com/WhiskeySockets/Baileys/pull/2749 (3868667)+ * https://github.com/WhiskeySockets/Baileys/pull/2765 (4f263f0)+ * Neither PR is merged. Retire after an upstream release includes both fixes.+ * All shapes are checked before writing. Unknown or partially patched trees fail.+ */+'use strict';+const fs = require('fs');+const path = require('path');+const DEFAULT_BAILEYS = path.join(__dirname, '..', 'node_modules', '@whiskeysockets', 'baileys');+const QR_FIND = String.raw` // QR gen+ ws.on('CB:iq,type:set,pair-device', async (stanza) => {+ const iq = {+ tag: 'iq',+ attrs: {+ to: S_WHATSAPP_NET,+ type: 'result',+ id: stanza.attrs.id+ }+ };+ await sendNode(iq);+ const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');+ const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');+ const advB64 = creds.advSecretKey;+ let qrMs = qrTimeout || 60000; // time to let a QR live+ const genPairQR = () => {+ if (!ws.isOpen) {+ return;+ }+ const refNode = refNodes.shift();+ if (!refNode) {+ void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));+ return;+ }+ const ref = refNode.content.toString('utf-8');+ const qr = buildPairingQRData(ref, noiseKeyB64, identityKeyB64, advB64, browser);+ ev.emit('connection.update', { qr });+ qrTimer = setTimeout(genPairQR, qrMs);+ qrMs = qrTimeout || 20000; // shorter subsequent qrs+ };+ genPairQR();+ });+`;+const QR_REPLACE = String.raw` // OpenWA: Baileys #2765 companion registration refresh (rc14 backport).+ let refreshPairingQR;+ ws.on('CB:iq,type:set,pair-device', async (stanza) => {+ await sendNode({tag: 'iq', attrs: {to: S_WHATSAPP_NET, type: 'result', id: stanza.attrs.id}});+ const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');+ const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');+ let currentRef;+ const renderQR = () => {+ if (!ws.isOpen || currentRef === undefined || creds.me) return;+ // Read the secret on every render: the server can retire it mid-flow.+ const qr = buildPairingQRData(currentRef, noiseKeyB64, identityKeyB64, creds.advSecretKey, browser);+ ev.emit('connection.update', {qr});+ };+ refreshPairingQR = renderQR;+ let qrMs = qrTimeout || 60000;+ const genPairQR = () => {+ if (!ws.isOpen || creds.me) return;+ const refNode = refNodes.shift();+ if (!refNode) {+ void end(new Boom('QR refs attempts ended', {statusCode: DisconnectReason.timedOut}));+ return;+ }+ currentRef = refNode.content.toString('utf-8');+ renderQR();+ qrTimer = setTimeout(genPairQR, qrMs);+ qrMs = qrTimeout || 20000;+ };+ clearTimeout(qrTimer);+ genPairQR();+ });+ ws.on('CB:notification,type:companion_reg_refresh', node => {+ if (creds.me || !ws.isOpen) return;+ if (!['companion_reg_refresh', 'pair-device-rotate-qr'].some(tag => getBinaryNodeChild(node, tag))) return;+ creds.advSecretKey = randomBytes(32).toString('base64');+ ev.emit('creds.update', {advSecretKey: creds.advSecretKey});+ logger.info({}, 'companion registration refreshed');+ // Re-render the same ref. Do not consume the pool or reset its timer.+ refreshPairingQR?.();+ });+`;+const ACK_FIND = 'buildAckStanza(node, errorCode, authState.creds.me.id)';+const ACK_REPLACE = 'buildAckStanza(node, errorCode, authState.creds.me?.id)';+const GROUPS = [+ ['lib/Socket/socket.js', QR_FIND, QR_REPLACE],+ ['lib/Socket/messages-recv.js', ACK_FIND, ACK_REPLACE],+];+function classify(dir) {+ const items = [];+ for (const [relative, find, replace] of GROUPS) {+ const file = path.join(dir, relative);+ let source;+ try {+ source = fs.readFileSync(file, 'utf8');+ } catch (error) {+ error.partial = items.some(item => item.state === 'applied');+ throw error;+ }+ const replaced = source.split(replace).length - 1;+ const pristine = source.replace(replace, '').split(find).length - 1;+ const refreshHandlers = source.split("ws.on('CB:notification,type:companion_reg_refresh'").length - 1;+ const conflictingRefresh = relative === 'lib/Socket/socket.js' && refreshHandlers !== replaced;+ items.push({+ file,+ source,+ find,+ replace,+ state: conflictingRefresh+ ? 'unknown'+ : replaced === 1 && pristine === 0+ ? 'applied'+ : replaced === 0 && pristine === 1+ ? 'pristine'+ : 'unknown',+ });+ }+ return items;+}+function isApplied(dir = DEFAULT_BAILEYS) {+ try {+ return classify(dir).every(item => item.state === 'applied');+ } catch {+ return true;+ }+}+function applyPairingPatch(dir = DEFAULT_BAILEYS) {+ const items = classify(dir);+ if (items.every(item => item.state === 'applied')) return { skipped: true };+ if (!items.every(item => item.state === 'pristine')) {+ const error = Error(+ 'Unknown or partially patched Baileys pairing shape; no files written. Re-evaluate upstream #2749/#2765.',+ );+ error.partial = items.some(item => item.state === 'applied');+ throw error;+ }+ try {+ for (const item of items) fs.writeFileSync(item.file, item.source.replace(item.find, item.replace));+ } catch (error) {+ // A failed write may have left part of either file; best-effort cannot accept that tree.+ error.partial = true;+ throw error;+ }+ return { skipped: false };+}+function run(dir = DEFAULT_BAILEYS, bestEffort = process.argv.includes('--best-effort')) {+ try {+ const result = applyPairingPatch(dir);+ console.log(+ 'patch-baileys-pairing: ' ++ (result.skipped ? 'already applied' : 'applied ACK and registration-refresh backports'),+ );+ } catch (error) {+ if (bestEffort && !error.partial) {+ console.warn('patch-baileys-pairing: skipped: ' + error.message);+ return 0;+ }+ console.error('patch-baileys-pairing: ' + error.message);+ return 1;+ }+ return 0;+}+if (require.main === module) process.exitCode = run();+module.exports = { applyPairingPatch, isApplied, run, QR_FIND, QR_REPLACE, ACK_FIND, ACK_REPLACE };diff --git a/scripts/patch-baileys-pairing.spec.js b/scripts/patch-baileys-pairing.spec.jsnew file mode 100644index 000000000..d784d5363--- /dev/null+++ b/scripts/patch-baileys-pairing.spec.js@@ -0,0 +1,93 @@+'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 {+ applyPairingPatch,+ isApplied,+ run,+ QR_FIND,+ QR_REPLACE,+ ACK_FIND,+ ACK_REPLACE,+} = require('./patch-baileys-pairing');+function fixture(t) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'openwa-pairing-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.mkdirSync(path.join(dir, 'lib/Socket'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'lib/Socket/socket.js'), '// before\n' + QR_FIND + '// after\n');+ fs.writeFileSync(path.join(dir, 'lib/Socket/messages-recv.js'), ACK_FIND);+ return dir;+}+test('applies both backports once and stands down only on the complete result', t => {+ const dir = fixture(t);+ assert.equal(isApplied(dir), false);+ assert.deepEqual(applyPairingPatch(dir), { skipped: false });+ assert.equal(isApplied(dir), true);+ const files = ['socket', 'messages-recv'].map(name => path.join(dir, 'lib/Socket', name + '.js'));+ const before = files.map(file => fs.readFileSync(file, 'utf8'));+ assert.deepEqual(applyPairingPatch(dir), { skipped: true });+ assert.deepEqual(+ files.map(file => fs.readFileSync(file, 'utf8')),+ before,+ );+});+for (const variant of ['unknown', 'partial', 'duplicate'])+ test('refuses ' + variant + ' trees before either file is written', t => {+ const dir = fixture(t),+ file = path.join(dir, 'lib/Socket/messages-recv.js');+ fs.writeFileSync(+ file,+ variant === 'unknown'+ ? 'changed upstream code'+ : variant === 'partial'+ ? ACK_REPLACE+ : ACK_FIND + '\n' + ACK_FIND,+ );+ const qr = fs.readFileSync(path.join(dir, 'lib/Socket/socket.js'), 'utf8');+ assert.throws(() => applyPairingPatch(dir), /Unknown or partially patched/);+ assert.equal(isApplied(dir), false);+ assert.equal(fs.readFileSync(path.join(dir, 'lib/Socket/socket.js'), 'utf8'), qr);+ });+test('missing dependency fails the prepared build instead of reporting a patch', t => {+ const dir = fixture(t);+ fs.rmSync(path.join(dir, 'lib/Socket/messages-recv.js'));+ assert.throws(() => applyPairingPatch(dir));+ assert.equal(isApplied(dir), true);+});+test('best-effort skips unknown shapes but refuses partial patches', t => {+ const dir = fixture(t);+ const file = path.join(dir, 'lib/Socket/messages-recv.js');+ fs.writeFileSync(file, 'unknown upstream shape');+ assert.equal(run(dir, true), 0);+ assert.equal(run(dir, false), 1);+ fs.writeFileSync(file, ACK_REPLACE);+ assert.equal(run(dir, true), 1);+});+test('best-effort still fails if a validated patch cannot finish writing', t => {+ const dir = fixture(t);+ const write = fs.writeFileSync;+ t.mock.method(fs, 'writeFileSync', (file, data) => {+ if (file.endsWith('messages-recv.js')) throw new Error('write failed');+ return write(file, data);+ });+ assert.equal(run(dir, true), 1);+ assert.equal(isApplied(dir), false);+});+test('best-effort refuses a repaired socket with the ACK file missing', t => {+ const dir = fixture(t);+ fs.writeFileSync(path.join(dir, 'lib/Socket/socket.js'), QR_REPLACE);+ fs.rmSync(path.join(dir, 'lib/Socket/messages-recv.js'));+ assert.equal(run(dir, true), 1);+});+test('refuses a pre-existing refresh handler before changing either file', t => {+ const dir = fixture(t);+ fs.appendFileSync(+ path.join(dir, 'lib/Socket/socket.js'),+ "ws.on('CB:notification,type:companion_reg_refresh', handler);",+ );+ assert.throws(() => applyPairingPatch(dir), /Unknown/);+ assert.equal(fs.readFileSync(path.join(dir, 'lib/Socket/messages-recv.js'), 'utf8'), ACK_FIND);+});diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex a6ac4a6b3..d1bac1991 100644--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -1,7 +1,7 @@/*** Post-install hook (npm `postinstall`).*- * Thirteen conditional steps, each skipped when its target is absent so the hook is a no-op where the+ * Fourteen 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@@ -38,9 +38,12 @@* 12. `node scripts/patch-baileys-appstate.js --best-effort` when present, the app-state resync* bound, gated the same way.* 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+ * newsletter-create parse fix. Steps 12-14 are the Baileys patches. Every patcher runs whenever* its script is present, whatever ENGINE_TYPE is set to.*+ * 14. `node scripts/patch-baileys-pairing.js --best-effort` when present, preserving pre-login+ * notification ACKs and refreshing pairing credentials. A partial patch remains fatal.+ ** 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.*/@@ -193,6 +196,15 @@ function planSteps(root, env = process.env) {options: { stdio: 'inherit', cwd: root, env: cleanEnv },});}+ const baileysPairingPatcher = path.join(root, 'scripts', 'patch-baileys-pairing.js');+ if (fs.existsSync(baileysPairingPatcher)) {+ steps.push({+ name: 'Baileys pairing refresh (scripts/patch-baileys-pairing.js --best-effort)',+ command: process.execPath,+ args: [baileysPairingPatcher, '--best-effort'],+ options: { stdio: 'inherit', cwd: root, env: cleanEnv },+ });+ }return steps;}diff --git a/scripts/postinstall.spec.js b/scripts/postinstall.spec.jsindex c8dff88da..7957e0604 100644--- a/scripts/postinstall.spec.js+++ b/scripts/postinstall.spec.js@@ -37,6 +37,7 @@ const EXPECTED_PATCHER_ORDER = ['patch-wwebjs-download-mimetype.js','patch-baileys-appstate.js','patch-baileys-newsletter-create.js',+ 'patch-baileys-pairing.js',];/** Bare temp dir optionally holding a dashboard/ and/or the patch scripts. */diff --git a/src/engine/adapters/baileys-lifecycle.spec.ts b/src/engine/adapters/baileys-lifecycle.spec.tsindex e22f283df..51799232d 100644--- a/src/engine/adapters/baileys-lifecycle.spec.ts+++ b/src/engine/adapters/baileys-lifecycle.spec.ts@@ -1,8 +1,11 @@+jest.mock('qrcode', () => ({ toDataURL: jest.fn() }));jest.mock('@whiskeysockets/baileys', () => ({ __esModule: true, initAuthCreds: jest.fn() }));jest.mock('./baileys-auth-store', () => ({useAtomicMultiFileAuthState: jest.fn().mockRejectedValue(new Error('stop after auth load')),}));+import * as qrcode from 'qrcode';+import { EngineStatus } from '../interfaces/whatsapp-engine.interface';import * as BaileysLib from '@whiskeysockets/baileys';import { useAtomicMultiFileAuthState } from './baileys-auth-store';import { BaileysLifecycle, type BaileysLifecycleHost } from './baileys-lifecycle';@@ -74,3 +77,96 @@ describe('BaileysLifecycle unlink cleanup', () => {expect(fenceStoredWrites.mock.invocationCallOrder[0]).toBeLessThan(clearSession.mock.invocationCallOrder[0]);});});++describe('BaileysLifecycle QR refresh', () => {+ // Exercise the promise overload used by the adapter, rather than qrcode's+ // callback overload (whose return type is void).+ const renderQr = jest.mocked(qrcode.toDataURL as (qr: string) => Promise<string>);+ type Renderer = {+ handleQrCode: (qr: string) => Promise<void>;+ qrCode: string | null;+ sock: unknown;+ status: EngineStatus;+ };+ function fixture() {+ const onQRCode = jest.fn(),+ noCallback = () => undefined;+ const host = {+ authPath: '/fixture',+ config: { sessionId: 'fixture' },+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },+ getOnQRCode: () => onQRCode,+ getOnStateChanged: noCallback,+ getOnError: noCallback,+ } as unknown as BaileysLifecycleHost;+ const lifecycle = new BaileysLifecycle(host);+ const renderer = lifecycle as unknown as Renderer;+ renderer.sock = { ws: { isOpen: true } };+ renderer.status = EngineStatus.QR_READY;+ renderer.qrCode = 'retired-image';+ return { renderer, onQRCode };+ }+ it('clears a retired image immediately and ignores a slow older render', async () => {+ const { renderer, onQRCode } = fixture();+ let finishOld!: (image: string) => void, finishNew!: (image: string) => void;+ renderQr+ .mockImplementationOnce(+ () =>+ new Promise<string>(resolve => {+ finishOld = resolve;+ }),+ )+ .mockImplementationOnce(+ () =>+ new Promise<string>(resolve => {+ finishNew = resolve;+ }),+ );+ const old = renderer.handleQrCode('retired-secret');+ expect(renderer.qrCode).toBeNull();+ const fresh = renderer.handleQrCode('current-secret');+ expect(renderer.qrCode).toBeNull();+ finishNew('current-image');+ await fresh;+ finishOld('retired-image');+ await old;+ expect(renderer.qrCode).toBe('current-image');+ expect(onQRCode).toHaveBeenCalledTimes(1);+ expect(onQRCode).toHaveBeenCalledWith('current-image');+ });+ it.each([EngineStatus.AUTHENTICATING, EngineStatus.READY])(+ 'does not publish a pending render after linking enters %s',+ async status => {+ const { renderer, onQRCode } = fixture();+ let finish!: (image: string) => void;+ renderQr.mockImplementationOnce(+ () =>+ new Promise<string>(resolve => {+ finish = resolve;+ }),+ );+ const pending = renderer.handleQrCode('pending');+ renderer.status = status;+ finish('expired-image');+ await pending;+ expect(renderer.qrCode).toBeNull();+ expect(onQRCode).not.toHaveBeenCalled();+ },+ );+ it('discards a pending render after the socket acquires a pairing-code identity', async () => {+ const { renderer, onQRCode } = fixture();+ let finish!: (image: string) => void;+ renderQr.mockImplementationOnce(+ () =>+ new Promise<string>(resolve => {+ finish = resolve;+ }),+ );+ const pending = renderer.handleQrCode('pending');+ (renderer.sock as { user?: { id: string } }).user = { id: '[email protected]' };+ finish('expired-image');+ await pending;+ expect(renderer.qrCode).toBeNull();+ expect(onQRCode).not.toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex 9c1d28bcf..096154d41 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -191,6 +191,7 @@ export class BaileysLifecycle {sock: WASocket | null = null;private status: EngineStatus = EngineStatus.DISCONNECTED;private qrCode: string | null = null;+ private qrRenderSequence = 0;private phoneNumber: string | null = null;private pushName: string | null = null;private intentionalClose = false;@@ -816,12 +817,22 @@ export class BaileysLifecycle {/** Render the raw Baileys QR ref to a PNG data URL, then publish it (mirrors the whatsapp-web.js engine). */private async handleQrCode(qr: string): Promise<void> {const sock = this.sock;+ const sequence = ++this.qrRenderSequence;+ // A registration refresh retires the previous secret before PNG rendering finishes.+ this.qrCode = null;try {const rendered = await qrcode.toDataURL(qr);// The socket can drop, or the link be accepted, while the QR renders. The handler has already// moved the status on, and publishing now would stamp QR_READY on a dead socket until the// backoff reconnect, or reopen the pairing guard on a socket that is committed to a restart.- if (this.sock !== sock || !sock?.ws.isOpen || this.status === EngineStatus.AUTHENTICATING) {+ if (+ sequence !== this.qrRenderSequence ||+ this.sock !== sock ||+ !sock?.ws.isOpen ||+ this.status === EngineStatus.AUTHENTICATING ||+ this.status === EngineStatus.READY ||+ sock.user?.id+ ) {return;}this.qrCode = rendered;diff --git a/src/engine/docs-29-counts.spec.ts b/src/engine/docs-29-counts.spec.tsindex e908f8c71..f282c1aff 100644--- a/src/engine/docs-29-counts.spec.ts+++ b/src/engine/docs-29-counts.spec.ts@@ -155,6 +155,7 @@ describe('docs/29 counts match the capability matrix', () => {ten: 10,eleven: 11,twelve: 12,+ thirteen: 13,};const spelled = doc.match(/OpenWA ships (\w+) exact, self-disabling source transforms/);const wrongProse: string[] = [];