Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): send media downloads through the session proxy

Yudhi Armyndharisb66db746aa77
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3ce9b6e97..4a275be7c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Security
+
+- Baileys sessions with an HTTP, HTTPS or SOCKS5 proxy download inbound media through the proxy instead of connecting direct, and look up the WhatsApp Web version through it instead of always falling back; with a SOCKS4 proxy both are skipped, and inbound media arrives as the omitted marker.
+
### Added
- `GET /api/sessions` accepts a `name` query parameter that returns only the session with that exact name, also on the MCP `SessionFindAll` tool and the JavaScript, Python, Go, Java and PHP SDKs ([#1594](https://github.com/rmyndharis/OpenWA/issues/1594)). Thanks @rivenash.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 2f1f435ac..23001073a 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -551,6 +551,11 @@ network cannot reach WhatsApp directly. Set `proxyUrl`/`proxyType` on the same r
> WebSocket never connects, **no QR code is ever delivered**, and `POST /api/sessions/:sessionId/start`
> returns `504 Gateway Timeout` after ~30s. Leave `proxyUrl` unset unless you genuinely need a proxy.
+On the Baileys engine a `socks4` proxy carries the WebSocket and media uploads only: inbound media is not
+downloaded (it arrives as the omitted marker) and the WhatsApp Web version is not looked up remotely, so
+neither can leave outside the proxy. With `socks5`, `http` or `https` both also go through the proxy. Fetches
+of a URL you pass in, such as a catalog product `imageUrl` or an opt-in link preview, still connect directly.
+
**Response** `201`
```json
diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.ts
index 190930e4e..ed3f5afd8 100644
--- a/src/engine/adapters/baileys-events.spec.ts
+++ b/src/engine/adapters/baileys-events.spec.ts
@@ -92,6 +92,7 @@ function makeHost(overrides: Partial<BaileysEventsHost> = {}): BaileysEventsHost
getSocketOrNull: () => null,
logger: createLogger('BaileysEventsSpec'),
loadLib: () => Promise.resolve(libStub),
+ getFetchDispatcher: () => undefined,
toNeutralJid: (jid: string) => jid,
normalizedSelfJid: () => '[email protected]',
// connectedAt only gates handleMessagesUpsert's history-replay skip; mapMessage itself never
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index 6913ecfe7..752c9defa 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -33,6 +33,7 @@ import {
isMediaDownloadEnabled,
withInboundDownloadTimeout,
} from './inbound-media-cap';
+import type { Dispatcher } from 'undici';
import type { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
import { type createLogger } from '../../common/services/logger.service';
import { createSilentLogger } from './baileys-logger';
@@ -98,6 +99,8 @@ export interface BaileysEventsHost {
normalizedSelfJid(): string;
/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */
loadLib(): Promise<typeof BaileysLib>;
+ /** Session proxy dispatcher for the media download: undefined = direct, null = proxy fetch cannot use. */
+ getFetchDispatcher(): Dispatcher | null | undefined;
/** Unix-seconds timestamp of the last 'open' connection.update — the live-vs-history discriminator. */
readonly connectedAt: number;
/** The adapter's inbound media download gate (shared so the bound holds across all inbound paths). */
@@ -745,6 +748,13 @@ export class BaileysEvents {
msg: WAMessage,
maxBytes: number,
): Promise<Buffer | { overflowBytes: number } | null> {
+ // A proxied session must not fetch media around its proxy (#859). Baileys reads the dispatcher
+ // from the nested `options` (a top-level one is ignored); a proxy scheme fetch cannot use fails
+ // the download, which the caller turns into the omitted marker.
+ const dispatcher = this.host.getFetchDispatcher();
+ if (dispatcher === null) {
+ throw new Error('Media download is not supported through this proxy scheme');
+ }
// Hold the stream handle in the outer scope so the timeout can destroy it. A genuine
// download/read error still rejects (propagating to the caller's catch as before).
let stream: (AsyncIterable<Buffer> & { destroy?: () => void }) | undefined;
@@ -753,7 +763,7 @@ export class BaileysEvents {
stream = (await b.downloadMediaMessage(
msg,
'stream',
- {},
+ dispatcher ? { options: { dispatcher } as RequestInit } : {},
{
logger: createSilentLogger(),
reuploadRequest: this.host.getSocket().updateMediaMessage,
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index ba1ed0e82..4cbcb54e8 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -5,6 +5,7 @@ import type { Agent } from 'https';
import * as qrcode from 'qrcode';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { SocksProxyAgent } from 'socks-proxy-agent';
+import { Dispatcher1Wrapper, ProxyAgent, type Dispatcher } from 'undici';
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { WASocket } from '@whiskeysockets/baileys';
import type { ILogger } from '@whiskeysockets/baileys/lib/Utils/logger.js';
@@ -50,8 +51,9 @@ const BAILEYS_LOGOUT_ACK_TIMEOUT_MS = 8_000;
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
+ * 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,
+ * which needs {@link createProxyDispatcher} instead. 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.
@@ -67,6 +69,35 @@ export function createProxyAgent(proxyUrl: string): Agent {
throw new Error(`Unsupported proxy protocol for the baileys engine: ${protocol}`);
}
+/**
+ * Build the global-fetch dispatcher for a session egress proxy, used by Baileys' media download and
+ * version lookup. Global fetch accepts only an undici dispatcher, never a Node http Agent, and Node's
+ * bundled undici predates the handler API of the installed one, so the agent is wrapped to speak the
+ * older interface. undici has no SOCKS4 transport: null tells the caller to skip the request rather
+ * than send it direct.
+ */
+export function createProxyDispatcher(proxyUrl: string): Dispatcher | null {
+ const { protocol, username, password } = new URL(proxyUrl);
+ if (protocol === 'http:' || protocol === 'https:') {
+ return new Dispatcher1Wrapper(new ProxyAgent(proxyUrl));
+ }
+ if (protocol === 'socks5:') {
+ // undici hands SOCKS5 the URL credentials still percent-encoded (it decodes them only for the HTTP
+ // Proxy-Authorization header), so a password written as `p%40ss` would fail auth. Pass them decoded;
+ // the options object is not a literal because undici's typings omit these two runtime options.
+ const options = {
+ uri: proxyUrl,
+ username: decodeURIComponent(username) || undefined,
+ password: decodeURIComponent(password) || undefined,
+ };
+ return new Dispatcher1Wrapper(new ProxyAgent(options));
+ }
+ if (protocol === 'socks4:') {
+ return null;
+ }
+ throw new Error(`Unsupported proxy protocol for the baileys engine: ${protocol}`);
+}
+
/**
* Connection lifecycle extracted from BaileysAdapter: connect/reconnect with capped backoff, QR
* rendering, logout with the remove-companion-device ACK, terminal-close handling, and the state
@@ -149,6 +180,8 @@ export class BaileysLifecycle {
private lastConnectionCloseAt = 0;
/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */
private lib?: typeof BaileysLib;
+ /** The session proxy's fetch dispatcher, built once: the proxy URL is fixed for the adapter's life. */
+ private dispatcher?: Dispatcher | null;
constructor(private readonly host: BaileysLifecycleHost) {
this.versionResolver = new BaileysVersionResolver({
@@ -163,6 +196,21 @@ export class BaileysLifecycle {
return (this.lib ??= await import('@whiskeysockets/baileys'));
}
+ /**
+ * Dispatcher for Baileys' global-fetch calls: undefined without a proxy (direct), null when the
+ * proxy scheme has no fetch transport, so the caller must skip the request instead of going direct.
+ */
+ fetchDispatcher(): Dispatcher | null | undefined {
+ const { proxyUrl } = this.host.config;
+ if (!proxyUrl) {
+ return undefined;
+ }
+ if (this.dispatcher === undefined) {
+ this.dispatcher = createProxyDispatcher(proxyUrl);
+ }
+ return this.dispatcher;
+ }
+
async initialize(): Promise<void> {
// Single-use after teardown: disconnect()/destroy()/forceDestroy()/logout() set this latch, and
// it must NOT be re-armed here. A retired adapter (e.g. one whose session was stopped/deleted
@@ -217,7 +265,7 @@ export class BaileysLifecycle {
}
const b = await this.loadLib();
const { state, saveCreds } = await b.useMultiFileAuthState(this.host.authPath);
- const version = await this.versionResolver.resolve(b, { dispatcher: proxyAgent });
+ const version = await this.versionResolver.resolve(b, { dispatcher: this.fetchDispatcher() });
// BaileysLogger matches ILogger exactly; cast needed because the module resolves the type
// through a deep import path that TypeScript does not auto-unify here. Shared by the key
// store wrapper below and the socket itself, rather than constructing two instances.
@@ -275,7 +323,8 @@ export class BaileysLifecycle {
version,
browser: BAILEYS_BROWSER,
printQRInTerminal: false,
- // Session egress proxy (#859): the WS and media transfers share one agent; undefined = direct.
+ // Session egress proxy (#859): the WS and media uploads share one agent; undefined = direct.
+ // Media downloads use fetchDispatcher() instead, since Baileys fetches them with global fetch.
agent: proxyAgent,
fetchAgent: proxyAgent,
// Enable the initial sync. Baileys defaults `shouldSyncHistoryMessage` to `() => !!syncFullHistory`,
diff --git a/src/engine/adapters/baileys-media-abort.spec.ts b/src/engine/adapters/baileys-media-abort.spec.ts
index 7cd850fc3..e4cede8c8 100644
--- a/src/engine/adapters/baileys-media-abort.spec.ts
+++ b/src/engine/adapters/baileys-media-abort.spec.ts
@@ -24,13 +24,14 @@ function imageMessage(id: string, fileLength: number): WAMessage {
};
}
-function build(): { events: BaileysEvents; warns: string[] } {
+function build(dispatcher?: object | null): { events: BaileysEvents; warns: string[] } {
const warns: string[] = [];
const events = new BaileysEvents({
getSocket: () => ({ updateMediaMessage: jest.fn() }) as unknown as WASocket,
getSocketOrNull: () => null,
logger: { ...createLogger('BaileysMediaAbortSpec'), warn: (m: string) => warns.push(m) },
loadLib: () => Promise.resolve({ normalizeMessageContent: (c: unknown) => c, downloadMediaMessage }),
+ getFetchDispatcher: () => dispatcher,
toNeutralJid: (jid: string) => jid,
normalizedSelfJid: () => '[email protected]',
connectedAt: 0,
@@ -121,3 +122,45 @@ describe('BaileysEvents aborted media download size', () => {
expect(warns[0]).not.toContain('MEDIA_DOWNLOAD_MAX_BYTES');
});
});
+
+describe('BaileysEvents media download through a session proxy', () => {
+ beforeEach(() => {
+ downloadMediaMessage.mockReset();
+ process.env.MEDIA_DOWNLOAD_ENABLED = 'true';
+ });
+
+ afterEach(() => {
+ delete process.env.MEDIA_DOWNLOAD_ENABLED;
+ });
+
+ it('hands the proxy dispatcher to Baileys in the nested fetch options', async () => {
+ const dispatcher = { dispatch: jest.fn() };
+ downloadMediaMessage.mockResolvedValue({
+ // eslint-disable-next-line @typescript-eslint/require-await
+ async *[Symbol.asyncIterator]() {
+ yield Buffer.from('IMG');
+ },
+ });
+ const { events } = build(dispatcher);
+
+ await events.mapMessage(imageMessage('PROXIED', 3), 'imageMessage');
+
+ // Baileys reads `options.options.dispatcher`; a top-level `dispatcher` would be ignored.
+ expect(downloadMediaMessage).toHaveBeenCalledWith(
+ expect.anything(),
+ 'stream',
+ { options: { dispatcher } },
+ expect.anything(),
+ );
+ });
+
+ it('never downloads direct when the proxy scheme has no fetch dispatcher', async () => {
+ const { events, warns } = build(null);
+
+ const incoming = await events.mapMessage(imageMessage('SOCKS4', 3), 'imageMessage');
+
+ expect(downloadMediaMessage).not.toHaveBeenCalled();
+ expect(incoming.media).toEqual({ mimetype: 'image/png', filename: undefined, omitted: true, sizeBytes: 3 });
+ expect(warns).toEqual([expect.stringContaining('download failed')]);
+ });
+});
diff --git a/src/engine/adapters/baileys-proxy.spec.ts b/src/engine/adapters/baileys-proxy.spec.ts
new file mode 100644
index 000000000..becb7ad07
--- /dev/null
+++ b/src/engine/adapters/baileys-proxy.spec.ts
@@ -0,0 +1,87 @@
+import * as http from 'http';
+import * as net from 'net';
+import type { AddressInfo } from 'net';
+import { Dispatcher1Wrapper } from 'undici';
+import { createProxyDispatcher } from './baileys-lifecycle';
+
+/**
+ * Baileys fetches media and the WhatsApp Web version with global fetch, which takes only an undici
+ * dispatcher that speaks the handler API of the undici bundled in Node, never a Node http Agent. The
+ * last case runs a real fetch through a local proxy, so an incompatible dispatcher fails here.
+ */
+
+const listen = async <T extends net.Server>(server: T): Promise<T> => {
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ return server;
+};
+const portOf = (server: net.Server): number => (server.address() as AddressInfo).port;
+const close = (server: net.Server): Promise<void> => new Promise(resolve => server.close(() => resolve()));
+
+describe('createProxyDispatcher', () => {
+ it('wraps a dispatcher for http, https and socks5 proxies', () => {
+ for (const url of ['http://u:[email protected]:8080', 'https://proxy.example:443', 'socks5://proxy.example:1080']) {
+ expect(createProxyDispatcher(url)).toBeInstanceOf(Dispatcher1Wrapper);
+ }
+ });
+
+ it('returns null for socks4, which fetch cannot use', () => {
+ expect(createProxyDispatcher('socks4://proxy.example:1080')).toBeNull();
+ });
+
+ it('throws on an unsupported scheme', () => {
+ expect(() => createProxyDispatcher('ftp://proxy.example:21')).toThrow(/unsupported proxy/i);
+ });
+
+ it('routes a global fetch through the proxy', async () => {
+ const seen: string[] = [];
+ const proxy = await listen(
+ http.createServer((req, res) => {
+ seen.push(`${req.method} ${req.url}`);
+ res.end('via proxy');
+ }),
+ );
+ try {
+ const response = await fetch('http://media.example.invalid/file', {
+ dispatcher: createProxyDispatcher(`http://127.0.0.1:${portOf(proxy)}`),
+ } as RequestInit);
+ expect(await response.text()).toBe('via proxy');
+ expect(seen).toEqual(['GET http://media.example.invalid/file']);
+ } finally {
+ proxy.closeAllConnections();
+ await close(proxy);
+ }
+ });
+
+ it('sends percent-encoded socks5 credentials decoded', async () => {
+ // Minimal SOCKS5 server: ask for username/password auth (RFC 1929), record it, then refuse.
+ const seen: string[] = [];
+ const sockets = new Set<net.Socket>();
+ const proxy = await listen(
+ net.createServer(socket => {
+ sockets.add(socket);
+ socket.once('data', () => {
+ socket.write(Buffer.from([0x05, 0x02]));
+ socket.once('data', auth => {
+ const userLen = auth[1];
+ const user = auth.subarray(2, 2 + userLen).toString();
+ const passLen = auth[2 + userLen];
+ const pass = auth.subarray(3 + userLen, 3 + userLen + passLen).toString();
+ seen.push(`${user}:${pass}`);
+ socket.end(Buffer.from([0x01, 0x01]));
+ });
+ });
+ }),
+ );
+ try {
+ await expect(
+ fetch('http://media.example.invalid/file', {
+ dispatcher: createProxyDispatcher(`socks5://us%40er:p%40ss%[email protected]:${portOf(proxy)}`),
+ } as RequestInit),
+ ).rejects.toThrow();
+ expect(seen).toEqual(['us@er:p@ss:1']);
+ } finally {
+ sockets.forEach(socket => socket.destroy());
+ await close(proxy);
+ }
+ });
+});
diff --git a/src/engine/adapters/baileys-version-resolver.spec.ts b/src/engine/adapters/baileys-version-resolver.spec.ts
index 67b01b572..8088bc422 100644
--- a/src/engine/adapters/baileys-version-resolver.spec.ts
+++ b/src/engine/adapters/baileys-version-resolver.spec.ts
@@ -38,6 +38,23 @@ describe('BaileysVersionResolver', () => {
const asBaileysLib = (mock: unknown): typeof BaileysLib => mock as typeof BaileysLib;
+ describe('Proxy scheme without a fetch dispatcher', () => {
+ it('when the dispatcher is null, skips both remote tiers instead of fetching direct', async () => {
+ fs.writeFileSync(path.join(tmpDir, 'last_known_wa_version.json'), JSON.stringify([2, 3000, 1043857760]));
+ const resolver = createResolver();
+ const mockLib = {
+ fetchLatestWaWebVersion: jest.fn(),
+ fetchLatestBaileysVersion: jest.fn(),
+ };
+
+ const version = await resolver.resolve(asBaileysLib(mockLib), { dispatcher: null });
+
+ expect(version).toEqual([2, 3000, 1043857760]);
+ expect(mockLib.fetchLatestWaWebVersion).not.toHaveBeenCalled();
+ expect(mockLib.fetchLatestBaileysVersion).not.toHaveBeenCalled();
+ });
+ });
+
describe('Tier 1: BAILEYS_WA_VERSION environment variable override', () => {
it('when BAILEYS_WA_VERSION is set in dot format, returns the overridden version immediately without network calls', async () => {
// Arrange
diff --git a/src/engine/adapters/baileys-version-resolver.ts b/src/engine/adapters/baileys-version-resolver.ts
index 87200c1f4..1710c7df1 100644
--- a/src/engine/adapters/baileys-version-resolver.ts
+++ b/src/engine/adapters/baileys-version-resolver.ts
@@ -23,6 +23,8 @@ export interface BaileysVersionResolverOptions {
}
export interface ResolveOptions {
+ /** Global-fetch dispatcher for the session proxy. null means the session is proxied through a scheme
+ * fetch cannot use, so both remote tiers are skipped rather than fetched direct around the proxy. */
dispatcher?: unknown;
}
@@ -51,14 +53,20 @@ export class BaileysVersionResolver {
return envVersion;
}
- const waWebVersion = await this.resolveFromWaWeb(b, resolveOptions);
- if (waWebVersion) {
- return waWebVersion;
- }
+ if (resolveOptions.dispatcher === null) {
+ this.options.logger.log('Remote WhatsApp Web version lookup is not supported through this proxy scheme', {
+ sessionId: this.options.sessionId,
+ });
+ } else {
+ const waWebVersion = await this.resolveFromWaWeb(b, resolveOptions);
+ if (waWebVersion) {
+ return waWebVersion;
+ }
- const baileysVersion = await this.resolveFromBaileys(b, resolveOptions);
- if (baileysVersion) {
- return baileysVersion;
+ const baileysVersion = await this.resolveFromBaileys(b, resolveOptions);
+ if (baileysVersion) {
+ return baileysVersion;
+ }
}
const cachedVersion = this.resolveFromDiskCache();
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 5e6424b44..b61ed168f 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -137,6 +137,7 @@ jest.mock('@whiskeysockets/baileys', () => ({
import { HttpsProxyAgent } from 'https-proxy-agent';
import { NotFoundException, BadRequestException } from '@nestjs/common';
import { SocksProxyAgent } from 'socks-proxy-agent';
+import { Dispatcher1Wrapper } from 'undici';
import { BaileysAdapter, createProxyAgent } from './baileys.adapter';
import {
EditedMessage,
@@ -5181,6 +5182,20 @@ describe('BaileysAdapter proxy support', () => {
expect(lastSocketConfig().agent).toBeInstanceOf(SocksProxyAgent);
});
+ it('hands the version lookup a fetch dispatcher, not the socket agent', async () => {
+ await proxied('http://user:[email protected]:8080').initialize(noopCallbacks());
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const lookup = jest.requireMock('@whiskeysockets/baileys').fetchLatestBaileysVersion as jest.Mock;
+ const [[options]] = lookup.mock.calls as Array<[{ dispatcher?: unknown }]>;
+ expect(options.dispatcher).toBeInstanceOf(Dispatcher1Wrapper);
+ });
+
+ it('skips the remote version lookup rather than going direct for a socks4 proxy', async () => {
+ await proxied('socks4://proxy.example:1080').initialize(noopCallbacks());
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ expect(jest.requireMock('@whiskeysockets/baileys').fetchLatestBaileysVersion).not.toHaveBeenCalled();
+ });
+
it('leaves agent/fetchAgent unset without a proxyUrl', async () => {
await newAdapter().initialize(noopCallbacks());
const cfg = lastSocketConfig();
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 6daf60dc6..49055d0c4 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -133,6 +133,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
toNeutralJid: jid => this.sessionStore.toNeutralJid(jid),
normalizedSelfJid: () => this.normalizedSelfJid(),
loadLib: () => this.loadLib(),
+ getFetchDispatcher: () => this.lifecycle.fetchDispatcher(),
toUnixSeconds,
inboundLimiter: this.inboundLimiter,
recordKeyLidMappings: key => this.sessionStore.recordKeyLidMappings(key),