Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): bound inbound media downloads with a wall-clock timeout (#510)

Yudhi Armyndharis4cb9ebe8ec26
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index de3d81a1e..5a990b07c 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -46,7 +46,9 @@ import {
coerceDeclaredSize,
inboundMediaConcurrency,
inboundMediaMaxBytes,
+ inboundMediaTimeoutMs,
isMediaDownloadEnabled,
+ withInboundDownloadTimeout,
} from './inbound-media-cap';
import { ConcurrencyLimiter } from './concurrency-limiter';
@@ -981,28 +983,39 @@ export class BaileysAdapter implements IWhatsAppEngine {
* for under-cap media the concatenated buffer is byte-identical to the 'buffer' mode it replaces.
*/
private async downloadInboundMediaCapped(msg: WAMessage, maxBytes: number): Promise<Buffer | null> {
- const b = await this.loadLib();
- const stream = (await b.downloadMediaMessage(
- msg,
- 'stream',
- {},
- {
- logger: createSilentLogger(),
- reuploadRequest: this.sock!.updateMediaMessage,
- },
- )) as AsyncIterable<Buffer> & { destroy?: () => void };
-
- const chunks: Buffer[] = [];
- let total = 0;
- for await (const chunk of stream) {
- total += chunk.length;
- if (total > maxBytes) {
- stream.destroy?.();
- return null;
+ // 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); only a
+ // wall-clock timeout or the byte-cap overflow resolves to null.
+ let stream: (AsyncIterable<Buffer> & { destroy?: () => void }) | undefined;
+ const download = (async (): Promise<Buffer | null> => {
+ const b = await this.loadLib();
+ stream = (await b.downloadMediaMessage(
+ msg,
+ 'stream',
+ {},
+ {
+ logger: createSilentLogger(),
+ reuploadRequest: this.sock!.updateMediaMessage,
+ },
+ )) as AsyncIterable<Buffer> & { destroy?: () => void };
+
+ const chunks: Buffer[] = [];
+ let total = 0;
+ for await (const chunk of stream) {
+ total += chunk.length;
+ if (total > maxBytes) {
+ stream.destroy?.();
+ return null;
+ }
+ chunks.push(chunk);
}
- chunks.push(chunk);
- }
- return Buffer.concat(chunks);
+ return Buffer.concat(chunks);
+ })();
+
+ // 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 (same null the cap-abort returns).
+ return withInboundDownloadTimeout(download, inboundMediaTimeoutMs(), () => stream?.destroy?.());
}
private async mapMessage(msg: WAMessage, contentType: string | undefined): Promise<IncomingMessage> {
@@ -1090,9 +1103,10 @@ export class BaileysAdapter implements IWhatsAppEngine {
const buf = await this.downloadInboundMediaCapped(msg, maxBytes);
if (buf === null) {
media = { mimetype, filename, omitted: true, sizeBytes: maxBytes };
- this.logger.warn('Inbound media exceeded MEDIA_DOWNLOAD_MAX_BYTES mid-download; aborted', {
- msgId: msg.key.id,
- });
+ this.logger.warn(
+ 'Inbound media download aborted (over MEDIA_DOWNLOAD_MAX_BYTES or past MEDIA_DOWNLOAD_TIMEOUT_MS); emitting omitted marker',
+ { msgId: msg.key.id },
+ );
} else {
// capInboundMedia is the last line (lazy base64, never persist/webhook/broadcast an over-cap
// blob); the real heap bound is the pre-gate + streaming abort + concurrency limiter.
diff --git a/src/engine/adapters/inbound-media-cap.spec.ts b/src/engine/adapters/inbound-media-cap.spec.ts
index 3ff2e8cdb..96824b7ac 100644
--- a/src/engine/adapters/inbound-media-cap.spec.ts
+++ b/src/engine/adapters/inbound-media-cap.spec.ts
@@ -2,6 +2,8 @@ import {
capInboundMedia,
inboundMediaMaxBytes,
inboundMediaConcurrency,
+ inboundMediaTimeoutMs,
+ withInboundDownloadTimeout,
coerceDeclaredSize,
isMediaDownloadEnabled,
} from './inbound-media-cap';
@@ -9,13 +11,60 @@ import {
describe('inbound media cap', () => {
const ENV = 'MEDIA_DOWNLOAD_MAX_BYTES';
const CONC = 'INBOUND_MEDIA_CONCURRENCY';
+ const TMO = 'MEDIA_DOWNLOAD_TIMEOUT_MS';
const orig = process.env[ENV];
const origConc = process.env[CONC];
+ const origTmo = process.env[TMO];
afterEach(() => {
if (orig === undefined) delete process.env[ENV];
else process.env[ENV] = orig;
if (origConc === undefined) delete process.env[CONC];
else process.env[CONC] = origConc;
+ if (origTmo === undefined) delete process.env[TMO];
+ else process.env[TMO] = origTmo;
+ });
+
+ describe('inboundMediaTimeoutMs', () => {
+ it('defaults to 30000', () => {
+ delete process.env[TMO];
+ expect(inboundMediaTimeoutMs()).toBe(30_000);
+ });
+ it('honors a positive override', () => {
+ process.env[TMO] = '5000';
+ expect(inboundMediaTimeoutMs()).toBe(5000);
+ });
+ it('falls back to the default for a non-positive/garbage override', () => {
+ process.env[TMO] = '0';
+ expect(inboundMediaTimeoutMs()).toBe(30_000);
+ process.env[TMO] = 'abc';
+ expect(inboundMediaTimeoutMs()).toBe(30_000);
+ });
+ });
+
+ describe('withInboundDownloadTimeout', () => {
+ it('returns the value when the download settles before the deadline', async () => {
+ const onTimeout = jest.fn();
+ await expect(withInboundDownloadTimeout(Promise.resolve('buf'), 1000, onTimeout)).resolves.toBe('buf');
+ expect(onTimeout).not.toHaveBeenCalled();
+ });
+
+ it('resolves null and runs onTimeout when the download outlasts the deadline', async () => {
+ const onTimeout = jest.fn();
+ const slow = new Promise<string>(resolve => setTimeout(() => resolve('late'), 1000).unref?.());
+ await expect(withInboundDownloadTimeout(slow, 5, onTimeout)).resolves.toBeNull();
+ expect(onTimeout).toHaveBeenCalledTimes(1);
+ });
+
+ it('swallows a late rejection from the abandoned download (no unhandled rejection)', async () => {
+ let rejectFn: (e: Error) => void = () => undefined;
+ const slow = new Promise<string>((_, reject) => {
+ rejectFn = reject;
+ });
+ await expect(withInboundDownloadTimeout(slow, 5)).resolves.toBeNull();
+ // Reject AFTER the race settled — must not surface as an unhandled rejection.
+ rejectFn(new Error('media socket closed'));
+ await Promise.resolve();
+ });
});
describe('inboundMediaConcurrency', () => {
diff --git a/src/engine/adapters/inbound-media-cap.ts b/src/engine/adapters/inbound-media-cap.ts
index 028c6fd85..962aab05e 100644
--- a/src/engine/adapters/inbound-media-cap.ts
+++ b/src/engine/adapters/inbound-media-cap.ts
@@ -22,6 +22,43 @@ export function inboundMediaConcurrency(): number {
return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_INBOUND_MEDIA_CONCURRENCY;
}
+/** Default inbound media download timeout: 30s. Shares MEDIA_DOWNLOAD_TIMEOUT_MS with the outbound download. */
+const DEFAULT_INBOUND_MEDIA_TIMEOUT_MS = 30_000;
+
+/** Resolved per-download wall-clock timeout; a non-positive/garbage override falls back to the default. */
+export function inboundMediaTimeoutMs(): number {
+ const parsed = Number.parseInt(process.env.MEDIA_DOWNLOAD_TIMEOUT_MS ?? '', 10);
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_INBOUND_MEDIA_TIMEOUT_MS;
+}
+
+/**
+ * Bound an inbound media download by a wall-clock deadline. The byte cap and concurrency limiter don't
+ * bound TIME: a remote sender can trickle bytes slowly (never tripping the cap) and hold a concurrency
+ * slot indefinitely — a slow-loris on the inbound pipeline. On timeout `onTimeout` runs (e.g. destroy
+ * the stream so the abandoned download can't keep allocating) and the result resolves `null`, the same
+ * "no usable media" sentinel the byte-cap abort returns. A late rejection from the abandoned download is
+ * swallowed so it can't surface as an unhandled rejection after the race has already settled.
+ */
+export function withInboundDownloadTimeout<T>(
+ promise: Promise<T>,
+ timeoutMs: number,
+ onTimeout?: () => void,
+): Promise<T | null> {
+ let timer: NodeJS.Timeout | undefined;
+ const timeout = new Promise<null>(resolve => {
+ timer = setTimeout(() => {
+ onTimeout?.();
+ resolve(null);
+ }, timeoutMs);
+ timer.unref?.();
+ });
+ // Defuse a post-settle rejection from the download we may stop awaiting.
+ promise.catch(() => undefined);
+ return Promise.race([promise, timeout]).finally(() => {
+ if (timer) clearTimeout(timer);
+ });
+}
+
/**
* Whether inbound media download is enabled. When false, the engine skips downloading media from
* incoming messages entirely — no decryption, no memory allocation, no storage. Override via
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 7545a37d2..4c3f7720b 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -53,7 +53,9 @@ import {
coerceDeclaredSize,
inboundMediaConcurrency,
inboundMediaMaxBytes,
+ inboundMediaTimeoutMs,
isMediaDownloadEnabled,
+ withInboundDownloadTimeout,
} from './inbound-media-cap';
import { ConcurrencyLimiter } from './concurrency-limiter';
@@ -225,7 +227,19 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
sizeBytes: declared,
};
}
- const media = await this.inboundLimiter.run(() => msg.downloadMedia());
+ // Bound the download by a wall-clock deadline: msg.downloadMedia() can't be aborted, so a
+ // trickling sender would otherwise pin a concurrency slot indefinitely. On timeout the slot is
+ // released (the run task resolves null) and the message is emitted without media.
+ const media = await this.inboundLimiter.run(() =>
+ withInboundDownloadTimeout(msg.downloadMedia(), inboundMediaTimeoutMs(), () =>
+ this.logger.warn(
+ 'Inbound media download timed out (MEDIA_DOWNLOAD_TIMEOUT_MS); emitting message without media',
+ {
+ msgId: msg.id._serialized,
+ },
+ ),
+ ),
+ );
if (!media) return undefined;
const capped = capInboundMedia({
mimetype: media.mimetype,