Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): wire baileys engine into the factory, config, and boot gate
rmyndharis860d83f66fff
diff --git a/.env.example b/.env.exampleindex 7e79beede..57a478661 100644--- a/.env.example+++ b/.env.example@@ -73,6 +73,10 @@ PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--d# 2.3000.1023204257 is confirmed to reach "ready" (incl. ARM64 / Raspberry Pi 5) — uncomment it:# WWEBJS_WEB_VERSION=2.3000.1023204257+# Baileys engine (used when ENGINE_TYPE=baileys). WebSocket client, no Chromium.+BAILEYS_AUTH_DIR=./data/baileys+# NOTE: proxy (PROXY_URL/PROXY_TYPE) is not yet supported by the baileys engine; it is ignored.+# Humanise single sends: show a "typing…" indicator and pause briefly (length-scaled, jittered)# before each text send so messages don't look instantaneous (anti-ban). ON by default — set to# false to disable. SIMULATE_TYPING_MAX_MS caps the pause (default 5000). Does not affect bulkdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0f8972c96..cbfaaf068 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ plugins instead of in core (#265).### Added+- **Baileys engine (minimal slice)** — `ENGINE_TYPE=baileys` now selects a second, browser-free WhatsApp engine built on `@whiskeysockets/baileys` (WebSocket/Noise protocol, no Chromium). This first slice supports linking (QR + pairing code), sending and receiving **text**, recipient resolution, and typing presence; all other operations return HTTP 501 until later slices add a message store. Config: `BAILEYS_AUTH_DIR` (default `./data/baileys`). Proxy is not yet supported on this engine. (#PR)- **Plugin capability layer (Tier-2 extension plugins):** scoped `ctx.messages` (`sendText` / `reply`,routed through `MessageService` so persistence and the send pipeline are preserved) and read-only`ctx.engine` (`getGroupInfo` / `getContacts` / `getContactById` / `checkNumberExists` / `getChats`) ondiff --git a/package.json b/package.jsonindex 38d915a84..21029a8a3 100644--- a/package.json+++ b/package.json@@ -111,6 +111,10 @@"transform": {"^.+\\.(t|j)s$": "ts-jest"},+ "moduleNameMapper": {+ "^@whiskeysockets/baileys$": "<rootDir>/../test/__mocks__/@whiskeysockets/baileys.ts",+ "^@whiskeysockets/baileys/(.*)$": "<rootDir>/../test/__mocks__/@whiskeysockets/baileys.ts"+ },"collectCoverageFrom": ["**/*.(t|j)s"],diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex f08c9b35b..a6c852d1a 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -64,6 +64,11 @@ export default () => ({executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || undefined,},sessionDataPath: process.env.SESSION_DATA_PATH || './data/sessions',+ // Baileys engine (used when ENGINE_TYPE=baileys). Multi-file auth state base dir; each session+ // gets its own subdirectory. Read by the Baileys plugin from the opaque engine config blob.+ baileys: {+ authDir: process.env.BAILEYS_AUTH_DIR || './data/baileys',+ },},// Webhook configurationdiff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.tsindex 7c74027e0..fc37c28a5 100644--- a/src/engine/engine.factory.spec.ts+++ b/src/engine/engine.factory.spec.ts@@ -54,6 +54,22 @@ describe('EngineFactory', () => {);});+ it('registers the built-in baileys engine alongside whatsapp-web.js with the opaque config blob', async () => {+ const registerBuiltInPlugin = jest.fn();+ const pluginLoader = {+ registerBuiltInPlugin,+ enablePlugin: jest.fn().mockResolvedValue(undefined),+ getPlugin: jest.fn(),+ } as unknown as PluginLoaderService;++ const factory = new EngineFactory(buildConfigService(), pluginLoader);+ await factory.onModuleInit();++ const registeredIds = registerBuiltInPlugin.mock.calls.map(call => (call as [{ id: string }])[0].id);+ expect(registeredIds).toContain('whatsapp-web.js');+ expect(registeredIds).toContain('baileys');+ });+it('falls back to the direct adapter when no engine plugin is available', () => {const pluginLoader = {getPlugin: jest.fn().mockReturnValue(undefined),diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.tsindex 84c7bec39..c8709c9d0 100644--- a/src/engine/engine.factory.ts+++ b/src/engine/engine.factory.ts@@ -4,6 +4,7 @@ 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 '../plugins/engines/whatsapp-web-js';+import { BaileysPlugin } from '../plugins/engines/baileys';import { createLogger } from '../common/services/logger.service';export interface EngineCreateOptions {@@ -46,6 +47,23 @@ export class EngineFactory implements OnModuleInit {// the plugin reads its own namespace (puppeteer.*, sessionDataPath) from context.config.this.pluginLoader.registerBuiltInPlugin(wwjsManifest, wwjsPlugin, this.configService.get('engine') ?? {});+ // Register Baileys as a second built-in engine plugin. Same opaque engine blob; the plugin+ // reads only its own namespace (baileys.authDir) from context.config.+ const baileysManifest: PluginManifest = {+ id: 'baileys',+ name: 'Baileys Engine',+ version: '1.0.0',+ type: PluginType.ENGINE,+ description: 'Baileys (WebSocket, no-browser) engine adapter',+ main: 'index.ts',+ provides: ['whatsapp-engine'],+ };+ this.pluginLoader.registerBuiltInPlugin(+ baileysManifest,+ new BaileysPlugin(),+ this.configService.get('engine') ?? {},+ );+// Auto-enable the configured enginetry {await this.pluginLoader.enablePlugin(this.engineType);diff --git a/test/__mocks__/@whiskeysockets/baileys.ts b/test/__mocks__/@whiskeysockets/baileys.tsnew file mode 100644index 000000000..ccce46980--- /dev/null+++ b/test/__mocks__/@whiskeysockets/baileys.ts@@ -0,0 +1,11 @@+/**+ * Unit-test stub for @whiskeysockets/baileys (ESM-only package).+ * ts-jest runs in CommonJS mode; this stub prevents "Cannot use import statement outside a module"+ * when any source file importing baileys is pulled into the unit test graph.+ * The e2e boot gate uses jest.mock() inline instead (test/baileys-engine.e2e-spec.ts).+ */+export default jest.fn();+export const useMultiFileAuthState = jest.fn();+export const fetchLatestBaileysVersion = jest.fn();+export const getContentType = jest.fn();+export const DisconnectReason = { loggedOut: 401 };diff --git a/test/baileys-engine.e2e-spec.ts b/test/baileys-engine.e2e-spec.tsnew file mode 100644index 000000000..f6ec4f4ee--- /dev/null+++ b/test/baileys-engine.e2e-spec.ts@@ -0,0 +1,59 @@+// archiver v8 is ESM-only (pulled in transitively via @Global StorageModule); stub for ts-jest CJS.+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));+// Stub the heavy Baileys lib: the boot gate only verifies registration/enable, never a socket connect.+jest.mock('@whiskeysockets/baileys', () => ({+ __esModule: true,+ default: jest.fn(),+ useMultiFileAuthState: jest.fn(),+ fetchLatestBaileysVersion: jest.fn(),+ getContentType: jest.fn(),+ DisconnectReason: { loggedOut: 401 },+}));++import { Test, TestingModule } from '@nestjs/testing';+import { INestApplication } from '@nestjs/common';+import { App } from 'supertest/types';+import { AppModule } from './../src/app.module';+import { EngineFactory } from './../src/engine/engine.factory';++/**+ * Boots the real app module graph with ENGINE_TYPE=baileys. This is the integration gate: it proves+ * the second registration block + config wiring boot cleanly (the DI module-load cycle only surfaces+ * at full boot) without the Baileys socket ever connecting (AUTO_START_SESSIONS=false; lib mocked).+ */+describe('Baileys engine boot (e2e)', () => {+ let app: INestApplication<App>;+ let factory: EngineFactory;+ const prevEngine = process.env.ENGINE_TYPE;++ beforeAll(async () => {+ process.env.ENGINE_TYPE = 'baileys';+ const moduleFixture: TestingModule = await Test.createTestingModule({+ imports: [AppModule],+ }).compile();+ app = moduleFixture.createNestApplication();+ await app.init();+ factory = moduleFixture.get(EngineFactory);+ });++ afterAll(async () => {+ process.env.ENGINE_TYPE = prevEngine;+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ it('selects baileys as the current engine', () => {+ expect(factory.getCurrentEngine()).toBe('baileys');+ });++ it('registers and enables the baileys engine plugin', () => {+ const engines = factory.getAvailableEngines();+ const baileys = engines.find(e => e.id === 'baileys');+ expect(baileys).toBeDefined();+ expect(baileys?.enabled).toBe(true);+ expect(baileys?.features).toEqual(['text-messages', 'typing-indicator']);+ });+});