Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(engine): report engine patches that never applied

Yudhi Armyndharis2d6c95fd7404
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7e9b08ca8..087919b35 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- Each engine now names the install-time patches its library is missing as it starts, rather than
+ only the message-id backport. A source install applies them with `--best-effort`, so a patch that
+ could not apply left one line in the `npm install` transcript and nothing afterwards; the
+ capability it repairs then failed with an error that named no cause. Diagnostic only, startup
+ continues. See docs/12 for the procedure.
- The dashboard's API Keys page can limit an operator or viewer key to chosen sessions, on creation
and on a key that already exists. Leaving the picker empty keeps access to every session, including
ones created later, and the keys table shows each key's scope. `allowedSessions` was already
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 33efb3bf3..ec7c9c28a 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -665,6 +665,45 @@ rm -rf node_modules/whatsapp-web.js && npm ci
> Pinning `WWEBJS_WEB_VERSION` does **not** work around this — the rename is present in every
> current WhatsApp Web build, so no pin avoids it.
+### Issue: Startup logs say install-time patches are missing
+
+**Symptoms:**
+
+- Startup logs contain `The installed whatsapp-web.js is missing N of OpenWA's install-time patches: …`,
+ or the same line naming `@whiskeysockets/baileys`
+- One capability fails while everything around it works: an unnamed `500` from a single route,
+ block/unblock refusing every id, a status media send that never arrives, a group description that
+ cannot be set, an app-state resync that never settles
+
+**Cause:** OpenWA applies nine exact source transforms to its engine libraries at install time
+(docs/29 §29.3). The Docker image runs them without `--best-effort`, so a source shape a patcher
+cannot recognise fails the image build. A source install runs them through `scripts/postinstall.js`
+with `--best-effort`, where a patcher that cannot apply prints one line into a long `npm install`
+transcript and the install still succeeds. The usual causes are `npm install --ignore-scripts` and
+an upstream release whose shape a patcher no longer recognises. Each engine now checks its own
+patches as it starts and names the ones that did not land, so the report arrives on the machine that
+is actually affected rather than in an install log nobody kept.
+
+**Solution:**
+
+```bash
+# Which patches are missing? Works on every platform, including Windows without grep.
+node -e "const fs=require('fs'),p=require('path');for(const f of fs.readdirSync('scripts').filter(n=>n.startsWith('patch-')&&n.endsWith('.js')&&!n.endsWith('.spec.js')).sort()){const m=require('./scripts/'+f);if(typeof m.isApplied!=='function')continue;const k=f.startsWith('patch-wwebjs-')?'whatsapp-web.js':'@whiskeysockets/baileys';try{console.log((m.isApplied(p.dirname(require.resolve(k+'/package.json')))?'APPLIED ':'NOT APPLIED')+' '+f)}catch{}}"
+
+# Apply each one it named, then restart
+node scripts/patch-wwebjs-group-description.js
+```
+
+If a patcher answers with an unsupported-shape error instead of applying, the installed library has
+moved and the transform needs re-evaluating against it. Reinstalling will not help; open an issue
+quoting the message it printed.
+
+> `patch-wwebjs-201832.js` is not in that list. It carries its own startup check and its own entry
+> above, because a partially applied backport needs different advice than one that never ran.
+
+> A patch that never applied is not fatal on its own: only the capability it repairs is affected and
+> the rest of the gateway runs normally, which is why this is easy to misread as a bug in one route.
+
### Issue: Reads on a large account fail with `Runtime.callFunctionOn timed out`
> **Engine:** This issue applies to the `whatsapp-web.js` engine only (Chromium/Puppeteer-based). It does not affect `ENGINE_TYPE=baileys`.
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 7540a8456..add36c3ba 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -131,6 +131,13 @@ OpenWA ships nine exact, self-disabling source transforms over the installed eng
patcher no-ops once the fix is present upstream, and an unrecognized source shape fails loudly
rather than shipping a silently partial patch.
+"Fails loudly" holds for the image build, not for `npm install`, where `--best-effort` turns a
+refusal into one line of a long transcript. So each patcher also exports an `isApplied()` predicate,
+its own stand-down branch read back against the installed file, and each engine reports the patches
+it is missing as it starts (`src/engine/adapters/engine-patch-status.ts`; 🔧¹ keeps the separate
+check described below). The report is diagnostic, not preventive: startup continues, so a session
+reaching READY is not evidence that every patch landed. See docs/12 for the operator procedure.
+
### 29.3.1 The nine patches
| # | Patcher | Library target | What it repairs | Stand-down predicate |
diff --git a/scripts/patch-baileys-appstate.js b/scripts/patch-baileys-appstate.js
index 81ca7f18e..88d0ebab2 100644
--- a/scripts/patch-baileys-appstate.js
+++ b/scripts/patch-baileys-appstate.js
@@ -33,8 +33,15 @@ const CHATS_PATH = path.join('lib', 'Socket', 'chats.js');
const LOOP_FIND = ` const decoded = await extractSyncdPatches(result, config?.options);
for (const key in decoded) {`;
+/**
+ * The apply function's stand-down predicate: present exactly when LOOP_REPLACE was written.
+ * Interpolated below rather than restated, the way patch-baileys-newsletter-create.js does it, so
+ * the marker and the text that carries it cannot drift apart.
+ */
+const PATCHED_MARKER = 'OpenWA: query() resolves undefined on its own timeout';
+
const LOOP_REPLACE = ` const decoded = await extractSyncdPatches(result, config?.options);
- // OpenWA: query() resolves undefined on its own timeout, which decodes to {}. Every
+ // ${PATCHED_MARKER}, 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) {
@@ -49,7 +56,7 @@ function applyAppStatePatch(baileysDir = DEFAULT_BAILEYS) {
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')) {
+ if (source.includes(PATCHED_MARKER)) {
return { skipped: true, reason: 'already patched' };
}
const occurrences = source.split(LOOP_FIND).length - 1;
@@ -80,4 +87,17 @@ function run() {
if (require.main === module) run();
-module.exports = { applyAppStatePatch, LOOP_FIND, LOOP_REPLACE };
+/**
+ * The stand-down branch above as a predicate, for the startup guard (engine-patch-status.ts).
+ * Unreadable reads as applied: a tree we cannot inspect is not evidence of a broken one, and the
+ * apply function treats a missing chats.js as nothing to patch rather than a fault.
+ */
+function isApplied(baileysDir = DEFAULT_BAILEYS) {
+ try {
+ return fs.readFileSync(path.join(baileysDir, CHATS_PATH), 'utf8').includes(PATCHED_MARKER);
+ } catch {
+ return true;
+ }
+}
+
+module.exports = { applyAppStatePatch, isApplied, PATCHED_MARKER, LOOP_FIND, LOOP_REPLACE };
diff --git a/scripts/patch-baileys-appstate.spec.js b/scripts/patch-baileys-appstate.spec.js
index 7f5887caa..e7e067ea2 100644
--- a/scripts/patch-baileys-appstate.spec.js
+++ b/scripts/patch-baileys-appstate.spec.js
@@ -6,7 +6,7 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
-const { applyAppStatePatch, LOOP_FIND } = require('./patch-baileys-appstate');
+const { applyAppStatePatch, isApplied, LOOP_FIND } = require('./patch-baileys-appstate');
/**
* Same contract as the sibling patcher specs: the patcher rewrites a file this repository does not
@@ -39,6 +39,13 @@ test('bounds the loop on an empty decode', () => {
assert.ok(patched.includes('for (const key in decoded) {'));
});
+test('isApplied tracks the transform', () => {
+ const { dir } = fakeBaileys(REAL_SHAPE);
+ assert.equal(isApplied(dir), false);
+ applyAppStatePatch(dir);
+ assert.equal(isApplied(dir), true);
+});
+
test('is idempotent — a second run does not double-patch', () => {
const { dir, file } = fakeBaileys(REAL_SHAPE);
applyAppStatePatch(dir);
diff --git a/scripts/patch-baileys-newsletter-create.js b/scripts/patch-baileys-newsletter-create.js
index 364046254..dc08583d5 100644
--- a/scripts/patch-baileys-newsletter-create.js
+++ b/scripts/patch-baileys-newsletter-create.js
@@ -116,4 +116,17 @@ function run() {
if (require.main === module) run();
-module.exports = { applyNewsletterCreatePatch, PARSE_FIND, PARSE_REPLACE, MARKER };
+/**
+ * The stand-down branch above as a predicate, for the startup guard (engine-patch-status.ts).
+ * Unreadable reads as applied: a tree we cannot inspect is not evidence of a broken one, and the
+ * apply function treats a missing newsletter.js as nothing to patch rather than a fault.
+ */
+function isApplied(baileysDir = DEFAULT_BAILEYS) {
+ try {
+ return fs.readFileSync(path.join(baileysDir, NEWSLETTER_PATH), 'utf8').includes(MARKER);
+ } catch {
+ return true;
+ }
+}
+
+module.exports = { applyNewsletterCreatePatch, isApplied, PARSE_FIND, PARSE_REPLACE, MARKER };
diff --git a/scripts/patch-baileys-newsletter-create.spec.js b/scripts/patch-baileys-newsletter-create.spec.js
index ce5303043..549da722a 100644
--- a/scripts/patch-baileys-newsletter-create.spec.js
+++ b/scripts/patch-baileys-newsletter-create.spec.js
@@ -6,7 +6,7 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
-const { applyNewsletterCreatePatch, PARSE_FIND, MARKER } = require('./patch-baileys-newsletter-create');
+const { applyNewsletterCreatePatch, isApplied, PARSE_FIND, MARKER } = require('./patch-baileys-newsletter-create');
/**
* Same contract as the sibling patcher specs: the patcher rewrites a file this repository does not
@@ -130,3 +130,11 @@ test('the marker the idempotence check keys on is actually written', () => {
assert.ok(fs.readFileSync(file, 'utf8').includes(MARKER));
fs.rmSync(dir, { recursive: true, force: true });
});
+
+test('isApplied is false on a pristine tree and true once the patch has run', () => {
+ const { dir } = fakeBaileys();
+ assert.equal(isApplied(dir), false);
+ applyNewsletterCreatePatch(dir);
+ assert.equal(isApplied(dir), true);
+ fs.rmSync(dir, { recursive: true, force: true });
+});
diff --git a/scripts/patch-wwebjs-block.js b/scripts/patch-wwebjs-block.js
index cafa3ab70..daa327e91 100644
--- a/scripts/patch-wwebjs-block.js
+++ b/scripts/patch-wwebjs-block.js
@@ -100,6 +100,21 @@ const GROUPS = [
},
];
+/**
+ * Both groups' stand-down branch as one predicate, for the startup guard
+ * (engine-patch-status.ts). A half-patched tree is a reachable, supported state here, and it reads
+ * as NOT applied: whichever half is missing still answers an opaque 500 on every id.
+ * Unreadable reads as applied, since a tree we cannot inspect is not evidence of a broken one.
+ */
+function isApplied(wwjsDir = DEFAULT_WWJS) {
+ try {
+ const source = fs.readFileSync(path.join(wwjsDir, CONTACT_PATH), 'utf8');
+ return GROUPS.every((group) => source.includes(group.replace));
+ } catch {
+ return true;
+ }
+}
+
function applyBlockPatches({ wwjsDir = DEFAULT_WWJS } = {}) {
const contactFile = path.join(wwjsDir, CONTACT_PATH);
if (!fs.existsSync(contactFile)) {
@@ -148,4 +163,4 @@ function run() {
if (require.main === module) run();
-module.exports = { applyBlockPatches, GROUPS, findFor, replaceFor, CONTACT_PATH };
+module.exports = { applyBlockPatches, isApplied, GROUPS, findFor, replaceFor, CONTACT_PATH };
diff --git a/scripts/patch-wwebjs-block.spec.js b/scripts/patch-wwebjs-block.spec.js
index 98308d486..11813db81 100644
--- a/scripts/patch-wwebjs-block.spec.js
+++ b/scripts/patch-wwebjs-block.spec.js
@@ -6,7 +6,7 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
-const { applyBlockPatches, GROUPS, findFor, replaceFor } = require('./patch-wwebjs-block');
+const { applyBlockPatches, isApplied, GROUPS, findFor, replaceFor } = require('./patch-wwebjs-block');
/**
* The patcher rewrites a file this repository does not own, so what has to hold is that it fires on
@@ -80,6 +80,14 @@ test('patches block and unblock, and is idempotent', () => {
fs.rmSync(dir, { recursive: true, force: true });
});
+test('isApplied tracks the transform, false before it runs and true after', () => {
+ const { dir } = fakeWwjs(pristineSource());
+ assert.equal(isApplied(dir), false);
+ applyBlockPatches({ wwjsDir: dir });
+ assert.equal(isApplied(dir), true);
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
test('refuses an unknown shape instead of shipping unpatched', () => {
const { dir } = fakeWwjs(pristineSource().replace('getContactToBlockOnlyUseIfNoAssociatedChat', 'someRenamedHelper'));
assert.throws(() => applyBlockPatches({ wwjsDir: dir }), /refusing to patch blind/);
diff --git a/scripts/patch-wwebjs-group-description.js b/scripts/patch-wwebjs-group-description.js
index a95c2f284..e79518bc1 100644
--- a/scripts/patch-wwebjs-group-description.js
+++ b/scripts/patch-wwebjs-group-description.js
@@ -61,6 +61,19 @@ function occurrences(source, needle) {
return source.split(needle).length - 1;
}
+/**
+ * The stand-down branch below as a predicate, for the startup guard (engine-patch-status.ts).
+ * Unreadable reads as applied: a tree we cannot inspect is not evidence of a broken one.
+ */
+function isApplied(wwjsDir = DEFAULT_WWJS) {
+ try {
+ const source = fs.readFileSync(path.join(wwjsDir, GROUP_CHAT_PATH), 'utf8');
+ return occurrences(source, OPTIONS_CALL) === 1 && occurrences(source, POSITIONAL_CALL) === 0;
+ } catch {
+ return true;
+ }
+}
+
function applyGroupDescriptionFix(wwjsDir = DEFAULT_WWJS) {
const groupChatFile = path.join(wwjsDir, GROUP_CHAT_PATH);
if (!fs.existsSync(groupChatFile)) {
@@ -105,4 +118,4 @@ function run() {
if (require.main === module) run();
-module.exports = { applyGroupDescriptionFix, POSITIONAL_CALL, OPTIONS_CALL };
+module.exports = { applyGroupDescriptionFix, isApplied, POSITIONAL_CALL, OPTIONS_CALL };
diff --git a/scripts/patch-wwebjs-group-description.spec.js b/scripts/patch-wwebjs-group-description.spec.js
index 84535fa7d..07d86bfaf 100644
--- a/scripts/patch-wwebjs-group-description.spec.js
+++ b/scripts/patch-wwebjs-group-description.spec.js
@@ -6,7 +6,12 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
-const { applyGroupDescriptionFix, POSITIONAL_CALL, OPTIONS_CALL } = require('./patch-wwebjs-group-description.js');
+const {
+ applyGroupDescriptionFix,
+ isApplied,
+ POSITIONAL_CALL,
+ OPTIONS_CALL,
+} = require('./patch-wwebjs-group-description.js');
function makeDependency(source) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openwa-group-description-'));
@@ -25,6 +30,16 @@ test('patches the description job call to the options object', () => {
assert.equal(fs.readFileSync(groupChat, 'utf8'), `before\n${OPTIONS_CALL}\nafter\n`);
});
+test('reports the patch as applied only once the transform has run', () => {
+ const { root } = makeDependency(`before\n${POSITIONAL_CALL}\nafter\n`);
+
+ assert.equal(isApplied(root), false);
+
+ applyGroupDescriptionFix(root);
+
+ assert.equal(isApplied(root), true);
+});
+
test('sends an empty description as null, which clears rather than writing an empty body', () => {
const { root, groupChat } = makeDependency(`before\n${POSITIONAL_CALL}\nafter\n`);
diff --git a/scripts/patch-wwebjs-newsletter-preview.js b/scripts/patch-wwebjs-newsletter-preview.js
index 19f470f70..734ad20e5 100644
--- a/scripts/patch-wwebjs-newsletter-preview.js
+++ b/scripts/patch-wwebjs-newsletter-preview.js
@@ -51,6 +51,19 @@ function applyBackport(wwjsDir = DEFAULT_WWJS) {
return { skipped: false, note: 'destination chat context added to link previews' };
}
+/**
+ * The stand-down branch above as a predicate, for the startup guard (engine-patch-status.ts).
+ * Unreadable reads as applied: a tree we cannot inspect is not evidence of a broken one.
+ */
+function isApplied(wwjsDir = DEFAULT_WWJS) {
+ try {
+ const source = fs.readFileSync(path.join(wwjsDir, UTILS_PATH), 'utf8');
+ return occurrences(source, LEGACY_CALL) === 0 && occurrences(source, CONTEXT_CALL) === 1;
+ } catch {
+ return true;
+ }
+}
+
function run() {
const bestEffort = process.argv.includes('--best-effort');
try {
@@ -70,4 +83,4 @@ function run() {
if (require.main === module) run();
-module.exports = { applyBackport, LEGACY_CALL, CONTEXT_CALL };
+module.exports = { applyBackport, isApplied, LEGACY_CALL, CONTEXT_CALL };
diff --git a/scripts/patch-wwebjs-newsletter-preview.spec.js b/scripts/patch-wwebjs-newsletter-preview.spec.js
index a748f69cd..fcd9fe5a1 100644
--- a/scripts/patch-wwebjs-newsletter-preview.spec.js
+++ b/scripts/patch-wwebjs-newsletter-preview.spec.js
@@ -6,7 +6,7 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
-const { applyBackport } = require('./patch-wwebjs-newsletter-preview.js');
+const { applyBackport, isApplied } = require('./patch-wwebjs-newsletter-preview.js');
const LEGACY_CALL =
"let preview = await window\n .require('WAWebLinkPreviewChatAction')\n .getLinkPreview(link);";
@@ -41,6 +41,14 @@ test('is idempotent when destination chat context is already present', () => {
assert.equal(fs.readFileSync(utils, 'utf8'), original);
});
+test('reports the patch as applied only once the transform has run', () => {
+ const { root } = makeDependency(`before\n${LEGACY_CALL}\nafter\n`);
+
+ assert.equal(isApplied(root), false);
+ applyBackport(root);
+ assert.equal(isApplied(root), true);
+});
+
test('rejects an unknown dependency shape without changing it', () => {
const { root, utils } = makeDependency('window.WWebJS.sendMessage = async () => {};\n');
const original = fs.readFileSync(utils, 'utf8');
diff --git a/scripts/patch-wwebjs-participant-arity.js b/scripts/patch-wwebjs-participant-arity.js
index 916ee652d..d74890be2 100644
--- a/scripts/patch-wwebjs-participant-arity.js
+++ b/scripts/patch-wwebjs-participant-arity.js
@@ -125,6 +125,21 @@ function occurrences(source, needle) {
return source.split(needle).length - 1;
}
+/**
+ * Every group's replacement present, for the startup guard (engine-patch-status.ts). All three
+ * actions must carry it: a tree left by the LEGACY shape above scores exactly one of three, and it
+ * still answers 500 when promoting an existing admin, so ANY would report that tree as healthy.
+ * Unreadable reads as applied, since a tree we cannot inspect is not evidence of a broken one.
+ */
+function isApplied(wwjsDir = DEFAULT_WWJS) {
+ try {
+ const source = fs.readFileSync(path.join(wwjsDir, GROUP_CHAT_PATH), 'utf8');
+ return ACTIONS.every((action) => occurrences(source, replaceFor(action)) === 1);
+ } catch {
+ return true;
+ }
+}
+
function applyParticipantArityPatches(wwjsDir = DEFAULT_WWJS) {
const groupChatFile = path.join(wwjsDir, GROUP_CHAT_PATH);
if (!fs.existsSync(groupChatFile)) {
@@ -189,6 +204,7 @@ if (require.main === module) run();
module.exports = {
applyParticipantArityPatches,
+ isApplied,
GROUPS,
ACTIONS,
findFor,
diff --git a/scripts/patch-wwebjs-participant-arity.spec.js b/scripts/patch-wwebjs-participant-arity.spec.js
index 80e5e4f68..c03ce4796 100644
--- a/scripts/patch-wwebjs-participant-arity.spec.js
+++ b/scripts/patch-wwebjs-participant-arity.spec.js
@@ -8,6 +8,7 @@ const path = require('path');
const {
applyParticipantArityPatches,
+ isApplied,
GROUPS,
ACTIONS,
findFor,
@@ -111,6 +112,16 @@ test('applies every group to the installed upstream shape', () => {
assert.equal(out.split('return { status: 200 };').length - 1, 0);
});
+test('isApplied is false on a pristine tree and true once the patch lands', () => {
+ // All three groups must carry their replacement: a tree left by the legacy shape scores one of
+ // three, and it still answers 500 when promoting an existing admin.
+ const { dir } = fakeWwjs(readInstalled());
+
+ assert.equal(isApplied(dir), false);
+ applyParticipantArityPatches(dir);
+ assert.equal(isApplied(dir), true);
+});
+
test('never calls the WA Web action with an empty list', () => {
const { dir, file } = fakeWwjs(readInstalled());
applyParticipantArityPatches(dir);
diff --git a/scripts/patch-wwebjs-ready-sync.js b/scripts/patch-wwebjs-ready-sync.js
index 7695a4372..9badbd672 100644
--- a/scripts/patch-wwebjs-ready-sync.js
+++ b/scripts/patch-wwebjs-ready-sync.js
@@ -76,6 +76,25 @@ function occurrences(source, needle) {
return source.split(needle).length - 1;
}
+/**
+ * The stand-down branch below as a predicate, for the startup guard (engine-patch-status.ts).
+ * Finds are counted with the replacements removed for the reason the apply loop documents: each
+ * replacement contains its own find. Unreadable reads as applied, since a tree we cannot inspect
+ * is not evidence of a broken one.
+ */
+function isApplied(wwjsDir = DEFAULT_WWJS) {
+ try {
+ const source = fs.readFileSync(path.join(wwjsDir, CLIENT_PATH), 'utf8');
+ return EDITS.every(
+ edit =>
+ occurrences(source, edit.replace) === 1 &&
+ occurrences(source.split(edit.replace).join(''), edit.find) === 0,
+ );
+ } catch {
+ return true;
+ }
+}
+
function applyReadySyncPatch(wwjsDir = DEFAULT_WWJS) {
const clientFile = path.join(wwjsDir, CLIENT_PATH);
if (!fs.existsSync(clientFile)) {
@@ -124,6 +143,7 @@ if (require.main === module) run();
module.exports = {
applyReadySyncPatch,
+ isApplied,
EDITS,
FLAG_INIT_FIND,
FLAG_INIT_REPLACE,
diff --git a/scripts/patch-wwebjs-ready-sync.spec.js b/scripts/patch-wwebjs-ready-sync.spec.js
index d8d01078b..166d15328 100644
--- a/scripts/patch-wwebjs-ready-sync.spec.js
+++ b/scripts/patch-wwebjs-ready-sync.spec.js
@@ -8,6 +8,7 @@ const path = require('path');
const {
applyReadySyncPatch,
+ isApplied,
FLAG_INIT_FIND,
FLAG_INIT_REPLACE,
ATTACH_MARK_FIND,
@@ -47,6 +48,15 @@ test('applies all three edits to a pristine upstream tree', () => {
}
});
+test('isApplied is false on a pristine tree and true once the patch has run', () => {
+ const { dir } = fakeWwjs(PRISTINE);
+
+ // Each replacement contains its own find, so a raw find count would read a patched tree as pristine.
+ assert.equal(isApplied(dir), false);
+ applyReadySyncPatch(dir);
+ assert.equal(isApplied(dir), true);
+});
+
test('is idempotent — a second run is a no-op, not a double patch', () => {
const { dir, clientFile } = fakeWwjs(PRISTINE);
applyReadySyncPatch(dir);
diff --git a/scripts/patch-wwebjs-status.js b/scripts/patch-wwebjs-status.js
index 5c6b73681..b12236997 100644
--- a/scripts/patch-wwebjs-status.js
+++ b/scripts/patch-wwebjs-status.js
@@ -120,6 +120,23 @@ function occurrences(source, needle) {
return source.split(needle).length - 1;
}
+/**
+ * Every group's stand-down branch as one predicate, for the startup guard
+ * (engine-patch-status.ts). The groups apply independently, so a tree carrying one and not the
+ * other is a reachable state and reads as NOT applied: half the repair is still a broken send.
+ * Unreadable reads as applied, since a tree we cannot inspect is not evidence of a broken one.
+ */
+function isApplied(wwjsDir = DEFAULT_WWJS) {
+ try {
+ const source = fs.readFileSync(path.join(wwjsDir, UTILS_PATH), 'utf8');
+ return GROUPS.every((group) =>
+ group.edits.every((edit) => occurrences(source, edit.find) === 0 && occurrences(source, edit.replace) === 1),
+ );
+ } catch {
+ return true;
+ }
+}
+
function applyStatusPatches(wwjsDir = DEFAULT_WWJS) {
const utilsFile = path.join(wwjsDir, UTILS_PATH);
if (!fs.existsSync(utilsFile)) {
@@ -181,6 +198,7 @@ if (require.main === module) run();
module.exports = {
applyStatusPatches,
+ isApplied,
GROUPS,
GATING_FIND,
GATING_REPLACE,
diff --git a/scripts/patch-wwebjs-status.spec.js b/scripts/patch-wwebjs-status.spec.js
index bad7b0f34..97dff2d9e 100644
--- a/scripts/patch-wwebjs-status.spec.js
+++ b/scripts/patch-wwebjs-status.spec.js
@@ -8,6 +8,7 @@ const path = require('path');
const {
applyStatusPatches,
+ isApplied,
GATING_FIND,
GATING_REPLACE,
MEDIA_DATA_FIND,
@@ -54,6 +55,15 @@ test('applies both repairs to a pristine upstream tree', () => {
}
});
+/** Both groups are independent, so the predicate only reads as applied once each one has landed. */
+test('isApplied tracks the transform: false on a pristine tree, true once patched', () => {
+ const { dir } = fakeWwjs(PRISTINE);
+
+ assert.equal(isApplied(dir), false);
+ applyStatusPatches(dir);
+ assert.equal(isApplied(dir), true);
+});
+
test('is idempotent — a second run is a no-op, not a double patch', () => {
const { dir, utilsFile } = fakeWwjs(PRISTINE);
applyStatusPatches(dir);
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index 5d73ce42d..ccba3d33d 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -13,6 +13,7 @@ import { type createLogger } from '../../common/services/logger.service';
import { BaileysAdapterConfig } from '../types/baileys.types';
import { createBaileysLogger } from './baileys-logger';
import { BaileysVersionResolver } from './baileys-version-resolver';
+import { unappliedPatches, unappliedPatchesMessage } from './engine-patch-status';
import type { BaileysEvents } from './baileys-events';
import type { BaileysHistory } from './baileys-history';
import type { BaileysSessionStore } from './baileys-session-store';
@@ -154,6 +155,15 @@ export class BaileysLifecycle {
if (this.intentionalClose) {
return;
}
+
+ // An install that skipped a Baileys patch fails later with errors that name no cause: an
+ // app-state resync that never terminates, a newsletter create that cannot parse its reply.
+ // Say so here instead, while the operator is still looking at the startup logs.
+ const unapplied = unappliedPatches('baileys');
+ if (unapplied.length) {
+ this.host.logger.error(unappliedPatchesMessage('baileys', unapplied));
+ }
+
try {
await this.connect();
} catch (err) {
diff --git a/src/engine/adapters/engine-patch-status.spec.ts b/src/engine/adapters/engine-patch-status.spec.ts
new file mode 100644
index 000000000..4acc2e594
--- /dev/null
+++ b/src/engine/adapters/engine-patch-status.spec.ts
@@ -0,0 +1,169 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { type PatchFamily, unappliedPatches, unappliedPatchesMessage } from './engine-patch-status';
+
+/**
+ * Guards the startup diagnostic for engine patches that never applied. The cost runs both ways, as
+ * it does for `wwebjs-backport-check.ts`: a missed detection restores the silence the guard exists
+ * to break, and a false alarm on every boot sends operators after patches they do not need. The
+ * "cannot tell" cases below are the second half of that, and they matter more here than in the
+ * single-patcher guard, because this one walks a directory and requires whatever it finds.
+ */
+describe('unappliedPatches', () => {
+ const tmpDirs: string[] = [];
+
+ function tmp(prefix: string): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
+ tmpDirs.push(dir);
+ return dir;
+ }
+
+ /** A scripts/ directory holding stub patchers, each written as the module the guard requires. */
+ function scriptsWith(modules: Record<string, string>): string {
+ const dir = tmp('openwa-patch-scripts-');
+ for (const [name, body] of Object.entries(modules)) fs.writeFileSync(path.join(dir, name), body);
+ return dir;
+ }
+
+ const patcher = (applied: boolean): string => `module.exports = { isApplied: () => ${String(applied)} };\n`;
+
+ afterAll(() => {
+ for (const dir of tmpDirs) fs.rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('names only the patchers whose predicate answers false', () => {
+ const scripts = scriptsWith({
+ 'patch-wwebjs-alpha.js': patcher(true),
+ 'patch-wwebjs-beta.js': patcher(false),
+ 'patch-wwebjs-gamma.js': patcher(false),
+ });
+
+ expect(unappliedPatches('wwebjs', scripts, tmp('dep-'))).toEqual(['patch-wwebjs-beta', 'patch-wwebjs-gamma']);
+ });
+
+ it('reports nothing when every patcher is applied', () => {
+ const scripts = scriptsWith({ 'patch-wwebjs-alpha.js': patcher(true) });
+
+ expect(unappliedPatches('wwebjs', scripts, tmp('dep-'))).toEqual([]);
+ });
+
+ it('keeps each family to its own patchers', () => {
+ const scripts = scriptsWith({
+ 'patch-wwebjs-alpha.js': patcher(false),
+ 'patch-baileys-alpha.js': patcher(false),
+ });
+
+ expect(unappliedPatches('wwebjs', scripts, tmp('dep-'))).toEqual(['patch-wwebjs-alpha']);
+ expect(unappliedPatches('baileys', scripts, tmp('dep-'))).toEqual(['patch-baileys-alpha']);
+ });
+
+ it('passes the resolved dependency directory to the predicate', () => {
+ const dep = tmp('dep-');
+ const scripts = scriptsWith({
+ 'patch-wwebjs-alpha.js': 'module.exports = { isApplied: dir => dir !== process.env.OPENWA_EXPECTED_DEP };\n',
+ });
+ process.env.OPENWA_EXPECTED_DEP = dep;
+
+ try {
+ // The predicate answers false only when it was handed exactly the directory we passed in, so
+ // a guard that called isApplied() with no argument would report nothing here.
+ expect(unappliedPatches('wwebjs', scripts, dep)).toEqual(['patch-wwebjs-alpha']);
+ } finally {
+ delete process.env.OPENWA_EXPECTED_DEP;
+ }
+ });
+
+ it('ignores specs, non-patchers and anything that is not a .js file', () => {
+ const scripts = scriptsWith({
+ 'patch-wwebjs-alpha.spec.js': patcher(false),
+ 'patch-wwebjs-alpha.js': patcher(true),
+ 'check-audit.mjs': patcher(false),
+ 'wwebjs-201832.patch': 'not javascript at all',
+ });
+
+ expect(unappliedPatches('wwebjs', scripts, tmp('dep-'))).toEqual([]);
+ });
+
+ it('skips a patcher that exports no predicate rather than reporting it', () => {
+ // This is patch-wwebjs-201832.js's situation: guarded elsewhere, so it opts out by omission.
+ const scripts = scriptsWith({
+ 'patch-wwebjs-legacy.js': 'module.exports = { applyBackport: () => undefined };\n',
+ 'patch-wwebjs-alpha.js': patcher(false),
+ });
+
+ expect(unappliedPatches('wwebjs', scripts, tmp('dep-'))).toEqual(['patch-wwebjs-alpha']);
+ });
+
+ it('skips a patcher that cannot be required instead of failing the boot', () => {
+ const scripts = scriptsWith({
+ 'patch-wwebjs-broken.js': 'this is not valid javascript {{{\n',
+ 'patch-wwebjs-alpha.js': patcher(false),
+ });
+
+ expect(unappliedPatches('wwebjs', scripts, tmp('dep-'))).toEqual(['patch-wwebjs-alpha']);
+ });
+
+ it('stays quiet when there is no scripts directory to read', () => {
+ expect(unappliedPatches('wwebjs', path.join(tmp('openwa-empty-'), 'absent'), tmp('dep-'))).toEqual([]);
+ });
+
+ it('stays quiet when the dependency cannot be resolved', () => {
+ const scripts = scriptsWith({ 'patch-wwebjs-alpha.js': patcher(false) });
+
+ // Both engines are always installed here, so the only way to reach the unresolvable branch is
+ // a family with no package behind it. That stands in for the real case: an install whose
+ // engine library is absent or pruned is not an install we can judge, and the patcher stubs
+ // above would otherwise be reported as missing.
+ expect(unappliedPatches('absent-engine' as PatchFamily, scripts)).toEqual([]);
+ });
+});
+
+describe('the patchers this repository actually ships', () => {
+ const scripts = path.join(__dirname, '..', '..', '..', 'scripts');
+ const shipped = fs
+ .readdirSync(scripts)
+ .filter(f => f.startsWith('patch-') && f.endsWith('.js') && !f.endsWith('.spec.js'))
+ .sort();
+
+ it('finds the patchers at all', () => {
+ // Vacuity guard: an empty scan would make both assertions below pass without checking anything.
+ expect(shipped.length).toBeGreaterThanOrEqual(9);
+ });
+
+ it('exports a predicate from every patcher except the one guarded elsewhere', () => {
+ const withoutPredicate = shipped.filter(f => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const patcher = require(path.join(scripts, f)) as { isApplied?: unknown };
+ return typeof patcher.isApplied !== 'function';
+ });
+
+ // patch-wwebjs-201832.js is covered by wwebjs-backport-check.ts, which has its own predicate,
+ // its own message and its own docs/12 entry. It is the ONLY patcher allowed to opt out: any
+ // other name here is a patcher whose failure to apply would be silent again.
+ expect(withoutPredicate).toEqual(['patch-wwebjs-201832.js']);
+ });
+
+ it('names a family this guard understands in every patcher filename', () => {
+ // A patcher named outside both prefixes would be silently invisible to unappliedPatches.
+ const unfamiliar = shipped.filter(f => !f.startsWith('patch-wwebjs-') && !f.startsWith('patch-baileys-'));
+
+ expect(unfamiliar).toEqual([]);
+ });
+});
+
+describe('unappliedPatchesMessage', () => {
+ it('names the library, the count, every patcher and a command that fixes one', () => {
+ const message = unappliedPatchesMessage('wwebjs', ['patch-wwebjs-block', 'patch-wwebjs-status']);
+
+ expect(message).toContain('whatsapp-web.js');
+ expect(message).toContain('missing 2');
+ expect(message).toContain('patch-wwebjs-block, patch-wwebjs-status');
+ expect(message).toContain('node scripts/patch-wwebjs-block.js');
+ expect(message).toContain('docs/12-troubleshooting-faq.md');
+ });
+
+ it('names the Baileys package for the baileys family', () => {
+ expect(unappliedPatchesMessage('baileys', ['patch-baileys-appstate'])).toContain('@whiskeysockets/baileys');
+ });
+});
diff --git a/src/engine/adapters/engine-patch-status.ts b/src/engine/adapters/engine-patch-status.ts
new file mode 100644
index 000000000..00259228a
--- /dev/null
+++ b/src/engine/adapters/engine-patch-status.ts
@@ -0,0 +1,106 @@
+import * as fs from 'fs';
+import * as path from 'path';
+
+/**
+ * Startup guard for OpenWA's install-time engine patches.
+ *
+ * The patches are applied two ways, and only one of them is loud. The Docker production stage runs
+ * every patcher WITHOUT `--best-effort`, so an unrecognised source shape fails the image build. A
+ * source install runs them through `scripts/postinstall.js` WITH `--best-effort`, where a patcher
+ * that cannot apply prints one line into a long `npm install` transcript and the install still
+ * succeeds. The operator then runs a tree that is missing a fix, and the symptom arrives later as
+ * exactly the opaque failure the patch existed to remove: an unnamed 500, a send that reports no
+ * message, a resync loop that never ends. None of those errors name their cause.
+ *
+ * So restate it on the machine that is actually affected, as the engine starts.
+ *
+ * Ground truth only. Each patcher exports `isApplied()`, which is that patcher's OWN stand-down
+ * branch, reading the installed file. There is deliberately no manifest and no recorded install
+ * outcome: a record can survive a dependency being reinstalled underneath it, and a guard that
+ * says "patched" about an unpatched tree is worse than no guard at all.
+ *
+ * Diagnostic, not preventive, matching `wwebjs-backport-check.ts`: startup continues, so a session
+ * reaching READY is not evidence that every patch landed.
+ *
+ * `scripts/patch-wwebjs-201832.js` is absent from this by design. It is the one patcher that
+ * already has a runtime guard (`wwebjs-backport-check.ts`, its own predicate and its own message),
+ * so it exports no `isApplied` and is skipped here rather than being reported twice or migrated in
+ * the same change. `engine-patch-status.spec.ts` pins it as the only such exception.
+ */
+
+/** Which library a patcher targets, read from its filename prefix. */
+export type PatchFamily = 'wwebjs' | 'baileys';
+
+const PACKAGE_FOR: Record<PatchFamily, string> = {
+ wwebjs: 'whatsapp-web.js',
+ baileys: '@whiskeysockets/baileys',
+};
+
+/** The one member of a patcher module this file uses. Everything else is the patcher's business. */
+interface Patcher {
+ isApplied?: (depDir?: string) => boolean;
+}
+
+/**
+ * `scripts/` as it sits beside the compiled output: `dist/engine/adapters` and `src/engine/adapters`
+ * are both three levels below the package root, so the same hop works built and under ts-jest. The
+ * production image copies the patchers in (Dockerfile), so this resolves there too.
+ */
+function defaultScriptsDir(): string {
+ return path.join(__dirname, '..', '..', '..', 'scripts');
+}
+
+/**
+ * Names of the patchers for `family` that the installed library does NOT carry, without the `.js`.
+ *
+ * Empty is the answer for every uncertainty: no `scripts/` directory, an unresolvable package, a
+ * patcher that exports no predicate. An install we cannot inspect is not evidence of a broken one,
+ * and a false alarm on every boot would send operators chasing a patch they do not need.
+ */
+export function unappliedPatches(family: PatchFamily, scriptsDir?: string, depDir?: string): string[] {
+ const dir = scriptsDir ?? defaultScriptsDir();
+
+ let resolvedDep: string;
+ try {
+ resolvedDep = depDir ?? path.dirname(require.resolve(`${PACKAGE_FOR[family]}/package.json`));
+ } catch {
+ return [];
+ }
+
+ let entries: string[];
+ try {
+ entries = fs.readdirSync(dir);
+ } catch {
+ return [];
+ }
+
+ const prefix = `patch-${family}-`;
+ const missing: string[] = [];
+ for (const entry of entries.sort()) {
+ if (!entry.startsWith(prefix) || !entry.endsWith('.js') || entry.endsWith('.spec.js')) continue;
+ let patcher: Patcher;
+ try {
+ // Requiring a patcher does not run it: each guards its own CLI behind `require.main`. The
+ // patchers are plain CommonJS loaded by computed path, so this cannot be an import.
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ patcher = require(path.join(dir, entry)) as Patcher;
+ } catch {
+ continue;
+ }
+ if (typeof patcher.isApplied !== 'function') continue;
+ if (patcher.isApplied(resolvedDep) === false) missing.push(entry.replace(/\.js$/, ''));
+ }
+ return missing;
+}
+
+/** The startup line for a non-empty `unappliedPatches` result. */
+export function unappliedPatchesMessage(family: PatchFamily, names: string[]): string {
+ return (
+ `The installed ${PACKAGE_FOR[family]} is missing ${names.length} of OpenWA's install-time ` +
+ `patches: ${names.join(', ')}. The capabilities each one repairs will fail with errors that ` +
+ 'name no cause. The install skipped them, usually because it ran with --ignore-scripts or ' +
+ 'because a patcher refused a source shape it did not recognise. Apply them with ' +
+ `\`node scripts/${names[0]}.js\` (or reinstall with \`npm install\`) and restart. ` +
+ 'See docs/12-troubleshooting-faq.md.'
+ );
+}
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index 310fb771c..9ff25c745 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -14,6 +14,7 @@ import { resolveAuthTimeoutMs, resolveEngineInitTimeoutMs } from '../engine-init
import { killOrphanedChromiumProcesses, removeStaleSingletonFiles } from './chromium-profile-hygiene';
import { isSupportedProxyUrl, buildProxyLaunchConfig } from './wwebjs-proxy';
import { BACKPORT_MISSING_MESSAGE, isBackportMissing } from './wwebjs-backport-check';
+import { unappliedPatches, unappliedPatchesMessage } from './engine-patch-status';
import { type WhatsAppWebJsConfig } from './whatsapp-web-js.adapter';
/**
@@ -170,6 +171,12 @@ export class WwebjsLifecycle {
this.host.logger.error(BACKPORT_MISSING_MESSAGE);
}
+ // The other seven whatsapp-web.js patchers fail the same way and were equally silent about it.
+ const unapplied = unappliedPatches('wwebjs');
+ if (unapplied.length) {
+ this.host.logger.error(unappliedPatchesMessage('wwebjs', unapplied));
+ }
+
try {
// Build puppeteer args, including proxy if configured
const puppeteerArgs = this.host.config.puppeteer?.args