Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): report the real size of an aborted media download

Yudhi Armyndharis5d9a2b6e2ce5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d41e1d1f9..e9a5fa09e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A Baileys reconnect loop is observable: `lastError` on the session, a `session.reconnect_loop` webhook every fifth attempt, and reconnect metrics ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
- The dashboard session card keeps the phone number, session id and last-active time while a linked session reconnects, instead of the pairing placeholder ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
- The Sessions page reports a dead live-event feed and re-reads the list once the feed recovers.
+- A Baileys media download aborted at `MEDIA_DOWNLOAD_MAX_BYTES` reports the bytes received as `sizeBytes`, and a timed-out one its declared size, instead of the cap.
- The takeover sweep marks sessions left `ready` or `initializing` by a node that never returned disconnected, regardless of `AUTO_START_SESSIONS`.
- Branch Docker images (`:main`, sha tags) rebuild the production apt layer, so they cannot serve stale OS packages from the build cache.
- The Message Tester's bulk-recipients file picker refuses files over 2 MB before reading them.
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index 9990ebd75..39de30cb8 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -718,16 +718,20 @@ export class BaileysEvents {
/**
* Download inbound media via a stream, accumulating chunks but ABORTING (destroy + discard) once the
- * running total exceeds `maxBytes`. Returns null on abort. Uses `downloadMediaMessage(..., 'stream')`
- * (not the raw `downloadContentFromMessage`) so the library's expired-media re-upload retry is kept;
- * for under-cap media the concatenated buffer is byte-identical to the 'buffer' mode it replaces.
+ * running total exceeds `maxBytes`. On that abort it resolves `{ overflowBytes }`, the bytes received
+ * when the cap tripped; past the wall-clock deadline it resolves null. Uses
+ * `downloadMediaMessage(..., 'stream')` (not the raw `downloadContentFromMessage`) so the library's
+ * expired-media re-upload retry is kept; 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> {
+ private async downloadInboundMediaCapped(
+ msg: WAMessage,
+ maxBytes: number,
+ ): Promise<Buffer | { overflowBytes: number } | 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.
+ // download/read error still rejects (propagating to the caller's catch as before).
let stream: (AsyncIterable<Buffer> & { destroy?: () => void }) | undefined;
- const download = (async (): Promise<Buffer | null> => {
+ const download = (async (): Promise<Buffer | { overflowBytes: number }> => {
const b = await this.host.loadLib();
stream = (await b.downloadMediaMessage(
msg,
@@ -745,7 +749,7 @@ export class BaileysEvents {
total += chunk.length;
if (total > maxBytes) {
stream.destroy?.();
- return null;
+ return { overflowBytes: total };
}
chunks.push(chunk);
}
@@ -754,7 +758,7 @@ 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 (same null the cap-abort returns).
+ // and treat it as no usable media.
return withInboundDownloadTimeout(download, inboundMediaTimeoutMs(), () => stream?.destroy?.());
}
@@ -822,8 +826,9 @@ export class BaileysEvents {
const declared = coerceDeclaredSize(subMessage?.fileLength);
if (declared > maxBytes) {
- // Pre-download gate: an honest over-cap sender's media is never decrypted into heap at all
- // (Baileys integrity-checks content against the declared size, so this is a robust bound).
+ // Pre-download gate: an honest over-cap sender's media is never decrypted into heap at all.
+ // Baileys does not check the decrypted bytes against the declared size, so a sender can
+ // understate it; the streaming abort below is the bound for that case.
this.host.logger.warn('Inbound media declared size exceeds MEDIA_DOWNLOAD_MAX_BYTES; skipped download', {
msgId: msg.key.id,
sizeBytes: declared,
@@ -836,11 +841,22 @@ export class BaileysEvents {
// can't materialise an over-cap blob. For under-cap media this yields the identical buffer.
const buf = await this.downloadInboundMediaCapped(msg, maxBytes);
if (buf === null) {
- this.host.logger.warn(
- 'Inbound media download aborted (over MEDIA_DOWNLOAD_MAX_BYTES or past MEDIA_DOWNLOAD_TIMEOUT_MS); emitting omitted marker',
- { msgId: msg.key.id },
- );
- return { mimetype, filename, omitted: true, sizeBytes: maxBytes };
+ // Nothing proves the real size, so report the declared one, as the failure branch below does.
+ this.host.logger.warn('Inbound media download passed MEDIA_DOWNLOAD_TIMEOUT_MS; emitting omitted marker', {
+ msgId: msg.key.id,
+ sizeBytes: declared,
+ });
+ return { mimetype, filename, omitted: true, sizeBytes: declared };
+ }
+ if (!Buffer.isBuffer(buf)) {
+ // The bytes received are a lower bound above the cap; the declared size passed the pre-gate, so
+ // it is smaller and says nothing here.
+ const sizeBytes = buf.overflowBytes;
+ this.host.logger.warn('Inbound media download exceeded MEDIA_DOWNLOAD_MAX_BYTES; emitting omitted marker', {
+ msgId: msg.key.id,
+ sizeBytes,
+ });
+ return { mimetype, filename, omitted: true, sizeBytes };
}
// 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.
@@ -853,7 +869,7 @@ export class BaileysEvents {
} catch (err) {
// A download failure yields the omitted marker, never a propagated throw: the media field stays
// present, matching the skip/pre-gate/abort exits above. The declared size is the honest number
- // here, since nothing was downloaded and the cap the abort reports would be a fabrication.
+ // here: the download never completed, so no measured size exists.
this.host.logger.warn('Inbound media download failed; emitting the omitted marker', {
error: err instanceof Error ? err.message : String(err),
msgId: msg.key.id,
diff --git a/src/engine/adapters/baileys-media-abort.spec.ts b/src/engine/adapters/baileys-media-abort.spec.ts
new file mode 100644
index 000000000..7cd850fc3
--- /dev/null
+++ b/src/engine/adapters/baileys-media-abort.spec.ts
@@ -0,0 +1,123 @@
+import { BaileysEvents, type BaileysEventsHost } from './baileys-events';
+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
+import { createLogger } from '../../common/services/logger.service';
+import type { WAMessage, WASocket } from '@whiskeysockets/baileys';
+
+/**
+ * An inbound download stops for one of two reasons, and the omitted marker has to say which size it
+ * knows. Past MEDIA_DOWNLOAD_MAX_BYTES the stream has proven the payload is larger than the cap, so
+ * the bytes received are a lower bound; the sender's declared size already passed the pre-gate and is
+ * smaller by construction. Past MEDIA_DOWNLOAD_TIMEOUT_MS nothing is proven, so the declared size is
+ * the only number, as on a download failure and on whatsapp-web.js. Reporting the cap for both, as
+ * before, made a 12-byte overflow and a stalled 4096-byte image look identical.
+ */
+
+type Stream = AsyncIterable<Buffer> & { destroy: jest.Mock };
+
+const downloadMediaMessage = jest.fn();
+
+function imageMessage(id: string, fileLength: number): WAMessage {
+ return {
+ key: { id, remoteJid: '[email protected]', fromMe: false },
+ messageTimestamp: 1_700_000_000,
+ message: { imageMessage: { mimetype: 'image/png', fileLength } },
+ };
+}
+
+function build(): { 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 }),
+ toNeutralJid: (jid: string) => jid,
+ normalizedSelfJid: () => '[email protected]',
+ connectedAt: 0,
+ inboundLimiter: new ConcurrencyLimiter(1),
+ recordKeyLidMappings: () => undefined,
+ recordMessage: () => undefined,
+ recordMessageEdit: () => undefined,
+ putStoredMessage: () => undefined,
+ getOnMessage: () => undefined,
+ getOnMessageCreate: () => undefined,
+ getOnMessageRevoked: () => undefined,
+ getOnMessageEdited: () => undefined,
+ getOnMessageReaction: () => undefined,
+ getOnMessageAck: () => undefined,
+ getOnGroupEvent: () => undefined,
+ getOnCall: () => undefined,
+ getOnPresenceUpdate: () => undefined,
+ getOnCallOutcome: () => undefined,
+ } as unknown as BaileysEventsHost);
+ return { events, warns };
+}
+
+describe('BaileysEvents aborted media download size', () => {
+ const saved = {
+ MEDIA_DOWNLOAD_ENABLED: process.env.MEDIA_DOWNLOAD_ENABLED,
+ MEDIA_DOWNLOAD_MAX_BYTES: process.env.MEDIA_DOWNLOAD_MAX_BYTES,
+ MEDIA_DOWNLOAD_TIMEOUT_MS: process.env.MEDIA_DOWNLOAD_TIMEOUT_MS,
+ };
+
+ beforeEach(() => {
+ downloadMediaMessage.mockReset();
+ // An ambient 'false' takes the skip exit, whose marker carries the declared size and would let
+ // the timeout case pass without downloading anything.
+ process.env.MEDIA_DOWNLOAD_ENABLED = 'true';
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ for (const [key, value] of Object.entries(saved)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ it('reports the bytes received when the stream passes MEDIA_DOWNLOAD_MAX_BYTES', async () => {
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '10';
+ const stream: Stream = {
+ // eslint-disable-next-line @typescript-eslint/require-await
+ async *[Symbol.asyncIterator]() {
+ yield Buffer.alloc(6);
+ yield Buffer.alloc(6);
+ yield Buffer.alloc(6);
+ },
+ destroy: jest.fn(),
+ };
+ downloadMediaMessage.mockResolvedValue(stream);
+ const { events, warns } = build();
+
+ // Declares 5 bytes, under the cap, so the pre-gate lets it through; the second chunk trips the cap.
+ const incoming = await events.mapMessage(imageMessage('LIAR', 5), 'imageMessage');
+
+ expect(incoming.media).toEqual({ mimetype: 'image/png', filename: undefined, omitted: true, sizeBytes: 12 });
+ expect(stream.destroy).toHaveBeenCalled();
+ expect(warns).toEqual([expect.stringContaining('MEDIA_DOWNLOAD_MAX_BYTES')]);
+ expect(warns[0]).not.toContain('MEDIA_DOWNLOAD_TIMEOUT_MS');
+ });
+
+ it('reports the declared size when the download passes MEDIA_DOWNLOAD_TIMEOUT_MS', async () => {
+ jest.useFakeTimers();
+ process.env.MEDIA_DOWNLOAD_TIMEOUT_MS = '50';
+ const stream: Stream = {
+ async *[Symbol.asyncIterator]() {
+ yield Buffer.alloc(16);
+ await new Promise<never>(() => undefined);
+ },
+ destroy: jest.fn(),
+ };
+ downloadMediaMessage.mockResolvedValue(stream);
+ const { events, warns } = build();
+
+ const pending = events.mapMessage(imageMessage('SLOW', 4096), 'imageMessage');
+ await jest.advanceTimersByTimeAsync(50);
+ const incoming = await pending;
+
+ expect(incoming.media).toEqual({ mimetype: 'image/png', filename: undefined, omitted: true, sizeBytes: 4096 });
+ expect(stream.destroy).toHaveBeenCalled();
+ expect(warns).toEqual([expect.stringContaining('MEDIA_DOWNLOAD_TIMEOUT_MS')]);
+ expect(warns[0]).not.toContain('MEDIA_DOWNLOAD_MAX_BYTES');
+ });
+});
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index cba96b6a0..849ad24bf 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -2698,7 +2698,7 @@ describe('BaileysAdapter inbound fan-out', () => {
});
await new Promise(r => setImmediate(r));
// The message is still emitted, and it still says it carried an image. sizeBytes is the DECLARED
- // size: nothing was downloaded, so reporting the cap (as the streaming abort does) would lie.
+ // size: nothing was downloaded, so reporting the cap would lie.
expect(onMessage).toHaveBeenCalledTimes(1);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const msg = onMessage.mock.calls[0][0] as { media?: unknown; body?: string };
diff --git a/src/engine/adapters/inbound-media-cap.ts b/src/engine/adapters/inbound-media-cap.ts
index b4deca39f..351b020b6 100644
--- a/src/engine/adapters/inbound-media-cap.ts
+++ b/src/engine/adapters/inbound-media-cap.ts
@@ -47,10 +47,10 @@ export function inboundMediaTimeoutMs(): number {
* 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 — a best-effort
* hook to abort the source where it's abortable (e.g. destroy a Baileys stream) — and the result resolves
- * `null`, the same "no usable media" sentinel the byte-cap abort returns. A non-abortable source (the wwjs
- * `downloadMedia()`) can't be stopped, so that caller must instead hold its concurrency slot until the real
- * download settles. A late rejection from the abandoned download is swallowed so it can't surface as an
- * unhandled rejection after the race has already settled.
+ * `null`, the "no usable media" sentinel. A non-abortable source (the wwjs `downloadMedia()`) can't be
+ * stopped, so that caller must instead hold its concurrency slot until the real download settles. 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>,