Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): restore wwjs block/unblock after the LID migration
Yudhi Armyndharise9779ef789c1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 463cba53b..3d5acf1c3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- whatsapp-web.js block and unblock work again. WhatsApp Web removed the contact resolver both calls used, so every id answered an opaque `500`; its replacement helpers are modal-driven UI wrappers that block nothing headless, and the server now refuses a phone-keyed block because individual chats are keyed by LID while the library folds every id back to a phone number. An install-time patch resolves through the chat-owning identity and calls the block action directly.- block and unblock accept a privacy id (`@lid`), the only id a contact without a known phone number has. The blocklist read answers those ids verbatim, so refusing them on the write left such a contact listed as blocked with no way to unblock it; ids that name no individual (group, newsletter, broadcast, free text) are still refused with `400`.- whatsapp-web.js `deleteChannel` classifies a dead browser page as the documented `503` plus an early death signal, like every other channel call; it reached the client directly, so a crash there answered an opaque `500` while the session still reported READY.- Baileys block/unblock answer `400` when WhatsApp cannot map the id between the phone-number and privacy-id dialects (no mapping either way, or an id that is neither). The library refuses those with a Boom the gateway could not classify, so a well-formed request got an opaque `500`; whatsapp-web.js already answered `400` for the same cause.diff --git a/Dockerfile b/Dockerfileindex 3f5a06c90..35507c5d7 100644--- a/Dockerfile+++ b/Dockerfile@@ -131,7 +131,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-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-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.@@ -153,6 +153,7 @@ RUN npm ci --omit=dev --ignore-scripts \&& node scripts/patch-wwebjs-status.js \&& node scripts/patch-wwebjs-ready-sync.js \&& node scripts/patch-wwebjs-participant-arity.js \+ && node scripts/patch-wwebjs-block.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 ba0ee16df..4c706fd0a 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 112 `IWhatsAppEngine` methods (29.4), **all 152Baileys + 81 whatsapp-web.js library methods** (29.5), all 34 + 31 library events (29.5.4), and all-7 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.+8 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/>+ 5 OpenWA patches"]+ WA --> WLIB["whatsapp-web.js 1.34.7<br/>+ 6 OpenWA patches"]BA --> BLIB["@whiskeysockets/baileys 7.0.0-rc13<br/>+ 2 OpenWA patches"]WLIB --> WEB["WhatsApp Web<br/>headless Chromium"]BLIB --> WAS["WhatsApp servers<br/>browser-free socket"]@@ -125,13 +125,13 @@ wrong interface method. Those three remain reader-verified.## 29.3 Install-time patches OpenWA applies to the libraries-OpenWA ships seven exact, self-disabling source transforms over the installed engines. Each runs at+OpenWA ships eight 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 loudlyrather than shipping a silently partial patch.-### 29.3.1 The seven patches+### 29.3.1 The eight patches| # | Patcher | Library target | What it repairs | Stand-down predicate || --- | ---------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |@@ -142,10 +142,11 @@ rather than shipping a silently partial patch.| 🔧⁵ | `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. |### 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 (5 on wwjs,+This is the patch visibility the matrix cells refer to. Every patch is engine-specific (6 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@@ -160,6 +161,7 @@ row-level marks.| 🔧⁵ app-state resync bound | No single row — keeps the Baileys socket's app-state resync from spinning (~1000 wasted 60s queries/day). Connection health under **every baileys cell**; the baileys column header carries `🔧⁵`. || 🔧⁶ newsletter-create parse | `createChannel` on **baileys** — without it the call always answers 500 and leaks the channel it just created. Row-marked. || 🔧⁷ participant arity | `removeParticipants`, `promoteParticipants`, `demoteParticipants` on **wwjs**. Without it a request naming only non-members throws an arity assertion on removal, and promote/demote answer `200` for people WhatsApp never touched; the patch returns one boolean per REQUESTED id so the adapter reports a real per-participant outcome. Row-marked. |+| 🔧⁸ 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. |Rows that are ✅ on **both** engines where one side is patch-dependent: `initialize` (🔧⁴ wwjs),`sendTextMessage` (🔧³ wwjs), `postTextStatus` / `postImageStatus` / `postVideoStatus` /@@ -942,7 +944,7 @@ adapter sources — re-derive the same way when anything changes:provides, and `transferChannelOwnership`, whose page function rejects locally against asubscriber list it cannot repopulate (both in 29.6.2). Both answer 501 on wwjs. `.d.ts` presenceis not capability, and only a live call distinguishes the two.-- **7** install-time patches (5 whatsapp-web.js + 2 Baileys), all exact and self-disabling.+- **8** install-time patches (6 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 4d51b9605..729bbf6a3 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-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",+ "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-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","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-block.js b/scripts/patch-wwebjs-block.jsnew file mode 100644index 000000000..8d8521bf2--- /dev/null+++ b/scripts/patch-wwebjs-block.js@@ -0,0 +1,151 @@+/**+ * Make whatsapp-web.js block/unblock work after WhatsApp Web's LID migration.+ *+ * `Contact.block()` / `Contact.unblock()` resolve their target through+ * `WAWebBlockContactUtils.getContactToBlockOnlyUseIfNoAssociatedChat(contact, 'ChatListBlock')`.+ * WhatsApp Web has since REMOVED that function, so both calls reject in the page with+ * `TypeError: window.require(...).getContactToBlockOnlyUseIfNoAssociatedChat is not a function`,+ * which reaches the caller as an opaque `500`. Measured live: every id shape fails, a phone-based+ * `@c.us` id exactly like a privacy `@lid` one, so the whole capability is dead rather than degraded.+ *+ * Restoring it is not a rename. Three things changed together:+ *+ * 1. The replacement helpers `handleBlock` / `handleUnblock` are UI wrappers: they call+ * `getIsPSA(chat)` and open a confirmation modal through ModalManager. Driving `handleBlock`+ * with a real chat returns without throwing and blocks NOTHING, because the modal is never+ * confirmed. Verified on the test server: the blocklist stayed at 188 entries.+ * 2. The server now refuses a phone-keyed block outright, logging+ * `[blocklist] trying to block a pn contact without a chat`. Blocking requires an identity that+ * owns a chat.+ * 3. Individual chats are keyed by LID now, while whatsapp-web.js folds every identity back to a+ * phone number: `getContactById('148004841455867@lid')` answers `id: [email protected]`. So the+ * id `Contact.block()` had in hand was precisely the one WhatsApp refuses.+ *+ * The fix therefore resolves the contact to the identity that actually owns the chat, and calls the+ * underlying action directly instead of the modal wrapper:+ *+ * `WAWebLidMigrationUtils.toUserLid(contact.id)` then `ChatCollection.get(lid)` then `chat.contact`+ * then `WAWebBlockContactAction.blockContact({ contact, blockEntryPoint })` / `unblockContact(contact)`+ *+ * `blockEntryPoint` is required by the action's new signature; the removed helper used to supply it.+ * When no LID or no chat is found the original contact is used, which keeps a phone-only account+ * working exactly as before rather than making this patch a hard dependency on the migration.+ *+ * Verified against a live wwjs session (WhatsApp Web, 2026-08-18): the blocklist went 188 to 189 on+ * block and 189 back to 188 on unblock, twice in a row, with the in-page blocklist collection+ * confirming the LID entry. Before the patch both calls answered `500`.+ *+ * The transform is exact and self-disabling: an unknown shape fails the build instead of silently+ * shipping without the fix, matching the sibling patchers.+ */+'use strict';++const fs = require('fs');+const path = require('path');++const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');+const CONTACT_PATH = path.join('src', 'structures', 'Contact.js');++/** The upstream body, byte-exact, differing only in the action call at the end. */+const findFor = (call) => ` const resolved = window+ .require('WAWebBlockContactUtils')+ .getContactToBlockOnlyUseIfNoAssociatedChat(+ contact,+ 'ChatListBlock',+ );+ await window+ .require('WAWebBlockContactAction')+ .${call};`;++/**+ * Resolve to the identity that owns the chat, then call the action directly.+ *+ * `toUserLid` throws for an account with no LID mapping, so it is wrapped: a throw means "no LID",+ * not "fail the block". Same for a missing chat. Both fall back to the contact we were given.+ */+const replaceFor = (call) => ` const req = (name) => {+ try {+ return window.require(name);+ } catch (error) {+ return null;+ }+ };+ const migration = req('WAWebLidMigrationUtils');+ const chats = req('WAWebChatCollection');+ let lid = null;+ if (migration && typeof migration.toUserLid === 'function') {+ try {+ lid = migration.toUserLid(contact.id);+ } catch (error) {+ lid = null;+ }+ }+ const lidId = lid ? String(lid._serialized || lid) : null;+ const chat = chats && chats.ChatCollection && lidId ? chats.ChatCollection.get(lidId) : null;+ const target = chat && chat.contact ? chat.contact : contact;+ await window+ .require('WAWebBlockContactAction')+ .${call};`;++const GROUPS = [+ {+ name: 'block',+ find: findFor('blockContact({ contact: resolved })'),+ replace: replaceFor("blockContact({ contact: target, blockEntryPoint: 'ChatListBlock' })"),+ },+ {+ name: 'unblock',+ find: findFor('unblockContact(resolved)'),+ replace: replaceFor('unblockContact(target)'),+ },+];++function applyBlockPatches({ wwjsDir = DEFAULT_WWJS } = {}) {+ const contactFile = path.join(wwjsDir, CONTACT_PATH);+ if (!fs.existsSync(contactFile)) {+ throw new Error(`whatsapp-web.js Contact.js not found at ${contactFile}`);+ }+ let source = fs.readFileSync(contactFile, 'utf8');+ const applied = [];+ const skipped = [];++ for (const group of GROUPS) {+ if (source.includes(group.replace)) {+ skipped.push(group.name);+ continue;+ }+ if (!source.includes(group.find)) {+ throw new Error(`unexpected ${group.name}() shape in ${CONTACT_PATH}: refusing to patch blind`);+ }+ source = source.replace(group.find, group.replace);+ applied.push(group.name);+ }++ if (applied.length > 0) {+ fs.writeFileSync(contactFile, source);+ }+ return { applied, skipped };+}++function run() {+ const bestEffort = process.argv.includes('--best-effort');+ try {+ const { applied, skipped } = applyBlockPatches();+ const report = [+ ...applied.map((name) => `applied ${name}`),+ ...skipped.map((name) => `skipped ${name} (already present)`),+ ].join('; ');+ console.log(`patch-wwebjs-block: ${report}`);+ } catch (error) {+ if (bestEffort) {+ console.warn(`patch-wwebjs-block: skipped, ${error.message}`);+ return;+ }+ console.error(`patch-wwebjs-block: ${error.message}`);+ process.exitCode = 1;+ }+}++if (require.main === module) run();++module.exports = { applyBlockPatches, GROUPS, findFor, replaceFor, CONTACT_PATH };diff --git a/scripts/patch-wwebjs-block.spec.js b/scripts/patch-wwebjs-block.spec.jsnew file mode 100644index 000000000..98308d486--- /dev/null+++ b/scripts/patch-wwebjs-block.spec.js@@ -0,0 +1,106 @@+'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 { applyBlockPatches, GROUPS, findFor, replaceFor } = require('./patch-wwebjs-block');++/**+ * The patcher rewrites a file this repository does not own, so what has to hold is that it fires on+ * exactly the shape it was written for and refuses everything else. A transform that silently did+ * nothing would ship a build where block and unblock still answer an opaque 500 on every id, which+ * is the whole failure this patch exists to remove.+ *+ * The fixture is the INSTALLED Contact.js rather than a hand-written approximation: a synthetic+ * fixture can only prove the patcher matches a shape I wrote, not the shape upstream ships. When the+ * installed tree is already patched (postinstall runs on `npm install`), the patch is reversed to+ * recover the pristine text, so the suite behaves the same before and after a local install.+ */+const INSTALLED_CONTACT = path.join(+ __dirname,+ '..',+ 'node_modules',+ 'whatsapp-web.js',+ 'src',+ 'structures',+ 'Contact.js',+);++/** The installed file as upstream ships it, un-patching first when postinstall already ran. */+function pristineSource() {+ let source = fs.readFileSync(INSTALLED_CONTACT, 'utf8');+ for (const group of GROUPS) {+ if (source.includes(group.replace)) {+ source = source.replace(group.replace, group.find);+ }+ }+ return source;+}++/** A throwaway whatsapp-web.js tree holding just the file the patcher edits. */+function fakeWwjs(source) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-block-'));+ const structures = path.join(dir, 'src', 'structures');+ fs.mkdirSync(structures, { recursive: true });+ fs.writeFileSync(path.join(structures, 'Contact.js'), source);+ return { dir, file: path.join(structures, 'Contact.js') };+}++test('the installed tree still has both shapes the patcher targets', () => {+ const source = pristineSource();+ for (const group of GROUPS) {+ assert.ok(source.includes(group.find), `upstream no longer matches the ${group.name}() shape`);+ }+});++test('patches block and unblock, and is idempotent', () => {+ const { dir, file } = fakeWwjs(pristineSource());+ const first = applyBlockPatches({ wwjsDir: dir });+ assert.deepEqual(first.applied, ['block', 'unblock']);+ assert.deepEqual(first.skipped, []);++ const patched = fs.readFileSync(file, 'utf8');+ // The dead helper is gone from both bodies, and the entry point the new action signature needs is+ // supplied on the block side only (unblockContact takes the contact positionally).+ assert.ok(!patched.includes('getContactToBlockOnlyUseIfNoAssociatedChat'));+ assert.ok(patched.includes("blockContact({ contact: target, blockEntryPoint: 'ChatListBlock' })"));+ assert.ok(patched.includes('unblockContact(target)'));+ // Both bodies resolve through the chat-owning identity.+ assert.equal(patched.split('migration.toUserLid(contact.id)').length - 1, 2);+ assert.equal(patched.split('chat && chat.contact ? chat.contact : contact').length - 1, 2);++ const second = applyBlockPatches({ wwjsDir: dir });+ assert.deepEqual(second.applied, []);+ assert.deepEqual(second.skipped, ['block', 'unblock']);+ assert.equal(fs.readFileSync(file, 'utf8'), patched, 'a second run must not change the file');++ fs.rmSync(dir, { recursive: true, force: true });+});++test('refuses an unknown shape instead of shipping unpatched', () => {+ const { dir } = fakeWwjs(pristineSource().replace('getContactToBlockOnlyUseIfNoAssociatedChat', 'someRenamedHelper'));+ assert.throws(() => applyBlockPatches({ wwjsDir: dir }), /refusing to patch blind/);+ fs.rmSync(dir, { recursive: true, force: true });+});++test('refuses a tree with no Contact.js at all', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-block-empty-'));+ assert.throws(() => applyBlockPatches({ wwjsDir: dir }), /Contact\.js not found/);+ fs.rmSync(dir, { recursive: true, force: true });+});++test('a half-patched tree still gets the missing half', () => {+ // Only block patched: unblock must still be applied rather than reported as already present.+ const half = pristineSource().replace(+ findFor('blockContact({ contact: resolved })'),+ replaceFor("blockContact({ contact: target, blockEntryPoint: 'ChatListBlock' })"),+ );+ const { dir } = fakeWwjs(half);+ const result = applyBlockPatches({ wwjsDir: dir });+ assert.deepEqual(result.applied, ['unblock']);+ assert.deepEqual(result.skipped, ['block']);+ fs.rmSync(dir, { recursive: true, force: true });+});diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex c1b0e6aa0..c440355c9 100644--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -23,9 +23,11 @@* marker + hasSynced level-check, gated the same way.* 6. `node scripts/patch-wwebjs-participant-arity.js --best-effort` when present — makes the group* participant writes report which requested ids resolved to members, gated the same way.- * 7. `node scripts/patch-baileys-appstate.js --best-effort` when present — the app-state resync+ * 7. `node scripts/patch-wwebjs-block.js --best-effort` when present, restoring block and+ * unblock after WhatsApp Web removed the contact resolver they used.+ * 8. `node scripts/patch-baileys-appstate.js --best-effort` when present, the app-state resync* bound, gated the same way.- * 8. `node scripts/patch-baileys-newsletter-create.js --best-effort` when present — the+ * 9. `node scripts/patch-baileys-newsletter-create.js --best-effort` when present, the* newsletter-create parse fix. Steps 7-8 are the Baileys patches, so a Baileys-only install* runs those and skips 2-6.*@@ -116,6 +118,15 @@ function planSteps(root, env = process.env) {options: { stdio: 'inherit', cwd: root, env: cleanEnv },});}+ const blockPatcher = path.join(root, 'scripts', 'patch-wwebjs-block.js');+ if (fs.existsSync(blockPatcher)) {+ steps.push({+ name: 'whatsapp-web.js block/unblock LID repair (scripts/patch-wwebjs-block.js --best-effort)',+ command: process.execPath,+ args: [blockPatcher, '--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({