Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): leave the protocol timeout to Puppeteer, bound it above

JuanGalzeranoac0dd2fce25a
diff --git a/.env.example b/.env.example
index 72bdb66e2..9a626b6e2 100644
--- a/.env.example
+++ b/.env.example
@@ -127,11 +127,13 @@ STATUS_SEED_ON_READY=false
# Path to a system Chromium/Chrome binary. Leave unset to use the bundled Puppeteer browser.
# Required in the Docker image and on hosts without a bundled browser (e.g. Alpine/ARM).
# PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
-# How long a single browser command may take before it is abandoned, in milliseconds. Default 300000
-# (5 min), above Puppeteer's own 180000. Raise it if a large account (thousands of chats) fails a
-# read with "Runtime.callFunctionOn timed out"; the renderer is still working, the command budget
-# just ran out. Must be a POSITIVE integer — 0 does not mean "no limit later", it means no timer is
-# armed at all, so a wedged browser holds the request forever instead of failing it as 503.
+# How long a single browser command may take before it is abandoned, in milliseconds. Unset means
+# Puppeteer's own budget (180000 today), so leaving it unset changes nothing. Raise it if a large account
+# (thousands of chats) fails a read with "Runtime.callFunctionOn timed out"; the renderer is still
+# working, the command budget just ran out. Must be a POSITIVE integer no greater than 2147483647:
+# 0 does not mean "no limit later", it means no timer is armed at all, so a wedged browser holds the
+# request forever instead of failing it as 503; and above 2147483647 Node's timer overflows and
+# fires after 1 ms, so the browser never finishes launching. The gateway refuses to boot on either.
# PUPPETEER_PROTOCOL_TIMEOUT_MS=300000
# A freshly linked account is shown a "What's new on WhatsApp Web" modal that must be acknowledged or
# WhatsApp unlinks the companion a few minutes later. The whatsapp-web.js engine clicks it
diff --git a/CHANGELOG.md b/CHANGELOG.md
index de8f63080..3ee5f60e9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,20 +10,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `PUPPETEER_PROTOCOL_TIMEOUT_MS` sets how long a single browser command may take on the
- whatsapp-web.js engine, defaulting to 300 000 ms, above Puppeteer's own 180 000 ms. A read that
- walks the whole store, such as `GET /sessions/{sessionId}/chats` on an account with thousands of
- chats, could run past the stock budget and fail with `Runtime.callFunctionOn timed out` while the
- renderer was still working. The value must be positive: Puppeteer only arms its timer for a
- truthy one, so `0` drops the bound instead of raising it and lets a wedged renderer hold the
- request forever.
+ whatsapp-web.js engine. A read that walks the whole store, such as
+ `GET /sessions/{sessionId}/chats` on an account with thousands of chats, can run past Puppeteer's
+ budget and fail with `Runtime.callFunctionOn timed out` while the renderer is still working, and
+ until now there was no way to raise it short of patching the dependency. Left unset it stays at
+ Puppeteer's own budget (180 000 ms today), so an upgrade changes nothing for a deployment that
+ does not set it; raise
+ it only after seeing that error, since raising it is also how long a wedged browser holds a command
+ before the gateway can give up on it. The value must be a positive integer no greater than
+ 2 147 483 647, rejected at boot on both ends: Puppeteer only arms its timer for a truthy value, so
+ `0` drops the bound instead of raising it and lets a wedged renderer hold the request forever,
+ while above 2 147 483 647 Node's timer overflows and fires after 1 ms, so the browser never
+ finishes launching.
### Changed
- The whatsapp-web.js transport classifier now rules out a protocol timeout explicitly. That
message carries no transport-death signature on the current Puppeteer, so nothing was
misreporting it and behaviour is unchanged; the point is the spec, which pins the invariant in
- both directions against the verbatim Puppeteer string so a future bump cannot start reading a
- slow command as a dead page.
+ both directions against the message the installed Puppeteer actually throws, so a future bump
+ cannot start reading a slow command as a dead page.
## [0.23.3] - 2026-08-24
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.md
index a62d332e4..904739b09 100644
--- a/docs/10-devops-infrastructure.md
+++ b/docs/10-devops-infrastructure.md
@@ -466,8 +466,9 @@ SESSION_DATA_PATH=./data/sessions
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
PUPPETEER_HEADLESS=true
PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox
-# Per-browser-command budget, ms. Default 300000. Raise for very large accounts; must stay positive.
-PUPPETEER_PROTOCOL_TIMEOUT_MS=300000
+# Optional per-browser-command budget, ms. Unset = Puppeteer's own budget. Raise only after seeing
+# "Runtime.callFunctionOn timed out"; positive integer, max 2147483647 (cost: see docs/12).
+# PUPPETEER_PROTOCOL_TIMEOUT_MS=300000
# ===========================================
# SECURITY
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index c4d890966..52f0ea686 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -684,13 +684,24 @@ answers `503` and takes the session down with it, and this is just a slow comman
**Solution:** raise the budget for that deployment.
```bash
-# 10 minutes, in .env or the environment
-PUPPETEER_PROTOCOL_TIMEOUT_MS=600000
+# 5 minutes, in .env or the environment. Unset means Puppeteer's own 180000.
+PUPPETEER_PROTOCOL_TIMEOUT_MS=300000
```
-> Do not set it to `0`. The gateway refuses to boot on a non-positive value: Puppeteer only arms
-> its timer for a truthy one, so `0` drops the bound altogether and a wedged renderer will hold the
-> command, and the request waiting on it, forever. A hung request is worse than a failed one.
+Raise it by as little as the account needs, because the budget is also how long a **wedged** browser
+holds a command before the gateway can give up on it. At 300000 that window is five minutes instead
+of three, and for its duration the stuck command holds the logout fence behind it: `start` and
+`delete` for that session answer `409 SESSION_NAME_TEARDOWN_PENDING`, and `forceKill` refuses with
+`400` because the engine was already evicted. There is no measurement in this repo saying how large
+an account has to be before 180000 is too small, so treat any value above it as an escape hatch you
+reached for after seeing the error above, not as a default worth pre-emptively setting.
+
+> Do not set it to `0`, and do not reach for a row of nines. The gateway refuses to boot on either.
+> Puppeteer only arms its timer for a truthy value, so `0` drops the bound altogether and a wedged
+> renderer will hold the command, and the request waiting on it, forever — a hung request is worse
+> than a failed one. Above `2147483647` Node's timer overflows, warns `TimeoutOverflowWarning`, and
+> fires after 1 ms instead, so every command in the launch handshake fails with this same error and
+> the browser never starts.
### Issue: Media Upload Fails
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index 03c9b7ebe..6fcd66966 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -52,6 +52,15 @@ export function resolveNonNegativeIntEnv(raw: string | undefined, fallback: numb
return Number(trimmed);
}
+/**
+ * Largest delay Node's timers accept. Above this a `setTimeout` overflows its 32-bit signed field,
+ * warns `TimeoutOverflowWarning`, and fires after 1 ms instead — so an operator reaching for an
+ * "effectively unlimited" budget by typing a row of nines gets the shortest possible one. Puppeteer
+ * arms `protocolTimeout` with a plain `setTimeout` (`common/CallbackRegistry.js`), so the ceiling
+ * applies to it directly and the browser never finishes launching.
+ */
+export const MAX_TIMER_MS = 2147483647;
+
/**
* The UI locale Chromium is pinned to. WhatsApp Web renders its chrome — including the new-account
* onboarding modal the whatsapp-web.js adapter dismisses (#982) — in the browser's language, and that
@@ -211,10 +220,17 @@ export default () => ({
// uses Puppeteer's bundled Chromium. Required on hosts where the bundled binary
// is missing or incompatible (Alpine, ARM, custom base images).
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || undefined,
- // How long one CDP command may take. Above Puppeteer's own 180 000 ms, which a single
- // `client.getChats()` can exceed on an account with thousands of chats. Bounded, never
- // disabled — see wwebjs-lifecycle.ts for why a falsy value is not "no limit".
- protocolTimeoutMs: parseInt(process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS || '300000', 10),
+ // How long one CDP command may take. An account with thousands of chats can push a single
+ // `client.getChats()` past Puppeteer's own budget; raising this is the escape hatch. Left
+ // UNDEFINED rather than defaulted to Puppeteer's number, so an unset or out-of-range value
+ // means "whatever puppeteer-core's `timeout ?? 180_000` says" instead of pinning today's
+ // figure here and silently outliving it. Out of range is not clamped either: see
+ // wwebjs-lifecycle.ts for why a falsy value is not "no limit", and MAX_TIMER_MS above for
+ // why a huge one is not either.
+ protocolTimeoutMs: (() => {
+ const n = parseInt(process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS || '', 10);
+ return Number.isFinite(n) && n > 0 && n <= MAX_TIMER_MS ? n : undefined;
+ })(),
},
sessionDataPath: process.env.SESSION_DATA_PATH || './data/sessions',
// Baileys engine (used when ENGINE_TYPE=baileys). Multi-file auth state base dir; each session
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index abf0a1496..2a8fe8ecc 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -9,6 +9,10 @@ type EnvConfig = Record<string, unknown>;
// DATABASE_NAME still points at the (now unused) default file.
const MAIN_DB_DEFAULT_PATH = './data/main.sqlite';
+// Duplicated rather than imported from configuration.ts (see MAIN_DB_DEFAULT_PATH above); the spec
+// asserts the two agree.
+const MAX_TIMER_MS = 2147483647;
+
/**
* Collision guard shared by boot validation (validateEnv below) and the migration CLI
* (src/database/data-source.ts / data-source-main.ts — the TypeORM CLI never runs ConfigModule's
@@ -291,6 +295,20 @@ export function validateEnv(config: EnvConfig): EnvConfig {
checkPositiveInt(key);
}
+ // The ceiling matters for the same reason from the other side: the docs forbid 0, so an operator
+ // who wants an effectively unlimited budget reaches for a row of nines. Rejected at boot rather
+ // than clamped, so they learn the value they wrote is not the value they would have got.
+ {
+ const raw = str('PUPPETEER_PROTOCOL_TIMEOUT_MS');
+ const n = raw !== undefined && DECIMAL_INTEGER.test(raw) ? Number(raw) : NaN;
+ if (Number.isInteger(n) && n > MAX_TIMER_MS) {
+ errors.push(
+ `PUPPETEER_PROTOCOL_TIMEOUT_MS must not exceed ${MAX_TIMER_MS} ms (got "${raw}"): Node's ` +
+ `timers overflow above that and fire after 1 ms, so the browser never finishes launching`,
+ );
+ }
+ }
+
// A heartbeat that does not fit inside the lease renews too late to matter: the claim lapses
// between ticks, peers adopt sessions from a perfectly healthy node, and nothing in the logs says
// why. The defaults must be substituted for whatever is unset — validating only the key the
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index b3e0e6c39..5979095a2 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -339,13 +339,12 @@ export class WwebjsLifecycle {
...(this.host.config.puppeteer?.executablePath
? { executablePath: this.host.config.puppeteer.executablePath }
: {}),
- // Per-CDP-command budget, spread only for a POSITIVE value so an unset or malformed config
- // keeps Puppeteer's own 180 000 ms default rather than being handed a falsy one:
- // `common/CallbackRegistry.js` arms the timer under `if (timeout)`, so 0 or NaN arms none
- // and a wedged renderer holds the command — and the request behind it — indefinitely.
- // A dead page must surface as a 503, never as a hang.
- ...(typeof this.host.config.puppeteer?.protocolTimeoutMs === 'number' &&
- this.host.config.puppeteer.protocolTimeoutMs > 0
+ // Per-CDP-command budget, spread only when the host configured one — configuration.ts
+ // leaves it undefined otherwise, and puppeteer-core nullish-coalesces a missing value to
+ // its own 180 000 ms (`cdp/Connection.js`). What must never reach it is a FALSY one:
+ // `common/CallbackRegistry.js` arms the timer under `if (timeout)`, so 0 arms none and a
+ // wedged renderer holds the command, and the request behind it, indefinitely.
+ ...(this.host.config.puppeteer?.protocolTimeoutMs !== undefined
? { protocolTimeout: this.host.config.puppeteer.protocolTimeoutMs }
: {}),
},
diff --git a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
index 12f2de109..3f39f0860 100644
--- a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
+++ b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
@@ -1,12 +1,15 @@
+import { Callback } from 'puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js';
import { Client } from 'whatsapp-web.js';
+import configuration, { MAX_TIMER_MS } from '../../config/configuration';
+import { validateEnv } from '../../config/env.validation';
import { WhatsAppWebJsAdapter } from './whatsapp-web-js.adapter';
/**
* The per-CDP-command budget handed to Puppeteer, and the one error it produces.
*
- * Two invariants worth pinning: the option must never reach Puppeteer falsy (that arms no timer at
- * all, so a wedged renderer hangs the request — see wwebjs-lifecycle.ts), and a protocol timeout
- * must never be read as a dead page.
+ * Three invariants worth pinning: the value is range-checked before it leaves the config layer,
+ * the option reaches the Client when set and is absent when not, and a protocol timeout is never
+ * read as a dead page. The death signatures themselves are covered in whatsapp-web-js.adapter.spec.
*/
describe('whatsapp-web.js protocol timeout', () => {
const SESSION_ID = 'sess-protocol-timeout';
@@ -49,19 +52,50 @@ describe('whatsapp-web.js protocol timeout', () => {
expect(await launchedPuppeteerOptions(300_000)).toMatchObject({ protocolTimeout: 300_000 });
});
- it('omits the option when unset, leaving Puppeteer its own 180 000 ms default', async () => {
+ it('omits the option when unset, leaving Puppeteer its own default', async () => {
const options = await launchedPuppeteerOptions(undefined);
- // Absent, not zero: passing 0 through would DISABLE the timer rather than fall back.
+ // Truly absent: `toHaveProperty` passes on a present-but-undefined key, so this is the check
+ // that the option was never spread rather than spread as undefined.
expect(options).not.toHaveProperty('protocolTimeout');
});
- it.each([
- ['zero', 0],
- ['negative', -1],
- ['NaN, e.g. from a malformed env value', Number.NaN],
- ])('omits the option for a %s value rather than arming no timer', async (_label, value) => {
- expect(await launchedPuppeteerOptions(value)).not.toHaveProperty('protocolTimeout');
+ describe('the bounds this knob exists to enforce', () => {
+ it('rejects a non-positive or over-range value at boot instead of handing it to Puppeteer', () => {
+ expect(() => validateEnv({ PUPPETEER_PROTOCOL_TIMEOUT_MS: '0' })).toThrow(/positive integer/);
+ expect(() => validateEnv({ PUPPETEER_PROTOCOL_TIMEOUT_MS: '-1' })).toThrow(/positive integer/);
+ expect(() => validateEnv({ PUPPETEER_PROTOCOL_TIMEOUT_MS: 'abc' })).toThrow(/positive integer/);
+ // The row of nines an operator reaches for when the docs forbid 0.
+ expect(() => validateEnv({ PUPPETEER_PROTOCOL_TIMEOUT_MS: String(MAX_TIMER_MS + 1) })).toThrow(/must not exceed/);
+ expect(() => validateEnv({ PUPPETEER_PROTOCOL_TIMEOUT_MS: '999999999999' })).toThrow(/must not exceed/);
+ expect(() => validateEnv({ PUPPETEER_PROTOCOL_TIMEOUT_MS: String(MAX_TIMER_MS) })).not.toThrow();
+ expect(() => validateEnv({ PUPPETEER_PROTOCOL_TIMEOUT_MS: '300000' })).not.toThrow();
+ });
+
+ it('leaves the option unset for anything out of range, never falsy', () => {
+ const parsed = (raw?: string): number | undefined => {
+ const saved = process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS;
+ if (raw === undefined) delete process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS;
+ else process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS = raw;
+ try {
+ return (configuration() as { engine: { puppeteer: { protocolTimeoutMs?: number } } }).engine.puppeteer
+ .protocolTimeoutMs;
+ } finally {
+ if (saved === undefined) delete process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS;
+ else process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS = saved;
+ }
+ };
+
+ // A blank compose forward is "unset", not 0.
+ expect(parsed(undefined)).toBeUndefined();
+ expect(parsed('')).toBeUndefined();
+ expect(parsed('0')).toBeUndefined();
+ expect(parsed('-1')).toBeUndefined();
+ expect(parsed('abc')).toBeUndefined();
+ expect(parsed(String(MAX_TIMER_MS + 1))).toBeUndefined();
+ expect(parsed('300000')).toBe(300_000);
+ expect(parsed(String(MAX_TIMER_MS))).toBe(MAX_TIMER_MS);
+ });
});
describe('the transport classifier', () => {
@@ -77,28 +111,29 @@ describe('whatsapp-web.js protocol timeout', () => {
};
/**
- * Verbatim from Puppeteer 24.38.0 `common/CallbackRegistry.js`, where the leading label is the
- * CDP method name. Pinning the real string is the point: a paraphrase would keep passing while
- * the message the library actually throws drifted out from under the guard.
+ * Provoked from the INSTALLED puppeteer-core rather than copied from it. The guard exists to
+ * survive a message the library may reshape on a version bump, so a hand-written literal would
+ * keep passing while the real string drifted out from under it — the one drift this test is
+ * here to catch. Driving the real `Callback` is also what shows the label is the bare CDP
+ * method name, with no `Protocol error (...)` prefix for the death pattern to match.
*/
- const PUPPETEER_PROTOCOL_TIMEOUT =
- "Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.";
+ const puppeteerProtocolTimeoutMessage = async (): Promise<string> => {
+ const callback = new Callback(1, 'Runtime.callFunctionOn', 1);
+ try {
+ await callback.promise;
+ } catch (error) {
+ return error instanceof Error ? error.message : String(error);
+ }
+ throw new Error('puppeteer-core did not reject on an expired protocolTimeout');
+ };
- it('does not treat a protocol timeout as a dead page', () => {
- // The renderer is slower than the budget, not gone — the next command may well succeed.
- // Reporting death here would tear down a live session and answer 503 for a working page.
- expect(classify(PUPPETEER_PROTOCOL_TIMEOUT)).toBe(false);
- });
+ it('does not treat a protocol timeout as a dead page', async () => {
+ const message = await puppeteerProtocolTimeoutMessage();
- it.each([
- 'Protocol error (Runtime.callFunctionOn): Session closed.',
- 'Protocol error (Page.navigate): Target closed',
- 'Attempted to use detached Frame',
- 'Connection closed',
- ])('still reports a genuine transport death: %s', message => {
- // The 503-on-dead-page contract, pinned from the other side: narrowing the classifier for
- // timeouts must not cost a single real death signature.
- expect(classify(message)).toBe(true);
+ // Guard the guard: if a bump ever drops the phrase this classifier keys on, fail here rather
+ // than silently start reporting slow reads as deaths.
+ expect(message).toMatch(/timed out\. Increase the 'protocolTimeout'/);
+ expect(classify(message)).toBe(false);
});
it('reports a death whose message also mentions a timeout', () => {