Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): clear Baileys auth state on logout so re-linking shows a fresh QR (#453)
Ulises Cuñe418d8825ca43
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 3b7b1d483..40a888ab5 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -1,4 +1,6 @@import { EventEmitter } from 'events';+import * as fs from 'fs';+import * as path from 'path';jest.mock('../../common/media/load-remote-media', () => ({loadRemoteMediaBuffer: jest.fn(),@@ -163,6 +165,43 @@ describe('BaileysAdapter lifecycle & status', () => {expect(makeWASocket).not.toHaveBeenCalled(); // no reconnect});+ it('on a logged-out close: clears the on-disk auth dir so a fresh connect shows a new QR', async () => {+ // Root cause of the "QR never appears after logout" bug: the now-invalid multi-file auth dir was+ // left on disk, so the next connect() reloaded the dead creds and Baileys retried them instead of+ // emitting a QR. A terminal loggedOut MUST wipe the auth dir.+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ try {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 401 } } },+ });+ await new Promise(r => setImmediate(r)); // let the fire-and-forget clearAuthState() settle+ expect(rmSpy).toHaveBeenCalledWith(+ path.join('./data/baileys', 'sess-1'),+ expect.objectContaining({ recursive: true, force: true }),+ );+ } finally {+ rmSpy.mockRestore();+ }+ });++ it('logout() clears the on-disk auth dir (stale creds would otherwise block re-linking)', async () => {+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ try {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ await adapter.logout();+ expect(rmSpy).toHaveBeenCalledWith(+ path.join('./data/baileys', 'sess-1'),+ expect.objectContaining({ recursive: true, force: true }),+ );+ } finally {+ rmSpy.mockRestore();+ }+ });+it('on a recoverable close: reconnects (re-creates the socket) and does NOT fire onDisconnected', async () => {const onDisconnected = jest.fn();const adapter = newAdapter();diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 78ba580a9..6de44fc36 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -1,3 +1,4 @@+import * as fs from 'fs';import * as path from 'path';import * as qrcode from 'qrcode';import type * as BaileysLib from '@whiskeysockets/baileys';@@ -314,8 +315,12 @@ export class BaileysAdapter implements IWhatsAppEngine {}if (statusCode === this.lib?.DisconnectReason.loggedOut) {- // Credentials invalidated — terminal. Re-linking requires a fresh QR/pairing.+ // Credentials invalidated — terminal. Re-linking requires a fresh QR/pairing, so the now-dead+ // multi-file auth dir MUST be wiped: otherwise the next connect() reloads the stale creds and+ // Baileys silently retries them instead of emitting a new QR, leaving the session stuck (no QR).this.setStatus(EngineStatus.DISCONNECTED);+ this.sock = null;+ void this.clearAuthState();this.callbacks.onDisconnected?.('logged out');return;}@@ -390,8 +395,25 @@ export class BaileysAdapter implements IWhatsAppEngine {this.sock = null;this.setStatus(EngineStatus.DISCONNECTED);await this.config.messageStore?.clearSession(this.config.sessionId).catch(() => undefined);- // leaves the multi-file auth dir on disk; a fresh link overwrites it. Add fs cleanup if- // stale creds ever block re-linking.+ // Wipe the multi-file auth dir so a fresh link starts clean — stale creds would otherwise be+ // reloaded on the next connect() and block re-linking (Baileys retries them, no QR emitted).+ await this.clearAuthState();+ }++ /**+ * Delete this session's on-disk multi-file auth state (`authDir/sessionId`). Required after a terminal+ * logout: Baileys would otherwise reload the now-invalid creds on the next connect() and retry them+ * instead of emitting a fresh QR, leaving re-linking stuck. `force` makes a missing dir a no-op.+ */+ private async clearAuthState(): Promise<void> {+ try {+ await fs.promises.rm(this.authPath, { recursive: true, force: true });+ this.logger.log('Cleared Baileys auth state', { authPath: this.authPath });+ } catch (err) {+ this.logger.warn('Failed to clear Baileys auth state', {+ error: err instanceof Error ? err.message : String(err),+ });+ }}destroy(): Promise<void> {