Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): drop QR and pairing state that outlived the socket

Yudhi Armyndharis605f3bc381de
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e50c77c61..7cb425302 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A WhatsApp-initiated unlink now clears the session's `phone` the way an operator logout does, so a restart
no longer relaunches the unlinked session into a QR nobody asked for; the next successful link sets it
again.
+- Baileys: a pairing request on a socket that has already begun closing answers the documented 409 instead of
+ a 500, and no longer writes a half-registered identity into the session's stored credentials.
+- Both engines drop the cached QR as soon as its socket or page dies, so `GET /sessions/{sessionId}/qr`
+ answers its documented 400 instead of 200 with a code that can no longer be scanned.
+
+### Documentation
+
+- The upgrade runbook and the migration guide state the `docker-compose.dev.yml` caveat before the first
+ `docker compose` command instead of after it, and name the `openwa` service substitution it needs.
## [0.23.2] - 2026-08-23
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index 4e831700e..5d73ce42d 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -770,8 +770,12 @@ export class BaileysLifecycle {
/**
* Cheap local liveness check for the session watchdog. Genuine dead-connection detection is owned
* by Baileys' built-in keepalive, which surfaces a close event (408) within ~35 s of a silent
- * drop — and the close handler above drops the status to INITIALIZING for the whole reconnect
- * backoff, so READY + a live socket is sufficient here.
+ * drop — and the close handler above then drops the status to INITIALIZING for the whole reconnect
+ * backoff, so READY + a live socket is sufficient here. Note the status trails the dead transport:
+ * Baileys emits that close only after `await ws.close()` resolves, which on a black-holed socket
+ * waits out ws's 30 s close timeout, so this reports live for that window too. Acceptable for the
+ * watchdog, whose next interval catches it; NOT sufficient for a request guard, which is why
+ * requestPairingCode below also tests `ws.isOpen`.
*/
// eslint-disable-next-line @typescript-eslint/require-await
async probeLiveness(): Promise<boolean> {
@@ -783,14 +787,22 @@ export class BaileysLifecycle {
}
/**
- * Gated on QR_READY, not on the socket merely existing: `this.sock` is assigned the moment makeWASocket
- * returns, before the WebSocket is open, and Baileys' sendNode throws a raw Boom 428 until it is. QR_READY
- * is set from the post-handshake `connection.update { qr }` event and every close drops it, so it is the
- * exact window a pairing request can succeed in. Same guard, for the same reason, as the whatsapp-web.js
- * engine's requestPairingCode.
+ * Gated on QR_READY AND a live WebSocket, not on the socket merely existing: `this.sock` is assigned the
+ * moment makeWASocket returns, before the WebSocket is open, and Baileys' sendNode throws a raw Boom 428
+ * until it is. QR_READY is set from the post-handshake `connection.update { qr }` event, so it opens the
+ * window; it does not close it promptly, which is why the status alone is not enough. Baileys emits its
+ * `connection.update { connection: 'close' }` only after `await ws.close()` resolves, and `ws` leaves a
+ * black-holed socket in CLOSING for its 30 s close timeout, so the status keeps reading QR_READY for up to
+ * half a minute after the connection stopped carrying anything. `ws.isOpen` is the same predicate Baileys'
+ * own sendRawMessage tests and the same liveness check handleQrCode makes before publishing. It matters
+ * beyond the status code here: requestPairingCode writes `creds.me` and emits `creds.update`, which we
+ * persist, BEFORE it sends, so a request in that window leaves the next connect trying to log in as a
+ * device that was never registered. The whatsapp-web.js engine needs no equivalent operand: its page and
+ * browser death listeners fire handlePuppeteerDeath, which drops the status in the same tick, so there
+ * the status is not the stale value it is here.
*/
async requestPairingCode(phoneNumber: string): Promise<string> {
- if (!this.sock || this.status !== EngineStatus.QR_READY) {
+ if (!this.sock?.ws.isOpen || this.status !== EngineStatus.QR_READY) {
throw new EngineNotReadyError('Session is not waiting to be linked. Start it and wait for the QR stage.');
}
return this.sock.requestPairingCode(phoneNumber);
@@ -814,6 +826,15 @@ export class BaileysLifecycle {
if (this.status === status) {
return;
}
+ // The cached QR belongs to the socket that produced it, so it dies with the QR_READY window.
+ // Enforced in the funnel rather than at each exit: every close sub-branch (intentional, 401, 440,
+ // 403, transient), the accepted link and every teardown route through here, and the exits that
+ // did not clear it by hand kept serving a dead QR over GET /qr for the whole reconnect backoff.
+ // Safe after the no-op guard above: a non-null qrCode implies QR_READY, so an unchanged status
+ // that is not QR_READY already has a null cache.
+ if (status !== EngineStatus.QR_READY) {
+ this.qrCode = null;
+ }
this.status = status;
this.host.getOnStateChanged()?.(status);
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 4ea16c17a..f95a47e28 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -624,6 +624,42 @@ describe('BaileysAdapter lifecycle & status', () => {
return adapter;
}
+ // Baileys emits its close update only after `await ws.close()` resolves, and ws parks a black-holed
+ // socket in CLOSING for its 30 s close timeout, so QR_READY outlives the usable connection. Sending in
+ // that window makes Baileys throw a raw Boom 428, which with no global exception filter surfaces as a
+ // 500 instead of the documented 409, after it has already written creds.me and emitted creds.update.
+ it('requestPairingCode rejects on a closing socket while the status still reads QR_READY', async () => {
+ const adapter = await initializeAtQrReady();
+ fakeSock.ws.isOpen = false; // ws.close() has run; the close event has not landed yet
+
+ // The status is genuinely still QR_READY, so the rejection can only come from the liveness check.
+ expect(adapter.getStatus()).toBe(EngineStatus.QR_READY);
+ await expect(adapter.requestPairingCode('628999')).rejects.toBeInstanceOf(EngineNotReadyError);
+ // Proves the library is never entered, so creds.me / creds.update / saveCreds never fire.
+ expect(fakeSock.requestPairingCode).not.toHaveBeenCalled();
+ });
+
+ // The cached QR belongs to the socket that produced it: once the socket closes nothing can accept that
+ // scan, so GET /qr must answer its documented 400 rather than 200 with a code that can never link.
+ it.each([
+ ['a transient close', 515, EngineStatus.INITIALIZING],
+ ['a terminal close', 403, EngineStatus.FAILED],
+ ])('drops the cached QR on %s', async (_label, statusCode, expected) => {
+ const adapter = await initializeAtQrReady();
+ expect(adapter.getQRCode()).not.toBeNull();
+ jest.useFakeTimers({ doNotFake: ['setImmediate'] });
+ try {
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: { output: { statusCode } } },
+ });
+ expect(adapter.getStatus()).toBe(expected);
+ expect(adapter.getQRCode()).toBeNull();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
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'] });
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index bdf9df3fa..49eb1d725 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -2118,6 +2118,31 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
expect(onQRCode).toHaveBeenCalledTimes(1);
});
+ // The cached QR belongs to the page that produced it. A Chromium crash or tab close while the operator
+ // is looking at the QR is the reachable vector: handlePuppeteerDeath fires at QR_READY, the session
+ // keeps the engine registered across its reconnect backoff, and GET /qr kept answering 200 with a code
+ // whose page is gone instead of the documented 400.
+ it('drops the cached QR when the page dies at QR_READY', async () => {
+ (qrcode.toDataURL as unknown as jest.Mock).mockClear();
+ const adapter = newAdapter();
+ const pupPage = Object.assign(new EventEmitter(), { evaluate: jest.fn().mockResolvedValue(true) });
+ const { client } = attachFakeClient(adapter, { pupPage: pupPage as unknown as FakeClient['pupPage'] });
+ // The death listeners are armed by runInitAttempt, not by setupEventHandlers.
+ (adapter as unknown as { attachPuppeteerLifecycleListeners: () => void }).attachPuppeteerLifecycleListeners();
+ const qrDone = deferredVoid();
+ (adapter as unknown as { callbacks: { onQRCode: jest.Mock } }).callbacks.onQRCode = jest.fn(() => qrDone.resolve());
+
+ client.emit('qr', '2@abc');
+ await qrDone.promise;
+ expect(adapter.getStatus()).toBe(EngineStatus.QR_READY);
+ expect(adapter.getQRCode()).not.toBeNull();
+
+ pupPage.emit('close');
+
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(adapter.getQRCode()).toBeNull();
+ });
+
// #982: whatsapp-web.js does NOT destroy the client on LOGOUT — it deletes the auth profile and
// re-runs inject() on the SAME browser, which re-arms the QR handler. The session lifecycle only
// tears the engine down after the reconnect backoff (~5s by default, operator-raisable to 300s), so
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index f29947603..73a322a21 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -722,6 +722,13 @@ export class WwebjsLifecycle {
if (status === EngineStatus.DISCONNECTED) {
this.disconnectReported = true;
}
+ // The cached QR belongs to the page that produced it, so it dies with the QR_READY window. Same
+ // funnel placement as the Baileys engine: only the 'authenticated' and init-retry exits cleared the
+ // cache by hand, so a browser or page death, a failed init, an auth failure and teardown all left a
+ // dead QR to be served over GET /qr for the whole reconnect backoff.
+ if (status !== EngineStatus.QR_READY) {
+ this.qrCode = null;
+ }
this.status = status;
this.host.getCallbacks().onStateChanged?.(status);
this.host.emitState(status);