Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): keep QR_READY off sockets that cannot take a pairing request

Yudhi Armyndharis584b9165161b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5f8f08cb6..25232e4ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Baileys: requesting a pairing code before the session reaches `qr_ready` answers the documented 409 instead
of a 500 with a `Connection Closed` stack trace, the same guard the whatsapp-web.js engine already carried.
Thanks @m7fz7.
+- Baileys: once WhatsApp accepts a QR scan or pairing code the session reports `authenticating` until the
+ restart completes, as whatsapp-web.js does, so a repeat pairing request in that window answers 409 instead
+ of overwriting the linked identity.
+- Baileys: a QR that finishes rendering after its socket dropped is discarded instead of marking the session
+ `qr_ready`.
## [0.23.2] - 2026-08-23
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index 1754c9357..da996cdf5 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -350,10 +350,11 @@ export class BaileysLifecycle {
private handleConnectionUpdate(update: {
connection?: string;
qr?: string;
+ isNewLogin?: boolean;
lastDisconnect?: { error?: unknown };
reachoutTimeLock?: { isActive?: boolean; timeEnforcementEnds?: Date; enforcementType?: string };
}): void {
- const { connection, qr, lastDisconnect, reachoutTimeLock } = update;
+ const { connection, qr, isNewLogin, lastDisconnect, reachoutTimeLock } = update;
// Arrives on its own update (no `connection` key) both when WhatsApp pushes a change and when
// probeAccountRestriction() pulls the current state — Baileys routes its own query result back
@@ -368,6 +369,14 @@ export class BaileysLifecycle {
void this.handleQrCode(qr);
}
+ if (isNewLogin) {
+ // WhatsApp accepted the QR scan or pairing code: it closes with 515 next and the reconnect
+ // opens READY. Left at QR_READY, a repeat pairing request in that window would pass the guard
+ // and overwrite the just-linked creds.me. AUTHENTICATING is what whatsapp-web.js reports here.
+ this.qrCode = null;
+ this.setStatus(EngineStatus.AUTHENTICATING);
+ }
+
if (connection === 'connecting') {
this.setStatus(EngineStatus.INITIALIZING);
}
@@ -550,8 +559,15 @@ export class BaileysLifecycle {
/** Render the raw Baileys QR ref to a PNG data URL, then publish it (mirrors the whatsapp-web.js engine). */
private async handleQrCode(qr: string): Promise<void> {
+ const sock = this.sock;
try {
- this.qrCode = await qrcode.toDataURL(qr);
+ const rendered = await qrcode.toDataURL(qr);
+ // The socket can drop while the QR renders. The close handler has already moved the status on,
+ // and publishing now would stamp QR_READY on a dead socket until the backoff reconnect.
+ if (this.sock !== sock || !sock?.ws.isOpen) {
+ return;
+ }
+ this.qrCode = rendered;
this.setStatus(EngineStatus.QR_READY);
this.host.getOnQRCode()?.(this.qrCode);
} catch (error) {
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index a041926a2..210a2703c 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -1,6 +1,7 @@
import { EventEmitter } from 'events';
import * as fs from 'fs';
import * as path from 'path';
+import * as qrcode from 'qrcode';
jest.mock('../../common/media/load-remote-media', () => ({
loadRemoteMediaBuffer: jest.fn(),
@@ -19,6 +20,8 @@ class FakeSock extends EventEmitter {
};
public emitter = new EventEmitter();
public user: { id: string; name?: string } | undefined;
+ // Baileys' WebSocketClient; the lifecycle reads isOpen after an await to detect a drop in between.
+ public ws = { isOpen: true };
public requestPairingCode = jest.fn().mockResolvedValue('ABCD-EFGH');
public end = jest.fn();
public logout = jest.fn().mockResolvedValue(undefined);
@@ -85,6 +88,12 @@ class FakeSock extends EventEmitter {
const fakeSock = new FakeSock();
const saveCreds = jest.fn().mockResolvedValue(undefined);
+// Real rendering, wrapped so a test can await the exact promise the lifecycle is waiting on.
+jest.mock('qrcode', () => {
+ const actual = jest.requireActual<typeof import('qrcode')>('qrcode');
+ return { ...actual, toDataURL: jest.fn().mockImplementation(actual.toDataURL) };
+});
+
jest.mock('@whiskeysockets/baileys', () => ({
__esModule: true,
default: jest.fn(() => {
@@ -195,6 +204,7 @@ function firstEditedMessage(callback: jest.Mock): EditedMessage {
describe('BaileysAdapter lifecycle & status', () => {
beforeEach(() => {
fakeSock.user = undefined;
+ fakeSock.ws.isOpen = true;
fakeSock.resetEmitter(); // drop listeners from previous test's initialize()
jest.clearAllMocks();
});
@@ -593,6 +603,69 @@ describe('BaileysAdapter lifecycle & status', () => {
expect(fakeSock.requestPairingCode).toHaveBeenCalledWith('628999');
});
+ /** Initialize and fire a QR update, resolving once the lifecycle has published it (rendering is async). */
+ async function initializeAtQrReady(): Promise<BaileysAdapter> {
+ let resolveQr!: () => void;
+ const qrPublished = new Promise<void>(resolve => {
+ resolveQr = resolve;
+ });
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({ onQRCode: () => resolveQr() }));
+ fakeSock.fire('connection.update', { qr: 'QR-STRING' });
+ await qrPublished;
+ expect(adapter.getStatus()).toBe(EngineStatus.QR_READY);
+ return adapter;
+ }
+
+ it('a drop after the QR was published moves the status off QR_READY, so requestPairingCode rejects again', async () => {
+ const adapter = await initializeAtQrReady();
+ jest.useFakeTimers({ doNotFake: ['setImmediate'] });
+ try {
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: { output: { statusCode: 515 } } },
+ });
+ expect(adapter.getStatus()).toBe(EngineStatus.INITIALIZING);
+ await expect(adapter.requestPairingCode('628999')).rejects.toBeInstanceOf(EngineNotReadyError);
+ expect(fakeSock.requestPairingCode).not.toHaveBeenCalled();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('discards a QR that finished rendering after the socket dropped', async () => {
+ const onQRCode = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({ onQRCode }));
+ fakeSock.fire('connection.update', { qr: 'QR-STRING' });
+ // The drop lands while the render is in flight: Baileys closes its WebSocket before it emits.
+ fakeSock.ws.isOpen = false;
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: { output: { statusCode: 515 } } },
+ });
+ // The lifecycle's continuation was queued on this promise before ours, so it has run by now.
+ await (qrcode.toDataURL as unknown as jest.Mock).mock.results[0].value;
+ expect(adapter.getStatus()).toBe(EngineStatus.INITIALIZING);
+ expect(adapter.getQRCode()).toBeNull();
+ expect(onQRCode).not.toHaveBeenCalled();
+ await expect(adapter.requestPairingCode('628999')).rejects.toBeInstanceOf(EngineNotReadyError);
+ await adapter.disconnect(); // clears the pending reconnect timer
+ });
+
+ it('moves to AUTHENTICATING and drops the QR once WhatsApp accepts the link, so a repeat pairing request rejects', async () => {
+ const adapter = await initializeAtQrReady();
+ fakeSock.fire('connection.update', { isNewLogin: true, qr: undefined });
+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);
+ expect(adapter.getQRCode()).toBeNull();
+ await expect(adapter.requestPairingCode('628999')).rejects.toBeInstanceOf(EngineNotReadyError);
+ expect(fakeSock.requestPairingCode).not.toHaveBeenCalled();
+ // The restart that follows still lands on READY.
+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
+ fakeSock.fire('connection.update', { connection: 'open' });
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ });
+
it('persists creds: subscribes saveCreds to creds.update', async () => {
const adapter = newAdapter();
await adapter.initialize(noopCallbacks({}));