Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): bound the app-state resync loop on an empty decode
Yudhi Armyndharisa4da6839c23c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d7c517fe2..5aec83041 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+- **A post-connect app-state resync can no longer spin for the life of the session** — Baileys' `resyncAppState` loops until every collection reports no more patches, but every exit from that loop, including the attempt counter its own comment introduces to "ensure we don't enter a loop that cannot be exited from", sits inside a `for…in` over the decoded patches; an unanswered query decodes to an empty object, so nothing was removed, nothing was counted, and the walk re-asked every sixty seconds until the socket closed. A postinstall patch ends the walk when the decode is empty, and fails the install rather than silently skipping if the upstream shape moves.- **A number check no longer answers "not on WhatsApp" when WhatsApp simply did not answer** — Baileys' `onWhatsApp` has no else branch after its result check, so an unanswered lookup resolved `undefined`, which the adapter folded into the same `null` a genuine miss produces; `GET /contacts/check/{number}` then reported `exists: false` and `checkNumberExists` returned false — a confident verdict about a number the gateway had heard nothing about, on the one route the send documentation tells callers to trust before sending. An empty result is still a real answer and still reports `false`; only the absent one now raises `503`.- **A group invite code now says why it could not be read** — fetching one is admin-only, but the groups list returns every group the account belongs to whatever its role, so the request lands on ids the caller was just handed: Baileys let WhatsApp's refusal escape as a bare `500` (13 of 16 groups on the test account) while whatsapp-web.js stringified its missing result into `{"inviteCode":"undefined"}` and the link `https://chat.whatsapp.com/undefined` behind a `200` (53 of 101). Both engines now answer `403`, the same status the group writes have answered since they were fixed, and an unanswered query answers `503` instead of the codeless link `https://chat.whatsapp.com/`.- **A catalog read no longer stalls for a minute and then reports an empty catalog** — Baileys answers an unanswered query with `undefined` rather than an error and its catalog parsers are null-safe, so a request WhatsApp never replied to was indistinguishable from a business with no products: `GET /catalog` and `/catalog/products` returned `200` with nothing in them after a silent 60 seconds, and `send-product` reported `404 Product not found` for a product it had simply never heard about. The walk now spends one 30-second budget across every page and answers `503`, and a server that repeats a page cursor instead of advancing no longer spins the walk until the process exhausts its heap.diff --git a/package.json b/package.jsonindex e6b96a507..759c5c0e3 100644--- a/package.json+++ b/package.json@@ -35,7 +35,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",+ "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-baileys-appstate.spec.js","test:watch": "jest --watch","test:cov": "jest --coverage","test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",diff --git a/scripts/patch-baileys-appstate.js b/scripts/patch-baileys-appstate.jsnew file mode 100644index 000000000..81ca7f18e--- /dev/null+++ b/scripts/patch-baileys-appstate.js@@ -0,0 +1,83 @@+/**+ * Bound Baileys' app-state resync loop so an unanswered query cannot spin it.+ *+ * `resyncAppState` (lib/Socket/chats.js) drives `while (collectionsToHandle.size)` until every+ * collection reports no more patches. Each pass issues an `iq` through `query()` — and `query()`+ * catches its own `defaultQueryTimeoutMs` (60s) and RESOLVES `undefined` rather than throwing. That+ * `undefined` reaches `extractSyncdPatches`, which yields `{}` (verified by execution against the+ * installed module, alongside a real-node control that also yields `{}`).+ *+ * Every exit from the loop — each `collectionsToHandle.delete(name)`, and every increment of the+ * `attemptsMap` the library's own comment introduces to "ensure we don't enter a loop that cannot be+ * exited from" — lives INSIDE `for (const key in decoded)`. With `decoded` empty that body never+ * runs, so nothing is removed, nothing is counted, and the guard never engages. The loop then burns+ * one 60-second query per pass for as long as the socket lives. It is not permanent: the `await+ * query(...)` sits outside the loop's try/catch, so a socket close rejects out of resyncAppState+ * entirely. On a long-lived gateway that is still on the order of a thousand wasted queries a day.+ *+ * The transform adds the exit the guard assumes: an empty decode ends the walk. Nothing came back,+ * and re-asking in a tight loop is what produced the defect — a later connect re-runs the sync+ * anyway (OpenWA calls it on every `open`).+ *+ * Exact and self-disabling, matching the whatsapp-web.js patchers: an unknown shape fails rather+ * than silently shipping without the fix. Remove this once upstream bounds the loop.+ */+'use strict';++const fs = require('fs');+const path = require('path');++const DEFAULT_BAILEYS = path.join(__dirname, '..', 'node_modules', '@whiskeysockets', 'baileys');+const CHATS_PATH = path.join('lib', 'Socket', 'chats.js');++const LOOP_FIND = ` const decoded = await extractSyncdPatches(result, config?.options);+ for (const key in decoded) {`;++const LOOP_REPLACE = ` const decoded = await extractSyncdPatches(result, config?.options);+ // OpenWA: query() resolves undefined on its own timeout, which decodes to {}. Every+ // exit below — including the attemptsMap guard — is inside this for-in, so an empty+ // decode would otherwise spin the while loop for the life of the socket.+ if (!Object.keys(decoded).length) {+ break;+ }+ for (const key in decoded) {`;++/** Apply the transform. Returns {skipped, reason} or {note} — never a partial write. */+function applyAppStatePatch(baileysDir = DEFAULT_BAILEYS) {+ const file = path.join(baileysDir, CHATS_PATH);+ if (!fs.existsSync(file)) {+ return { skipped: true, reason: `${CHATS_PATH} not found — nothing to patch` };+ }+ const source = fs.readFileSync(file, 'utf8');+ if (source.includes('OpenWA: query() resolves undefined on its own timeout')) {+ return { skipped: true, reason: 'already patched' };+ }+ const occurrences = source.split(LOOP_FIND).length - 1;+ if (occurrences !== 1) {+ throw new Error(+ `expected exactly 1 resyncAppState decode site in ${CHATS_PATH}, found ${occurrences} — ` ++ 'the upstream shape changed; re-check whether the loop is still unbounded before removing this patcher',+ );+ }+ fs.writeFileSync(file, source.replace(LOOP_FIND, LOOP_REPLACE), 'utf8');+ return { note: 'bounded the app-state resync loop on an empty decode' };+}++function run() {+ const bestEffort = process.argv.includes('--best-effort');+ try {+ const result = applyAppStatePatch();+ console.log(`patch-baileys-appstate: ${result.skipped ? `skipped — ${result.reason}` : result.note}`);+ } catch (error) {+ if (bestEffort) {+ console.warn(`patch-baileys-appstate: skipped — ${error.message}`);+ return;+ }+ console.error(`patch-baileys-appstate: ${error.message}`);+ process.exitCode = 1;+ }+}++if (require.main === module) run();++module.exports = { applyAppStatePatch, LOOP_FIND, LOOP_REPLACE };diff --git a/scripts/patch-baileys-appstate.spec.js b/scripts/patch-baileys-appstate.spec.jsnew file mode 100644index 000000000..7f5887caa--- /dev/null+++ b/scripts/patch-baileys-appstate.spec.js@@ -0,0 +1,69 @@+'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 { applyAppStatePatch, LOOP_FIND } = require('./patch-baileys-appstate');++/**+ * Same contract as the sibling patcher specs: the patcher rewrites a file this repository does not+ * own, so it must fire only on the exact shape it was written for, refuse loudly on anything else,+ * and be safe to run twice (postinstall runs on every install).+ */++function fakeBaileys(chatsSource) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'baileys-appstate-'));+ fs.mkdirSync(path.join(dir, 'lib', 'Socket'), { recursive: true });+ const file = path.join(dir, 'lib', 'Socket', 'chats.js');+ fs.writeFileSync(file, chatsSource);+ return { dir, file };+}++const REAL_SHAPE = ` while (collectionsToHandle.size) {+${LOOP_FIND}+ const name = key;+ }+ }+`;++test('bounds the loop on an empty decode', () => {+ const { dir, file } = fakeBaileys(REAL_SHAPE);+ const result = applyAppStatePatch(dir);+ assert.equal(result.skipped, undefined);+ const patched = fs.readFileSync(file, 'utf8');+ assert.match(patched, /if \(!Object\.keys\(decoded\)\.length\) \{\n\s+break;/);+ // The original walk is preserved, not replaced.+ assert.ok(patched.includes('for (const key in decoded) {'));+});++test('is idempotent — a second run does not double-patch', () => {+ const { dir, file } = fakeBaileys(REAL_SHAPE);+ applyAppStatePatch(dir);+ const once = fs.readFileSync(file, 'utf8');+ const second = applyAppStatePatch(dir);+ assert.equal(second.skipped, true);+ assert.equal(fs.readFileSync(file, 'utf8'), once);+});++test('refuses loudly when the upstream shape changed', () => {+ const { dir, file } = fakeBaileys('const decoded = somethingElse();\nfor (const key in decoded) {\n}\n');+ const before = fs.readFileSync(file, 'utf8');+ assert.throws(() => applyAppStatePatch(dir), /found 0/);+ // Refusing must not leave a partial write behind.+ assert.equal(fs.readFileSync(file, 'utf8'), before);+});++test('refuses when the decode site appears more than once', () => {+ const { dir } = fakeBaileys(`${LOOP_FIND}\n}\n${LOOP_FIND}\n}\n`);+ assert.throws(() => applyAppStatePatch(dir), /found 2/);+});++test('skips a tree that has no chats.js rather than throwing', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'baileys-absent-'));+ const result = applyAppStatePatch(dir);+ assert.equal(result.skipped, true);+ assert.match(result.reason, /not found/);+});diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex 973f5fa00..61eecca99 100644--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -100,6 +100,15 @@ function planSteps(root, env = process.env) {options: { stdio: 'inherit', cwd: root, env: cleanEnv },});}+ const baileysAppStatePatcher = path.join(root, 'scripts', 'patch-baileys-appstate.js');+ if (fs.existsSync(baileysAppStatePatcher)) {+ steps.push({+ name: 'Baileys app-state resync bound (scripts/patch-baileys-appstate.js --best-effort)',+ command: process.execPath,+ args: [baileysAppStatePatcher, '--best-effort'],+ options: { stdio: 'inherit', cwd: root, env: cleanEnv },+ });+ }return steps;}