Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): use one Chromium default flag list for every fallback
Yudhi Armyndharis54761e1184de
diff --git a/.env.minimal b/.env.minimalindex 18416d10c..5d55f71a2 100644--- a/.env.minimal+++ b/.env.minimal@@ -21,7 +21,7 @@ DATABASE_LOGGING=falseENGINE_TYPE=whatsapp-web.jsSESSION_DATA_PATH=./data/sessionsPUPPETEER_HEADLESS=true-PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage+PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu# WebhookWEBHOOK_TIMEOUT=10000diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 8deee3205..4e7db60fa 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -71,6 +71,18 @@ export const MAX_TIMER_MS = 2147483647;*/export const PINNED_BROWSER_LOCALE = 'en-US';+/**+ * Chromium launch flags used when PUPPETEER_ARGS is unset, and the single fallback for every other+ * path that has no configured args (the adapter, the Infrastructure save and status views).+ * --disable-dev-shm-usage keeps tabs from crashing on Docker's 64 MB /dev/shm.+ */+export const DEFAULT_PUPPETEER_ARGS: readonly string[] = [+ '--no-sandbox',+ '--disable-setuid-sandbox',+ '--disable-dev-shm-usage',+ '--disable-gpu',+];+/*** Append the locale pin unless the operator already set one. Deliberately applied AFTER the* PUPPETEER_ARGS override rather than baked into the default string: that variable REPLACES the@@ -82,7 +94,7 @@ export const PINNED_BROWSER_LOCALE = 'en-US';* session, and pushing per-session flags onto a shared array leaked proxy settings across sessions* once already (#840).*/-export function withPinnedBrowserLocale(args: string[]): string[] {+export function withPinnedBrowserLocale(args: readonly string[]): string[] {return args.some(arg => arg.startsWith('--lang')) ? [...args] : [...args, `--lang=${PINNED_BROWSER_LOCALE}`];}@@ -214,7 +226,7 @@ export default () => ({// A comma only splits before the next flag, since flag values carry commas of their own// (--disable-features=A,B, --window-size=1280,720).args: withPinnedBrowserLocale(- (process.env.PUPPETEER_ARGS || '--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu')+ (process.env.PUPPETEER_ARGS || DEFAULT_PUPPETEER_ARGS.join(',')).split(/\s+|,+(?=-)/).map(arg => arg.replace(/^,+|,+$/g, '')).filter(Boolean),diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.tsindex cfcfc0b31..7e1182c28 100644--- a/src/engine/adapters/wwebjs-lifecycle.ts+++ b/src/engine/adapters/wwebjs-lifecycle.ts@@ -10,7 +10,7 @@ import {import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { type createLogger } from '../../common/services/logger.service';-import { MAX_TIMER_MS } from '../../config/configuration';+import { DEFAULT_PUPPETEER_ARGS, MAX_TIMER_MS, withPinnedBrowserLocale } from '../../config/configuration';import { resolveWebVersionPin } from '../wa-web-version';import { resolveAuthTimeoutMs, resolveEngineInitTimeoutMs } from '../engine-init-timeout';import { killOrphanedChromiumProcesses, removeStaleSingletonFiles } from './chromium-profile-hygiene';@@ -235,15 +235,7 @@ export class WwebjsLifecycle {// Build puppeteer args, including proxy if configuredconst puppeteerArgs = this.host.config.puppeteer?.args? [...this.host.config.puppeteer.args]- : [- '--no-sandbox',- '--disable-setuid-sandbox',- '--disable-dev-shm-usage',- '--disable-accelerated-2d-canvas',- '--no-first-run',- '--no-zygote',- '--disable-gpu',- ];+ : withPinnedBrowserLocale(DEFAULT_PUPPETEER_ARGS);// Add proxy configuration if provided — but only when the URL parses to a supported scheme, so// a malformed/stored proxy value can't break the Chromium launch or smuggle a non-proxy scheme.diff --git a/src/engine/builtin/whatsapp-web-js/index.spec.ts b/src/engine/builtin/whatsapp-web-js/index.spec.tsindex bbcefb049..3b921c95a 100644--- a/src/engine/builtin/whatsapp-web-js/index.spec.ts+++ b/src/engine/builtin/whatsapp-web-js/index.spec.ts@@ -47,18 +47,31 @@ describe('WhatsAppWebJsPlugin.createEngine (opaque config)', () => {);});- it('falls back to safe defaults when context has no config', () => {+ it('falls back to safe defaults when context has no config, leaving the flag list to the adapter', () => {const plugin = new WhatsAppWebJsPlugin();plugin.createEngine({ sessionId: 'sess-2' });- expect(WhatsAppWebJsAdapter).toHaveBeenCalledWith(- expect.objectContaining({- sessionId: 'sess-2',- sessionDataPath: './data/sessions',- puppeteer: { headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: undefined },- }),- );+ const [config] = (WhatsAppWebJsAdapter as unknown as jest.Mock).mock.calls[0] as [+ { sessionId: string; sessionDataPath: string; puppeteer: Record<string, unknown> },+ ];+ expect(config.sessionId).toBe('sess-2');+ expect(config.sessionDataPath).toBe('./data/sessions');+ expect(config.puppeteer.headless).toBe(true);+ expect(config.puppeteer.args).toBeUndefined();+ });++ it('does not pin a flag list when a persisted puppeteer override carries no args', () => {+ const plugin = new WhatsAppWebJsPlugin();+ withContext(plugin, { puppeteer: { headless: false } });++ plugin.createEngine({ sessionId: 'sess-4' });++ const [config] = (WhatsAppWebJsAdapter as unknown as jest.Mock).mock.calls[0] as [+ { puppeteer: Record<string, unknown> },+ ];+ expect(config.puppeteer.headless).toBe(false);+ expect(config.puppeteer.args).toBeUndefined();});it('Uses the constructor-supplied engine config when onLoad never ran (enable-failure path)', () => {diff --git a/src/engine/builtin/whatsapp-web-js/index.ts b/src/engine/builtin/whatsapp-web-js/index.tsindex 5c79fc761..74af6709e 100644--- a/src/engine/builtin/whatsapp-web-js/index.ts+++ b/src/engine/builtin/whatsapp-web-js/index.ts@@ -53,7 +53,9 @@ export class WhatsAppWebJsPlugin implements IEnginePlugin {const puppeteer = engineConfig.puppeteer ?? {};const sessionDataPath = engineConfig.sessionDataPath ?? './data/sessions';const headless = puppeteer.headless ?? true;- const puppeteerArgs = puppeteer.args ?? ['--no-sandbox', '--disable-setuid-sandbox'];+ // No default here: the adapter owns the fallback flag list (DEFAULT_PUPPETEER_ARGS), so a persisted+ // plugin config whose `puppeteer` object has no `args` still launches with the documented flags.+ const puppeteerArgs = puppeteer.args;const executablePath = puppeteer.executablePath;const protocolTimeoutMs = puppeteer.protocolTimeoutMs;diff --git a/src/engine/builtin/whatsapp-web-js/launch-args.spec.ts b/src/engine/builtin/whatsapp-web-js/launch-args.spec.tsnew file mode 100644index 000000000..0ceb48373--- /dev/null+++ b/src/engine/builtin/whatsapp-web-js/launch-args.spec.ts@@ -0,0 +1,73 @@+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { Client } from 'whatsapp-web.js';+import { DEFAULT_PUPPETEER_ARGS, PINNED_BROWSER_LOCALE } from '../../../config/configuration';+import { WhatsAppWebJsPlugin } from './index';++/**+ * The Chromium flags a session launches with when no args are configured. The plugin passes+ * whatever it was given and the adapter owns the one fallback, so both paths are driven here+ * through the real plugin, adapter and wwebjs Client (with the browser launch stubbed out).+ */+describe('whatsapp-web.js launch args', () => {+ const SESSION_ID = 'sess-launch-args';+ let tmpRoot: string;+ let clientInitSpy: jest.SpyInstance;+ let savedWebVersion: string | undefined;++ const launchedArgs = async (config: Record<string, unknown>): Promise<string[]> => {+ const plugin = new WhatsAppWebJsPlugin({ sessionDataPath: tmpRoot, ...config });+ const adapter = plugin.createEngine({ sessionId: SESSION_ID });+ await adapter.initialize({});+ return (adapter as unknown as { client: { options: { puppeteer: { args: string[] } } } }).client.options.puppeteer+ .args;+ };++ beforeEach(() => {+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'wwebjs-launch-args-'));+ savedWebVersion = process.env.WWEBJS_WEB_VERSION;+ process.env.WWEBJS_WEB_VERSION = 'off';+ clientInitSpy = jest+ .spyOn(Client.prototype as unknown as { initialize: () => Promise<void> }, 'initialize')+ .mockResolvedValue(undefined);+ });++ afterEach(() => {+ clientInitSpy.mockRestore();+ if (savedWebVersion === undefined) delete process.env.WWEBJS_WEB_VERSION;+ else process.env.WWEBJS_WEB_VERSION = savedWebVersion;+ fs.rmSync(tmpRoot, { recursive: true, force: true });+ });++ it.each([+ ['no puppeteer config', {}],+ ['a persisted puppeteer override without args', { puppeteer: { headless: true } }],+ ])('launches with the documented default flags and locale pin for %s', async (_label, config) => {+ expect(await launchedArgs(config)).toEqual([+ '--no-sandbox',+ '--disable-setuid-sandbox',+ '--disable-dev-shm-usage',+ '--disable-gpu',+ `--lang=${PINNED_BROWSER_LOCALE}`,+ `--openwa-session=${SESSION_ID}`,+ ]);+ expect(DEFAULT_PUPPETEER_ARGS).toEqual([+ '--no-sandbox',+ '--disable-setuid-sandbox',+ '--disable-dev-shm-usage',+ '--disable-gpu',+ ]);+ });++ it('uses configured args verbatim and never mutates the shared array', async () => {+ const args = ['--no-sandbox', '--lang=de-DE'];++ expect(await launchedArgs({ puppeteer: { args } })).toEqual([+ '--no-sandbox',+ '--lang=de-DE',+ `--openwa-session=${SESSION_ID}`,+ ]);+ expect(args).toEqual(['--no-sandbox', '--lang=de-DE']);+ });+});diff --git a/src/modules/infra/config-sections.ts b/src/modules/infra/config-sections.tsindex 3f7b9559f..75da7030a 100644--- a/src/modules/infra/config-sections.ts+++ b/src/modules/infra/config-sections.ts@@ -1,4 +1,5 @@import { BadRequestException } from '@nestjs/common';+import { DEFAULT_PUPPETEER_ARGS } from '../../config/configuration';import { postgresSchemaError } from '../../config/env.validation';import type { EngineFactory } from '../../engine/engine.factory';import { DatabaseConfigDto, EngineConfigDto, RedisConfigDto, StorageConfigDto } from './dto/save-config.dto';@@ -222,10 +223,8 @@ export function applyEngineSection(updates.SESSION_DATA_PATH = engine.sessionDataPath || './data/sessions';}if (engine.browserArgs !== undefined) {- // Must match configuration.ts's PUPPETEER_ARGS default (4 flags). Once compose blank-forwards- // PUPPETEER_ARGS, this saved value wins at runtime — a 2-flag default here would silently drop- // --disable-dev-shm-usage (the Docker /dev/shm tab-crash guard) after any Infrastructure save.- updates.PUPPETEER_ARGS =- engine.browserArgs || '--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu';+ // Once compose blank-forwards PUPPETEER_ARGS, this saved value wins at runtime, so an empty field+ // saves the same default configuration.ts applies.+ updates.PUPPETEER_ARGS = engine.browserArgs || DEFAULT_PUPPETEER_ARGS.join(' ');}}diff --git a/src/modules/infra/infra-status.controller.spec.ts b/src/modules/infra/infra-status.controller.spec.tsindex 1d8894c3d..2be1f9d80 100644--- a/src/modules/infra/infra-status.controller.spec.ts+++ b/src/modules/infra/infra-status.controller.spec.ts@@ -129,6 +129,25 @@ describe('InfraStatusController.getStatus engine (reads the real engine.puppeteeexpect(status.engine.browserArgs).toBe('--foo --bar');expect(status.engine.sessionDataPath).toBe('./sess');});++ it('reports the default Chromium flags when no args are configured', async () => {+ const config = { get: (key: string, def?: unknown) => (key === 'engine.type' ? 'whatsapp-web.js' : def) };+ const ds = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) };+ const controller = new InfraStatusController(+ config as never,+ ds as never,+ ds as never,+ {} as never,+ { isDockerAvailable: () => false } as never,+ { isAvailable: () => Promise.resolve(false) } as never,+ { isS3Available: () => false, refreshS3Availability: () => Promise.resolve(false) } as never,+ );++ const status = await controller.getStatus();+ expect(status.engine.browserArgs).toBe(+ '--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu',+ );+ });});describe('InfraStatusController.getStatus storage (reads the real storage.localPath key)', () => {diff --git a/src/modules/infra/infra-status.controller.ts b/src/modules/infra/infra-status.controller.tsindex 3b8e33f76..759a33ef3 100644--- a/src/modules/infra/infra-status.controller.ts+++ b/src/modules/infra/infra-status.controller.ts@@ -23,6 +23,7 @@ import { StorageService } from '../../common/storage/storage.service';import { createLogger } from '../../common/services/logger.service';import { readGeneratedEnv } from './generated-env';import { isEnvPinned } from '../../config/env-precedence';+import { DEFAULT_PUPPETEER_ARGS } from '../../config/configuration';import { checkForUpdate, type UpdateCheck } from './update-check';interface InfraStatus {@@ -164,7 +165,7 @@ export class InfraStatusController {const engineHeadless = this.configService.get<boolean>('engine.puppeteer.headless', true) ?? true;const sessionDataPath = this.configService.get<string>('engine.sessionDataPath', './data/sessions');const browserArgs =- this.configService.get<string[]>('engine.puppeteer.args')?.join(' ') || '--no-sandbox --disable-gpu';+ this.configService.get<string[]>('engine.puppeteer.args')?.join(' ') || DEFAULT_PUPPETEER_ARGS.join(' ');// Built-in detection: prefer the actually-running bundled container as truth (so a stopped/missing// container, or a host-pinned external host, reads as NOT built-in), and require the app to be