Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(engine): honor the per-session egress proxy in the baileys engine (#973)

Yudhi Armyndharisfbce247e65ce
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ed56527d4..cbef61e08 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- **The Baileys engine now honors the per-session egress proxy** (#859). `proxyUrl` — http, https,
+ socks4 or socks5, credentialed form included — is applied through a Node-layer agent on both the
+ WhatsApp WebSocket and media up/downloads (`https-proxy-agent` / `socks-proxy-agent`, now direct
+ dependencies). Previously the engine warned `baileys_proxy_unsupported` and connected direct,
+ silently exposing the host's real egress IP for exactly the deployments that configured a proxy.
+ An unusable proxy value now fails the session start instead of falling back to a direct
+ connection. Credentials authenticate on the socket itself, so the Chromium first-CONNECT 407
+ limitation that can bite the wwjs engine's proxy-auth path does not apply to this engine.
+
### Fixed
- **The release runbook in `docs/15` now describes the process the repository actually uses.** §15.7
diff --git a/package-lock.json b/package-lock.json
index 1c5841b14..208eeb765 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -35,12 +35,14 @@
"class-validator": "^0.15.1",
"dockerode": "^5.0.1",
"helmet": "^8.3.0",
+ "https-proxy-agent": "^7.0.6",
"ioredis": "^5.11.1",
"pg": "^8.22.0",
"qrcode": "^1.5.4",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"socket.io": "^4.8.3",
+ "socks-proxy-agent": "^8.0.5",
"tar-stream": "^3.2.0",
"typeorm": "^1.1.0",
"undici": "^8.9.0",
@@ -5468,6 +5470,15 @@
"node": ">=14.0"
}
},
+ "node_modules/agent-base": {
+ "version": "7.1.4",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
"node_modules/ajv": {
"version": "6.15.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
@@ -9052,6 +9063,19 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/https-proxy-agent": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
"node_modules/human-signals": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",
@@ -11196,15 +11220,6 @@
"node": ">= 14"
}
},
- "node_modules/pac-proxy-agent/node_modules/agent-base": {
- "version": "7.1.4",
- "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
- "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
- "license": "MIT",
- "engines": {
- "node": ">= 14"
- }
- },
"node_modules/pac-proxy-agent/node_modules/http-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
@@ -11218,33 +11233,6 @@
"node": ">= 14"
}
},
- "node_modules/pac-proxy-agent/node_modules/https-proxy-agent": {
- "version": "7.0.6",
- "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
- "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
- "license": "MIT",
- "dependencies": {
- "agent-base": "^7.1.2",
- "debug": "4"
- },
- "engines": {
- "node": ">= 14"
- }
- },
- "node_modules/pac-proxy-agent/node_modules/socks-proxy-agent": {
- "version": "8.0.5",
- "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz",
- "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==",
- "license": "MIT",
- "dependencies": {
- "agent-base": "^7.1.2",
- "debug": "^4.3.4",
- "socks": "^2.8.3"
- },
- "engines": {
- "node": ">= 14"
- }
- },
"node_modules/pac-resolver": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz",
@@ -11865,15 +11853,6 @@
"node": ">= 14"
}
},
- "node_modules/proxy-agent/node_modules/agent-base": {
- "version": "7.1.4",
- "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
- "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
- "license": "MIT",
- "engines": {
- "node": ">= 14"
- }
- },
"node_modules/proxy-agent/node_modules/http-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
@@ -11887,19 +11866,6 @@
"node": ">= 14"
}
},
- "node_modules/proxy-agent/node_modules/https-proxy-agent": {
- "version": "7.0.6",
- "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
- "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
- "license": "MIT",
- "dependencies": {
- "agent-base": "^7.1.2",
- "debug": "4"
- },
- "engines": {
- "node": ">= 14"
- }
- },
"node_modules/proxy-agent/node_modules/lru-cache": {
"version": "7.18.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz",
@@ -11909,20 +11875,6 @@
"node": ">=12"
}
},
- "node_modules/proxy-agent/node_modules/socks-proxy-agent": {
- "version": "8.0.5",
- "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz",
- "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==",
- "license": "MIT",
- "dependencies": {
- "agent-base": "^7.1.2",
- "debug": "^4.3.4",
- "socks": "^2.8.3"
- },
- "engines": {
- "node": ">= 14"
- }
- },
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
@@ -12945,6 +12897,20 @@
"npm": ">= 3.0.0"
}
},
+ "node_modules/socks-proxy-agent": {
+ "version": "8.0.5",
+ "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz",
+ "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "^4.3.4",
+ "socks": "^2.8.3"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
"node_modules/sonic-boom": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",
diff --git a/package.json b/package.json
index 3ef1a9e32..981c4b4f6 100644
--- a/package.json
+++ b/package.json
@@ -84,12 +84,14 @@
"class-validator": "^0.15.1",
"dockerode": "^5.0.1",
"helmet": "^8.3.0",
+ "https-proxy-agent": "^7.0.6",
"ioredis": "^5.11.1",
"pg": "^8.22.0",
"qrcode": "^1.5.4",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"socket.io": "^4.8.3",
+ "socks-proxy-agent": "^8.0.5",
"tar-stream": "^3.2.0",
"typeorm": "^1.1.0",
"undici": "^8.9.0",
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 3454392f2..0c76653be 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -98,7 +98,9 @@ jest.mock('@whiskeysockets/baileys', () => ({
},
}));
-import { BaileysAdapter } from './baileys.adapter';
+import { HttpsProxyAgent } from 'https-proxy-agent';
+import { SocksProxyAgent } from 'socks-proxy-agent';
+import { BaileysAdapter, createProxyAgent } from './baileys.adapter';
import {
EditedMessage,
EngineStatus,
@@ -3441,3 +3443,73 @@ describe('BaileysAdapter status posting', () => {
expect(fakeStore.getMessage).not.toHaveBeenCalled();
});
});
+
+describe('BaileysAdapter proxy support', () => {
+ beforeEach(() => {
+ fakeSock.user = undefined;
+ fakeSock.resetEmitter();
+ jest.clearAllMocks();
+ });
+
+ const proxied = (proxyUrl: string): BaileysAdapter =>
+ new BaileysAdapter({
+ sessionId: 'sess-1',
+ dbSessionId: 'db-uuid-1',
+ authDir: './data/baileys',
+ messageStore: fakeStore,
+ proxyUrl,
+ });
+
+ const makeWASocketMock = (): jest.Mock =>
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ jest.requireMock('@whiskeysockets/baileys').default as jest.Mock;
+
+ const lastSocketConfig = (): Record<string, unknown> => {
+ const calls = makeWASocketMock().mock.calls as Array<[Record<string, unknown>]>;
+ const last = calls.at(-1);
+ if (!last) throw new Error('Expected makeWASocket to have been called');
+ return last[0];
+ };
+
+ it('selects HttpsProxyAgent for http/https proxy URLs', () => {
+ expect(createProxyAgent('http://user:[email protected]:8080')).toBeInstanceOf(HttpsProxyAgent);
+ expect(createProxyAgent('https://proxy.example:443')).toBeInstanceOf(HttpsProxyAgent);
+ });
+
+ it('selects SocksProxyAgent for socks4/socks5 proxy URLs', () => {
+ expect(createProxyAgent('socks5://user:[email protected]:1080')).toBeInstanceOf(SocksProxyAgent);
+ expect(createProxyAgent('socks4://proxy.example:1080')).toBeInstanceOf(SocksProxyAgent);
+ });
+
+ it('throws on an unsupported proxy scheme', () => {
+ expect(() => createProxyAgent('ftp://proxy.example:21')).toThrow(/unsupported proxy/i);
+ });
+
+ it('passes the agent to makeWASocket as both agent (WS) and fetchAgent (media)', async () => {
+ await proxied('http://user:[email protected]:8080').initialize(noopCallbacks());
+ const cfg = lastSocketConfig();
+ expect(cfg.agent).toBeInstanceOf(HttpsProxyAgent);
+ expect(cfg.fetchAgent).toBe(cfg.agent);
+ });
+
+ it('passes a SOCKS agent through for a socks5 URL', async () => {
+ await proxied('socks5://user:[email protected]:1080').initialize(noopCallbacks());
+ expect(lastSocketConfig().agent).toBeInstanceOf(SocksProxyAgent);
+ });
+
+ it('leaves agent/fetchAgent unset without a proxyUrl', async () => {
+ await newAdapter().initialize(noopCallbacks());
+ const cfg = lastSocketConfig();
+ expect(cfg.agent).toBeUndefined();
+ expect(cfg.fetchAgent).toBeUndefined();
+ });
+
+ it('fails closed: an unusable proxy value fails initialize instead of connecting direct', async () => {
+ const onError = jest.fn();
+ const adapter = proxied('ftp://proxy.example:21');
+ await expect(adapter.initialize(noopCallbacks({ onError }))).rejects.toThrow(/unsupported proxy/i);
+ expect(adapter.getStatus()).toBe(EngineStatus.FAILED);
+ expect(onError).toHaveBeenCalled();
+ expect(makeWASocketMock()).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index f7f93f32b..e7e96efe7 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -1,6 +1,9 @@
import * as fs from 'fs';
import * as path from 'path';
+import type { Agent } from 'https';
import * as qrcode from 'qrcode';
+import { HttpsProxyAgent } from 'https-proxy-agent';
+import { SocksProxyAgent } from 'socks-proxy-agent';
import type * as BaileysLib from '@whiskeysockets/baileys';
import type {
AnyMessageContent,
@@ -78,6 +81,24 @@ const BAILEYS_BROWSER: [string, string, string] = [
'120.0.0',
];
+/**
+ * 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
+ * authenticated on the socket itself, so none of the Chromium CDP auth timing the wwjs engine is
+ * 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 {
+ const { protocol } = new URL(proxyUrl);
+ if (protocol === 'http:' || protocol === 'https:') {
+ return new HttpsProxyAgent(proxyUrl);
+ }
+ if (protocol === 'socks4:' || protocol === 'socks5:') {
+ return new SocksProxyAgent(proxyUrl);
+ }
+ throw new Error(`Unsupported proxy protocol for the baileys engine: ${protocol}`);
+}
+
/** Fully silent logger so Baileys does not spam stdout; diagnostics flow via connection.update. */
function createSilentLogger(): BaileysLogger {
const noop = (): void => {};
@@ -180,13 +201,6 @@ export class BaileysAdapter implements IWhatsAppEngine {
// Isolate each session's auth state under its own subdirectory of the shared auth dir.
this.authPath = path.join(config.authDir, config.sessionId);
this.sessionStore = new BaileysSessionStore(config.lidMappingStore, config.sessionId);
- if (config.proxyUrl) {
- // Proxy support is gated for this slice — Baileys proxying needs an http/socks agent (a new dep).
- this.logger.warn('Proxy configured but not supported by the baileys engine in this slice; ignoring it', {
- action: 'baileys_proxy_unsupported',
- sessionId: config.sessionId,
- });
- }
}
// ----- Lifecycle -----
@@ -218,6 +232,15 @@ export class BaileysAdapter implements IWhatsAppEngine {
private async connectInner(): Promise<void> {
this.setStatus(EngineStatus.INITIALIZING);
+ // Build the egress proxy agent BEFORE any auth-state I/O so an unusable proxy value fails the
+ // session (engine_error) instead of silently connecting direct (#859).
+ let proxyAgent: Agent | undefined;
+ if (this.config.proxyUrl) {
+ proxyAgent = createProxyAgent(this.config.proxyUrl);
+ const { protocol, host } = new URL(this.config.proxyUrl);
+ // Credential-stripped, matching the wwjs adapter's log line (#628).
+ this.logger.log(`Using proxy: ${protocol}//${host}`, { sessionId: this.config.sessionId });
+ }
const b = await this.loadLib();
const { state, saveCreds } = await b.useMultiFileAuthState(this.authPath);
const { version } = await b.fetchLatestBaileysVersion();
@@ -276,6 +299,9 @@ export class BaileysAdapter implements IWhatsAppEngine {
version,
browser: BAILEYS_BROWSER,
printQRInTerminal: false,
+ // Session egress proxy (#859): the WS and media transfers share one agent; undefined = direct.
+ agent: proxyAgent,
+ fetchAgent: proxyAgent,
// Enable the initial sync. Baileys defaults `shouldSyncHistoryMessage` to `() => !!syncFullHistory`,
// so leaving both unset disables ALL history + app-state sync - no contacts, chats, recent history,
// or lid->phone mappings ever arrive (the address-book app-state sync only runs once history sync is