Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): stop a media download abandoned by its timeout
Yudhi Armyndharisb19718bf2abf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 771097cea..fec2df627 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- 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.+- A Baileys inbound media download that passes `MEDIA_DOWNLOAD_TIMEOUT_MS` before its stream opens stops instead of buffering in the background outside `INBOUND_MEDIA_CONCURRENCY`.## [0.23.5] - 2026-09-14diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex 752c9defa..f45b7c2c3 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -758,6 +758,9 @@ export class BaileysEvents {// 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;+ // The timeout can fire before the stream exists (an expired-media re-upload wait, a slow response):+ // the abandoned download must then stop on its own instead of buffering outside the limiter.+ let timedOut = false;const download = (async (): Promise<Buffer | { overflowBytes: number }> => {const b = await this.host.loadLib();stream = (await b.downloadMediaMessage(@@ -769,10 +772,17 @@ export class BaileysEvents {reuploadRequest: this.host.getSocket().updateMediaMessage,},)) as AsyncIterable<Buffer> & { destroy?: () => void };+ if (timedOut) {+ stream.destroy?.();+ return Buffer.alloc(0);+ }const chunks: Buffer[] = [];let total = 0;for await (const chunk of stream) {+ if (timedOut) {+ break;+ }total += chunk.length;if (total > maxBytes) {stream.destroy?.();@@ -786,7 +796,10 @@ export class BaileysEvents {// A slow/trickling sender never trips the byte cap, so without a deadline it pins a concurrency// slot (and, on Baileys, the whole inbound handler) indefinitely. On timeout, destroy the stream// and treat it as no usable media.- return withInboundDownloadTimeout(download, inboundMediaTimeoutMs(), () => stream?.destroy?.());+ return withInboundDownloadTimeout(download, inboundMediaTimeoutMs(), () => {+ timedOut = true;+ stream?.destroy?.();+ });}/**diff --git a/src/engine/adapters/baileys-media-abort.spec.ts b/src/engine/adapters/baileys-media-abort.spec.tsindex e4cede8c8..c7d41f48c 100644--- a/src/engine/adapters/baileys-media-abort.spec.ts+++ b/src/engine/adapters/baileys-media-abort.spec.ts@@ -121,6 +121,31 @@ describe('BaileysEvents aborted media download size', () => {expect(warns).toEqual([expect.stringContaining('MEDIA_DOWNLOAD_TIMEOUT_MS')]);expect(warns[0]).not.toContain('MEDIA_DOWNLOAD_MAX_BYTES');});++ it('stops a download whose stream only arrives after MEDIA_DOWNLOAD_TIMEOUT_MS', async () => {+ jest.useFakeTimers();+ process.env.MEDIA_DOWNLOAD_TIMEOUT_MS = '50';+ const read = jest.fn();+ const stream: Stream = {+ // eslint-disable-next-line @typescript-eslint/require-await+ async *[Symbol.asyncIterator]() {+ read();+ yield Buffer.alloc(16);+ },+ destroy: jest.fn(),+ };+ // Resolves after the deadline, as an expired-media re-upload wait does.+ downloadMediaMessage.mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(stream), 200)));+ const { events } = build();++ const pending = events.mapMessage(imageMessage('REUPLOAD', 4096), 'imageMessage');+ await jest.advanceTimersByTimeAsync(50);+ expect((await pending).media).toMatchObject({ omitted: true, sizeBytes: 4096 });++ await jest.advanceTimersByTimeAsync(200);+ expect(stream.destroy).toHaveBeenCalled();+ expect(read).not.toHaveBeenCalled();+ });});describe('BaileysEvents media download through a session proxy', () => {