Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): add resilient WhatsApp Web version resolution and fallback cache
Giovanni Orciuolo1d6d1fedf608
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex a26824cd3..2909a9db4 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -1,3 +1,4 @@+import * as path from 'path';import * as fs from 'fs';import type { Agent } from 'https';import * as qrcode from 'qrcode';@@ -11,6 +12,7 @@ import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error'import { type createLogger } from '../../common/services/logger.service';import { BaileysAdapterConfig } from '../types/baileys.types';import { createBaileysLogger } from './baileys-logger';+import { BaileysVersionResolver } from './baileys-version-resolver';import type { BaileysEvents } from './baileys-events';import type { BaileysHistory } from './baileys-history';import type { BaileysSessionStore } from './baileys-session-store';@@ -120,6 +122,7 @@ export class BaileysLifecycle {private phoneNumber: string | null = null;private pushName: string | null = null;private intentionalClose = false;+ private readonly versionResolver: BaileysVersionResolver;private connecting = false;private reconnectAttempts = 0;private reconnectTimer?: ReturnType<typeof setTimeout>;@@ -128,7 +131,13 @@ export class BaileysLifecycle {/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */private lib?: typeof BaileysLib;- constructor(private readonly host: BaileysLifecycleHost) {}+ constructor(private readonly host: BaileysLifecycleHost) {+ this.versionResolver = new BaileysVersionResolver({+ authDir: this.host.config.authDir || path.dirname(this.host.authPath),+ sessionId: this.host.config.sessionId,+ logger: this.host.logger,+ });+ }/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */async loadLib(): Promise<typeof BaileysLib> {@@ -180,7 +189,7 @@ export class BaileysLifecycle {}const b = await this.loadLib();const { state, saveCreds } = await b.useMultiFileAuthState(this.host.authPath);- const { version } = await b.fetchLatestBaileysVersion();+ const version = await this.versionResolver.resolve(b);// 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.@@ -781,4 +790,5 @@ 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.tsnew file mode 100644index 000000000..d882c711a--- /dev/null+++ b/src/engine/adapters/baileys-version-resolver.spec.ts@@ -0,0 +1,149 @@+import * as fs from 'fs';+import * as path from 'path';+import { BaileysVersionResolver, DEFAULT_FALLBACK_WA_VERSION } 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;++ const mockLogger = {+ log: jest.fn(),+ warn: jest.fn(),+ };++ const createResolver = () =>+ new BaileysVersionResolver({+ authDir: tempDir,+ sessionId: 'test-session',+ logger: mockLogger,+ });++ beforeEach(() => {+ delete process.env.BAILEYS_WA_VERSION;+ jest.clearAllMocks();+ if (fs.existsSync(tempDir)) {+ fs.rmSync(tempDir, { recursive: true, force: true });+ }+ });++ 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 });+ }+ });++ 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(mockLib as any);++ // Assert+ expect(version).toEqual([2, 3000, 1045340097]);+ expect(mockLib.fetchLatestWaWebVersion).not.toHaveBeenCalled();+ expect(mockLib.fetchLatestBaileysVersion).not.toHaveBeenCalled();+ });++ 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(mockLib as any);++ // Assert+ expect(version).toEqual([2, 3000, 1045340097]);+ });++ 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(),+ };++ // Act+ const version = await resolver.resolve(mockLib as any);++ // 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]);+ });++ 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 }),+ };++ // Act+ const version = await resolver.resolve(mockLib as any);++ // 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]);+ });++ 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');++ const resolver = createResolver();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockRejectedValue(new Error('offline')),+ fetchLatestBaileysVersion: jest.fn().mockRejectedValue(new Error('github 503')),+ };++ // Act+ const version = await resolver.resolve(mockLib as any);++ // 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()+ );+ });++ 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')),+ };++ // Act+ const version = await resolver.resolve(mockLib as any);++ // Assert+ expect(version).toEqual(DEFAULT_FALLBACK_WA_VERSION);+ });+});diff --git a/src/engine/adapters/baileys-version-resolver.ts b/src/engine/adapters/baileys-version-resolver.tsnew file mode 100644index 000000000..774255fae--- /dev/null+++ b/src/engine/adapters/baileys-version-resolver.ts@@ -0,0 +1,156 @@+import * as fs from 'fs';+import * as path from 'path';+import type * as BaileysLib from '@whiskeysockets/baileys';+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 */+export const DEFAULT_FALLBACK_WA_VERSION: WAVersion = [2, 3000, 1045340097];++export interface BaileysVersionResolverOptions {+ authDir: string;+ sessionId: string;+ logger: Pick<LoggerService, 'log' | 'warn'>;+}++/**+ * Resilient WhatsApp Web protocol version resolver.+ *+ * Implements multi-tier resolution:+ * 1. BAILEYS_WA_VERSION operator environment override+ * 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+ */+export class BaileysVersionResolver {+ private readonly cacheFilePath: string;++ constructor(private readonly options: BaileysVersionResolverOptions) {+ this.cacheFilePath = path.join(this.options.authDir, 'last_known_wa_version.json');+ }++ async resolve(b: typeof BaileysLib): Promise<WAVersion> {+ const envVersion = this.resolveFromEnv();+ if (envVersion) {+ return envVersion;+ }++ const waWebVersion = await this.resolveFromWaWeb(b);+ if (waWebVersion) {+ return waWebVersion;+ }++ const baileysVersion = await this.resolveFromBaileys(b);+ if (baileysVersion) {+ return baileysVersion;+ }++ const cachedVersion = this.resolveFromDiskCache();+ if (cachedVersion) {+ return cachedVersion;+ }++ return DEFAULT_FALLBACK_WA_VERSION;+ }++ private resolveFromEnv(): WAVersion | null {+ const raw = process.env.BAILEYS_WA_VERSION?.trim();+ if (!raw) {+ 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;+ }++ this.options.logger.warn(`Invalid BAILEYS_WA_VERSION format "${raw}", expected "major.minor.patch"`, {+ sessionId: this.options.sessionId,+ });+ return null;+ }++ private async resolveFromWaWeb(b: typeof BaileysLib): 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;+ this.saveCachedVersion(version);+ return version;+ }+ } catch (err) {+ this.options.logger.warn(`fetchLatestWaWebVersion failed: ${err instanceof Error ? err.message : String(err)}`, {+ sessionId: this.options.sessionId,+ });+ }++ return null;+ }++ private async resolveFromBaileys(b: typeof BaileysLib): 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;+ this.saveCachedVersion(version);+ return version;+ }+ } catch (err) {+ this.options.logger.warn(`fetchLatestBaileysVersion failed: ${err instanceof Error ? err.message : String(err)}`, {+ sessionId: this.options.sessionId,+ });+ }++ return null;+ }++ private resolveFromDiskCache(): WAVersion | null {+ try {+ if (!fs.existsSync(this.cacheFilePath)) {+ return null;+ }++ const content = fs.readFileSync(this.cacheFilePath, 'utf8');+ const parsed = 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;+ }+ } catch {+ // Non-blocking disk read fallback+ }++ return null;+ }++ private saveCachedVersion(version: WAVersion): void {+ try {+ const dir = path.dirname(this.cacheFilePath);+ if (!fs.existsSync(dir)) {+ fs.mkdirSync(dir, { recursive: true });+ }+ fs.writeFileSync(this.cacheFilePath, JSON.stringify(version), 'utf8');+ } catch {+ // Non-blocking best-effort caching+ }+ }++ private isValidVersion(v: unknown): v is WAVersion {+ return Array.isArray(v) && v.length === 3 && v.every(n => typeof n === 'number' && !isNaN(n) && n >= 0);+ }+}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex a2930a19b..56080edcc 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -612,13 +612,13 @@ 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 {- fetchLatestBaileysVersion: jest.Mock;+ useMultiFileAuthState: jest.Mock;};- baileys.fetchLatestBaileysVersion.mockRejectedValueOnce(new Error('network error'));+ baileys.useMultiFileAuthState.mockRejectedValueOnce(new Error('network error'));const onError = jest.fn();const adapter = newAdapter();diff --git a/test/__mocks__/@whiskeysockets/baileys.ts b/test/__mocks__/@whiskeysockets/baileys.tsindex 310f9492e..ae7fb25be 100644--- a/test/__mocks__/@whiskeysockets/baileys.ts+++ b/test/__mocks__/@whiskeysockets/baileys.ts@@ -12,6 +12,11 @@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 };