Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): skip the version lookup once teardown has started (#1850)
Yudhi Armyndharis0d8c86480986
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a63683801..6a602c7fe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -32,6 +32,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Skip or cancel the Baileys version lookup of a session stopped while it connects, so no proxy dispatcher outlives it.- Stop a request left over from before logout from reloading the dashboard login form.- Stop a dashboard Logs export from downloading rows after sign-out when its last page was throttled.- Stop reopening a just-saved dashboard template from loading its old values, which a second save wrote back.diff --git a/src/engine/adapters/baileys-lifecycle.spec.ts b/src/engine/adapters/baileys-lifecycle.spec.tsindex df8f958b8..012170ba3 100644--- a/src/engine/adapters/baileys-lifecycle.spec.ts+++ b/src/engine/adapters/baileys-lifecycle.spec.ts@@ -1,5 +1,9 @@jest.mock('qrcode', () => ({ toDataURL: jest.fn() }));-jest.mock('@whiskeysockets/baileys', () => ({ __esModule: true, initAuthCreds: jest.fn() }));+jest.mock('@whiskeysockets/baileys', () => ({+ __esModule: true,+ initAuthCreds: jest.fn(),+ makeCacheableSignalKeyStore: jest.fn((keys: unknown) => keys),+}));jest.mock('./baileys-auth-store', () => ({useAtomicMultiFileAuthState: jest.fn().mockRejectedValue(new Error('stop after auth load')),}));@@ -9,6 +13,7 @@ import { EngineStatus } from '../interfaces/whatsapp-engine.interface';import * as BaileysLib from '@whiskeysockets/baileys';import { useAtomicMultiFileAuthState } from './baileys-auth-store';import { BaileysLifecycle, type BaileysLifecycleHost } from './baileys-lifecycle';+import type { BaileysVersionResolver, ResolveOptions } from './baileys-version-resolver';describe('BaileysLifecycle.connect', () => {it('loads the auth state through the atomic store with the session auth dir, library and logger', async () => {@@ -234,4 +239,68 @@ describe('BaileysLifecycle proxy fetch dispatcher', () => {expect(fresh).not.toBe(dispatcher);await fresh?.close();});++ describe('teardown while connecting', () => {+ const settle = () => new Promise(resolve => setImmediate(resolve));+ function connecting() {+ const engine = lifecycle();+ engine.sock = null;+ type AuthState = Awaited<ReturnType<typeof useAtomicMultiFileAuthState>>;+ let releaseAuth: ((value: AuthState) => void) | undefined;+ jest.mocked(useAtomicMultiFileAuthState).mockImplementationOnce(+ () =>+ new Promise<AuthState>(resolve => {+ releaseAuth = resolve;+ }),+ );+ const resolver = (engine as unknown as { versionResolver: BaileysVersionResolver }).versionResolver;+ const resolve = jest.spyOn(resolver, 'resolve');+ const authRequested = async () => {+ while (!releaseAuth) await settle();+ };+ const loadAuth = () =>+ releaseAuth?.({ state: { creds: {}, keys: {} }, saveCreds: jest.fn() } as unknown as AuthState);+ return { engine, resolve, authRequested, loadAuth };+ }++ // The teardown closed the only dispatcher there was; a lookup after it would build one nothing+ // closes and send a stopped session's requests through its proxy.+ it('skips the version lookup when the session stops while its auth state loads', async () => {+ const { engine, resolve, authRequested, loadAuth } = connecting();+ const init = engine.initialize();+ await authRequested();+ await engine.disconnect();+ loadAuth();+ await init;++ expect(resolve).not.toHaveBeenCalled();+ expect((engine as unknown as { dispatcher?: unknown }).dispatcher).toBeUndefined();+ expect(engine.sock).toBeNull();+ });++ it('aborts the version lookup when the session stops during it', async () => {+ const { engine, resolve, authRequested, loadAuth } = connecting();+ let signal: AbortSignal | undefined;+ let finish: ((version: [number, number, number]) => void) | undefined;+ resolve.mockImplementationOnce(+ (_lib, options?: ResolveOptions) =>+ new Promise(done => {+ signal = options?.signal;+ finish = done;+ }),+ );+ const init = engine.initialize();+ await authRequested();+ loadAuth();+ while (!finish) await settle();+ expect(signal?.aborted).toBe(false);++ await engine.destroy();++ expect(signal?.aborted).toBe(true);+ finish([2, 3000, 1]);+ await init;+ expect(engine.sock).toBeNull();+ });+ });});diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex 4c11622f1..03f591810 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -194,7 +194,11 @@ export class BaileysLifecycle {private qrRenderSequence = 0;private phoneNumber: string | null = null;private pushName: string | null = null;- private intentionalClose = false;+ /** Aborted by disconnect()/logout()/destroy(); the adapter is single-use from then on. */+ private readonly teardown = new AbortController();+ private get intentionalClose(): boolean {+ return this.teardown.signal.aborted;+ }private readonly versionResolver: BaileysVersionResolver;private connecting = false;private reconnectAttempts = 0;@@ -311,7 +315,16 @@ export class BaileysLifecycle {}const b = await this.loadLib();const { state, saveCreds } = await useAtomicMultiFileAuthState(this.host.authPath, b, this.host.logger);- const version = await this.versionResolver.resolve(b, { dispatcher: this.fetchDispatcher() });+ // A teardown during those loads already closed the dispatcher: the lookup would build a new one+ // that nothing closes and send the stopped session's requests through its proxy. One during the+ // lookup aborts it, and the latch check below bails.+ if (this.intentionalClose) {+ return;+ }+ const version = await this.versionResolver.resolve(b, {+ dispatcher: this.fetchDispatcher(),+ signal: this.teardown.signal,+ });// 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.@@ -856,7 +869,7 @@ export class BaileysLifecycle {}disconnect(): Promise<void> {- this.intentionalClose = true;+ this.teardown.abort();if (this.reconnectTimer) {clearTimeout(this.reconnectTimer);this.reconnectTimer = undefined;@@ -874,7 +887,7 @@ export class BaileysLifecycle {}async logout(): Promise<void> {- this.intentionalClose = true;+ this.teardown.abort();if (this.reconnectTimer) {clearTimeout(this.reconnectTimer);this.reconnectTimer = undefined;@@ -1035,7 +1048,7 @@ export class BaileysLifecycle {}destroy(): Promise<void> {- this.intentionalClose = true;+ this.teardown.abort();if (this.reconnectTimer) {clearTimeout(this.reconnectTimer);this.reconnectTimer = undefined;diff --git a/src/engine/adapters/baileys-version-resolver.spec.ts b/src/engine/adapters/baileys-version-resolver.spec.tsindex 2df78c3eb..1e213b8d0 100644--- a/src/engine/adapters/baileys-version-resolver.spec.ts+++ b/src/engine/adapters/baileys-version-resolver.spec.ts@@ -54,6 +54,48 @@ describe('BaileysVersionResolver', () => {expect(version).toEqual([2, 3000, 1043857760]);expect(mockLib.fetchLatestWaWebVersion).toHaveBeenCalledWith(expect.objectContaining({ dispatcher }));});++ // A torn-down session discards the result, so its lookup must not go on making proxied requests+ // or warn about falling back.+ it('cancels the in-flight lookup and tries nothing further once the session is torn down', async () => {+ fs.writeFileSync(path.join(tmpDir, 'last_known_wa_version.json'), JSON.stringify([2, 3000, 1]));+ const teardown = new AbortController();+ let requestSignal: AbortSignal | undefined;+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn((options: { signal: AbortSignal }) => {+ requestSignal = options.signal;+ teardown.abort();+ return Promise.resolve({ isLatest: false, version: [2, 3000, 0], error: new Error('aborted') });+ }),+ fetchLatestBaileysVersion: jest.fn(),+ };++ await createResolver().resolve(asBaileysLib(mockLib), { dispatcher: {}, signal: teardown.signal });++ expect(requestSignal?.aborted).toBe(true);+ expect(mockLib.fetchLatestBaileysVersion).not.toHaveBeenCalled();+ expect(mockLogger.warn).not.toHaveBeenCalled();+ });++ it('skips the cache and fallback warnings when the session is torn down during the second lookup', async () => {+ fs.writeFileSync(path.join(tmpDir, 'last_known_wa_version.json'), JSON.stringify([2, 3000, 1]));+ const teardown = new AbortController();+ const mockLib = {+ fetchLatestWaWebVersion: jest.fn().mockRejectedValue(new Error('unreachable')),+ fetchLatestBaileysVersion: jest.fn(() => {+ teardown.abort();+ return Promise.resolve({ isLatest: false, version: [2, 3000, 0], error: new Error('client closed') });+ }),+ };++ await createResolver().resolve(asBaileysLib(mockLib), { dispatcher: {}, signal: teardown.signal });++ expect(mockLib.fetchLatestBaileysVersion).toHaveBeenCalledTimes(1);+ expect(mockLogger.warn).toHaveBeenCalledTimes(1);+ expect(mockLogger.warn).toHaveBeenCalledWith('fetchLatestWaWebVersion failed: unreachable', {+ sessionId: 'test-session',+ });+ });});describe('Tier 1: BAILEYS_WA_VERSION environment variable override', () => {diff --git a/src/engine/adapters/baileys-version-resolver.ts b/src/engine/adapters/baileys-version-resolver.tsindex 3d2dc0c4a..02e9f9de1 100644--- a/src/engine/adapters/baileys-version-resolver.ts+++ b/src/engine/adapters/baileys-version-resolver.ts@@ -25,6 +25,11 @@ export interface BaileysVersionResolverOptions {export interface ResolveOptions {/** Global-fetch dispatcher for the session proxy; undefined on an unproxied session (direct). */dispatcher?: unknown;+ /**+ * Aborted when the session is torn down. The caller discards the result then, so the lookup stops+ * without further requests or fallback warnings, and the in-flight WhatsApp Web request is cancelled.+ */+ signal?: AbortSignal;}/**@@ -56,11 +61,17 @@ export class BaileysVersionResolver {if (waWebVersion) {return waWebVersion;}+ if (resolveOptions.signal?.aborted) {+ return DEFAULT_FALLBACK_WA_VERSION;+ }const baileysVersion = await this.resolveFromBaileys(b, resolveOptions);if (baileysVersion) {return baileysVersion;}+ if (resolveOptions.signal?.aborted) {+ return DEFAULT_FALLBACK_WA_VERSION;+ }const cachedVersion = this.resolveFromDiskCache();if (cachedVersion) {@@ -110,7 +121,10 @@ export class BaileysVersionResolver {try {const fetchOptions = {...(resolveOptions.dispatcher ? { dispatcher: resolveOptions.dispatcher } : {}),- signal: AbortSignal.timeout(this.timeoutMs),+ signal: AbortSignal.any([+ AbortSignal.timeout(this.timeoutMs),+ ...(resolveOptions.signal ? [resolveOptions.signal] : []),+ ]),} as unknown as RequestInit;const result = await b.fetchLatestWaWebVersion(fetchOptions);@@ -120,12 +134,18 @@ export class BaileysVersionResolver {this.saveCachedVersion(version);return version;}+ if (resolveOptions.signal?.aborted) {+ return null;+ }this.options.logger.warn(`fetchLatestWaWebVersion returned isLatest=false (${JSON.stringify(result?.version)}); advancing to next tier`,{ sessionId: this.options.sessionId },);} catch (err) {+ if (resolveOptions.signal?.aborted) {+ return null;+ }this.options.logger.warn(`fetchLatestWaWebVersion failed: ${err instanceof Error ? err.message : String(err)}`, {sessionId: this.options.sessionId,});@@ -168,12 +188,18 @@ export class BaileysVersionResolver {this.saveCachedVersion(version);return version;}+ if (resolveOptions.signal?.aborted) {+ return null;+ }this.options.logger.warn(`fetchLatestBaileysVersion returned isLatest=false (${JSON.stringify(result?.version)}); advancing to next tier`,{ sessionId: this.options.sessionId },);} catch (err) {+ if (resolveOptions.signal?.aborted) {+ return null;+ }this.options.logger.warn(`fetchLatestBaileysVersion failed: ${err instanceof Error ? err.message : String(err)}`,{ sessionId: this.options.sessionId },