Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwjs): repair media status posting against current WhatsApp Web

Yudhi Armyndharis7f17083b1aa9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5367622c2..6dfbfff8c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,9 +21,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`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.
+ Media status was failing for a second and unrelated upstream reason: `sendStatusMediaMsgAction`
+ no longer accepts the positional `(msg, mediaUpdate)` call whatsapp-web.js 1.34.7 makes, so
+ WhatsApp Web's own bundle threw `Cannot read properties of undefined (reading 'id')`. The same
+ patcher (`scripts/patch-wwebjs-status.js`, formerly `patch-wwebjs-status-gating.js`) now also
+ rewrites that call to the current single-options-object signature, adopting the open upstream
+ fix (wwebjs/whatsapp-web.js#201816). Image, video and voice status post again, verified live.
+ The patcher also now runs in the production image build, which previously shipped without the
+ gating guard.
### Security
diff --git a/Dockerfile b/Dockerfile
index c253614b4..cc33e86da 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -120,12 +120,14 @@ COPY package*.json ./
# scripts/postinstall.js rides along: `npm ci` below runs the hook, which fails
# when the file is missing. With the patcher present the hook applies it in
# --best-effort mode; the explicit fatal run right after is the real gate.
-COPY scripts/postinstall.js scripts/patch-wwebjs-201832.js scripts/wwebjs-201832.patch scripts/patch-wwebjs-newsletter-preview.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/
-# Install production dependencies only, then apply the backports.
+# Install production dependencies only, then apply the backports. The status patcher runs LAST:
+# its transforms were written against the tree the other two leave behind.
RUN npm ci --omit=dev \
&& node scripts/patch-wwebjs-201832.js \
&& node scripts/patch-wwebjs-newsletter-preview.js \
+ && node scripts/patch-wwebjs-status.js \
&& npm cache clean --force
# Replace the npm the base image bundles. npm is not on the request path — the entrypoint runs
diff --git a/package.json b/package.json
index d7a6c40a7..e9010bf06 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 scripts/patch-wwebjs-status-gating.spec.js",
+ "test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.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/check-dockerignore.mjs b/scripts/check-dockerignore.mjs
index 677671883..bf62ba0e5 100644
--- a/scripts/check-dockerignore.mjs
+++ b/scripts/check-dockerignore.mjs
@@ -144,6 +144,7 @@ const mustKeep = [
'scripts/postinstall.js',
'scripts/patch-wwebjs-201832.js',
'scripts/patch-wwebjs-newsletter-preview.js',
+ 'scripts/patch-wwebjs-status.js',
'scripts/wwebjs-201832.patch',
'docker-entrypoint.sh',
'docs/01-project-overview.md',
diff --git a/scripts/patch-wwebjs-status-gating.js b/scripts/patch-wwebjs-status-gating.js
deleted file mode 100644
index 9365e503e..000000000
--- a/scripts/patch-wwebjs-status-gating.js
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * 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.js
deleted file mode 100644
index 2590cc7f2..000000000
--- a/scripts/patch-wwebjs-status-gating.spec.js
+++ /dev/null
@@ -1,90 +0,0 @@
-'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/patch-wwebjs-status.js b/scripts/patch-wwebjs-status.js
new file mode 100644
index 000000000..5c6b73681
--- /dev/null
+++ b/scripts/patch-wwebjs-status.js
@@ -0,0 +1,191 @@
+/**
+ * Repair status posting on whatsapp-web.js 1.34.7, which current WhatsApp Web builds have broken in
+ * two independent places. Both faults were confirmed on a live account against stock 1.34.7 with
+ * none of this project's code involved.
+ *
+ * 1. Ranking-gating guard. Every status message is built with
+ * `window.require('WAWebStatusGatingUtils').canCheckStatusRankingPosterGating()` as
+ * `cannotBeRanked`. That helper is gone from current WhatsApp Web builds, so the call threw
+ * before the message was ever sent — text, image, video and voice alike. The replacement calls
+ * the helper when it is there and falls back to `false` (the pre-gating meaning) when it is not,
+ * keeping behaviour intact wherever the API still exists rather than assuming it is gone
+ * everywhere.
+ *
+ * 2. Media send signature. `sendStatusMediaMsgAction` no longer accepts the positional
+ * `(msg, mediaUpdate)` pair; it takes a single options object and builds the message itself,
+ * so the old call dies inside WhatsApp Web's bundle with
+ * `Cannot read properties of undefined (reading 'id')`. The replacement is adopted from the
+ * open upstream fix (wwebjs/whatsapp-web.js#201816): pass
+ * `{ mediaMsgData, beforeSend, funnelContext }` and return a model built from `mediaMsgData`,
+ * since the model constructed for the old flow is no longer the message that gets sent. The
+ * upstream PR also hardcodes `cannotBeRanked: false`; the guard above is kept instead because
+ * it preserves the live call on builds that still provide the helper.
+ *
+ * Each transform is deliberately exact and self-disabling: an unknown shape fails the build
+ * instead of silently shipping without the fix, matching the sibling patchers. The two edits of
+ * the media repair are all-or-nothing — applying one without the other would leave the injected
+ * code referencing a variable that no longer exists — and the file is written once, after every
+ * group has been resolved, so a refused transform never leaves a half-patched tree behind.
+ */
+'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 GATING_FIND = ` cannotBeRanked: window
+ .require('WAWebStatusGatingUtils')
+ .canCheckStatusRankingPosterGating(),`;
+
+const GATING_REPLACE = ` 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;
+ }
+ })(),`;
+
+const MEDIA_DATA_FIND = ` const mediaUpdate = (data) =>
+ window.require('WAWebMediaUpdateMsg')(data, mediaOptions);`;
+
+const MEDIA_DATA_REPLACE = ` const mediaMsgData = {
+ ...message,
+ from: from,
+ to: chat.id,
+ author: from,
+ };`;
+
+const MEDIA_SEND_FIND = ` await window
+ .require('WAWebSendStatusMsgAction')
+ [
+ isMedia
+ ? 'sendStatusMediaMsgAction'
+ : 'sendStatusTextMsgAction'
+ ](...(isMedia ? [msg, mediaUpdate] : [statusOptions]));
+
+ return msg;`;
+
+const MEDIA_SEND_REPLACE = ` await window
+ .require('WAWebSendStatusMsgAction')
+ [
+ isMedia
+ ? 'sendStatusMediaMsgAction'
+ : 'sendStatusTextMsgAction'
+ ](
+ ...(isMedia
+ ? [
+ {
+ mediaMsgData,
+ beforeSend: async () => {},
+ funnelContext: undefined,
+ },
+ ]
+ : [statusOptions]),
+ );
+
+ return isMedia
+ ? new (window.require('WAWebCollections').Msg.modelClass)(
+ mediaMsgData,
+ )
+ : msg;`;
+
+/**
+ * The independently skippable units. A group is applied only when every edit's `find` is present
+ * exactly once and none of its `replace`s are, and skipped only when the mirror holds — anything
+ * else is an upstream shape this patcher was not written for, and it must refuse loudly.
+ */
+const GROUPS = [
+ {
+ name: 'status ranking-gating guard',
+ edits: [{ find: GATING_FIND, replace: GATING_REPLACE }],
+ },
+ {
+ name: 'media status send repair',
+ edits: [
+ { find: MEDIA_DATA_FIND, replace: MEDIA_DATA_REPLACE },
+ { find: MEDIA_SEND_FIND, replace: MEDIA_SEND_REPLACE },
+ ],
+ },
+];
+
+function occurrences(source, needle) {
+ return source.split(needle).length - 1;
+}
+
+function applyStatusPatches(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}`);
+ }
+
+ let source = fs.readFileSync(utilsFile, 'utf8');
+ const applied = [];
+ const skipped = [];
+
+ for (const group of GROUPS) {
+ const finds = group.edits.map((edit) => occurrences(source, edit.find));
+ const replaces = group.edits.map((edit) => occurrences(source, edit.replace));
+
+ if (finds.every((count) => count === 0) && replaces.every((count) => count === 1)) {
+ skipped.push(group.name);
+ continue;
+ }
+ if (finds.every((count) => count === 1) && replaces.every((count) => count === 0)) {
+ for (const edit of group.edits) {
+ source = source.replace(edit.find, edit.replace);
+ }
+ applied.push(group.name);
+ continue;
+ }
+ throw new Error(
+ `unsupported Utils.js shape for the ${group.name} ` +
+ `(unpatched: ${finds.join(',')}, patched: ${replaces.join(',')}); ` +
+ 're-evaluate this transform against the installed whatsapp-web.js',
+ );
+ }
+
+ if (applied.length) {
+ fs.writeFileSync(utilsFile, source);
+ }
+ return { applied, skipped };
+}
+
+function run() {
+ const bestEffort = process.argv.includes('--best-effort');
+ try {
+ const { applied, skipped } = applyStatusPatches();
+ const report = [
+ ...applied.map((name) => `applied ${name}`),
+ ...skipped.map((name) => `skipped ${name} (already present)`),
+ ].join('; ');
+ console.log(`patch-wwebjs-status: ${report}`);
+ } catch (error) {
+ if (bestEffort) {
+ console.warn(`patch-wwebjs-status: skipped — ${error.message}`);
+ return;
+ }
+ console.error(`patch-wwebjs-status: ${error.message}`);
+ process.exitCode = 1;
+ }
+}
+
+if (require.main === module) run();
+
+module.exports = {
+ applyStatusPatches,
+ GROUPS,
+ GATING_FIND,
+ GATING_REPLACE,
+ MEDIA_DATA_FIND,
+ MEDIA_DATA_REPLACE,
+ MEDIA_SEND_FIND,
+ MEDIA_SEND_REPLACE,
+};
diff --git a/scripts/patch-wwebjs-status.spec.js b/scripts/patch-wwebjs-status.spec.js
new file mode 100644
index 000000000..bad7b0f34
--- /dev/null
+++ b/scripts/patch-wwebjs-status.spec.js
@@ -0,0 +1,206 @@
+'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 {
+ applyStatusPatches,
+ GATING_FIND,
+ GATING_REPLACE,
+ MEDIA_DATA_FIND,
+ MEDIA_DATA_REPLACE,
+ MEDIA_SEND_FIND,
+ MEDIA_SEND_REPLACE,
+} = require('./patch-wwebjs-status');
+
+/**
+ * The patcher rewrites a file this repository does not own, so what has to hold is that it only
+ * ever fires on the exact shapes 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-status-'));
+ 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') };
+}
+
+/** Fake Utils.js source holding the given snippets in their real relative order. */
+const withSnippets = (mediaData, gating, mediaSend) =>
+ `exports.x = async () => {\n${mediaData}\n const msg = new Model({\n${gating}\n });\n${mediaSend}\n};\n`;
+
+const PRISTINE = withSnippets(MEDIA_DATA_FIND, GATING_FIND, MEDIA_SEND_FIND);
+
+test('applies both repairs to a pristine upstream tree', () => {
+ const { dir, utilsFile } = fakeWwjs(PRISTINE);
+
+ const result = applyStatusPatches(dir);
+
+ assert.deepEqual(result.applied, ['status ranking-gating guard', 'media status send repair']);
+ assert.deepEqual(result.skipped, []);
+ const patched = fs.readFileSync(utilsFile, 'utf8');
+ for (const replacement of [GATING_REPLACE, MEDIA_DATA_REPLACE, MEDIA_SEND_REPLACE]) {
+ assert.ok(patched.includes(replacement));
+ }
+ for (const needle of [GATING_FIND, MEDIA_DATA_FIND, MEDIA_SEND_FIND]) {
+ assert.ok(!patched.includes(needle));
+ }
+});
+
+test('is idempotent — a second run is a no-op, not a double patch', () => {
+ const { dir, utilsFile } = fakeWwjs(PRISTINE);
+ applyStatusPatches(dir);
+ const once = fs.readFileSync(utilsFile, 'utf8');
+
+ const result = applyStatusPatches(dir);
+
+ assert.deepEqual(result.applied, []);
+ assert.deepEqual(result.skipped, ['status ranking-gating guard', 'media status send repair']);
+ assert.equal(fs.readFileSync(utilsFile, 'utf8'), once);
+});
+
+/**
+ * The state an already-guarded install is actually in: the gating guard landed in an earlier run
+ * (or an earlier version of this patcher), the media repair did not exist yet. The groups must
+ * resolve independently — skipping one is not a reason to refuse the other.
+ */
+test('applies only the media repair when the gating guard is already present', () => {
+ const { dir, utilsFile } = fakeWwjs(withSnippets(MEDIA_DATA_FIND, GATING_REPLACE, MEDIA_SEND_FIND));
+
+ const result = applyStatusPatches(dir);
+
+ assert.deepEqual(result.applied, ['media status send repair']);
+ assert.deepEqual(result.skipped, ['status ranking-gating guard']);
+ const patched = fs.readFileSync(utilsFile, 'utf8');
+ assert.ok(patched.includes(MEDIA_SEND_REPLACE));
+ assert.equal(patched.split(GATING_REPLACE).length - 1, 1, 'the existing guard must survive unchanged');
+});
+
+/**
+ * The important one. If upstream changes a 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(
+ withSnippets(MEDIA_DATA_FIND, ' cannotBeRanked: somethingElse(),', MEDIA_SEND_FIND),
+ );
+ const before = fs.readFileSync(utilsFile, 'utf8');
+
+ assert.throws(() => applyStatusPatches(dir), /unsupported Utils\.js shape for the status ranking-gating guard/);
+ assert.equal(fs.readFileSync(utilsFile, 'utf8'), before, 'must not modify a file it did not understand');
+});
+
+/**
+ * The media repair's two edits reference each other (`mediaMsgData` is declared by one and used by
+ * the other), so a tree where only one matches must be refused as a whole — and the refusal must
+ * also discard the OTHER group's otherwise-applyable edit, because the file is only ever written
+ * once, whole.
+ */
+test('refuses a half-matching media group and leaves the whole file untouched', () => {
+ const { dir, utilsFile } = fakeWwjs(withSnippets(MEDIA_DATA_REPLACE, GATING_FIND, MEDIA_SEND_FIND));
+ const before = fs.readFileSync(utilsFile, 'utf8');
+
+ assert.throws(() => applyStatusPatches(dir), /unsupported Utils\.js shape for the media status send repair/);
+ assert.equal(
+ fs.readFileSync(utilsFile, 'utf8'),
+ before,
+ 'the applyable gating edit must not be written when a later group refuses',
+ );
+});
+
+test('refuses when a call appears more than once', () => {
+ const { dir } = fakeWwjs(PRISTINE + withSnippets(MEDIA_DATA_FIND, GATING_FIND, MEDIA_SEND_FIND));
+
+ assert.throws(() => applyStatusPatches(dir), /unpatched: 2/);
+});
+
+/**
+ * A tree holding a needle AND its replacement at once (a botched merge, a manually re-added call)
+ * satisfies neither the apply nor the skip precondition — treating it as applyable would write a
+ * second copy of the replacement into the file.
+ */
+test('refuses a tree containing both the unpatched and the patched form', () => {
+ const { dir, utilsFile } = fakeWwjs(withSnippets(MEDIA_DATA_FIND, `${GATING_FIND}\n${GATING_REPLACE}`, MEDIA_SEND_FIND));
+ const before = fs.readFileSync(utilsFile, 'utf8');
+
+ assert.throws(() => applyStatusPatches(dir), /unsupported Utils\.js shape for the status ranking-gating guard/);
+ assert.equal(fs.readFileSync(utilsFile, 'utf8'), before);
+});
+
+test('reports a missing whatsapp-web.js rather than pretending to patch it', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-status-empty-'));
+
+ assert.throws(() => applyStatusPatches(dir), /Utils\.js not found/);
+});
+
+/**
+ * The exit-code contract both consumers stand on: postinstall passes `--best-effort` and must get
+ * exit 0 for an unrecognised tree (a Baileys-only install must not fail `npm install`), while the
+ * production image build runs the patcher bare and MUST get exit 1 for the same tree — that
+ * failing build is the only thing standing between an upstream reshape and a shipped image whose
+ * status posting is still broken. Exercised end-to-end via a copy of the script next to a fake
+ * node_modules, because the default target path is resolved relative to the script file.
+ */
+test('CLI: unrecognised tree exits 1 bare and 0 under --best-effort', () => {
+ const { spawnSync } = require('node:child_process');
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-status-cli-'));
+ fs.mkdirSync(path.join(root, 'scripts'));
+ const script = path.join(root, 'scripts', 'patch-wwebjs-status.js');
+ fs.copyFileSync(path.join(__dirname, 'patch-wwebjs-status.js'), script);
+ const utilsDir = path.join(root, 'node_modules', 'whatsapp-web.js', 'src', 'util', 'Injected');
+ fs.mkdirSync(utilsDir, { recursive: true });
+ fs.writeFileSync(path.join(utilsDir, 'Utils.js'), 'exports.x = () => {};\n');
+
+ const bare = spawnSync(process.execPath, [script], { encoding: 'utf8' });
+ assert.equal(bare.status, 1, 'the production image build must fail on a tree the patcher cannot repair');
+ assert.match(bare.stderr, /unsupported Utils\.js shape/);
+
+ const bestEffort = spawnSync(process.execPath, [script, '--best-effort'], { encoding: 'utf8' });
+ assert.equal(bestEffort.status, 0, 'postinstall must not fail an install the patcher cannot help');
+ assert.match(bestEffort.stderr, /skipped/);
+});
+
+/**
+ * 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('gating guard calls the helper when present and falls back to false, rather than replacing it outright', () => {
+ assert.ok(
+ GATING_REPLACE.includes("typeof gating?.canCheckStatusRankingPosterGating === 'function'"),
+ 'must still call the real helper when the build provides it',
+ );
+ assert.ok(GATING_REPLACE.includes('gating.canCheckStatusRankingPosterGating()'), 'helper result is used as-is');
+ assert.ok(GATING_REPLACE.includes(': false'), 'absent helper falls back to the pre-gating meaning');
+ assert.ok(GATING_REPLACE.includes('catch'), 'a throwing require must not take the status post down');
+});
+
+/**
+ * The media repair must stay shaped like the upstream fix it adopts (wwebjs/whatsapp-web.js#201816):
+ * a single options object carrying the message data, and a returned model built from that same data
+ * — the model constructed for the old positional flow is no longer the message that gets sent.
+ */
+test('media repair passes the upstream options object and returns a model built from it', () => {
+ assert.ok(MEDIA_DATA_REPLACE.includes('...message,'), 'mediaMsgData starts from the built message');
+ assert.ok(MEDIA_DATA_REPLACE.includes('to: chat.id,'), 'destination is the status chat');
+ assert.ok(MEDIA_DATA_REPLACE.includes('author: from,'), 'author is the sender');
+
+ assert.ok(MEDIA_SEND_REPLACE.includes('mediaMsgData,'), 'options carry the message data');
+ assert.ok(MEDIA_SEND_REPLACE.includes('beforeSend: async () => {},'), 'beforeSend hook is provided');
+ assert.ok(MEDIA_SEND_REPLACE.includes('funnelContext: undefined,'), 'funnelContext is explicit');
+ assert.ok(!MEDIA_SEND_REPLACE.includes('[msg, mediaUpdate]'), 'the broken positional call is gone');
+ assert.ok(
+ MEDIA_SEND_REPLACE.includes('return isMedia'),
+ 'media returns the model built from mediaMsgData, text keeps the original msg',
+ );
+ assert.ok(MEDIA_SEND_REPLACE.includes(': msg;'), 'text status return value is unchanged');
+});
diff --git a/scripts/postinstall.js b/scripts/postinstall.js
index a3a13c09d..8691baa8e 100644
--- a/scripts/postinstall.js
+++ b/scripts/postinstall.js
@@ -1,7 +1,7 @@
/**
* Post-install hook (npm `postinstall`).
*
- * Three conditional steps, each skipped when its target is absent so the hook is a no-op where the
+ * Four 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 run dashboard:ci` when dashboard/ exists — the dashboard carries its own lockfile and
@@ -15,6 +15,8 @@
* tree — which must never be waved through. So a non-zero status here is propagated as-is.
* 3. `node scripts/patch-wwebjs-newsletter-preview.js --best-effort` when present. The production
* Docker stage runs it again without best-effort, making dependency drift a build failure.
+ * 4. `node scripts/patch-wwebjs-status.js --best-effort` when present — the status posting
+ * repairs, gated the same way as step 3.
*
* 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.
@@ -55,12 +57,12 @@ function planSteps(root) {
options: { stdio: 'inherit', cwd: root },
});
}
- const gatingPatcher = path.join(root, 'scripts', 'patch-wwebjs-status-gating.js');
- if (fs.existsSync(gatingPatcher)) {
+ const statusPatcher = path.join(root, 'scripts', 'patch-wwebjs-status.js');
+ if (fs.existsSync(statusPatcher)) {
steps.push({
- name: 'whatsapp-web.js status gating guard (scripts/patch-wwebjs-status-gating.js --best-effort)',
+ name: 'whatsapp-web.js status send repair (scripts/patch-wwebjs-status.js --best-effort)',
command: process.execPath,
- args: [gatingPatcher, '--best-effort'],
+ args: [statusPatcher, '--best-effort'],
options: { stdio: 'inherit', cwd: root },
});
}
diff --git a/scripts/postinstall.spec.js b/scripts/postinstall.spec.js
index cfafa22af..40122c173 100644
--- a/scripts/postinstall.spec.js
+++ b/scripts/postinstall.spec.js
@@ -17,11 +17,11 @@ const { planSteps, failureReason, run } = require('./postinstall.js');
const OK = { status: 0, signal: null, error: null };
-/** Bare temp dir optionally holding a dashboard/ and/or the patch script. */
-function makeRoot({ dashboard = false, patcher = false, previewPatcher = false } = {}) {
+/** Bare temp dir optionally holding a dashboard/ and/or the patch scripts. */
+function makeRoot({ dashboard = false, patcher = false, previewPatcher = false, statusPatcher = false } = {}) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openwa-postinstall-'));
if (dashboard) fs.mkdirSync(path.join(root, 'dashboard'));
- if (patcher || previewPatcher) {
+ if (patcher || previewPatcher || statusPatcher) {
fs.mkdirSync(path.join(root, 'scripts'));
}
if (patcher) {
@@ -30,6 +30,9 @@ function makeRoot({ dashboard = false, patcher = false, previewPatcher = false }
if (previewPatcher) {
fs.writeFileSync(path.join(root, 'scripts', 'patch-wwebjs-newsletter-preview.js'), '// stub\n');
}
+ if (statusPatcher) {
+ fs.writeFileSync(path.join(root, 'scripts', 'patch-wwebjs-status.js'), '// stub\n');
+ }
return root;
}
@@ -79,12 +82,21 @@ test('planSteps: both present plans dashboard first, patcher second', () => {
assert.equal(steps[1].command, process.execPath);
});
-test('planSteps: dashboard and both patchers run in stable order', () => {
- const steps = planSteps(makeRoot({ dashboard: true, patcher: true, previewPatcher: true }));
- assert.equal(steps.length, 3);
+test('planSteps: status patcher plans its own best-effort repair', () => {
+ const steps = planSteps(makeRoot({ statusPatcher: true }));
+ assert.equal(steps.length, 1);
+ assert.equal(steps[0].command, process.execPath);
+ assert.match(steps[0].args[0], /patch-wwebjs-status\.js$/);
+ assert.deepEqual(steps[0].args.slice(1), ['--best-effort']);
+});
+
+test('planSteps: dashboard and all patchers run in stable order', () => {
+ const steps = planSteps(makeRoot({ dashboard: true, patcher: true, previewPatcher: true, statusPatcher: true }));
+ assert.equal(steps.length, 4);
assert.equal(steps[0].command, 'npm run dashboard:ci');
assert.match(steps[1].args[0], /patch-wwebjs-201832\.js$/);
assert.match(steps[2].args[0], /patch-wwebjs-newsletter-preview\.js$/);
+ assert.match(steps[3].args[0], /patch-wwebjs-status\.js$/);
});
test('run: nothing to do exits 0 and never spawns', () => {