Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(engine): drop the unreachable whatsapp-web.js fallback
Yudhi Armyndharis26373d44d208
diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.mdindex ce2ca3e3d..4bd393f14 100644--- a/docs/03-system-architecture.md+++ b/docs/03-system-architecture.md@@ -960,19 +960,16 @@ same value: `sessionId` is the session **UUID** (`Session.id`), which is the on-since 0.23.5, and `dbSessionId` is that UUID under the name FK-bound stores such as`baileys_stored_messages` read. An out-of-tree engine plugin that keys its own storage by `sessionId`has to re-key it on upgrade: `SessionAuthDirMigration` renames the two built-in shapes only. There is-no `EngineType` union, no `switch`, and no `Unknown engine type` throw: if the plugin is unavailable it-logs a warning and falls back to the legacy direct adapter — but that fallback can only build-`whatsapp-web.js`. For any other configured engine (e.g. `ENGINE_TYPE=baileys` with its plugin-missing) `createFallbackEngine` **throws** rather than silently running the wrong engine, so the-session fails loudly at start. (A typo in `ENGINE_TYPE` is rejected at boot by `validateEnv`, which-whitelists `whatsapp-web.js` | `baileys`.)+no `EngineType` union and no `switch`. If the configured engine's plugin is not registered,+`create()` throws `Engine '<type>' is not registered`; there is no direct-adapter fallback, so the+session fails loudly at start instead of running some other engine. (A typo in `ENGINE_TYPE` is+rejected at boot by `validateEnv`, which whitelists `whatsapp-web.js` | `baileys`.)```typescript// engine/engine.factory.tsimport { Injectable, OnModuleInit } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { IWhatsAppEngine } from './interfaces/whatsapp-engine.interface';-import { WhatsAppWebJsAdapter } from './adapters/whatsapp-web-js.adapter';import { PluginLoaderService, PluginType, IEnginePlugin } from '../core/plugins';export interface EngineCreateOptions {@@ -1015,19 +1012,8 @@ export class EngineFactory implements OnModuleInit {}) as IWhatsAppEngine;}- // Plugin missing -> warn, then fall back to the direct whatsapp-web.js adapter.- return this.createFallbackEngine(options);- }-- private createFallbackEngine(options: EngineCreateOptions): IWhatsAppEngine {- // The legacy fallback can only construct whatsapp-web.js. Building it for a different configured- // engine would silently run the WRONG one — fail loudly instead.- if (this.engineType !== 'whatsapp-web.js') {- throw new Error(- `Engine '${this.engineType}' is unavailable and has no direct fallback; cannot start the session.`,- );- }- return new WhatsAppWebJsAdapter(/* ...sessionDataPath, puppeteer, proxy, lidMappingStore... */);+ // Both built-ins are always registered, so this is reached only by a broken host.+ throw new Error(`Engine '${this.engineType}' is not registered; cannot start the session.`);}}```diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 595a9b562..300fd8de8 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -86,9 +86,9 @@ export function validateEnv(config: EnvConfig): EnvConfig {errors.push(`DATABASE_TYPE must be "sqlite" or "postgres" (got ${JSON.stringify(dbType)})`);}- // Whitelist the registered engine/storage ids so a typo fails fast at boot instead of silently- // falling back to the default (engine.factory swallows an unknown ENGINE_TYPE → legacy wwebjs;- // STORAGE_TYPE → local). Values must match the ids registered in engine.factory / configuration.+ // Whitelist the registered engine/storage ids so a typo fails fast at boot: an unknown ENGINE_TYPE+ // would otherwise fail every session start, and an unknown STORAGE_TYPE would silently fall back to+ // local. Values must match the ids registered in engine.factory / configuration.const checkEnum = (key: string, allowed: string[]): void => {const value = rawEnum(key);if (value !== undefined && !allowed.includes(value)) {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 6b2d1c410..c51636785 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -5910,10 +5910,10 @@ describe('WhatsAppWebJsAdapter orphaned Chromium sweep (pre-launch)', () => {it('does not mutate the caller-owned puppeteer args array shared across sessions', async () => {// Every adapter receives the SAME array instance — ConfigService.get() returns a live reference- // into the cached config tree, via the plugin path (engine/builtin/whatsapp-web-js) and the- // factory fallback alike. Appending in place therefore rewrites global config for the rest of- // the process lifetime, leaking one session's flags (proxy, session marker) into every later- // launch. Without the defensive copy this assertion sees both session markers accumulate.+ // into the cached config tree, via the plugin path (engine/builtin/whatsapp-web-js). Appending+ // in place therefore rewrites global config for the rest of the process lifetime, leaking one+ // session's flags (proxy, session marker) into every later launch. Without the defensive copy+ // this assertion sees both session markers accumulate.const sharedArgs = ['--no-sandbox'];const argsFor = async (sessionId: string): Promise<string[] | undefined> => {const adapter = new WhatsAppWebJsAdapter({diff --git a/src/engine/builtin/baileys/manifest.json b/src/engine/builtin/baileys/manifest.jsondeleted file mode 100644index c59f4bf1f..000000000--- a/src/engine/builtin/baileys/manifest.json+++ /dev/null@@ -1,21 +0,0 @@-{- "id": "baileys",- "name": "Baileys Engine",- "version": "1.0.0",- "type": "engine",- "description": "Baileys (WebSocket, no-browser) engine adapter for OpenWA",- "author": "OpenWA Team",- "main": "index.ts",- "provides": ["whatsapp-engine", "text-messages"],- "configSchema": {- "type": "object",- "properties": {- "authDir": {- "type": "string",- "title": "Auth Directory",- "description": "Base directory for Baileys multi-file auth state (per-session subdirs)",- "default": "./data/baileys"- }- }- }-}diff --git a/src/engine/builtin/whatsapp-web-js/manifest.json b/src/engine/builtin/whatsapp-web-js/manifest.jsondeleted file mode 100644index 60f69516f..000000000--- a/src/engine/builtin/whatsapp-web-js/manifest.json+++ /dev/null@@ -1,41 +0,0 @@-{- "id": "whatsapp-web.js",- "name": "WhatsApp Web.js Engine",- "version": "1.0.0",- "type": "engine",- "description": "Official WhatsApp-web.js engine adapter for OpenWA",- "author": "OpenWA Team",- "main": "index.ts",- "provides": [- "whatsapp-engine",- "text-messages",- "media-messages",- "group-management"- ],- "configSchema": {- "type": "object",- "properties": {- "sessionDataPath": {- "type": "string",- "title": "Session Data Path",- "description": "Path to store session data",- "default": "./data/sessions"- },- "headless": {- "type": "boolean",- "title": "Headless Mode",- "description": "Run Puppeteer in headless mode",- "default": true- },- "puppeteerArgs": {- "type": "array",- "title": "Puppeteer Arguments",- "description": "Additional arguments for Puppeteer",- "default": [- "--no-sandbox",- "--disable-setuid-sandbox"- ]- }- }- }-}\ No newline at end of filediff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.tsindex 2a39df1db..e3847bc37 100644--- a/src/engine/engine.factory.spec.ts+++ b/src/engine/engine.factory.spec.ts@@ -138,36 +138,41 @@ describe('EngineFactory', () => {expect(registeredIds).toContain('baileys');});- it('falls back to the direct adapter when no engine plugin is available', () => {- const pluginLoader = {- getPlugin: jest.fn().mockReturnValue(undefined),- } as unknown as PluginLoaderService;-- const factory = new EngineFactory(- buildConfigService(),- pluginLoader,- buildMessageStore(),- buildLidStore(),- buildChatStateStore(),- );- expect(() => factory.create({ sessionId: 'sess-2', dbSessionId: 'db-2' })).not.toThrow();- });-- it('throws instead of silently building whatsapp-web.js when a non-wwebjs engine has no plugin', () => {- // The legacy fallback only builds wwebjs; reaching it with ENGINE_TYPE=baileys must fail loudly- // rather than run the wrong engine.- const pluginLoader = {- getPlugin: jest.fn().mockReturnValue(undefined),- } as unknown as PluginLoaderService;+ describe('create() with no usable engine plugin', () => {+ let tmpRoot: string;+ beforeEach(() => {+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'engine-missing-'));+ });+ afterEach(() => {+ fs.rmSync(tmpRoot, { recursive: true, force: true });+ });- const factory = new EngineFactory(- buildConfigService({ 'engine.type': 'baileys' }),- pluginLoader,- buildMessageStore(),- buildLidStore(),- buildChatStateStore(),- );- expect(() => factory.create({ sessionId: 'sess-b', dbSessionId: 'db-b' })).toThrow(/baileys/i);+ const missing: Array<[string, unknown]> = [+ ['no plugin', undefined],+ ['a plugin without an instance', { instance: undefined }],+ ['a non-engine plugin', { instance: { type: PluginType.EXTENSION } }],+ ];++ describe.each(['whatsapp-web.js', 'baileys'])('ENGINE_TYPE=%s', engineType => {+ it.each(missing)('throws for %s instead of building another engine', (_label, entry) => {+ const pluginLoader = {+ getPlugin: jest.fn().mockReturnValue(entry),+ } as unknown as PluginLoaderService;+ const factory = new EngineFactory(+ buildConfigService({+ 'engine.type': engineType,+ 'engine.sessionDataPath': path.join(tmpRoot, 'sessions'),+ 'engine.baileys.authDir': path.join(tmpRoot, 'baileys'),+ }),+ pluginLoader,+ buildMessageStore(),+ buildLidStore(),+ buildChatStateStore(),+ );+ const create = () => factory.create({ sessionId: SESSION_ID, dbSessionId: SESSION_ID });+ expect(create).toThrow(`Engine '${engineType}' is not registered; cannot start the session.`);+ });+ });});describe('create() makes the session credential directories owner-only', () => {diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.tsindex a20b08625..de3377f0c 100644--- a/src/engine/engine.factory.ts+++ b/src/engine/engine.factory.ts@@ -3,7 +3,6 @@ import * as path from 'path';import { Injectable, OnModuleInit } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { IWhatsAppEngine } from './interfaces/whatsapp-engine.interface';-import { WhatsAppWebJsAdapter } from './adapters/whatsapp-web-js.adapter';import { PluginLoaderService, PluginType, IEnginePlugin, PluginManifest } from '../core/plugins';import { WhatsAppWebJsPlugin } from './builtin/whatsapp-web-js';import { BaileysPlugin } from './builtin/baileys';@@ -113,10 +112,9 @@ export class EngineFactory implements OnModuleInit {}// Both engine shapes' credential dirs are made owner-only up front, whichever engine this- // session runs and whichever construction path serves it (plugin or fallback): a whatsapp-web.js- // profile and a baileys creds.json each hold everything needed to take over the linked account,- // so read access to the data volume must not be enough. Mirrors purgeSessionData, which removes- // BOTH shapes for the same engine-switch-residue reason.+ // session runs: a whatsapp-web.js profile and a baileys creds.json each hold everything needed+ // to take over the linked account, so read access to the data volume must not be enough.+ // Mirrors purgeSessionData, which removes BOTH shapes for the same engine-switch-residue reason.ensurePrivateDir(this.wwjsAuthDir(options.sessionId));ensurePrivateDir(this.baileysAuthDir(options.sessionId));@@ -135,12 +133,9 @@ export class EngineFactory implements OnModuleInit {}) as IWhatsAppEngine;}- // Fallback to direct adapter creation (legacy support)- this.logger.warn(`Engine plugin ${this.engineType} not available, using fallback`, {- action: 'engine_fallback',- });-- return this.createFallbackEngine(options);+ // Both built-ins are registered with an instance in onModuleInit and ENGINE_TYPE is whitelisted at+ // boot, so this is reached only by a broken host. Never build some other engine in its place.+ throw new Error(`Engine '${this.engineType}' is not registered; cannot start the session.`);}/**@@ -236,36 +231,6 @@ export class EngineFactory implements OnModuleInit {);}- private createFallbackEngine(options: EngineCreateOptions): IWhatsAppEngine {- // This legacy fallback can only construct the whatsapp-web.js adapter. If a different engine was- // requested (e.g. ENGINE_TYPE=baileys) and its plugin wasn't available, building wwebjs here would- // silently run the WRONG engine — fail loudly so the misconfiguration is visible instead.- if (this.engineType !== 'whatsapp-web.js') {- throw new Error(- `Engine '${this.engineType}' is unavailable and has no direct fallback; cannot start the session.`,- );- }-- // Legacy direct creation (fallback)- return new WhatsAppWebJsAdapter({- sessionId: options.sessionId,- sessionDataPath: this.configService.get<string>('engine.sessionDataPath') ?? './data/sessions',- puppeteer: {- headless: this.configService.get<boolean>('engine.puppeteer.headless') ?? true,- args: this.configService.get<string[]>('engine.puppeteer.args') ?? ['--no-sandbox', '--disable-setuid-sandbox'],- executablePath: this.configService.get<string>('engine.puppeteer.executablePath'),- protocolTimeoutMs: this.configService.get<number>('engine.puppeteer.protocolTimeoutMs'),- },- proxy: options.proxyUrl- ? {- url: options.proxyUrl,- type: options.proxyType ?? 'http',- }- : undefined,- lidMappingStore: this.lidMappingStore,- });- }-// ============================================================================// Query Methods for API/Dashboard// ============================================================================