Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): enforce the protocol timeout bounds at the launch sink
Yudhi Armyndharisda89043e2aea
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.tsindex 5979095a2..310fb771c 100644--- a/src/engine/adapters/wwebjs-lifecycle.ts+++ b/src/engine/adapters/wwebjs-lifecycle.ts@@ -8,6 +8,7 @@ import {} from '../interfaces/whatsapp-engine.interface';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { type createLogger } from '../../common/services/logger.service';+import { MAX_TIMER_MS } from '../../config/configuration';import { resolveWebVersionPin } from '../wa-web-version';import { resolveAuthTimeoutMs, resolveEngineInitTimeoutMs } from '../engine-init-timeout';import { killOrphanedChromiumProcesses, removeStaleSingletonFiles } from './chromium-profile-hygiene';@@ -318,6 +319,19 @@ export class WwebjsLifecycle {proxyAuthentication: { username: string; password: string } | undefined,versionPin: Awaited<ReturnType<typeof resolveWebVersionPin>>,): Promise<void> {+ // Range-checked at the sink, not only in configuration.ts: a plugin config written through+ // `PUT /api/plugins/whatsapp-web.js/config` is validated as an object and merged over the env+ // blob at every boot, so it can carry a value the config layer never saw. Both bounds are+ // load-bearing. `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; above+ // MAX_TIMER_MS Node's timer overflows and fires after 1 ms, so the browser never launches.+ const configuredProtocolTimeout = this.host.config.puppeteer?.protocolTimeoutMs;+ const protocolTimeout =+ typeof configuredProtocolTimeout === 'number' &&+ configuredProtocolTimeout > 0 &&+ configuredProtocolTimeout <= MAX_TIMER_MS+ ? configuredProtocolTimeout+ : undefined;const client = new Client({authStrategy: new LocalAuth({clientId: this.host.config.sessionId,@@ -339,14 +353,9 @@ export class WwebjsLifecycle {...(this.host.config.puppeteer?.executablePath? { executablePath: this.host.config.puppeteer.executablePath }: {}),- // 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 }- : {}),+ // Per-CDP-command budget, spread only when the host configured a usable one (see above).+ // Absent, puppeteer-core nullish-coalesces to its own 180 000 ms (`cdp/Connection.js`).+ ...(protocolTimeout !== undefined ? { protocolTimeout } : {}),},...(authTimeoutMs !== undefined ? { authTimeoutMs } : {}),...(proxyAuthentication ? { proxyAuthentication } : {}),diff --git a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts b/src/engine/adapters/wwebjs-protocol-timeout.spec.tsindex 3f39f0860..b53aa0f35 100644--- a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts+++ b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts@@ -60,6 +60,16 @@ describe('whatsapp-web.js protocol timeout', () => {expect(options).not.toHaveProperty('protocolTimeout');});+ it('omits the option for a value configuration.ts would never produce', async () => {+ // The config layer is not the only writer: a plugin config (PUT /api/plugins/{id}/config) is+ // validated as an object and merged over the env blob at boot, so the sink enforces the bounds+ // too. 0 arms no timer at all; over MAX_TIMER_MS overflows Node's and fires after 1 ms.+ expect(await launchedPuppeteerOptions(0)).not.toHaveProperty('protocolTimeout');+ expect(await launchedPuppeteerOptions(-1)).not.toHaveProperty('protocolTimeout');+ expect(await launchedPuppeteerOptions(MAX_TIMER_MS + 1)).not.toHaveProperty('protocolTimeout');+ expect(await launchedPuppeteerOptions(MAX_TIMER_MS)).toMatchObject({ protocolTimeout: MAX_TIMER_MS });+ });+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/);@@ -134,6 +144,11 @@ describe('whatsapp-web.js protocol timeout', () => {// than silently start reporting slow reads as deaths.expect(message).toMatch(/timed out\. Increase the 'protocolTimeout'/);expect(classify(message)).toBe(false);++ // The case that makes the carve-out load-bearing rather than decorative: puppeteer's own+ // `_reject` formats a rejected command as `Protocol error (label): message`, which the death+ // pattern matches. Without the carve-out this reads as a dead page.+ expect(classify(`Protocol error (Runtime.callFunctionOn): ${message}`)).toBe(false);});it('reports a death whose message also mentions a timeout', () => {diff --git a/src/engine/builtin/whatsapp-web-js/index.spec.ts b/src/engine/builtin/whatsapp-web-js/index.spec.tsindex b500f9b08..bbcefb049 100644--- a/src/engine/builtin/whatsapp-web-js/index.spec.ts+++ b/src/engine/builtin/whatsapp-web-js/index.spec.ts@@ -20,7 +20,12 @@ describe('WhatsAppWebJsPlugin.createEngine (opaque config)', () => {const plugin = new WhatsAppWebJsPlugin();withContext(plugin, {sessionDataPath: '/data/sessions',- puppeteer: { headless: false, args: ['--single-process'], executablePath: '/usr/bin/chromium' },+ puppeteer: {+ headless: false,+ args: ['--single-process'],+ executablePath: '/usr/bin/chromium',+ protocolTimeoutMs: 300_000,+ },});plugin.createEngine({ sessionId: 'sess-1', proxyUrl: 'http://p', proxyType: 'http' });@@ -29,7 +34,14 @@ describe('WhatsAppWebJsPlugin.createEngine (opaque config)', () => {expect.objectContaining({sessionId: 'sess-1',sessionDataPath: '/data/sessions',- puppeteer: { headless: false, args: ['--single-process'], executablePath: '/usr/bin/chromium' },+ // protocolTimeoutMs is asserted with a value, not just carried: an object with the key+ // present-but-undefined equals one without it, so a dropped hop would pass unnoticed.+ puppeteer: {+ headless: false,+ args: ['--single-process'],+ executablePath: '/usr/bin/chromium',+ protocolTimeoutMs: 300_000,+ },proxy: { url: 'http://p', type: 'http' },}),);