Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwjs): make a no-op participant status change idempotent
Yudhi Armyndharis45b6ac0aa448
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 77f26bbf6..63e41c49e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The chart's optional ServiceMonitor now scrapes one target per pod instead of two. Its selector matched only the shared selector labels, which both the ClusterIP and the headless Service carry, so Prometheus discovered a target through each and produced two sets of series distinguished only by the `service` label — enough to double-count any naive aggregation. The headless Service also publishes not-ready addresses, so it kept a target pointed at a pod whose port is still closed during boot and reported it as down. The ServiceMonitor and the ClusterIP Service now share a `openwa.io/scrape-target` label that the headless Service does not carry. After upgrading, series previously collected through the headless target stop appearing: check any dashboard or alerting rule that matches on the `service` label, which now always resolves to the ClusterIP Service.- The Helm chart no longer restarts the pod while it is still starting. The container binds its port only after every bootstrap hook has finished, so during boot the endpoint is closed rather than unhealthy and each liveness probe is a connection refusal; with no startup probe the liveness settings governed that window and allowed 50 seconds before the kubelet killed the container. This is not limited to deployments using session auto-start: the database connect retry alone is up to 10 attempts three seconds apart, so a database that is slow to accept connections can consume 30 of those 50 seconds on a stock install. A startup probe now allows 300 seconds (a 5-second period, 60 failures) and fires immediately, so a fast boot is recognised in about five seconds rather than after a fixed delay — the pod becomes live sooner than before, not later. A boot that is genuinely unbounded is not made safe by any fixed budget.- A Helm upgrade that changes only `env` or `secretEnv` now restarts the pod, so the new configuration actually reaches the running container. The pod template carried nothing derived from the ConfigMap or Secret, so such an upgrade rendered a byte-identical template and triggered no rollout: the release reported success while the process kept its previous values, because Kubernetes reads `envFrom` only when a container is created. The pod template now carries checksums of the rendered ConfigMap and Secret. Two consequences worth reading before upgrading: a configuration change now restarts this single-instance StatefulSet where previously it did not, and the chart can only observe configuration it renders itself — with `existingSecret` set no Secret is created, so changes to that operator-managed Secret still need `kubectl rollout restart`. The Secret checksum is published as a pod annotation, which is readable by anyone who can list pods; `values.yaml` notes what that means when choosing between `secretEnv` and `existingSecret`.+- Promoting a participant who is already an admin, or demoting one who is already not, answers `200` instead of `500` on the whatsapp-web.js engine. WhatsApp Web rejects a status change that would change nothing, and the minified page bundle reports that rejection without a name, so the request failed with no usable diagnosis. The install-time patch now skips a participant whose status already matches the request, which makes both operations idempotent: the requested end state already holds.- A participant id carrying a recognised domain but a nonsense user-part — `NOT A [email protected]`, `@c.us` — is now rejected with `400` like any other malformed id. The earlier check tested only the domain, so these still reached WhatsApp Web and produced the same undiagnosable `500` the check was added to prevent. The same rule now backs the `mentions` validator, which had the identical gap, and it covers the two membership-request routes, which take the same ids and were missed the first time. A bare phone number is also qualified before it reaches the Baileys socket; previously it went out without a domain, which WhatsApp does not read as an id at all, so the write silently did nothing. Fixes #1220.- Messages that existed before the full-text index was created are indexed on the next boot instead of being permanently unsearchable, and ordinary edits and deletes on them work again. The boot-time backfill was gated on the index being empty, but `messages_fts` is an FTS5 external-content table whose `count(*)` returns the row count of `messages`, so the condition could never hold and the backfill never ran; until those rows are indexed the sync triggers issue delete commands for documents that were never added and SQLite rejects the whole statement. The guard is now a rowid-level completeness check, so it also repairs a partially populated index rather than only an empty one.- A WhatsApp-level refusal of a group participant add, remove, promote or demote on the Baileys engine is now reported as `403` instead of propagating as an unhandled error. Participant refusals normally arrive one per participant and were already mapped; a refusal of the request itself arrives through the other channel, and this was the only write in the Baileys group adapter that did not map it. A dropped connection or a timeout is still reported as itself rather than as a permissions problem. Refs #1220.diff --git a/scripts/patch-wwebjs-participant-arity.js b/scripts/patch-wwebjs-participant-arity.jsindex 252d7c83e..916ee652d 100644--- a/scripts/patch-wwebjs-participant-arity.js+++ b/scripts/patch-wwebjs-participant-arity.js@@ -46,7 +46,43 @@ const findFor = (action) => ` ).filter(Boolean);.${action}(chat, participants);return { status: 200 };`;+/**+ * Which resolved members still need the call. `remove` acts on every member; `promote`/`demote` act+ * only on those not already in the requested state — WhatsApp Web rejects a status change that would+ * change nothing, and the minified page bundle reports that as an unnamed error, so promoting an+ * existing admin answered 500. Skipping them makes the operation idempotent: the requested end state+ * already holds, which is exactly what the caller asked for.+ */+const actionableFor = (action) =>+ action === 'promoteParticipants'+ ? 'participants.filter((p) => p && !p.isAdmin)'+ : action === 'demoteParticipants'+ ? 'participants.filter((p) => p && p.isAdmin)'+ : 'participants.filter(Boolean)';+const replaceFor = (action) => ` );+ const matched = participants.map(Boolean);+ const present = ${actionableFor(action)};+ // 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 };`;++/**+ * The shape an earlier version of this patcher left behind: same transform, but `present` was every+ * resolved member regardless of the status change being a no-op. A tree carrying it matches neither+ * the pristine find nor the current replace, so the patcher would refuse it as an unknown shape.+ * Reverse it to pristine first and the normal apply path takes over — that is what makes upgrading+ * the patcher safe on a tree someone already installed against.+ */+const LEGACY_REPLACE = (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.@@ -61,6 +97,23 @@ const replaceFor = (action) => ` );}return { status: 200, matched };`;+/**+ * Rewind any legacy-patched body to the pristine upstream shape. A no-op on pristine or current+ * trees.+ *+ * Skips an action whose legacy body is IDENTICAL to the current one — `removeParticipants` acts on+ * every member in both versions. Rewinding that would undo a correctly patched tree and then re-apply+ * it, so `applied` would never be empty and the patcher would stop being idempotent.+ */+function normalizeLegacy(source) {+ for (const action of ACTIONS) {+ const legacy = LEGACY_REPLACE(action);+ if (legacy === replaceFor(action)) continue;+ source = source.split(legacy).join(findFor(action));+ }+ return source;+}+const ACTIONS = ['removeParticipants', 'promoteParticipants', 'demoteParticipants'];const GROUPS = ACTIONS.map((action) => ({@@ -78,7 +131,10 @@ function applyParticipantArityPatches(wwjsDir = DEFAULT_WWJS) {throw new Error(`whatsapp-web.js GroupChat.js not found at ${groupChatFile}`);}- let source = fs.readFileSync(groupChatFile, 'utf8');+ const original = fs.readFileSync(groupChatFile, 'utf8');+ // Rewind a tree patched by an earlier version of this file, so the apply path below sees either+ // the pristine shape or the current one — never a third state it would have to refuse.+ let source = normalizeLegacy(original);const applied = [];const skipped = [];@@ -137,4 +193,6 @@ module.exports = {ACTIONS,findFor,replaceFor,+ LEGACY_REPLACE,+ normalizeLegacy,};diff --git a/scripts/patch-wwebjs-participant-arity.spec.js b/scripts/patch-wwebjs-participant-arity.spec.jsindex 058258907..80e5e4f68 100644--- a/scripts/patch-wwebjs-participant-arity.spec.js+++ b/scripts/patch-wwebjs-participant-arity.spec.js@@ -12,6 +12,7 @@ const {ACTIONS,findFor,replaceFor,+ LEGACY_REPLACE,} = require('./patch-wwebjs-participant-arity');/**@@ -128,6 +129,46 @@ test('never calls the WA Web action with an empty list', () => {}});+test('acts only on members whose status would actually change', () => {+ // WhatsApp Web rejects a status change that changes nothing, and the minified bundle reports that+ // as an unnamed error — promoting an existing admin answered 500. Reproduced live before this test+ // was written. `remove` keeps acting on every member; only the two status ops narrow.+ const { dir, file } = fakeWwjs(readInstalled());+ applyParticipantArityPatches(dir);+ const out = fs.readFileSync(file, 'utf8');++ assert.equal(out.split('const present = participants.filter((p) => p && !p.isAdmin);').length - 1, 1);+ assert.equal(out.split('const present = participants.filter((p) => p && p.isAdmin);').length - 1, 1);+ assert.equal(out.split('const present = participants.filter(Boolean);').length - 1, 1);+});++test('upgrades a tree left behind by the previous version of this patcher', () => {+ // The legacy shape matches neither the pristine find nor the current replace, so without the+ // rewind the patcher would refuse an already-installed tree as an unknown shape — the upgrade+ // would fail on exactly the machines that already had the fix.+ let legacy = readInstalled();+ for (const action of ACTIONS) {+ legacy = legacy.split(findFor(action)).join(LEGACY_REPLACE(action));+ }+ assert.notEqual(legacy, readInstalled(), 'the legacy fixture must differ, or this proves nothing');++ const { dir, file } = fakeWwjs(legacy);+ const { applied, skipped } = applyParticipantArityPatches(dir);++ // Two applied, not three: removeParticipants' body is unchanged between versions, so the legacy+ // tree already carries its final shape and it is skipped rather than rewritten.+ assert.deepEqual(applied.sort(), ['demoteParticipants batch truth', 'promoteParticipants batch truth']);+ assert.deepEqual(skipped, ['removeParticipants batch truth']);+ const out = fs.readFileSync(file, 'utf8');+ assert.equal(out.split('const present = participants.filter((p) => p && !p.isAdmin);').length - 1, 1);+ assert.equal(out.split('const present = participants.filter((p) => p && p.isAdmin);').length - 1, 1);+ // Only the two status ops changed between versions; removeParticipants' body is identical in both,+ // so asserting its legacy text is gone would assert the wrong thing.+ for (const action of ['promoteParticipants', 'demoteParticipants']) {+ assert.equal(out.split(LEGACY_REPLACE(action)).length - 1, 0, `${action} still carries the legacy body`);+ }+});+test('is idempotent — a second run skips every group', () => {const { dir } = fakeWwjs(readInstalled());