Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): unblock every wwjs blocklist entry of the person
Yudhi Armyndharisb808a8a7a5f7
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex ccdde696a..7869ccb8a 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -153,7 +153,7 @@ reaching READY is not evidence that every patch landed. See docs/12 for the oper| 🔧⁶ | `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-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. | Rc14 backport with one adaptation: once `creds.me` is set the QR timer stops, which upstream keeps running; remove once an upstream release includes both fixes and recheck the pairing-code timeout. || 🔧⁷ | `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-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. Unblock then unblocks, once each, the other blocklist entries the same person holds under its phone id or LID. | 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. |diff --git a/scripts/patch-wwebjs-block.js b/scripts/patch-wwebjs-block.jsindex daa327e91..3b9e2e481 100644--- a/scripts/patch-wwebjs-block.js+++ b/scripts/patch-wwebjs-block.js@@ -35,6 +35,10 @@* 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`.*+ * Unblock then reads the blocklist once more and unblocks, once each, the entries the same person still+ * holds under another id (a phone-keyed block from before the migration beside the LID one), which the+ * blocklist read lists under the same id. This part is not verified live: no session held both entries.+ ** The transform is exact and self-disabling: an unknown shape fails the build instead of silently* shipping without the fix, matching the sibling patchers.*/@@ -87,6 +91,30 @@ const replaceFor = (call) => ` const req = (name) => {.require('WAWebBlockContactAction').${call};`;+/**+ * Unblock only, after the action call. A contact blocked under its phone id before the LID migration+ * and under its LID after it holds two blocklist entries, which the blocklist read lists as one id, so+ * unblocking the chat-owning entry can leave the other one listed. Every other entry of the same person,+ * taken from one read of the blocklist after that call, is unblocked once; nothing is retried. An entry+ * WhatsApp refuses to unblock stays listed, as before, and does not fail an unblock that already went out.+ */+const UNBLOCK_REST = `+ const serial = (id) => (id ? String(id._serialized || id.$1 || id) : null);+ const person = new Set([serial(contact.id), serial(lid), serial(target.id)].filter(Boolean));+ const collections = req('WAWebCollections');+ const entries = collections && collections.Blocklist ? collections.Blocklist.getModelsArray() : [];+ const others = new Set(+ entries.map((entry) => serial(entry.id)).filter((id) => person.has(id) && id !== serial(target.id)),+ );+ for (const id of others) {+ try {+ const other = await collections.Contact.find(id);+ await window.require('WAWebBlockContactAction').unblockContact(other);+ } catch (error) {+ // Left listed, as before this cleanup existed; the chat-owning entry is unblocked already.+ }+ }`;+const GROUPS = [{name: 'block',@@ -96,14 +124,30 @@ const GROUPS = [{name: 'unblock',find: findFor('unblockContact(resolved)'),- replace: replaceFor('unblockContact(target)'),+ replace: replaceFor('unblockContact(target)') + UNBLOCK_REST,},];+/** The unblock body an earlier version of this patcher left behind. */+const LEGACY_UNBLOCK_REPLACE = replaceFor('unblockContact(target)');++/**+ * Rewind a tree whose unblock body the earlier version patched to the pristine shape, so the apply path+ * sees either the pristine shape or the current one, never a third state it would have to refuse. The+ * current body starts with the earlier one, so a tree that already carries it is left as it is.+ */+function normalizeLegacy(source) {+ const unblock = GROUPS.find((group) => group.name === 'unblock');+ if (source.includes(unblock.replace)) return source;+ return source.split(LEGACY_UNBLOCK_REPLACE).join(unblock.find);+}+/*** Both groups' stand-down branch as one predicate, for the startup guard* (engine-patch-status.ts). A half-patched tree is a reachable, supported state here, and it reads- * as NOT applied: whichever half is missing still answers an opaque 500 on every id.+ * as NOT applied: whichever half is missing still answers an opaque 500 on every id. A tree carrying+ * the earlier unblock body reads as not applied too: block and unblock work there, but an entry the+ * person holds under the other id survives the unblock.* Unreadable reads as applied, since a tree we cannot inspect is not evidence of a broken one.*/function isApplied(wwjsDir = DEFAULT_WWJS) {@@ -120,7 +164,7 @@ function applyBlockPatches({ wwjsDir = DEFAULT_WWJS } = {}) {if (!fs.existsSync(contactFile)) {throw new Error(`whatsapp-web.js Contact.js not found at ${contactFile}`);}- let source = fs.readFileSync(contactFile, 'utf8');+ let source = normalizeLegacy(fs.readFileSync(contactFile, 'utf8'));const applied = [];const skipped = [];@@ -163,4 +207,13 @@ function run() {if (require.main === module) run();-module.exports = { applyBlockPatches, isApplied, GROUPS, findFor, replaceFor, CONTACT_PATH };+module.exports = {+ applyBlockPatches,+ isApplied,+ GROUPS,+ findFor,+ replaceFor,+ CONTACT_PATH,+ LEGACY_UNBLOCK_REPLACE,+ normalizeLegacy,+};diff --git a/scripts/patch-wwebjs-block.spec.js b/scripts/patch-wwebjs-block.spec.jsindex 11813db81..ec8b83523 100644--- a/scripts/patch-wwebjs-block.spec.js+++ b/scripts/patch-wwebjs-block.spec.js@@ -6,7 +6,15 @@ const fs = require('fs');const os = require('os');const path = require('path');-const { applyBlockPatches, isApplied, GROUPS, findFor, replaceFor } = require('./patch-wwebjs-block');+const {+ applyBlockPatches,+ isApplied,+ GROUPS,+ findFor,+ replaceFor,+ LEGACY_UNBLOCK_REPLACE,+ normalizeLegacy,+} = require('./patch-wwebjs-block');/*** The patcher rewrites a file this repository does not own, so what has to hold is that it fires on@@ -29,7 +37,10 @@ const INSTALLED_CONTACT = path.join('Contact.js',);-/** The installed file as upstream ships it, un-patching first when postinstall already ran. */+/**+ * The installed file as upstream ships it, un-patching first when postinstall already ran, by this+ * version of the patcher or by the earlier one.+ */function pristineSource() {let source = fs.readFileSync(INSTALLED_CONTACT, 'utf8');for (const group of GROUPS) {@@ -37,7 +48,7 @@ function pristineSource() {source = source.replace(group.replace, group.find);}}- return source;+ return normalizeLegacy(source);}/** A throwaway whatsapp-web.js tree holding just the file the patcher edits. */@@ -100,6 +111,143 @@ test('refuses a tree with no Contact.js at all', () => {fs.rmSync(dir, { recursive: true, force: true });});+test('upgrades a tree left behind by the previous version of this patcher', () => {+ // The earlier unblock body matches neither the pristine find nor the current replace, so without the+ // rewind the patcher would refuse the trees that already carry the block fix.+ const legacy = pristineSource()+ .replace(findFor('blockContact({ contact: resolved })'), GROUPS[0].replace)+ .replace(findFor('unblockContact(resolved)'), LEGACY_UNBLOCK_REPLACE);+ const { dir, file } = fakeWwjs(legacy);+ assert.equal(isApplied(dir), false, 'the earlier unblock body lacks the cleanup');+ const result = applyBlockPatches({ wwjsDir: dir });+ assert.deepEqual(result.applied, ['unblock']);+ assert.deepEqual(result.skipped, ['block']);+ assert.equal(isApplied(dir), true);+ assert.equal(fs.readFileSync(file, 'utf8').split(GROUPS[1].replace).length - 1, 1);+ assert.deepEqual(applyBlockPatches({ wwjsDir: dir }).applied, [], 'a second run must not change the file');+ fs.rmSync(dir, { recursive: true, force: true });+});++/**+ * Run the patched Contact.block() / unblock() against a stand-in WhatsApp Web. `blocked` is the blocklist+ * (PHONE and LID are one person, OTHER someone else); `unblockContact` removes only the entry of the contact+ * it was handed unless `removes` says otherwise, and throws for an id listed in `refuses`.+ */+const PHONE = '[email protected]';+const LID = '100000000000001@lid';+const OTHER = '[email protected]';+function onPage({ blocked, removes, refuses = [], lidMapping = true }) {+ const { dir } = fakeWwjs(pristineSource());+ applyBlockPatches({ wwjsDir: dir });+ const structures = path.join(dir, 'src', 'structures');+ fs.copyFileSync(path.join(path.dirname(INSTALLED_CONTACT), 'Base.js'), path.join(structures, 'Base.js'));+ const Contact = require(path.join(structures, 'Contact.js'));++ const wid = id => ({ _serialized: id });+ const contactFor = id => ({ id: wid(id) });+ let blocklist = [...blocked];+ const unblocked = [];+ const blockedVia = [];+ const modules = {+ WAWebCollections: {+ Contact: { find: async id => contactFor(id) },+ Blocklist: { getModelsArray: () => blocklist.map(id => ({ id: wid(id) })) },+ },+ WAWebLidMigrationUtils: {+ toUserLid: id => {+ if (!lidMapping) throw new Error('no lid');+ return id._serialized === PHONE ? wid(LID) : id;+ },+ },+ WAWebChatCollection: { ChatCollection: { get: id => (id === LID ? { contact: contactFor(LID) } : undefined) } },+ WAWebBlockContactAction: {+ unblockContact: async contact => {+ const id = contact.id._serialized;+ unblocked.push(id);+ if (refuses.includes(id)) throw new Error('refused');+ const gone = removes ? removes(id) : [id];+ blocklist = blocklist.filter(entry => !gone.includes(entry));+ },+ blockContact: async ({ contact }) => {+ blockedVia.push(contact.id._serialized);+ },+ },+ };+ globalThis.window = { require: name => modules[name] };+ const client = { pupPage: { evaluate: (fn, ...args) => fn(...args) } };+ return {+ contact: new Contact(client, { id: wid(PHONE) }),+ unblocked,+ blockedVia,+ blocklist: () => blocklist,+ done: () => {+ delete globalThis.window;+ fs.rmSync(dir, { recursive: true, force: true });+ },+ };+}++test('unblock clears a person blocked under both the LID and the phone id', async () => {+ const page = onPage({ blocked: [LID, PHONE, OTHER] });+ assert.equal(await page.contact.unblock(), true);+ assert.deepEqual(page.unblocked, [LID, PHONE]);+ assert.deepEqual(page.blocklist(), [OTHER], 'someone else on the blocklist is left alone');+ page.done();+});++test('unblock of a person blocked under the LID only makes one call', async () => {+ const page = onPage({ blocked: [LID] });+ await page.contact.unblock();+ assert.deepEqual(page.unblocked, [LID]);+ assert.deepEqual(page.blocklist(), []);+ page.done();+});++test('unblock reaches a person blocked under the phone id only', async () => {+ const page = onPage({ blocked: [PHONE] });+ await page.contact.unblock();+ assert.deepEqual(page.unblocked, [LID, PHONE]);+ assert.deepEqual(page.blocklist(), []);+ page.done();+});++test('unblock makes no second call when WhatsApp clears both entries at once', async () => {+ const page = onPage({ blocked: [LID, PHONE], removes: () => [LID, PHONE] });+ await page.contact.unblock();+ assert.deepEqual(page.unblocked, [LID]);+ page.done();+});++test('unblock tries each other entry once and never retries', async () => {+ const page = onPage({ blocked: [LID, PHONE, PHONE], removes: () => [] });+ await page.contact.unblock();+ assert.deepEqual(page.unblocked, [LID, PHONE]);+ page.done();+});++test('a refused second entry leaves unblock resolved, with that entry still listed', async () => {+ const page = onPage({ blocked: [LID, PHONE], refuses: [PHONE] });+ assert.equal(await page.contact.unblock(), true);+ assert.deepEqual(page.unblocked, [LID, PHONE]);+ assert.deepEqual(page.blocklist(), [PHONE]);+ page.done();+});++test('unblock of an account with no LID mapping unblocks the contact it was given', async () => {+ const page = onPage({ blocked: [PHONE], lidMapping: false });+ await page.contact.unblock();+ assert.deepEqual(page.unblocked, [PHONE]);+ page.done();+});++test('block still makes exactly one call, to the chat-owning identity', async () => {+ const page = onPage({ blocked: [PHONE] });+ assert.equal(await page.contact.block(), true);+ assert.deepEqual(page.blockedVia, [LID]);+ assert.deepEqual(page.unblocked, []);+ page.done();+});+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(