Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): keep the pairing guard closed once a link is accepted
Yudhi Armyndharis8f9e0aa3b945
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1812b77c8..5a7334001 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,9 +15,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Changed- `POST /sessions/{sessionId}/pairing-code`: the 409 description in the OpenAPI contract and API reference- now says to wait for `qr_ready`, not `ready`, which on this route means the session is already linked.-- `GET /sessions/{sessionId}/qr` no longer declares a 409: the route reads the engine's cached QR and never- answers one. Its 400 already covers the not-ready case.+ now says to wait for `qr_ready`, not `ready`, which on this route means the session is already linked, and+ to wait for `ready` once a code was accepted.+- `GET /sessions/{sessionId}/qr` no longer declares the engine-not-ready 409: the route reads the engine's+ cached QR and never answers one. Its 400 already covers the not-ready case.### Fixed@@ -27,9 +28,9 @@ 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 insteadof 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: once WhatsApp accepts a QR scan or pairing code the session leaves `qr_ready` (`authenticating`,+ then `initializing` across the restart WhatsApp requests) and ignores the QR refreshes Baileys keeps+ emitting until then, so a repeat pairing request 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`.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 045e19c6c..a6b1d9dcb 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -718,7 +718,7 @@ Request an 8-char pairing code to link via phone number (alternative to QR).`status` is the lowercase session status.-**Errors:** `400` validation, or session not started, or already authenticated · `401` · `403` · `404` not found · `409` session not waiting to be linked yet; wait for `status` to read `qr_ready` and retry+**Errors:** `400` validation, or session not started, or already authenticated · `401` · `403` · `404` not found · `409` session not waiting to be linked yet; wait for `status` to read `qr_ready` and retry (after a code was accepted, wait for `ready` instead)#### POST /api/sessions/:sessionId/presence/subscribediff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 149a52f53..4abb6ef7b 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -278,7 +278,7 @@ curl -X POST "$BASE/api/sessions" -H "X-API-Key: $API_KEY" -H "Content-Type: app### Issue: Session stuck at `authenticating`, never reaches `ready`-> **Engine:** This issue applies to the `whatsapp-web.js` engine only. If you are using `ENGINE_TYPE=baileys`, skip this section.+> **Engine:** This stall applies to the `whatsapp-web.js` engine only. Baileys also reports `authenticating`, but only for the seconds between WhatsApp accepting the link and the restart it requests; it cannot park there, so if you are using `ENGINE_TYPE=baileys`, skip this section.**Symptoms:** After scanning the QR the phone links the device, but the session stays at`authenticating` indefinitely and never becomes `ready`. `GET /sessions/:sessionId/qr` returns 400 whilediff --git a/docs/examples/session-phone-number-pairing.md b/docs/examples/session-phone-number-pairing.mdindex 5a50a8106..e9780f349 100644--- a/docs/examples/session-phone-number-pairing.md+++ b/docs/examples/session-phone-number-pairing.md@@ -95,6 +95,6 @@ After the code is accepted, the OpenWA session should move to a connected/ready- If OpenWA returns `Session is not started`, call `POST /api/sessions/{sessionId}/start` first.- If OpenWA returns `Session is already authenticated`, the account is already linked and no pairing code is needed.-- If OpenWA returns 409 `Session is not waiting to be linked`, the engine is still connecting (or reconnecting after a drop). Wait for `status` to read `qr_ready` and request again.+- If OpenWA returns 409 `Session is not waiting to be linked`, the engine is still connecting (or reconnecting after a drop). Wait for `status` to read `qr_ready` and request again. After a code was accepted the same 409 is answered until the session is `ready`; do not request another code then.- If the phone number is rejected, send digits only in international format, without `+`, spaces, or punctuation.- If you want to create a brand-new WhatsApp account programmatically, that is outside OpenWA's scope. OpenWA only links an existing WhatsApp account.diff --git a/openapi.json b/openapi.jsonindex eb1bd8521..f879001bb 100644--- a/openapi.json+++ b/openapi.json@@ -818,7 +818,7 @@"description": "Session not found"},"409": {- "description": "The session is not waiting to be linked: the engine is still connecting, or reconnecting after a drop, so the request never reached WhatsApp. Wait for `status` to read `qr_ready` and retry. A session that reads `ready` is already linked and answers `400` instead."+ "description": "The session is not waiting to be linked: the engine is still connecting, or reconnecting after a drop, so the request never reached WhatsApp. Wait for `status` to read `qr_ready` and retry. Once a code has been accepted the session moves through `authenticating` and `initializing` to `ready` and answers this until then; wait for `ready` in that case. A session that reads `ready` is already linked and answers `400` instead."}},"summary": "Request an 8-char pairing code to link via phone number (alternative to QR)",diff --git a/src/common/openapi/engine-status-responses.ts b/src/common/openapi/engine-status-responses.tsindex 785135bc1..4b40228b9 100644--- a/src/common/openapi/engine-status-responses.ts+++ b/src/common/openapi/engine-status-responses.ts@@ -29,8 +29,10 @@ export const ENGINE_NOT_READY_409 =*/export const PAIRING_NOT_READY_409 ='The session is not waiting to be linked: the engine is still connecting, or reconnecting after a ' +- 'drop, so the request never reached WhatsApp. Wait for `status` to read `qr_ready` and retry. A ' +- 'session that reads `ready` is already linked and answers `400` instead.';+ 'drop, so the request never reached WhatsApp. Wait for `status` to read `qr_ready` and retry. Once a ' ++ 'code has been accepted the session moves through `authenticating` and `initializing` to `ready` and ' ++ 'answers this until then; wait for `ready` in that case. A session that reads `ready` is already ' ++ 'linked and answers `400` instead.';/*** The catalog and status services pass a `NotFoundException` factory to `EngineRegistry.require()`diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex da996cdf5..4e831700e 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -363,16 +363,19 @@ export class BaileysLifecycle {this.reportReachoutTimelock(reachoutTimeLock);}- if (qr) {+ // Baileys keeps rotating the QR (every 20-60 s) until the socket ends, including after the link+ // was accepted; a refresh in that window must not put the session back at QR_READY.+ if (qr && this.status !== EngineStatus.AUTHENTICATING) {// Baileys hands us the raw QR ref string; render it to a PNG data URL so the stored// value matches the whatsapp-web.js engine's contract (the dashboard does <img src={qrCode}>).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.+ // WhatsApp accepted the QR scan or pairing code. It asks for a restart next (a 515 close, which+ // the branch below turns into INITIALIZING) 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 at the same point.this.qrCode = null;this.setStatus(EngineStatus.AUTHENTICATING);}@@ -562,9 +565,10 @@ export class BaileysLifecycle {const sock = this.sock;try {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) {+ // The socket can drop, or the link be accepted, while the QR renders. The handler has already+ // moved the status on, and publishing now would stamp QR_READY on a dead socket until the+ // backoff reconnect, or reopen the pairing guard on a socket that is committed to a restart.+ if (this.sock !== sock || !sock?.ws.isOpen || this.status === EngineStatus.AUTHENTICATING) {return;}this.qrCode = rendered;diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 210a2703c..4ea16c17a 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -604,13 +604,20 @@ describe('BaileysAdapter lifecycle & status', () => {});/** Initialize and fire a QR update, resolving once the lifecycle has published it (rendering is async). */- async function initializeAtQrReady(): Promise<BaileysAdapter> {+ async function initializeAtQrReady(onQRCode: jest.Mock = jest.fn()): Promise<BaileysAdapter> {let resolveQr!: () => void;const qrPublished = new Promise<void>(resolve => {resolveQr = resolve;});const adapter = newAdapter();- await adapter.initialize(noopCallbacks({ onQRCode: () => resolveQr() }));+ await adapter.initialize(+ noopCallbacks({+ onQRCode: (url: string) => {+ onQRCode(url);+ resolveQr();+ },+ }),+ );fakeSock.fire('connection.update', { qr: 'QR-STRING' });await qrPublished;expect(adapter.getStatus()).toBe(EngineStatus.QR_READY);@@ -654,18 +661,49 @@ describe('BaileysAdapter lifecycle & status', () => {});it('moves to AUTHENTICATING and drops the QR once WhatsApp accepts the link, so a repeat pairing request rejects', async () => {- const adapter = await initializeAtQrReady();+ const onQRCode = jest.fn();+ const adapter = await initializeAtQrReady(onQRCode);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.++ // Baileys keeps rotating the QR until the socket ends; a refresh must not reopen the guard.+ fakeSock.fire('connection.update', { qr: 'QR-REFRESH' });+ expect(qrcode.toDataURL).toHaveBeenCalledTimes(1);+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);+ expect(onQRCode).toHaveBeenCalledTimes(1);++ // WhatsApp then asks for a restart (515): INITIALIZING across the reconnect, READY on open.+ jest.useFakeTimers({ doNotFake: ['setImmediate'] });+ try {+ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 515 } } },+ });+ expect(adapter.getStatus()).toBe(EngineStatus.INITIALIZING);+ } finally {+ jest.useRealTimers();+ }fakeSock.user = { id: '628999:[email protected]', name: 'Me' };fakeSock.fire('connection.update', { connection: 'open' });expect(adapter.getStatus()).toBe(EngineStatus.READY);});+ it('discards a QR whose render finished after WhatsApp accepted the link', async () => {+ const onQRCode = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onQRCode }));+ fakeSock.fire('connection.update', { qr: 'QR-STRING' });+ fakeSock.fire('connection.update', { isNewLogin: true, qr: undefined });+ await (qrcode.toDataURL as unknown as jest.Mock).mock.results[0].value;+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);+ expect(adapter.getQRCode()).toBeNull();+ expect(onQRCode).not.toHaveBeenCalled();+ await expect(adapter.requestPairingCode('628999')).rejects.toBeInstanceOf(EngineNotReadyError);+ });+it('persists creds: subscribes saveCreds to creds.update', async () => {const adapter = newAdapter();await adapter.initialize(noopCallbacks({}));diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.tsindex ebe5e2895..6184c43ba 100644--- a/src/modules/session/session-engine-event-wiring.ts+++ b/src/modules/session/session-engine-event-wiring.ts@@ -89,7 +89,8 @@ export class SessionEngineEventWiring {* `previouslyLinked` is whether the session row carried a phone when this engine started, i.e.* it had completed a link before. A QR from such an engine means the stored credentials are gone* or no longer accepted, and when that happened while the engine was down nothing else in the- * log says so, hence the one-shot warning below.+ * log says so, hence the warning below. One-shot per engine start: a lifecycle reconnect builds a+ * new table from the row, which still carries the phone, and warns again.*/buildCallbacks(id: string,