Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwjs): guard the status ranking-gating call upstream removed
Yudhi Armyndharisa419547904bf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 365922560..5367622c2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- **Status posting on the whatsapp-web.js engine, which current WhatsApp Web had broken outright.**+ whatsapp-web.js 1.34.7 builds every status message with+ `window.require('WAWebStatusGatingUtils').canCheckStatusRankingPosterGating()`. That helper no+ longer exists in current WhatsApp Web builds, so the call threw before the message was sent and+ took down text, image, video and voice status alike — a `500` on every attempt.++ Confirmed on a live account against the published image with none of this project's newer code+ present, so it is upstream rather than a regression here. The postinstall patcher now guards the+ call: it is used when the build still provides it, and falls back to `false` — what+ `cannotBeRanked` meant before WhatsApp introduced the gating check — when it does not. Text status+ posts again, verified live.++ **Media status is still failing** for a second and unrelated upstream reason: WhatsApp Web's own+ bundle throws `Cannot read properties of undefined (reading 'id')` inside+ `sendStatusMediaMsgAction`. That is inside minified upstream code and is not fixed here.+### Security- **Five advisories in the production dependency tree resolved**, all through transitive bumps —diff --git a/package.json b/package.jsonindex d424def53..d7a6c40a7 100644--- a/package.json+++ b/package.json@@ -34,7 +34,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",+ "test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status-gating.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-wwebjs-status-gating.js b/scripts/patch-wwebjs-status-gating.jsnew file mode 100644index 000000000..9365e503e--- /dev/null+++ b/scripts/patch-wwebjs-status-gating.js@@ -0,0 +1,91 @@+/**+ * Stop whatsapp-web.js from crashing on every status post when WhatsApp Web drops the status+ * ranking-gating helper.+ *+ * whatsapp-web.js 1.34.7 builds the status message with+ * `window.require('WAWebStatusGatingUtils').canCheckStatusRankingPosterGating()` and uses the result+ * as `cannotBeRanked`. That helper is gone from current WhatsApp Web builds, so the call throws+ * `TypeError: window.require(...).canCheckStatusRankingPosterGating is not a function` before the+ * message is ever sent — and because the field is built inline for every status, it takes down+ * text, image, video and voice status alike. Verified on a live account: all four fail identically,+ * on stock 1.34.7, with none of this project's code involved.+ *+ * The replacement calls the helper when it is there and falls back to `false` when it is not, which+ * is what `cannotBeRanked` meant before WhatsApp introduced the gating check. That keeps current+ * behaviour intact wherever the API still exists rather than assuming it is gone everywhere.+ *+ * The source transform is deliberately 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 UTILS_PATH = path.join('src', 'util', 'Injected', 'Utils.js');++const UNGUARDED_CALL = ` cannotBeRanked: window+ .require('WAWebStatusGatingUtils')+ .canCheckStatusRankingPosterGating(),`;++const GUARDED_CALL = ` cannotBeRanked: (() => {+ // WAWebStatusGatingUtils.canCheckStatusRankingPosterGating is absent from+ // current WhatsApp Web builds; calling it unguarded threw before the status+ // was sent, breaking every status type. false is the pre-gating meaning.+ try {+ const gating = window.require('WAWebStatusGatingUtils');+ return typeof gating?.canCheckStatusRankingPosterGating === 'function'+ ? gating.canCheckStatusRankingPosterGating()+ : false;+ } catch {+ return false;+ }+ })(),`;++function occurrences(source, needle) {+ return source.split(needle).length - 1;+}++function applyGatingGuard(wwjsDir = DEFAULT_WWJS) {+ const utilsFile = path.join(wwjsDir, UTILS_PATH);+ if (!fs.existsSync(utilsFile)) {+ throw new Error(`whatsapp-web.js Utils.js not found at ${utilsFile}`);+ }++ const source = fs.readFileSync(utilsFile, 'utf8');+ const unguarded = occurrences(source, UNGUARDED_CALL);+ const guarded = occurrences(source, GUARDED_CALL);++ if (unguarded === 0 && guarded === 1) {+ return { skipped: true, reason: 'installed whatsapp-web.js already guards the status gating call' };+ }+ if (unguarded !== 1 || guarded !== 0) {+ throw new Error(+ `unsupported Utils.js shape (unguarded calls: ${unguarded}, guarded calls: ${guarded}); ` ++ 're-evaluate the status gating guard against the installed whatsapp-web.js',+ );+ }++ fs.writeFileSync(utilsFile, source.replace(UNGUARDED_CALL, GUARDED_CALL));+ return { skipped: false, note: 'status ranking-gating call guarded against a missing helper' };+}++function run() {+ const bestEffort = process.argv.includes('--best-effort');+ try {+ const result = applyGatingGuard();+ console.log(`patch-wwebjs-status-gating: ${result.skipped ? `skipped — ${result.reason}` : result.note}`);+ } catch (error) {+ if (bestEffort) {+ console.warn(`patch-wwebjs-status-gating: skipped — ${error.message}`);+ return;+ }+ console.error(`patch-wwebjs-status-gating: ${error.message}`);+ process.exitCode = 1;+ }+}++if (require.main === module) run();++module.exports = { applyGatingGuard, UNGUARDED_CALL, GUARDED_CALL };diff --git a/scripts/patch-wwebjs-status-gating.spec.js b/scripts/patch-wwebjs-status-gating.spec.jsnew file mode 100644index 000000000..2590cc7f2--- /dev/null+++ b/scripts/patch-wwebjs-status-gating.spec.js@@ -0,0 +1,90 @@+'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 { applyGatingGuard, UNGUARDED_CALL, GUARDED_CALL } = require('./patch-wwebjs-status-gating');++/**+ * The patcher rewrites a file this repository does not own, so what has to hold is that it only+ * ever fires on the exact shape it was written for. A transform that silently does nothing (or+ * half-applies to a changed upstream) would ship a build whose status posting is still broken,+ * which is the failure this patch exists to prevent.+ */++/** A throwaway whatsapp-web.js tree containing just the file the patcher edits. */+function fakeWwjs(utilsSource) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-gating-'));+ const utilsDir = path.join(dir, 'src', 'util', 'Injected');+ fs.mkdirSync(utilsDir, { recursive: true });+ fs.writeFileSync(path.join(utilsDir, 'Utils.js'), utilsSource);+ return { dir, utilsFile: path.join(utilsDir, 'Utils.js') };+}++const withCall = (call) => `exports.x = () => {\n const msg = new Model({\n${call}\n });\n};\n`;++test('guards the unguarded call', () => {+ const { dir, utilsFile } = fakeWwjs(withCall(UNGUARDED_CALL));++ const result = applyGatingGuard(dir);++ assert.equal(result.skipped, false);+ const patched = fs.readFileSync(utilsFile, 'utf8');+ assert.ok(patched.includes(GUARDED_CALL));+ assert.ok(!patched.includes(UNGUARDED_CALL));+});++test('is idempotent — a second run is a no-op, not a double patch', () => {+ const { dir, utilsFile } = fakeWwjs(withCall(UNGUARDED_CALL));+ applyGatingGuard(dir);+ const once = fs.readFileSync(utilsFile, 'utf8');++ const result = applyGatingGuard(dir);++ assert.equal(result.skipped, true);+ assert.equal(fs.readFileSync(utilsFile, 'utf8'), once);+});++/**+ * The important one. If upstream changes the call, the patcher must refuse loudly rather than leave+ * the file untouched and report success — a silent skip ships a build that still throws on every+ * status post, and nothing downstream would notice until a user tried to post one.+ */+test('refuses an upstream shape it does not recognise', () => {+ const { dir, utilsFile } = fakeWwjs(withCall(' cannotBeRanked: somethingElse(),'));+ const before = fs.readFileSync(utilsFile, 'utf8');++ assert.throws(() => applyGatingGuard(dir), /unsupported Utils\.js shape/);+ assert.equal(fs.readFileSync(utilsFile, 'utf8'), before, 'must not modify a file it did not understand');+});++test('refuses when the call appears more than once', () => {+ const { dir } = fakeWwjs(withCall(UNGUARDED_CALL) + withCall(UNGUARDED_CALL));++ assert.throws(() => applyGatingGuard(dir), /unguarded calls: 2/);+});++test('reports a missing whatsapp-web.js rather than pretending to patch it', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-gating-empty-'));++ assert.throws(() => applyGatingGuard(dir), /Utils\.js not found/);+});++/**+ * The guard has to preserve behaviour where the helper still exists — otherwise the patch would+ * silently change what WhatsApp records for every status on builds that were working fine. Asserted+ * on the snippet's shape rather than by evaluating it: this is generated code destined for a+ * browser page, and building a function out of a string to test it is not worth the hazard.+ */+test('calls the helper when present and falls back to false, rather than replacing it outright', () => {+ assert.ok(+ GUARDED_CALL.includes("typeof gating?.canCheckStatusRankingPosterGating === 'function'"),+ 'must still call the real helper when the build provides it',+ );+ assert.ok(GUARDED_CALL.includes('gating.canCheckStatusRankingPosterGating()'), 'helper result is used as-is');+ assert.ok(GUARDED_CALL.includes(': false'), 'absent helper falls back to the pre-gating meaning');+ assert.ok(GUARDED_CALL.includes('catch'), 'a throwing require must not take the status post down');+});diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex 97c88d51f..a3a13c09d 100644--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -55,6 +55,15 @@ function planSteps(root) {options: { stdio: 'inherit', cwd: root },});}+ const gatingPatcher = path.join(root, 'scripts', 'patch-wwebjs-status-gating.js');+ if (fs.existsSync(gatingPatcher)) {+ steps.push({+ name: 'whatsapp-web.js status gating guard (scripts/patch-wwebjs-status-gating.js --best-effort)',+ command: process.execPath,+ args: [gatingPatcher, '--best-effort'],+ options: { stdio: 'inherit', cwd: root },+ });+ }return steps;}