Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(scripts,engine): apply the wwebjs backport via git when GNU patch is missing, and say so at startup when neither landed (#974)

Yudhi Armyndharis739c44106cb0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cbef61e08..c0646f40e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A source install without the GNU `patch` binary no longer silently ships an unpatched
+ whatsapp-web.js.** OpenWA backports the fix for the WhatsApp Web 2.3000.x message-id rename during
+ `npm install`; when the `patch` binary was missing — the default on Windows outside Git Bash — the
+ install printed one warning, exited successfully, and left whatsapp-web.js broken. The failure then
+ surfaced only in production, as sends returning `the engine returned no message` despite delivering,
+ and chat, media and typing operations throwing the minified `r: r`. The backport now falls back to
+ `git apply`, which every source install has by definition and which produces a byte-identical tree.
+ With neither applier present the install still degrades rather than failing, so a Baileys-only setup
+ is unaffected — but the whatsapp-web.js engine now logs an explicit, actionable error at session
+ start instead of failing opaquely later. Prerequisites and a troubleshooting entry are documented.
+
- **The release runbook in `docs/15` now describes the process the repository actually uses.** §15.7
documented a release-branch-and-PR flow with a generic pre-release checklist; releases are in fact
cut as a single `chore(release)` commit on `main` plus an annotated `v*` tag, with everything from
diff --git a/docs/08-development-guidelines.md b/docs/08-development-guidelines.md
index 9ca4aa662..afa0675f2 100644
--- a/docs/08-development-guidelines.md
+++ b/docs/08-development-guidelines.md
@@ -608,6 +608,11 @@ export class AllExceptionsFilter implements ExceptionFilter {
- pgAdmin or DBeaver
```
+> `npm install` patches whatsapp-web.js for the WhatsApp Web 2.3000.x message-id rename. It applies
+> the patch with GNU `patch`, falling back to `git apply` — so Git alone is enough, including on
+> Windows outside Git Bash. With neither available the install still succeeds, but the
+> whatsapp-web.js engine then fails on every send; see `docs/12-troubleshooting-faq.md`.
+
### Quick Start
```bash
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index a33d6755a..f537b06a8 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -527,6 +527,40 @@ curl -H "X-API-Key: $API_KEY" \
"http://localhost:2785/api/sessions/default/contacts/check/628123456789"
```
+### Issue: Sends return 500 "engine returned no message", and chats or media fail with `r: r`
+
+**Symptoms:**
+
+- `POST /api/sessions/{id}/messages/send-text` returns `{"statusCode":500,"message":"Internal server error"}` — but the message *is* delivered
+- Logs show `the engine returned no message for this send, so it may not have been delivered`
+- Unrelated operations fail with the minified error `r: r`: `GET /api/sessions/{id}/chats`, media downloads, typing indicators
+- Startup logs may contain `The installed whatsapp-web.js is missing the message-id backport…`
+
+**Cause:** WhatsApp Web 2.3000.x renamed the internal message-id property that whatsapp-web.js
+reads. OpenWA ships a backport that restores it, applied at install time by
+`scripts/patch-wwebjs-201832.js`. When the install cannot run it — neither GNU `patch` nor `git`
+available, or `npm install --ignore-scripts` — whatsapp-web.js stays unpatched and every operation
+that reads a message id fails. Source installs only; the Docker image always applies the backport.
+
+**Solution:**
+
+```bash
+# Is the backport missing? Works on every platform, including Windows without grep.
+node -e "console.log(require('fs').readFileSync('node_modules/whatsapp-web.js/src/structures/Base.js','utf8').includes('_normalizeId')?'PATCHED':'NOT PATCHED')"
+
+# Apply it, then restart
+node scripts/patch-wwebjs-201832.js
+```
+
+If that reports a partially patched tree, reinstall the dependency first:
+
+```bash
+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: Media Upload Fails
**Symptoms:**
diff --git a/scripts/patch-wwebjs-201832.js b/scripts/patch-wwebjs-201832.js
index 5260b54ca..52f48f6d1 100644
--- a/scripts/patch-wwebjs-201832.js
+++ b/scripts/patch-wwebjs-201832.js
@@ -13,10 +13,11 @@
* Self-removing: it no-ops once the installed whatsapp-web.js already defines
* `Base._normalizeId` (i.e. upstream shipped #201832 and OpenWA bumped its dep).
*
- * Why `patch` and not `git apply`: a bare `git -C node_modules/whatsapp-web.js
+ * Why `patch` first and not `git apply`: a bare `git -C node_modules/whatsapp-web.js
* apply` silently no-ops ("Skipped / 0 files changed") because the parent repo's
* .git interferes with the diff's blob-SHA index lines. `patch` has no repo
- * discovery and applies cleanly.
+ * discovery and applies cleanly. `git apply` is still the fallback when the `patch`
+ * binary is missing — see applyWithGit, which fences off that repo discovery.
*
* Known reject on 1.34.7: Contact.js hunk #2 targets a LID-aware block()/
* unblock() path that does not exist in 1.34.7 (the PR's base is ahead there).
@@ -98,6 +99,38 @@ function findArtifacts(root, dir = root) {
return out;
}
+/**
+ * Fallback applier for hosts without the GNU `patch` binary — the default on Windows outside Git
+ * Bash, and the reason a native install could silently ship an unpatched whatsapp-web.js while
+ * `npm install` still reported success (#889). Anyone installing from source necessarily has git,
+ * so this closes that gap without adding a dependency.
+ *
+ * GIT_CEILING_DIRECTORIES is what makes it work at all: without it git discovers the parent OpenWA
+ * repo, whose index the diff's blob SHAs do not match, and skips every file while exiting 0. Aimed
+ * at node_modules, discovery stops before it can reach any repo.
+ *
+ * `--reject` reproduces GNU patch's behaviour on this patch exactly — byte-identical tree, the same
+ * single Contact.js reject, the same exit 1 — so the caller's artifact and REQUIRED_SITES checks
+ * apply unchanged. core.autocrlf is forced off because a Windows global config would otherwise
+ * rewrite line endings in the files it touches, producing a tree no other platform generates.
+ */
+function applyWithGit(wwjsDir, patchFile) {
+ try {
+ execFileSync('git', ['-c', 'core.autocrlf=false', 'apply', '-p1', '--reject', '--ignore-whitespace', patchFile], {
+ cwd: wwjsDir,
+ env: { ...process.env, GIT_CEILING_DIRECTORIES: path.dirname(wwjsDir) },
+ stdio: 'pipe',
+ });
+ } catch (e) {
+ // Exit 1 = hunks rejected: expected, and verified against EXPECTED_REJECTS by the caller.
+ if (e.status === 1) return;
+ const detail = e.stderr ? String(e.stderr).trim() : e.message;
+ const err = new Error(`neither \`patch\` nor \`git apply\` could run (${e.code ?? `exit ${e.status}`}): ${detail}`);
+ // ENOENT means git never executed either, so the tree is untouched and degrading is still safe.
+ throw e.code === 'ENOENT' ? err : partialTree(err);
+ }
+}
+
function applyBackport(wwjsDir = DEFAULT_WWJS, patchFile = DEFAULT_PATCH) {
const baseJs = path.join(wwjsDir, 'src', 'structures', 'Base.js');
if (!fs.existsSync(baseJs)) {
@@ -157,13 +190,14 @@ function applyBackport(wwjsDir = DEFAULT_WWJS, patchFile = DEFAULT_PATCH) {
);
} catch (e) {
// `patch` exits 1 when hunks reject — expected here (Contact.js hunk #2), and the reject set is
- // verified below. Anything else (2 = serious trouble, ENOENT = `patch` not installed) is a real
- // failure: rethrow it rather than let the assertions below misreport it as version skew.
- if (e.status !== 1) {
+ // verified below. ENOENT means the binary is absent: apply with git instead of leaving the dep
+ // unpatched. Anything else (2 = serious trouble) is a real failure: rethrow it rather than let
+ // the assertions below misreport it as version skew.
+ if (e.code === 'ENOENT') {
+ applyWithGit(wwjsDir, patchFile);
+ } else if (e.status !== 1) {
const detail = e.stderr ? String(e.stderr).trim() : e.message;
- const err = new Error(`\`patch\` failed (${e.code ?? `exit ${e.status}`}): ${detail}`);
- // ENOENT means `patch` never executed, so the tree is untouched and degrading is still safe.
- throw e.code === 'ENOENT' ? err : partialTree(err);
+ throw partialTree(new Error(`\`patch\` failed (${e.code ?? `exit ${e.status}`}): ${detail}`));
}
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 3cdf62d0e..12176ec02 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -76,6 +76,7 @@ import {
} from '../types/whatsapp-web-js.types';
import { buildEditedMessage, buildIncomingMessageBase, mapContactFields } from './message-mapper';
import { buildVCard } from './vcard';
+import { BACKPORT_MISSING_MESSAGE, isBackportMissing } from './wwebjs-backport-check';
import {
capInboundMedia,
chatHistoryMediaBudgetBytes,
@@ -465,6 +466,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.callbacks = callbacks;
this.setStatus(EngineStatus.INITIALIZING);
+ // An install that skipped the message-id backport fails later with errors that name no cause
+ // (#889) — say so here instead, while the operator is still looking at the startup logs.
+ if (isBackportMissing()) {
+ this.logger.error(BACKPORT_MISSING_MESSAGE);
+ }
+
try {
// Build puppeteer args, including proxy if configured
const puppeteerArgs = this.config.puppeteer?.args
diff --git a/src/engine/adapters/wwebjs-backport-201832.spec.ts b/src/engine/adapters/wwebjs-backport-201832.spec.ts
index 66aaf72b8..3292146cb 100644
--- a/src/engine/adapters/wwebjs-backport-201832.spec.ts
+++ b/src/engine/adapters/wwebjs-backport-201832.spec.ts
@@ -218,11 +218,35 @@ describe('patch-wwebjs-201832 (build-time backport of upstream #201832)', () =>
expect(res.stderr).toMatch(/PARTIALLY patched/);
});
- it('degrades when `patch` is not installed, leaving the tree pristine', () => {
+ it('falls back to `git apply` when only `patch` is missing', () => {
+ // The Windows-outside-Git-Bash case, and the one that let #889 happen: git.exe is on PATH but
+ // patch.exe ships only inside Git Bash, so the backport was skipped and `npm install` still
+ // reported success. Anyone installing from source has git by definition, so the dep gets
+ // patched instead of silently shipping broken.
const dir = copyWwjs();
- // The case the flag exists for (Windows outside WSL, Baileys-only setups): `patch` never runs, so
- // nothing was written and a warning beats breaking `npm install`. Emptying PATH is what makes the
- // lookup fail; node itself is invoked by absolute path and is unaffected.
+ const gitOnly = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-gitonly-'));
+ tmpDirs.push(gitOnly);
+ fs.symlinkSync(execFileSync('which', ['git'], { encoding: 'utf8' }).trim(), path.join(gitOnly, 'git'));
+
+ const res = spawnSync(process.execPath, [SCRIPT, '--best-effort', dir], {
+ encoding: 'utf8',
+ env: { ...process.env, PATH: gitOnly },
+ });
+
+ expect(res.status).toBe(0);
+ // Every normalization site landed, and the tree is whole enough that a second run stands down —
+ // the same bar the `patch` path is held to, since git apply must not diverge from it.
+ expect(applyBackport(dir)).toEqual({
+ skipped: true,
+ reason: 'installed whatsapp-web.js already normalizes message ids',
+ });
+ });
+
+ it('degrades when neither `patch` nor git is installed, leaving the tree pristine', () => {
+ const dir = copyWwjs();
+ // With no applier at all (a stripped container, a Baileys-only setup), nothing was written and a
+ // warning beats breaking `npm install` — the trade this flag exists to make. Emptying PATH is what
+ // makes both lookups fail; node itself is invoked by absolute path and is unaffected.
const emptyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-nopath-'));
tmpDirs.push(emptyDir);
diff --git a/src/engine/adapters/wwebjs-backport-check.spec.ts b/src/engine/adapters/wwebjs-backport-check.spec.ts
new file mode 100644
index 000000000..5fef8863a
--- /dev/null
+++ b/src/engine/adapters/wwebjs-backport-check.spec.ts
@@ -0,0 +1,51 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { isBackportMissing } from './wwebjs-backport-check';
+
+/**
+ * Guards the startup diagnostic for an unpatched whatsapp-web.js (#889). The cost of getting this
+ * wrong runs both ways: a missed detection restores the silence the check exists to break, and a
+ * false alarm sends operators after a patch they do not need.
+ */
+describe('isBackportMissing', () => {
+ const tmpDirs: string[] = [];
+
+ /** A whatsapp-web.js install stubbed down to the one file the check reads. */
+ function install(messageJs: string): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-check-'));
+ tmpDirs.push(dir);
+ fs.mkdirSync(path.join(dir, 'src', 'structures'), { recursive: true });
+ fs.writeFileSync(path.join(dir, 'src', 'structures', 'Message.js'), messageJs);
+ return dir;
+ }
+
+ afterAll(() => {
+ for (const dir of tmpDirs) fs.rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('flags a tree that still reads the pre-rename id', () => {
+ expect(isBackportMissing(install('this.id = data.id;'))).toBe(true);
+ });
+
+ it('accepts the shape our patcher lands', () => {
+ expect(isBackportMissing(install('this.id = Base._normalizeId(data.id);'))).toBe(false);
+ });
+
+ it('accepts an upstream fix that inlines the $1 fallback instead', () => {
+ // The check must stand down for any fix, not just ours — otherwise the first upstream release
+ // that lands this differently makes every healthy install log a phantom error.
+ expect(isBackportMissing(install('this.id = data.id._serialized || data.id.$1;'))).toBe(false);
+ });
+
+ it('stays quiet about an install it cannot inspect', () => {
+ expect(isBackportMissing(path.join(os.tmpdir(), 'wwjs-not-installed-here'))).toBe(false);
+ });
+
+ it('can reach the file it reads in a real install', () => {
+ // The no-argument path fails open, so a resolution that silently stopped working — an `exports`
+ // map on a future whatsapp-web.js would do it — would retire the check without failing anything.
+ const installed = path.dirname(require.resolve('whatsapp-web.js/package.json'));
+ expect(fs.existsSync(path.join(installed, 'src', 'structures', 'Message.js'))).toBe(true);
+ });
+});
diff --git a/src/engine/adapters/wwebjs-backport-check.ts b/src/engine/adapters/wwebjs-backport-check.ts
new file mode 100644
index 000000000..e67f8cbbc
--- /dev/null
+++ b/src/engine/adapters/wwebjs-backport-check.ts
@@ -0,0 +1,45 @@
+import * as fs from 'fs';
+import * as path from 'path';
+
+/**
+ * Startup guard for the whatsapp-web.js message-id backport that scripts/patch-wwebjs-201832.js
+ * applies at install time.
+ *
+ * WhatsApp Web 2.3000.x renamed the serialized message-id property `id._serialized` to `id.$1`.
+ * whatsapp-web.js 1.34.7 still reads the old name, so an install that never received the backport
+ * breaks opaquely once WhatsApp Web serves that shape: a send resolves with no message object at
+ * all (the gateway then refuses to report a delivery it cannot confirm) and chat and media reads
+ * throw the minified `r: r` (#889). None of those errors name their cause.
+ *
+ * The install already warns when it skips the patch, but that is one line in a full `npm install`
+ * transcript, and the symptom only appears later, when WhatsApp Web rolls a build that carries the
+ * rename. So restate it on the machine that is actually broken, as the engine starts.
+ *
+ * The marker is the patcher's own stand-down predicate, so the two can never disagree about what
+ * "patched" means.
+ */
+const NORMALIZED_ID_MARKER = /_normalizeId\(|\.\$1/;
+
+export const BACKPORT_MISSING_MESSAGE =
+ 'The installed whatsapp-web.js is missing the message-id backport this build requires. On current ' +
+ 'WhatsApp Web builds every send will fail with "the engine returned no message" — even when the ' +
+ 'message is delivered — and chat and media reads will fail with "r: r". The install skipped the ' +
+ 'patch, usually because neither the `patch` binary nor git was available. Apply it with ' +
+ '`node scripts/patch-wwebjs-201832.js` (or reinstall with `npm install`) and restart. ' +
+ 'See docs/12-troubleshooting-faq.md.';
+
+/**
+ * Whether the installed whatsapp-web.js is known NOT to carry the backport.
+ *
+ * Any uncertainty reads as false — package unresolvable, sources pruned, a bundled install. An
+ * install we cannot inspect is not evidence of a broken one, and a false alarm would send operators
+ * chasing a patch they do not need.
+ */
+export function isBackportMissing(wwjsDir?: string): boolean {
+ try {
+ const dir = wwjsDir ?? path.dirname(require.resolve('whatsapp-web.js/package.json'));
+ return !NORMALIZED_ID_MARKER.test(fs.readFileSync(path.join(dir, 'src', 'structures', 'Message.js'), 'utf8'));
+ } catch {
+ return false;
+ }
+}