Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): retry a connection refused at the WebSocket upgrade

Yudhi Armyndharis20a6bdfcd530
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d41e1d1f9..5ae9df737 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The Baileys live path drops contentless protocol traffic (sender-key distributions, message-history notices) instead of delivering it as a bodyless `unknown` `message.received`, matching what the history path already does ([#1568](https://github.com/rmyndharis/OpenWA/issues/1568)). Thanks @berodcdev for the report.
- The group invite-code read, over REST or the MCP `GroupGetInviteCode` tool, requires the OPERATOR role; the code is a transferable join capability, so a VIEWER key can no longer extract it.
-- A Baileys reconnect loop is observable: `lastError` on the session, a `session.reconnect_loop` webhook every fifth attempt, and reconnect metrics ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
+- A Baileys reconnect loop is observable: `lastError` on the session, a `session.reconnect_loop` webhook every fifth attempt, and reconnect metrics; a connection attempt refused at the WebSocket upgrade is closed and retried instead of leaving the session at `initializing` ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
- The dashboard session card keeps the phone number, session id and last-active time while a linked session reconnects, instead of the pairing placeholder ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
- The Sessions page reports a dead live-event feed and re-reads the list once the feed recovers.
- The takeover sweep marks sessions left `ready` or `initializing` by a node that never returned disconnected, regardless of `AUTO_START_SESSIONS`.
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index d799e196e..99767021e 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -1,5 +1,6 @@
import * as path from 'path';
import * as fs from 'fs';
+import type { ClientRequest, IncomingMessage } from 'http';
import type { Agent } from 'https';
import * as qrcode from 'qrcode';
import { HttpsProxyAgent } from 'https-proxy-agent';
@@ -35,6 +36,14 @@ const BAILEYS_BROWSER: [string, string, string] = [
*/
const BAILEYS_LOGOUT_ACK_TIMEOUT_MS = 8_000;
+/**
+ * Backstop for a socket whose WebSocket never leaves CONNECTING, which emits no open, error or close
+ * and so never reaches the reconnect path. Above Baileys' connectTimeoutMs (20 s by default), which
+ * ws already enforces on a handshake that gets no answer, and applied only while the WebSocket is
+ * still connecting, so it never cuts into a login or a socket waiting for its QR to be scanned.
+ */
+const BAILEYS_WS_CONNECTING_DEADLINE_MS = 60_000;
+
/**
* Build the Node-layer agent for a session egress proxy (#859). Both the WhatsApp WebSocket
* (`agent`) and media up/downloads (`fetchAgent`) ride it; credentials stay in the URL and are
@@ -129,6 +138,8 @@ export class BaileysLifecycle {
private connecting = false;
private reconnectAttempts = 0;
private reconnectTimer?: ReturnType<typeof setTimeout>;
+ /** The current socket's BAILEYS_WS_CONNECTING_DEADLINE_MS backstop. */
+ private connectingTimer?: ReturnType<typeof setTimeout>;
/** Date.now() of the last close that scheduled a reconnect — input to the stability reset. */
private lastConnectionCloseAt = 0;
/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */
@@ -293,6 +304,22 @@ export class BaileysLifecycle {
});
this.sock = sock;
+ // Baileys re-emits ws's 'unexpected-response', and any listener there stops ws from aborting the
+ // handshake itself: an upgrade answered with anything but 101 (a 503 from WhatsApp's edge or from a
+ // session proxy) leaves the socket CONNECTING for good, and the session at INITIALIZING with no
+ // retry (#1546). Ending it emits the close that handleConnectionUpdate logs, backs off and retries.
+ // A plain Error on purpose: a Boom carrying the HTTP status would turn a 401, 403 or 440 upgrade
+ // response into the terminal close of the same code.
+ sock.ws.on('unexpected-response', (_req: ClientRequest, res: IncomingMessage) => {
+ void sock.end(new Error(`WebSocket upgrade refused (HTTP ${res.statusCode})`));
+ });
+ this.connectingTimer = setTimeout(() => {
+ if (this.sock === sock && sock.ws.isConnecting) {
+ void sock.end(new Error(`WebSocket still connecting after ${BAILEYS_WS_CONNECTING_DEADLINE_MS} ms`));
+ }
+ }, BAILEYS_WS_CONNECTING_DEADLINE_MS);
+ this.connectingTimer.unref();
+
sock.ev.on(
'creds.update',
() =>
@@ -397,6 +424,7 @@ export class BaileysLifecycle {
}
if (connection === 'open') {
+ clearTimeout(this.connectingTimer);
this.qrCode = null;
this.phoneNumber = this.host.extractPhone(this.sock?.user?.id);
this.pushName = this.sock?.user?.name ?? null;
@@ -416,6 +444,7 @@ export class BaileysLifecycle {
}
if (connection === 'close') {
+ clearTimeout(this.connectingTimer);
const statusCode = (lastDisconnect?.error as { output?: { statusCode?: number } } | undefined)?.output
?.statusCode;
@@ -466,6 +495,7 @@ export class BaileysLifecycle {
this.host.logger.log('Baileys connection dropped; reconnecting', {
sessionId: this.host.config.sessionId,
statusCode,
+ reason: (lastDisconnect?.error as Error | undefined)?.message,
action: 'baileys_connection_dropped',
});
@@ -607,6 +637,7 @@ export class BaileysLifecycle {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = undefined;
}
+ clearTimeout(this.connectingTimer);
void this.sock?.end(undefined);
this.sock = null;
// Cached call handles die with the socket — drop them so a later rejectCall() reports
@@ -687,6 +718,7 @@ export class BaileysLifecycle {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = undefined;
}
+ clearTimeout(this.connectingTimer);
try {
void sourceSock.end(undefined);
} catch {
@@ -772,6 +804,7 @@ export class BaileysLifecycle {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = undefined;
}
+ clearTimeout(this.connectingTimer);
void this.sock?.end(undefined);
this.sock = null;
this.host.liveCalls.clear();
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index cba96b6a0..45ddba9b3 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -20,8 +20,9 @@ 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 };
+ // Baileys' WebSocketClient; the lifecycle reads isOpen after an await to detect a drop in between,
+ // and listens on it for an upgrade response that never became a WebSocket.
+ public ws = Object.assign(new EventEmitter(), { isOpen: true, isConnecting: false });
public requestPairingCode = jest.fn().mockResolvedValue('ABCD-EFGH');
public end = jest.fn();
public logout = jest.fn().mockResolvedValue(undefined);
@@ -82,6 +83,7 @@ class FakeSock extends EventEmitter {
}
resetEmitter(): void {
this.emitter.removeAllListeners();
+ this.ws.removeAllListeners();
}
}
@@ -1198,6 +1200,123 @@ describe('BaileysAdapter reconnect socket teardown (no leak)', () => {
});
});
+// Baileys re-emits ws's 'unexpected-response', which stops ws from aborting the handshake itself: an
+// upgrade answered with a non-101 status leaves the real socket CONNECTING with no open, error or close.
+describe('BaileysAdapter connection attempt stuck at the WebSocket upgrade', () => {
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ const baileys = () => jest.requireMock('@whiskeysockets/baileys') as { default: jest.Mock };
+
+ // The lifecycle's backstop for a socket still connecting, set above Baileys' 20 s connectTimeoutMs.
+ const CONNECTING_DEADLINE_MS = 60_000;
+
+ // initialize() needs real timers (loadLib is a dynamic import), so the socket under test is the one
+ // a reconnect attempt creates under fake timers: its listener and backstop timer are controllable.
+ const startReconnectAttempt = async (over: Partial<EngineEventCallbacks> = {}): Promise<BaileysAdapter> => {
+ fakeSock.user = undefined;
+ fakeSock.resetEmitter();
+ jest.clearAllMocks();
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks(over));
+ jest.useFakeTimers();
+ jest.spyOn(Math, 'random').mockReturnValue(0);
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: { output: { statusCode: 515 } } },
+ });
+ baileys().default.mockClear();
+ fakeSock.ws.isOpen = false;
+ fakeSock.ws.isConnecting = true;
+ await jest.advanceTimersByTimeAsync(1_000); // attempt 1 creates the socket that never opens
+ expect(baileys().default).toHaveBeenCalledTimes(1);
+ fakeSock.end.mockClear(); // drop the previous socket's teardown end()
+ return adapter;
+ };
+
+ afterEach(() => {
+ fakeSock.ws.isOpen = true;
+ fakeSock.ws.isConnecting = false;
+ jest.useRealTimers();
+ jest.restoreAllMocks();
+ });
+
+ // 503 is what WhatsApp's edge or a session proxy answers; 401/403/440 must not reach the terminal
+ // close branches of the same codes, which would fail the session or wipe its credentials.
+ it.each([503, 401, 403, 440])(
+ 'ends a socket whose upgrade got HTTP %i with a plain Error, and its close schedules the next attempt',
+ async statusCode => {
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ const onReconnecting = jest.fn();
+ const onError = jest.fn();
+ const onDisconnected = jest.fn();
+ const adapter = await startReconnectAttempt({ onReconnecting, onError, onDisconnected });
+ onReconnecting.mockClear();
+ // Real Baileys end() closes the WebSocket, then emits the close carrying the error it was given.
+ fakeSock.end.mockImplementationOnce((error: unknown) => {
+ fakeSock.fire('connection.update', { connection: 'close', lastDisconnect: { error } });
+ });
+
+ fakeSock.ws.emit('unexpected-response', {}, { statusCode });
+
+ expect(fakeSock.end).toHaveBeenCalledTimes(1);
+ const [error] = fakeSock.end.mock.calls[0] as [unknown];
+ expect(error).toBeInstanceOf(Error);
+ expect(error).not.toBeInstanceOf(Boom);
+ expect((error as Error).message).toContain(`HTTP ${statusCode}`);
+
+ expect(onReconnecting).toHaveBeenCalledWith(2, 2_000);
+ expect(adapter.getStatus()).toBe(EngineStatus.INITIALIZING);
+ expect(onError).not.toHaveBeenCalled();
+ expect(onDisconnected).not.toHaveBeenCalled();
+ expect(rmSpy).not.toHaveBeenCalled();
+ // The close also retired the backstop: only the reconnect timer is left.
+ expect(jest.getTimerCount()).toBe(1);
+
+ await jest.advanceTimersByTimeAsync(2_000);
+ expect(baileys().default).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it('ends a socket still connecting at the deadline exactly once', async () => {
+ await startReconnectAttempt();
+
+ await jest.advanceTimersByTimeAsync(CONNECTING_DEADLINE_MS - 1);
+ expect(fakeSock.end).not.toHaveBeenCalled();
+ await jest.advanceTimersByTimeAsync(1);
+ expect(fakeSock.end).toHaveBeenCalledTimes(1);
+ expect(fakeSock.end).toHaveBeenCalledWith(expect.any(Error));
+
+ await jest.advanceTimersByTimeAsync(CONNECTING_DEADLINE_MS * 2);
+ expect(fakeSock.end).toHaveBeenCalledTimes(1);
+ });
+
+ // A socket showing a QR has an open WebSocket but never emits connection 'open'.
+ it('leaves a socket whose WebSocket opened before the deadline alone', async () => {
+ await startReconnectAttempt();
+ fakeSock.ws.isConnecting = false;
+ fakeSock.ws.isOpen = true;
+
+ await jest.advanceTimersByTimeAsync(CONNECTING_DEADLINE_MS);
+ expect(fakeSock.end).not.toHaveBeenCalled();
+ });
+
+ it('clears the deadline once the connection opens', async () => {
+ await startReconnectAttempt();
+ expect(jest.getTimerCount()).toBe(1);
+ fakeSock.ws.isConnecting = false;
+ fakeSock.ws.isOpen = true;
+ fakeSock.fire('connection.update', { connection: 'open' });
+ expect(jest.getTimerCount()).toBe(0);
+ });
+
+ it.each(['disconnect', 'destroy', 'forceDestroy', 'logout'] as const)('clears the deadline on %s()', async method => {
+ const adapter = await startReconnectAttempt();
+ expect(jest.getTimerCount()).toBe(1);
+ // logout() without a linked identity still shuts the socket down locally, then rejects.
+ await adapter[method]().catch(() => undefined);
+ expect(jest.getTimerCount()).toBe(0);
+ });
+});
+
describe('BaileysAdapter status honesty across the reconnect backoff', () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const baileys = () => jest.requireMock('@whiskeysockets/baileys') as { default: jest.Mock };