Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): address maintainer review on version resolver tiers, timeouts, proxy and env registration
Giovanni Orciuolo5b68034e50dc
diff --git a/.env.example b/.env.exampleindex 354d387c1..d07a43d0d 100644--- a/.env.example+++ b/.env.example@@ -193,6 +193,9 @@ OPENWA_PIDS_LIMIT=2048# Device name shown in WhatsApp Settings → Linked Devices for NEW pairings (existing sessions keep# the name they were paired with until re-linked). Default: OpenWA.# BAILEYS_BROWSER_NAME=+# Pin a specific WhatsApp Web protocol version for the Baileys engine (e.g. 2.3000.1045340097).+# Leave unset (default) for automatic multi-tier resolution (live WA Web endpoint -> upstream Defaults -> local cache -> safe fallback).+# BAILEYS_WA_VERSION=2.3000.1045340097# Surface the Baileys library's own logs for debugging (trace|debug|info|warn|error). Silent by default.# `trace` dumps the decoded WhatsApp wire frames to stdout (context "baileys-wire").diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 8c6c0026c..14d51b728 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -94,6 +94,7 @@ services:- WEBHOOK_CONTACT_DETAILS=${WEBHOOK_CONTACT_DETAILS:-}- BAILEYS_MARK_ONLINE_ON_CONNECT=${BAILEYS_MARK_ONLINE_ON_CONNECT:-}- BAILEYS_SYNC_FULL_HISTORY=${BAILEYS_SYNC_FULL_HISTORY:-}+ - BAILEYS_WA_VERSION=${BAILEYS_WA_VERSION:-}- ALLOW_UNSIGNED_INGRESS=${ALLOW_UNSIGNED_INGRESS:-}- STORE_EPHEMERAL_MESSAGES=${STORE_EPHEMERAL_MESSAGES:-}- RESOLVE_LID_TO_PHONE=${RESOLVE_LID_TO_PHONE:-}diff --git a/docker-compose.yml b/docker-compose.ymlindex 49f300414..76cd66ee5 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -234,6 +234,7 @@ services:- WEBHOOK_CONTACT_DETAILS=${WEBHOOK_CONTACT_DETAILS:-}- BAILEYS_MARK_ONLINE_ON_CONNECT=${BAILEYS_MARK_ONLINE_ON_CONNECT:-}- BAILEYS_SYNC_FULL_HISTORY=${BAILEYS_SYNC_FULL_HISTORY:-}+ - BAILEYS_WA_VERSION=${BAILEYS_WA_VERSION:-}- ALLOW_UNSIGNED_INGRESS=${ALLOW_UNSIGNED_INGRESS:-}- STORE_EPHEMERAL_MESSAGES=${STORE_EPHEMERAL_MESSAGES:-}- RESOLVE_LID_TO_PHONE=${RESOLVE_LID_TO_PHONE:-}diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.tsindex 8364223a7..264505424 100644--- a/src/config/env-precedence.ts+++ b/src/config/env-precedence.ts@@ -90,6 +90,7 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = ['WEBHOOK_CONTACT_DETAILS','BAILEYS_MARK_ONLINE_ON_CONNECT','BAILEYS_SYNC_FULL_HISTORY',+ 'BAILEYS_WA_VERSION','ALLOW_UNSIGNED_INGRESS','STORE_EPHEMERAL_MESSAGES','RESOLVE_LID_TO_PHONE',diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.tsindex 0d40f44fe..cc14f17e4 100644--- a/src/config/env.validation.spec.ts+++ b/src/config/env.validation.spec.ts@@ -207,6 +207,11 @@ describe('validateEnv', () => {expect(() => validateEnv({ WEBHOOK_SSRF_PROTECT: 'off' })).toThrow(/WEBHOOK_SSRF_PROTECT/);expect(() => validateEnv({ WEBHOOK_CONTACT_DETAILS: 'on' })).toThrow(/WEBHOOK_CONTACT_DETAILS/);expect(() => validateEnv({ BAILEYS_SYNC_FULL_HISTORY: 'True' })).toThrow(/BAILEYS_SYNC_FULL_HISTORY/);+ expect(() => validateEnv({ BAILEYS_WA_VERSION: '2.3000' })).toThrow(/BAILEYS_WA_VERSION/);+ expect(() => validateEnv({ BAILEYS_WA_VERSION: '1.2.3' })).toThrow(/BAILEYS_WA_VERSION/);+ expect(() => validateEnv({ BAILEYS_WA_VERSION: 'abc' })).toThrow(/BAILEYS_WA_VERSION/);+ expect(() => validateEnv({ BAILEYS_WA_VERSION: '2.3000.1045340097' })).not.toThrow();+ expect(() => validateEnv({ BAILEYS_WA_VERSION: '2,3000,1045340097' })).not.toThrow();expect(() => validateEnv({ BAILEYS_MARK_ONLINE_ON_CONNECT: 'ture' })).toThrow(/BAILEYS_MARK_ONLINE_ON_CONNECT/);expect(() => validateEnv({ POSTGRES_BUILTIN: 'yes' })).toThrow(/POSTGRES_BUILTIN/);expect(() => validateEnv({ REDIS_BUILTIN: 'yes' })).toThrow(/REDIS_BUILTIN/);diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex d843f855b..9039a9fa2 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -220,6 +220,28 @@ export function validateEnv(config: EnvConfig): EnvConfig {checkInt(key);}+ // BAILEYS_WA_VERSION: optional version pin for the Baileys engine (e.g. 2.3000.1045340097 or 2,3000,1045340097)+ for (const key of ['BAILEYS_WA_VERSION']) {+ const raw = str(key);+ if (raw !== undefined) {+ const match = raw.match(/^(\d+)[.,](\d+)[.,](\d+)$/);+ if (!match) {+ errors.push(+ `${key} must be a valid WhatsApp Web version (e.g. "2.3000.1045340097"; got ${JSON.stringify(raw)})`,+ );+ } else {+ const major = parseInt(match[1], 10);+ const minor = parseInt(match[2], 10);+ const patch = parseInt(match[3], 10);+ if (major !== 2 || minor < 2000 || patch < 0) {+ errors.push(+ `${key} must be a valid WhatsApp Web version (e.g. "2.3000.1045340097"; got ${JSON.stringify(raw)})`,+ );+ }+ }+ }+ }+// Some knobs are nonsensical at 0 and contradict the "non-negative" intent: a rate-limit LIMIT of 0// disables that tier's throttling (a self-DoS), and a webhook timeout of 0 aborts every delivery// immediately. Require a positive integer for these.diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex 2909a9db4..a2c7d67cc 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -189,7 +189,7 @@ export class BaileysLifecycle {}const b = await this.loadLib();const { state, saveCreds } = await b.useMultiFileAuthState(this.host.authPath);- const version = await this.versionResolver.resolve(b);+ const version = await this.versionResolver.resolve(b, { dispatcher: proxyAgent });// BaileysLogger matches ILogger exactly; cast needed because the module resolves the type// through a deep import path that TypeScript does not auto-unify here. Shared by the key// store wrapper below and the socket itself, rather than constructing two instances.@@ -790,5 +790,4 @@ export class BaileysLifecycle {this.status = status;this.host.getOnStateChanged()?.(status);}-}diff --git a/src/engine/adapters/baileys-version-resolver.spec.ts b/src/engine/adapters/baileys-version-resolver.spec.tsindex d882c711a..67b01b572 100644--- a/src/engine/adapters/baileys-version-resolver.spec.ts+++ b/src/engine/adapters/baileys-version-resolver.spec.ts@@ -1,149 +1,361 @@import * as fs from 'fs';+import * as os from 'os';import * as path from 'path';-import { BaileysVersionResolver, DEFAULT_FALLBACK_WA_VERSION } from './baileys-version-resolver';+import type * as BaileysLib from '@whiskeysockets/baileys';+import { BaileysVersionResolver, DEFAULT_FALLBACK_WA_VERSION, WAVersion } from './baileys-version-resolver';describe('BaileysVersionResolver', () => {- const tempDir = path.join(__dirname, '../../../test/tmp-resolver-test');- const cacheFile = path.join(tempDir, 'last_known_wa_version.json');- const originalEnv = process.env.BAILEYS_WA_VERSION;+ let tmpDir: string;+ let mockLogger: { log: jest.Mock; warn: jest.Mock };- const mockLogger = {- log: jest.fn(),- warn: jest.fn(),- };+ beforeEach(() => {+ delete process.env.BAILEYS_WA_VERSION;+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-ver-test-'));+ mockLogger = {+ log: jest.fn(),+ warn: jest.fn(),+ };+ });++ afterEach(() => {+ delete process.env.BAILEYS_WA_VERSION;+ try {+ if (fs.existsSync(tmpDir)) {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+ } catch {+ // Best effort cleanup in os.tmpdir+ }+ });- const createResolver = () =>+ const createResolver = (timeoutMs?: number) =>new BaileysVersionResolver({- authDir: tempDir,+ authDir: tmpDir,sessionId: 'test-session',logger: mockLogger,+ timeoutMs,});- beforeEach(() => {- delete process.env.BAILEYS_WA_VERSION;- jest.clearAllMocks();- if (fs.existsSync(tempDir)) {- fs.rmSync(tempDir, { recursive: true, force: true });- }- });+ const asBaileysLib = (mock: unknown): typeof BaileysLib => mock as typeof BaileysLib;- afterAll(() => {- if (originalEnv) {- process.env.BAILEYS_WA_VERSION = originalEnv;- } else {- delete process.env.BAILEYS_WA_VERSION;- }- if (fs.existsSync(tempDir)) {- fs.rmSync(tempDir, { recursive: true, force: true });- }- });+ describe('Tier 1: BAILEYS_WA_VERSION environment variable override', () => {+ it('when BAILEYS_WA_VERSION is set in dot format, returns the overridden version immediately without network calls', async () => {+ // Arrange+ process.env.BAILEYS_WA_VERSION = '2.3000.1045340097';+ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn(),+ fetchLatestBaileysVersion: jest.fn(),+ };- it('when BAILEYS_WA_VERSION is set with dots, returns the overridden version', async () => {- // Arrange- process.env.BAILEYS_WA_VERSION = '2.3000.1045340097';- const resolver = createResolver();- const mockLib = {- fetchLatestWaWebVersion: jest.fn(),- fetchLatestBaileysVersion: jest.fn(),- };+ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));- // Act- const version = await resolver.resolve(mockLib as any);+ // Assert+ expect(version).toEqual([2, 3000, 1045340097]);+ expect(mockLib.fetchLatestWaWebVersion).not.toHaveBeenCalled();+ expect(mockLib.fetchLatestBaileysVersion).not.toHaveBeenCalled();+ expect(mockLogger.log).toHaveBeenCalledWith('Using BAILEYS_WA_VERSION override: 2.3000.1045340097', {+ sessionId: 'test-session',+ });+ });- // Assert- expect(version).toEqual([2, 3000, 1045340097]);- expect(mockLib.fetchLatestWaWebVersion).not.toHaveBeenCalled();- expect(mockLib.fetchLatestBaileysVersion).not.toHaveBeenCalled();- });+ it('when BAILEYS_WA_VERSION is set in comma format, parses and returns the version', async () => {+ // Arrange+ process.env.BAILEYS_WA_VERSION = '2,3000,1045340097';+ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn(),+ };- it('when BAILEYS_WA_VERSION is set with commas, returns the overridden version', async () => {- // Arrange- process.env.BAILEYS_WA_VERSION = '2,3000,1045340097';- const resolver = createResolver();- const mockLib = {- fetchLatestWaWebVersion: jest.fn(),- fetchLatestBaileysVersion: jest.fn(),- };+ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));- // Act- const version = await resolver.resolve(mockLib as any);+ // Assert+ expect(version).toEqual([2, 3000, 1045340097]);+ expect(mockLogger.log).toHaveBeenCalledWith('Using BAILEYS_WA_VERSION override: 2.3000.1045340097', {+ sessionId: 'test-session',+ });+ });++ it('when BAILEYS_WA_VERSION is malformed (e.g. missing patch), logs warning and falls through to next tier', async () => {+ // Arrange+ process.env.BAILEYS_WA_VERSION = '2.3000';+ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1045345293],+ isLatest: true,+ }),+ };- // Assert- expect(version).toEqual([2, 3000, 1045340097]);+ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));++ // Assert+ expect(version).toEqual([2, 3000, 1045345293]);+ expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('Invalid BAILEYS_WA_VERSION'), {+ sessionId: 'test-session',+ });+ });++ it('when BAILEYS_WA_VERSION has unreasonable numbers (e.g. 1.2.3), logs warning and falls through', async () => {+ // Arrange+ process.env.BAILEYS_WA_VERSION = '1.2.3';+ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1045345293],+ isLatest: true,+ }),+ };++ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));++ // Assert+ expect(version).toEqual([2, 3000, 1045345293]);+ expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('Invalid BAILEYS_WA_VERSION'), {+ sessionId: 'test-session',+ });+ });});- it('when fetchLatestWaWebVersion succeeds, resolves and writes version to disk cache', async () => {- // Arrange- const resolver = createResolver();- const mockLib = {- fetchLatestWaWebVersion: jest.fn().mockResolvedValue({ version: [2, 3000, 1045340097], isLatest: true }),- fetchLatestBaileysVersion: jest.fn(),- };+ describe('Tier 2: fetchLatestWaWebVersion (live WhatsApp Web service worker)', () => {+ it('when fetchLatestWaWebVersion succeeds (isLatest=true), returns version, persists to disk cache, and forwards dispatcher', async () => {+ // Arrange+ const resolver = createResolver();+ const mockDispatcher = { id: 'mock-proxy-dispatcher' };+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1045345293],+ isLatest: true,+ }),+ fetchLatestBaileysVersion: jest.fn(),+ };++ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib), { dispatcher: mockDispatcher });++ // Assert+ expect(version).toEqual([2, 3000, 1045345293]);+ expect(mockLib.fetchLatestWaWebVersion).toHaveBeenCalledTimes(1);+ const fnMock = mockLib.fetchLatestWaWebVersion as jest.Mock<Promise<unknown>, [Record<string, unknown>?]>;+ const callOptions = fnMock.mock.calls[0]?.[0];+ expect(callOptions?.dispatcher).toBe(mockDispatcher);+ expect(callOptions?.signal).toBeInstanceOf(AbortSignal);+ expect(mockLib.fetchLatestBaileysVersion).not.toHaveBeenCalled();- // Act- const version = await resolver.resolve(mockLib as any);+ // Verify disk cache was saved+ const cachePath = path.join(tmpDir, 'last_known_wa_version.json');+ expect(fs.existsSync(cachePath)).toBe(true);+ const rawCache: string = fs.readFileSync(cachePath, 'utf8');+ const cacheContent: unknown = JSON.parse(rawCache);+ expect(cacheContent).toEqual([2, 3000, 1045345293]);+ });++ it('when fetchLatestWaWebVersion returns Baileys error stub (isLatest=false), does NOT write to cache and advances to Tier 3', async () => {+ // Arrange+ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1043857760], // Baileys frozen stub+ isLatest: false,+ error: new Error('fetch error'),+ }),+ fetchLatestBaileysVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1043857760],+ isLatest: true,+ }),+ };++ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));++ // Assert+ expect(version).toEqual([2, 3000, 1043857760]);+ expect(mockLib.fetchLatestBaileysVersion).toHaveBeenCalled();+ expect(mockLogger.warn).toHaveBeenCalledWith(+ expect.stringContaining('fetchLatestWaWebVersion returned isLatest=false'),+ { sessionId: 'test-session' },+ );+ });++ it('when fetchLatestWaWebVersion rejects, logs warning and advances to Tier 3', async () => {+ // Arrange+ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockRejectedValue(new Error('Network offline')),+ fetchLatestBaileysVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1043857760],+ isLatest: true,+ }),+ };- // Assert- expect(version).toEqual([2, 3000, 1045340097]);- expect(mockLib.fetchLatestWaWebVersion).toHaveBeenCalled();- expect(mockLib.fetchLatestBaileysVersion).not.toHaveBeenCalled();- expect(fs.existsSync(cacheFile)).toBe(true);- expect(JSON.parse(fs.readFileSync(cacheFile, 'utf8'))).toEqual([2, 3000, 1045340097]);+ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));++ // Assert+ expect(version).toEqual([2, 3000, 1043857760]);+ expect(mockLib.fetchLatestBaileysVersion).toHaveBeenCalled();+ expect(mockLogger.warn).toHaveBeenCalledWith(+ expect.stringContaining('fetchLatestWaWebVersion failed: Network offline'),+ { sessionId: 'test-session' },+ );+ });});- it('when fetchLatestWaWebVersion fails, falls back to fetchLatestBaileysVersion and caches it', async () => {- // Arrange- const resolver = createResolver();- const mockLib = {- fetchLatestWaWebVersion: jest.fn().mockRejectedValue(new Error('WA Web connection timeout')),- fetchLatestBaileysVersion: jest.fn().mockResolvedValue({ version: [2, 3000, 1043857760], isLatest: true }),- };+ describe('Tier 3: fetchLatestBaileysVersion (upstream repository Defaults/index.ts)', () => {+ it('when Tier 2 returns isLatest=false and Tier 3 succeeds (isLatest=true), returns version and persists to disk cache', async () => {+ // Arrange+ const resolver = createResolver();+ const mockDispatcher = { id: 'mock-proxy-agent' };+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1043857760],+ isLatest: false,+ }),+ fetchLatestBaileysVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1043857760],+ isLatest: true,+ }),+ };++ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib), { dispatcher: mockDispatcher });++ // Assert+ expect(version).toEqual([2, 3000, 1043857760]);+ expect(mockLib.fetchLatestBaileysVersion).toHaveBeenCalledWith({+ dispatcher: mockDispatcher,+ });++ const cachePath = path.join(tmpDir, 'last_known_wa_version.json');+ expect(fs.existsSync(cachePath)).toBe(true);+ const rawCache: string = fs.readFileSync(cachePath, 'utf8');+ const cacheContent: unknown = JSON.parse(rawCache);+ expect(cacheContent).toEqual([2, 3000, 1043857760]);+ });++ it('when fetchLatestBaileysVersion returns isLatest=false, does NOT poison disk cache and advances to Tier 4', async () => {+ // Arrange: Seed good cached value from a previous run+ const cachePath = path.join(tmpDir, 'last_known_wa_version.json');+ const seededVersion: WAVersion = [2, 3000, 1045340097];+ fs.writeFileSync(cachePath, JSON.stringify(seededVersion), 'utf8');++ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1043857760],+ isLatest: false,+ }),+ fetchLatestBaileysVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1043857760],+ isLatest: false,+ }),+ };- // Act- const version = await resolver.resolve(mockLib as any);+ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));- // Assert- expect(version).toEqual([2, 3000, 1043857760]);- expect(mockLib.fetchLatestWaWebVersion).toHaveBeenCalled();- expect(mockLib.fetchLatestBaileysVersion).toHaveBeenCalled();- expect(fs.existsSync(cacheFile)).toBe(true);- expect(JSON.parse(fs.readFileSync(cacheFile, 'utf8'))).toEqual([2, 3000, 1043857760]);+ // Assert: Good seeded cache must NOT be overwritten by the Baileys frozen stub+ expect(version).toEqual(seededVersion);+ const rawCache: string = fs.readFileSync(cachePath, 'utf8');+ const cacheContent: unknown = JSON.parse(rawCache);+ expect(cacheContent).toEqual(seededVersion);+ expect(mockLogger.warn).toHaveBeenCalledWith('Using cached WhatsApp Web version from disk: 2.3000.1045340097', {+ sessionId: 'test-session',+ });+ });++ it('when fetchLatestBaileysVersion hangs, timeout race aborts and advances to Tier 4 (disk cache)', async () => {+ // Arrange: Seed cache+ const cachePath = path.join(tmpDir, 'last_known_wa_version.json');+ const seededVersion: WAVersion = [2, 3000, 999999];+ fs.writeFileSync(cachePath, JSON.stringify(seededVersion), 'utf8');++ // Use a fast 50ms timeout for test+ const resolver = createResolver(50);+ const hangingPromise = new Promise<{ version: WAVersion; isLatest: boolean }>(() => {});+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockResolvedValue({+ version: [2, 3000, 1043857760],+ isLatest: false,+ }),+ fetchLatestBaileysVersion: jest.fn().mockReturnValue(hangingPromise),+ };++ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));++ // Assert+ expect(version).toEqual(seededVersion);+ expect(mockLogger.warn).toHaveBeenCalledWith(+ expect.stringContaining('fetchLatestBaileysVersion failed: fetchLatestBaileysVersion timeout'),+ { sessionId: 'test-session' },+ );+ });});- it('when remote fetches fail and valid disk cache exists, returns cached version', async () => {- // Arrange- fs.mkdirSync(tempDir, { recursive: true });- fs.writeFileSync(cacheFile, JSON.stringify([2, 3000, 888888]), 'utf8');+ describe('Tier 4: Local disk cache', () => {+ it('when remote fetches fail and valid disk cache exists, returns cached version', async () => {+ // Arrange+ const cachePath = path.join(tmpDir, 'last_known_wa_version.json');+ fs.writeFileSync(cachePath, JSON.stringify([2, 3000, 888888]), 'utf8');- const resolver = createResolver();- const mockLib = {- fetchLatestWaWebVersion: jest.fn().mockRejectedValue(new Error('offline')),- fetchLatestBaileysVersion: jest.fn().mockRejectedValue(new Error('github 503')),- };+ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockResolvedValue({ isLatest: false }),+ fetchLatestBaileysVersion: jest.fn().mockResolvedValue({ isLatest: false }),+ };- // Act- const version = await resolver.resolve(mockLib as any);+ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));- // Assert- expect(version).toEqual([2, 3000, 888888]);- expect(mockLogger.warn).toHaveBeenCalledWith(- expect.stringContaining('Using cached WhatsApp Web version from disk: 2.3000.888888'),- expect.anything()- );+ // Assert+ expect(version).toEqual([2, 3000, 888888]);+ expect(mockLogger.warn).toHaveBeenCalledWith('Using cached WhatsApp Web version from disk: 2.3000.888888', {+ sessionId: 'test-session',+ });+ });++ it('when disk cache contains corrupt JSON, falls through to Tier 5', async () => {+ // Arrange+ const cachePath = path.join(tmpDir, 'last_known_wa_version.json');+ fs.writeFileSync(cachePath, '{ corrupt json', 'utf8');++ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockResolvedValue({ isLatest: false }),+ fetchLatestBaileysVersion: jest.fn().mockResolvedValue({ isLatest: false }),+ };++ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));++ // Assert+ expect(version).toEqual(DEFAULT_FALLBACK_WA_VERSION);+ });});- it('when network fetches fail and disk cache is missing, returns DEFAULT_FALLBACK_WA_VERSION', async () => {- // Arrange- const resolver = createResolver();- const mockLib = {- fetchLatestWaWebVersion: jest.fn().mockRejectedValue(new Error('offline')),- fetchLatestBaileysVersion: jest.fn().mockRejectedValue(new Error('github down')),- };+ describe('Tier 5: DEFAULT_FALLBACK_WA_VERSION', () => {+ it('when all remote fetches fail and disk cache is missing, returns DEFAULT_FALLBACK_WA_VERSION and logs warning', async () => {+ // Arrange+ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockResolvedValue({ isLatest: false }),+ fetchLatestBaileysVersion: jest.fn().mockResolvedValue({ isLatest: false }),+ };- // Act- const version = await resolver.resolve(mockLib as any);+ // Act+ const version = await resolver.resolve(asBaileysLib(mockLib));- // Assert- expect(version).toEqual(DEFAULT_FALLBACK_WA_VERSION);+ // Assert+ expect(version).toEqual(DEFAULT_FALLBACK_WA_VERSION);+ expect(mockLogger.warn).toHaveBeenCalledWith(+ expect.stringContaining('using fallback WhatsApp Web version: 2.3000.1045340097'),+ { sessionId: 'test-session' },+ );+ });});});diff --git a/src/engine/adapters/baileys-version-resolver.ts b/src/engine/adapters/baileys-version-resolver.tsindex 774255fae..b6323fb12 100644--- a/src/engine/adapters/baileys-version-resolver.ts+++ b/src/engine/adapters/baileys-version-resolver.ts@@ -5,13 +5,25 @@ import type { LoggerService } from '../../common/services/logger.service';export type WAVersion = [number, number, number];-/** Default modern fallback version when all remote endpoints and local caches are unavailable */+/**+ * Default modern fallback version when all remote endpoints and local caches are unavailable.+ * WhatsApp Web protocol versions follow semantic versioning [major, minor, client_revision].+ * Refresh during major version bumps or when WhatsApp deprecates older client revisions.+ */export const DEFAULT_FALLBACK_WA_VERSION: WAVersion = [2, 3000, 1045340097];+/** Default timeout for remote version resolution network calls (5 seconds) */+export const VERSION_RESOLVER_TIMEOUT_MS = 5000;+export interface BaileysVersionResolverOptions {authDir: string;sessionId: string;logger: Pick<LoggerService, 'log' | 'warn'>;+ timeoutMs?: number;+}++export interface ResolveOptions {+ dispatcher?: unknown;}/**@@ -22,27 +34,29 @@ export interface BaileysVersionResolverOptions {* 2. Direct WhatsApp Web service worker endpoint (fetchLatestWaWebVersion -> web.whatsapp.com/sw.js)* 3. Upstream repository Defaults/index.ts (fetchLatestBaileysVersion -> GitHub raw)* 4. Local disk cache (last_known_wa_version.json in authDir)- * 5. Safe modern fallback version+ * 5. Safe modern fallback version (DEFAULT_FALLBACK_WA_VERSION)*/export class BaileysVersionResolver {private readonly cacheFilePath: string;+ private readonly timeoutMs: number;constructor(private readonly options: BaileysVersionResolverOptions) {this.cacheFilePath = path.join(this.options.authDir, 'last_known_wa_version.json');+ this.timeoutMs = options.timeoutMs ?? VERSION_RESOLVER_TIMEOUT_MS;}- async resolve(b: typeof BaileysLib): Promise<WAVersion> {+ async resolve(b: typeof BaileysLib, resolveOptions: ResolveOptions = {}): Promise<WAVersion> {const envVersion = this.resolveFromEnv();if (envVersion) {return envVersion;}- const waWebVersion = await this.resolveFromWaWeb(b);+ const waWebVersion = await this.resolveFromWaWeb(b, resolveOptions);if (waWebVersion) {return waWebVersion;}- const baileysVersion = await this.resolveFromBaileys(b);+ const baileysVersion = await this.resolveFromBaileys(b, resolveOptions);if (baileysVersion) {return baileysVersion;}@@ -52,6 +66,10 @@ export class BaileysVersionResolver {return cachedVersion;}+ this.options.logger.warn(+ `All remote version endpoints and disk cache unavailable; using fallback WhatsApp Web version: ${DEFAULT_FALLBACK_WA_VERSION.join('.')}`,+ { sessionId: this.options.sessionId },+ );return DEFAULT_FALLBACK_WA_VERSION;}@@ -61,32 +79,51 @@ export class BaileysVersionResolver {return null;}- const parts = raw.split(/[.,]/).map(p => parseInt(p.trim(), 10));- if (parts.length === 3 && parts.every(n => !isNaN(n) && n >= 0)) {- this.options.logger.log(`Using BAILEYS_WA_VERSION override: ${parts.join('.')}`, {- sessionId: this.options.sessionId,- });- return parts as WAVersion;+ const match = raw.match(/^(\d+)[.,](\d+)[.,](\d+)$/);+ if (match) {+ const major = parseInt(match[1], 10);+ const minor = parseInt(match[2], 10);+ const patch = parseInt(match[3], 10);++ if (major === 2 && minor >= 2000 && patch >= 0) {+ const version: WAVersion = [major, minor, patch];+ this.options.logger.log(`Using BAILEYS_WA_VERSION override: ${version.join('.')}`, {+ sessionId: this.options.sessionId,+ });+ return version;+ }}- this.options.logger.warn(`Invalid BAILEYS_WA_VERSION format "${raw}", expected "major.minor.patch"`, {- sessionId: this.options.sessionId,- });+ this.options.logger.warn(+ `Invalid BAILEYS_WA_VERSION "${raw}", expected format "2.3000.xxxxxxxxx" (e.g. "2.3000.1045340097")`,+ { sessionId: this.options.sessionId },+ );return null;}- private async resolveFromWaWeb(b: typeof BaileysLib): Promise<WAVersion | null> {+ private async resolveFromWaWeb(b: typeof BaileysLib, resolveOptions: ResolveOptions): Promise<WAVersion | null> {if (typeof b.fetchLatestWaWebVersion !== 'function') {return null;}try {- const result = await b.fetchLatestWaWebVersion();- if (this.isValidVersion(result?.version)) {- const version = result.version as WAVersion;+ const fetchOptions = {+ ...(resolveOptions.dispatcher ? { dispatcher: resolveOptions.dispatcher } : {}),+ signal: AbortSignal.timeout(this.timeoutMs),+ } as unknown as RequestInit;++ const result = await b.fetchLatestWaWebVersion(fetchOptions);++ if (result?.isLatest === true && this.isValidVersion(result?.version)) {+ const version = result.version;this.saveCachedVersion(version);return version;}++ this.options.logger.warn(+ `fetchLatestWaWebVersion returned isLatest=false (${JSON.stringify(result?.version)}); advancing to next tier`,+ { sessionId: this.options.sessionId },+ );} catch (err) {this.options.logger.warn(`fetchLatestWaWebVersion failed: ${err instanceof Error ? err.message : String(err)}`, {sessionId: this.options.sessionId,@@ -96,22 +133,43 @@ export class BaileysVersionResolver {return null;}- private async resolveFromBaileys(b: typeof BaileysLib): Promise<WAVersion | null> {+ private async resolveFromBaileys(b: typeof BaileysLib, resolveOptions: ResolveOptions): Promise<WAVersion | null> {if (typeof b.fetchLatestBaileysVersion !== 'function') {return null;}try {- const result = await b.fetchLatestBaileysVersion();- if (this.isValidVersion(result?.version)) {- const version = result.version as WAVersion;+ // Baileys' fetchLatestBaileysVersion does not forward signal, so race it with a timeout+ let timeoutId: NodeJS.Timeout | undefined;+ const timeoutPromise = new Promise<never>((_, reject) => {+ timeoutId = setTimeout(() => reject(new Error('fetchLatestBaileysVersion timeout')), this.timeoutMs);+ });++ const fetchOptions = (resolveOptions.dispatcher+ ? { dispatcher: resolveOptions.dispatcher }+ : undefined) as unknown as RequestInit;++ const fetchPromise = b.fetchLatestBaileysVersion(fetchOptions);++ const result = await Promise.race([fetchPromise, timeoutPromise]).finally(() => {+ if (timeoutId) clearTimeout(timeoutId);+ });++ if (result?.isLatest === true && this.isValidVersion(result?.version)) {+ const version = result.version;this.saveCachedVersion(version);return version;}++ this.options.logger.warn(+ `fetchLatestBaileysVersion returned isLatest=false (${JSON.stringify(result?.version)}); advancing to next tier`,+ { sessionId: this.options.sessionId },+ );} catch (err) {- this.options.logger.warn(`fetchLatestBaileysVersion failed: ${err instanceof Error ? err.message : String(err)}`, {- sessionId: this.options.sessionId,- });+ this.options.logger.warn(+ `fetchLatestBaileysVersion failed: ${err instanceof Error ? err.message : String(err)}`,+ { sessionId: this.options.sessionId },+ );}return null;@@ -124,12 +182,12 @@ export class BaileysVersionResolver {}const content = fs.readFileSync(this.cacheFilePath, 'utf8');- const parsed = JSON.parse(content);+ const parsed: unknown = JSON.parse(content);if (this.isValidVersion(parsed)) {this.options.logger.warn(`Using cached WhatsApp Web version from disk: ${parsed.join('.')}`, {sessionId: this.options.sessionId,});- return parsed as WAVersion;+ return parsed;}} catch {// Non-blocking disk read fallback@@ -151,6 +209,10 @@ export class BaileysVersionResolver {}private isValidVersion(v: unknown): v is WAVersion {- return Array.isArray(v) && v.length === 3 && v.every(n => typeof n === 'number' && !isNaN(n) && n >= 0);+ return (+ Array.isArray(v) &&+ v.length === 3 &&+ v.every((n: unknown) => typeof n === 'number' && Number.isInteger(n) && n >= 0)+ );}}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 56080edcc..d5fef48aa 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -612,7 +612,7 @@ describe('BaileysAdapter lifecycle & status', () => {expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);});- // I5 — first-connect error surfacing+ // I5 — first-connect error surfacingit('I5: first connect failure → initialize() rejects, status FAILED, onError fired', async () => {// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertionconst baileys = jest.requireMock('@whiskeysockets/baileys') as {diff --git a/test/__mocks__/@whiskeysockets/baileys.ts b/test/__mocks__/@whiskeysockets/baileys.tsindex ae7fb25be..310f9492e 100644--- a/test/__mocks__/@whiskeysockets/baileys.ts+++ b/test/__mocks__/@whiskeysockets/baileys.ts@@ -12,11 +12,6 @@export default jest.fn();export const useMultiFileAuthState = jest.fn();export const fetchLatestBaileysVersion = jest.fn();-export const Browsers = {- ubuntu: jest.fn((browser: string) => ['Ubuntu', browser, '22.04.4']),- macOS: jest.fn((browser: string) => ['Mac OS', browser, '14.4.1']),- windows: jest.fn((browser: string) => ['Windows', browser, '10.0.22631']),-};export const getContentType = jest.fn();export const DisconnectReason = { loggedOut: 401 };