Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): close the proxy socket of an abandoned CONNECT
Yudhi Armyndharis0afed0e43826
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4a275be7c..771097cea 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- A session whose automatic reconnect fails to relaunch the engine (a network, DNS or browser launch error) keeps retrying with backoff instead of stopping in `failed` until restarted by hand; an authentication failure or a stale browser profile still ends in `failed` ([#1580](https://github.com/rmyndharis/OpenWA/issues/1580)).- A session that runs out of reconnect attempts fires the `session:error` plugin hook when it lands in `failed`.- An explicit `maxReconnectAttempts` is honoured and the reconnect delay is capped at 5 minutes; the budget used to restart once the backoff passed 5 minutes, so the limit was never reached and the documented 1-hour cap never applied.+- A Baileys session behind an HTTP(S) proxy that never answers CONNECT no longer leaves an open connection to the proxy on every reconnect attempt.## [0.23.5] - 2026-09-14diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex 4cbcb54e8..f03bd6c2e 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -2,6 +2,7 @@ import * as path from 'path';import * as fs from 'fs';import type { ClientRequest, IncomingMessage } from 'http';import type { Agent } from 'https';+import type { Socket } from 'net';import * as qrcode from 'qrcode';import { HttpsProxyAgent } from 'https-proxy-agent';import { SocksProxyAgent } from 'socks-proxy-agent';@@ -50,6 +51,45 @@ const BAILEYS_LOGOUT_ACK_TIMEOUT_MS = 8_000;*/const BAILEYS_WS_CONNECTING_DEADLINE_MS = 60_000;+/** Bound on an HTTP(S) proxy's CONNECT reply, matching Baileys' default connectTimeoutMs. */+const PROXY_CONNECT_TIMEOUT_MS = 20_000;++/**+ * HttpsProxyAgent whose proxy socket cannot outlive the request that asked for it. The library awaits+ * the CONNECT reply with no abort hook or timeout, so a proxy that accepts TCP and never answers kept+ * its socket open after ws abandoned the handshake: one more open connection per reconnect attempt.+ * The socket is destroyed when the request is aborted (what ws does) or when the reply is overdue (a+ * request destroyed before it has a socket emits nothing). The signal has to be in connectOpts while+ * super.connect() runs synchronously, which is where the socket is opened; it is restored right after+ * so concurrent requests on the agent keep their own.+ */+class AbortableHttpsProxyAgent extends HttpsProxyAgent<string> {+ constructor(+ proxyUrl: string,+ private readonly connectTimeoutMs: number,+ ) {+ super(proxyUrl);+ }++ override async connect(req: ClientRequest, opts: Parameters<HttpsProxyAgent<string>['connect']>[1]): Promise<Socket> {+ const controller = new AbortController();+ const abort = (): void => controller.abort();+ req.once('abort', abort);+ const timer = setTimeout(abort, this.connectTimeoutMs);+ timer.unref();+ const connectOpts = this.connectOpts;+ this.connectOpts = { ...connectOpts, signal: controller.signal };+ const pending = super.connect(req, opts);+ this.connectOpts = connectOpts;+ try {+ return await pending;+ } finally {+ clearTimeout(timer);+ req.off('abort', abort);+ }+ }+}+/*** Build the Node-layer agent for a session egress proxy (#859). The WhatsApp WebSocket (`agent`) and* media uploads (`fetchAgent`) ride it; downloads and the version lookup go through global fetch,@@ -58,10 +98,10 @@ const BAILEYS_WS_CONNECTING_DEADLINE_MS = 60_000;* exposed to applies here. The scheme set matches the create-session DTO validator; anything else* (a pre-validation DB row) throws, failing the session closed rather than silently going direct.*/-export function createProxyAgent(proxyUrl: string): Agent {+export function createProxyAgent(proxyUrl: string, connectTimeoutMs = PROXY_CONNECT_TIMEOUT_MS): Agent {const { protocol } = new URL(proxyUrl);if (protocol === 'http:' || protocol === 'https:') {- return new HttpsProxyAgent(proxyUrl);+ return new AbortableHttpsProxyAgent(proxyUrl, connectTimeoutMs);}if (protocol === 'socks4:' || protocol === 'socks5:') {return new SocksProxyAgent(proxyUrl);diff --git a/test/baileys-proxy-agent.e2e-spec.ts b/test/baileys-proxy-agent.e2e-spec.tsnew file mode 100644index 000000000..1c7f752ca--- /dev/null+++ b/test/baileys-proxy-agent.e2e-spec.ts@@ -0,0 +1,62 @@+// test/__mocks__ holds a stub of this package, which Jest applies to node modules on its own; this+// suite needs the real CONNECT negotiation.+jest.unmock('https-proxy-agent');++import * as http from 'http';+import * as https from 'https';+import * as net from 'net';+import type { AddressInfo } from 'net';+import { createProxyAgent } from './../src/engine/adapters/baileys-lifecycle';++/**+ * The Baileys proxy agent against a proxy that accepts TCP and never answers CONNECT, the case the+ * connecting backstop exists for, through the real https-proxy-agent the unit suites stub out.+ * Each abandoned attempt must release its proxy socket, or every reconnect leaves one more open.+ */+describe('Baileys proxy agent (e2e)', () => {+ const silentProxy = async (): Promise<{ server: net.Server; accepted: Promise<net.Socket> }> => {+ let onAccepted!: (socket: net.Socket) => void;+ const accepted = new Promise<net.Socket>(resolve => (onAccepted = resolve));+ const server = net.createServer(socket => {+ // Reading is what lets the server see the client's FIN.+ socket.resume();+ socket.on('error', () => undefined);+ onAccepted(socket);+ });+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ return { server, accepted };+ };++ const closedWithin = (socket: net.Socket, ms: number): Promise<boolean> =>+ new Promise(resolve => {+ const timer = setTimeout(() => resolve(false), ms);+ socket.once('close', () => {+ clearTimeout(timer);+ resolve(true);+ });+ });++ it.each<[string, number, (req: http.ClientRequest) => void]>([+ // What ws does when Baileys ends a socket still in its handshake; the deadline is out of reach.+ ['aborted', 60_000, req => req.abort()],+ // Destroyed before it has a socket, which emits nothing: the CONNECT deadline closes it instead.+ ['destroyed', 300, req => req.destroy()],+ ])('closes the proxy socket when a request still waiting on CONNECT is %s', async (_label, deadlineMs, stop) => {+ const { server, accepted } = await silentProxy();+ const req = https.request({+ host: '127.0.0.1',+ port: 443,+ agent: createProxyAgent(`http://127.0.0.1:${(server.address() as AddressInfo).port}`, deadlineMs),+ });+ req.on('error', () => undefined);+ req.end();+ const socket = await accepted;+ try {+ stop(req);+ expect(await closedWithin(socket, 1000)).toBe(true);+ } finally {+ socket.destroy();+ await new Promise<void>(resolve => server.close(() => resolve()));+ }+ });+});