Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

build(wwjs): report which requested participants resolved to members

Yudhi Armyndharis9a30ae1e046f
diff --git a/scripts/patch-wwebjs-participant-arity.js b/scripts/patch-wwebjs-participant-arity.js
new file mode 100644
index 000000000..252d7c83e
--- /dev/null
+++ b/scripts/patch-wwebjs-participant-arity.js
@@ -0,0 +1,140 @@
+/**
+ * Make whatsapp-web.js report which requested participants it actually acted on.
+ *
+ * `GroupChat.removeParticipants` / `promoteParticipants` / `demoteParticipants` resolve every
+ * requested id against the group's OWN participant collection and silently drop what they cannot
+ * find (`.filter(Boolean)`), then hand the survivors to a WA Web request builder and resolve
+ * `{status: 200}` for the whole batch. Two failures follow, both reproduced live (#1220):
+ *
+ * 1. When EVERY requested id is dropped the builder receives an empty repeated field and asserts
+ * "expected at least 1 children, but found 0". The page rejects, and because the adapter only
+ * inspects a RESOLVED value the error escapes as an unnamed `500`.
+ * 2. When only SOME are dropped — or, for promote/demote, when all are — the call still resolves
+ * `{status: 200}` with no indication of what was ignored, so the adapter reports success for
+ * people WhatsApp never touched. Promote and demote have no arity assertion at all, which makes
+ * their version of this silent rather than loud.
+ *
+ * One transform per page function, each its own group so an upstream change to one does not disable
+ * the other two:
+ * - keep the resolved array WITH its holes, so position still maps to the requested id;
+ * - derive `matched` (a boolean per requested id) and `present` (the survivors);
+ * - call the WA Web action only when something survived — an empty batch is not a request;
+ * - return `matched` alongside the status. The adapter treats a missing or wrong-length `matched`
+ * as "unpatched tree" and keeps its old behaviour, matching the `eventsAttached` marker
+ * convention in patch-wwebjs-ready-sync.js.
+ *
+ * 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. The file is written
+ * once, after the whole group set resolves.
+ */
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+
+const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');
+const GROUP_CHAT_PATH = path.join('src', 'structures', 'GroupChat.js');
+
+/**
+ * The three page bodies are identical apart from the action name, which is what makes each find
+ * unique. Building them from one template keeps the 16-space indentation in step with upstream
+ * rather than repeating it three times by hand.
+ */
+const findFor = (action) => ` ).filter(Boolean);
+ await window
+ .require('WAWebModifyParticipantsGroupAction')
+ .${action}(chat, participants);
+ return { status: 200 };`;
+
+const replaceFor = (action) => ` );
+ const matched = participants.map(Boolean);
+ const present = participants.filter(Boolean);
+ // A requested id that is not a member of this group resolved to undefined above.
+ // Handing an empty list to the request builder trips its repeated-field arity
+ // assertion, so skip the call entirely when nothing resolved, and report which
+ // requested ids did — the batch status alone cannot distinguish a real change
+ // from a silently dropped one.
+ if (present.length) {
+ await window
+ .require('WAWebModifyParticipantsGroupAction')
+ .${action}(chat, present);
+ }
+ return { status: 200, matched };`;
+
+const ACTIONS = ['removeParticipants', 'promoteParticipants', 'demoteParticipants'];
+
+const GROUPS = ACTIONS.map((action) => ({
+ name: `${action} batch truth`,
+ edits: [{ find: findFor(action), replace: replaceFor(action) }],
+}));
+
+function occurrences(source, needle) {
+ return source.split(needle).length - 1;
+}
+
+function applyParticipantArityPatches(wwjsDir = DEFAULT_WWJS) {
+ const groupChatFile = path.join(wwjsDir, GROUP_CHAT_PATH);
+ if (!fs.existsSync(groupChatFile)) {
+ throw new Error(`whatsapp-web.js GroupChat.js not found at ${groupChatFile}`);
+ }
+
+ let source = fs.readFileSync(groupChatFile, '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 GroupChat.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(groupChatFile, source);
+ }
+ return { applied, skipped };
+}
+
+function run() {
+ const bestEffort = process.argv.includes('--best-effort');
+ try {
+ const { applied, skipped } = applyParticipantArityPatches();
+ const report = [
+ ...applied.map((name) => `applied ${name}`),
+ ...skipped.map((name) => `skipped ${name} (already present)`),
+ ].join('; ');
+ console.log(`patch-wwebjs-participant-arity: ${report}`);
+ } catch (error) {
+ if (bestEffort) {
+ console.warn(`patch-wwebjs-participant-arity: skipped — ${error.message}`);
+ return;
+ }
+ console.error(`patch-wwebjs-participant-arity: ${error.message}`);
+ process.exitCode = 1;
+ }
+}
+
+if (require.main === module) run();
+
+module.exports = {
+ applyParticipantArityPatches,
+ GROUPS,
+ ACTIONS,
+ findFor,
+ replaceFor,
+};
diff --git a/scripts/patch-wwebjs-participant-arity.spec.js b/scripts/patch-wwebjs-participant-arity.spec.js
new file mode 100644
index 000000000..058258907
--- /dev/null
+++ b/scripts/patch-wwebjs-participant-arity.spec.js
@@ -0,0 +1,158 @@
+'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 {
+ applyParticipantArityPatches,
+ GROUPS,
+ ACTIONS,
+ findFor,
+ replaceFor,
+} = require('./patch-wwebjs-participant-arity');
+
+/**
+ * The patcher rewrites a file this repository does not own, so what has to hold is that it fires on
+ * exactly the shapes it was written for and refuses everything else. A transform that silently did
+ * nothing would ship a build where removing a non-member still answers 500 and promoting one still
+ * answers 200 claiming success — the two failures this patch exists to prevent (#1220).
+ *
+ * The fixture is the INSTALLED GroupChat.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.
+ */
+const INSTALLED_GROUP_CHAT = path.join(
+ __dirname,
+ '..',
+ 'node_modules',
+ 'whatsapp-web.js',
+ 'src',
+ 'structures',
+ 'GroupChat.js',
+);
+
+/** 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-arity-'));
+ const structures = path.join(dir, 'src', 'structures');
+ fs.mkdirSync(structures, { recursive: true });
+ const file = path.join(structures, 'GroupChat.js');
+ fs.writeFileSync(file, source);
+ return { dir, file };
+}
+
+/**
+ * The installed tree may ALREADY be patched: `npm ci` runs postinstall, which applies this very
+ * patcher, so on a CI runner the file is transformed before this spec ever reads it while a local
+ * checkout that never re-installed still holds the pristine upstream text. Reversing the transform
+ * first makes the fixture identical in both states.
+ *
+ * This does not weaken the check. If upstream drifts, neither the patched nor the unpatched anchor
+ * is present, the reversal is a no-op, and the assertions below fail — which is the point.
+ */
+const readInstalled = () => {
+ let source = fs.readFileSync(INSTALLED_GROUP_CHAT, 'utf8');
+ for (const action of ACTIONS) {
+ source = source.split(replaceFor(action)).join(findFor(action));
+ }
+ return source;
+};
+
+test('the unpatched-shape reversal is an exact inverse of the transform', () => {
+ // This is what makes the fixture safe on a CI runner, where `npm ci` has already run postinstall
+ // and patched the installed tree before this spec reads it. If the reversal were not an exact
+ // inverse, every assertion below would be testing a shape that never existed.
+ const pristine = readInstalled();
+ const { dir, file } = fakeWwjs(pristine);
+ applyParticipantArityPatches(dir);
+
+ let reversed = fs.readFileSync(file, 'utf8');
+ assert.notEqual(reversed, pristine, 'the patch must actually change the file, or this proves nothing');
+ for (const action of ACTIONS) {
+ reversed = reversed.split(replaceFor(action)).join(findFor(action));
+ }
+ assert.equal(reversed, pristine);
+});
+
+test('the fixture models the shape the patcher acts on', () => {
+ // Guard the guard: if the installed tree stopped containing these anchors every assertion below
+ // would fail for the wrong reason, or pass vacuously once the patcher started skipping.
+ assert.equal(GROUPS.length, 3, `expected three groups, found ${GROUPS.length}`);
+ const source = readInstalled();
+ for (const action of ACTIONS) {
+ assert.equal(
+ source.split(findFor(action)).length - 1,
+ 1,
+ `installed GroupChat.js does not contain exactly one unpatched ${action} body`,
+ );
+ }
+});
+
+test('applies every group to the installed upstream shape', () => {
+ const { dir, file } = fakeWwjs(readInstalled());
+
+ const { applied, skipped } = applyParticipantArityPatches(dir);
+
+ assert.equal(applied.length, 3);
+ assert.deepEqual(skipped, []);
+
+ const out = fs.readFileSync(file, 'utf8');
+ assert.equal(out.split('return { status: 200, matched };').length - 1, 3);
+ assert.equal(out.split('const matched = participants.map(Boolean);').length - 1, 3);
+ assert.equal(out.split('if (present.length) {').length - 1, 3);
+ // The surviving participants, not the holed array, are what reaches WhatsApp.
+ for (const action of ACTIONS) {
+ assert.ok(out.includes(`.${action}(chat, present);`), `${action} still passes the unfiltered array`);
+ }
+ // The bare `{ status: 200 }` return must be gone from all three, or one of them still lies.
+ assert.equal(out.split('return { status: 200 };').length - 1, 0);
+});
+
+test('never calls the WA Web action with an empty list', () => {
+ const { dir, file } = fakeWwjs(readInstalled());
+ applyParticipantArityPatches(dir);
+ const out = fs.readFileSync(file, 'utf8');
+
+ // Every action call in the three patched bodies must sit inside the arity guard. Matching the
+ // guard and the call as one block is what makes this a check rather than a spot inspection: two
+ // separate `includes` would both pass even if the guard sat around unrelated code.
+ for (const action of ACTIONS) {
+ const guardedCall = `if (present.length) {
+ await window
+ .require('WAWebModifyParticipantsGroupAction')
+ .${action}(chat, present);
+ }`;
+ assert.equal(out.split(guardedCall).length - 1, 1, `${action} is not guarded by the arity check`);
+ }
+});
+
+test('is idempotent — a second run skips every group', () => {
+ const { dir } = fakeWwjs(readInstalled());
+
+ applyParticipantArityPatches(dir);
+ const second = applyParticipantArityPatches(dir);
+
+ assert.deepEqual(second.applied, []);
+ assert.equal(second.skipped.length, 3);
+});
+
+test('refuses an unknown shape instead of writing a half-patched tree', () => {
+ // One action drifts upstream; the other two still match. The patcher must refuse rather than
+ // apply the two it recognises and leave the third silently broken.
+ const drifted = readInstalled().replace(
+ findFor('demoteParticipants'),
+ ' ).filter((x) => x);\n await somethingElse();\n return { status: 200 };',
+ );
+ const { dir, file } = fakeWwjs(drifted);
+ const before = fs.readFileSync(file, 'utf8');
+
+ assert.throws(() => applyParticipantArityPatches(dir), /unsupported GroupChat\.js shape/);
+ assert.equal(fs.readFileSync(file, 'utf8'), before, 'a refused run must leave the file untouched');
+});
+
+test('refuses a tree that is missing the file entirely', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-arity-empty-'));
+ assert.throws(() => applyParticipantArityPatches(dir), /GroupChat\.js not found/);
+});