Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine,message): bound peer-fed session maps and inline-media aggregation (#951)

Yudhi Armyndharis93242fec0e92
diff --git a/.env.example b/.env.example
index 700f3721b..f8f208815 100644
--- a/.env.example
+++ b/.env.example
@@ -153,6 +153,11 @@ BAILEYS_SYNC_FULL_HISTORY=false
# cap (legacy unbounded behaviour). Default 5000.
# LID_MAPPING_CACHE_MAX=5000
+# Per-map cap on the Baileys session store's in-memory maps (contacts, chats, lastMessages, lidToPn,
+# ephemeralByChat — all fed by peer traffic). A miss falls back to the persisted lid table, a
+# re-resolution, or a defined empty result, so eviction never loses data. 0 disables the cap. Default 5000.
+# BAILEYS_SESSION_STORE_MAX_ENTRIES=5000
+
# Observability — Prometheus scrape endpoint at GET /api/metrics.
# Disabled by default; set a token to enable. Scrapers must send `Authorization: Bearer <token>`.
# METRICS_TOKEN=change-me-to-a-long-random-string
@@ -291,6 +296,11 @@ WEBHOOK_SSRF_PROTECT=true
# download holds memory up to MEDIA_DOWNLOAD_MAX_BYTES; this bounds N. A non-positive/garbage value
# falls back to the default.
# INBOUND_MEDIA_CONCURRENCY=4 # default 4
+# Aggregate base64 budget for media inlined by ONE GET .../messages/:chatId/history?includeMedia=true
+# call. Once the running total crosses it, remaining media messages return the declared-only `omitted`
+# marker instead of a download, so a media-heavy history can't stack ~100 × the per-message cap into a
+# single response. A non-positive/garbage value falls back to the default.
+# CHAT_HISTORY_MEDIA_BUDGET_BYTES=26214400 # default 25 MiB
# Per-file cap on status (Story) media persisted to disk/S3. A status whose media exceeds this is
# stored omitted (mediaOmitted=true) rather than rejected. A non-positive/garbage value falls back.
# STATUS_MEDIA_MAX_BYTES=10485760 # default 10 MiB
diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.ts
index afeaf2675..ef0eb3565 100644
--- a/src/engine/adapters/baileys-session-store.spec.ts
+++ b/src/engine/adapters/baileys-session-store.spec.ts
@@ -1,4 +1,5 @@
import { BaileysSessionStore } from './baileys-session-store';
+import type { LidMappingStore } from '../identity/lid-mapping-store.service';
describe('BaileysSessionStore', () => {
let store: BaileysSessionStore;
@@ -363,4 +364,119 @@ describe('BaileysSessionStore', () => {
expect(s.resolvePhone('666@lid')).toBeNull();
});
});
+
+ describe('map bounds (BAILEYS_SESSION_STORE_MAX_ENTRIES)', () => {
+ const ENV = 'BAILEYS_SESSION_STORE_MAX_ENTRIES';
+ const orig = process.env[ENV];
+ afterEach(() => {
+ if (orig === undefined) delete process.env[ENV];
+ else process.env[ENV] = orig;
+ });
+
+ const storeWithCap = (cap: string, lidStore?: LidMappingStore) => {
+ process.env[ENV] = cap;
+ return new BaileysSessionStore(lidStore);
+ };
+
+ it('evicts the oldest contact once over the cap; the miss reads as "unknown"', () => {
+ const s = storeWithCap('2');
+ s.upsertContacts([{ id: '[email protected]', name: 'A' }]);
+ s.upsertContacts([{ id: '[email protected]', name: 'B' }]);
+ s.upsertContacts([{ id: '[email protected]', name: 'C' }]);
+ expect(s.listContacts()).toHaveLength(2);
+ expect(s.findContact('[email protected]')).toBeNull(); // evicted — same as never seen
+ expect(s.findContact('[email protected]')?.name).toBe('B');
+ expect(s.findContact('[email protected]')?.name).toBe('C');
+ });
+
+ it('treats a read as usage: a refreshed entry survives while a stale one is evicted (LRU)', () => {
+ const s = storeWithCap('2');
+ s.upsertContacts([{ id: '[email protected]', name: 'A' }]);
+ s.upsertContacts([{ id: '[email protected]', name: 'B' }]);
+ expect(s.findContact('[email protected]')?.name).toBe('A'); // refresh A
+ s.upsertContacts([{ id: '[email protected]', name: 'C' }]); // evicts B, not A
+ expect(s.findContact('[email protected]')?.name).toBe('A');
+ expect(s.findContact('[email protected]')).toBeNull();
+ });
+
+ it('bounds chats: listChats stays at the cap and drops the oldest conversation', () => {
+ const s = storeWithCap('2');
+ s.upsertChats([{ id: '[email protected]', name: 'A' }]);
+ s.upsertChats([{ id: '[email protected]', name: 'B' }]);
+ s.upsertChats([{ id: '[email protected]', name: 'C' }]);
+ expect(s.listChats().map(c => c.id)).toEqual(['[email protected]', '[email protected]']);
+ });
+
+ it('bounds lastMessages: an evicted preview reads as the null miss callers already handle', () => {
+ const s = storeWithCap('2');
+ for (const [i, ts] of [
+ ['628111', 100],
+ ['628222', 200],
+ ['628333', 300],
+ ] as const) {
+ s.recordMessage({
+ key: { remoteJid: `${i}@s.whatsapp.net`, fromMe: false, id: `M-${i}` },
+ message: { conversation: 'hi' },
+ messageTimestamp: ts,
+ });
+ }
+ expect(s.lastMessage('[email protected]')).toBeNull(); // sendSeen/markUnread/deleteChat → false
+ expect(s.lastMessage('[email protected]')?.key.id).toBe('M-628333');
+ });
+
+ it('bounds lidToPn: an evicted mapping still resolves via the write-through persistent table', () => {
+ const map = new Map<string, string | null>();
+ const lidStore = {
+ getCached: jest.fn((lid: string) => map.get(lid)),
+ lidsForPhone: jest.fn(() => [] as string[]),
+ remember: jest.fn((lid: string, phone: string | null) => {
+ map.set(lid, phone);
+ return Promise.resolve();
+ }),
+ };
+ const s = storeWithCap('2', lidStore);
+ s.addLidMappings([
+ { lid: '111@lid', pn: '[email protected]' },
+ { lid: '222@lid', pn: '[email protected]' },
+ { lid: '333@lid', pn: '[email protected]' },
+ ]);
+ // 111 was evicted from memory: resolution falls through to the persisted row (getCached hit).
+ expect(s.resolvePhone('111@lid')).toBe('628111');
+ expect(lidStore.getCached).toHaveBeenCalledWith('111');
+ // 333 is still in memory: no persistent-table read needed.
+ expect(s.resolvePhone('333@lid')).toBe('628333');
+ expect(lidStore.getCached).not.toHaveBeenCalledWith('333');
+ });
+
+ it('bounds ephemeralByChat (two keys per chat): the oldest chat timer falls back to undefined', () => {
+ const s = storeWithCap('2'); // timer map allows 2 × cap = 4 keys → two chats
+ for (const i of ['628111', '628222', '628333']) {
+ s.recordMessage({
+ key: { remoteJid: `${i}@s.whatsapp.net`, fromMe: false, id: `M-${i}` },
+ message: { conversation: 'hi' },
+ messageTimestamp: 100,
+ ephemeralDuration: 86400,
+ });
+ }
+ expect(s.getEphemeralExpiration('[email protected]')).toBeUndefined(); // evicted → no forced timer
+ expect(s.getEphemeralExpiration('[email protected]')).toBe(86400);
+ expect(s.getEphemeralExpiration('[email protected]')).toBe(86400);
+ });
+
+ it('treats 0 as unbounded (legacy behaviour)', () => {
+ const s = storeWithCap('0');
+ for (let i = 0; i < 100; i++) {
+ s.upsertContacts([{ id: `62${1000 + i}@s.whatsapp.net` }]);
+ }
+ expect(s.listContacts()).toHaveLength(100);
+ });
+
+ it('falls back to the 5000 default for a garbage override', () => {
+ const s = storeWithCap('not-a-number');
+ s.upsertContacts(Array.from({ length: 5001 }, (_, i) => ({ id: `62${100000 + i}@s.whatsapp.net` })));
+ expect(s.listContacts()).toHaveLength(5000);
+ expect(s.findContact('[email protected]')).toBeNull(); // the oldest went first
+ expect(s.findContact('[email protected]')).not.toBeNull();
+ });
+ });
});
diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.ts
index 63fb1ce65..9984f5037 100644
--- a/src/engine/adapters/baileys-session-store.ts
+++ b/src/engine/adapters/baileys-session-store.ts
@@ -9,16 +9,75 @@ interface LastMessage {
text: string;
}
+// Default per-map entry cap, matching the other per-session bounds (LID_MAPPING_CACHE_MAX,
+// BAILEYS_MESSAGE_STORE_LIMIT, the session lidPhoneCache — all 5000). Every read below has a defined
+// miss path, so an eviction only costs a re-resolution/re-read, never data loss.
+export const SESSION_STORE_MAP_CAP_DEFAULT = 5000;
+
+/**
+ * Insertion-ordered Map with an LRU cap, the same discipline as LidMappingStoreService: a read or
+ * write re-inserts the key at the most-recent end, and a set evicts the least-recently-used entry
+ * while over `max`. `max = 0` means unbounded.
+ */
+class LruMap<K, V> {
+ private readonly map = new Map<K, V>();
+
+ constructor(private readonly max: number) {}
+
+ has(key: K): boolean {
+ return this.map.has(key);
+ }
+
+ get(key: K): V | undefined {
+ if (!this.map.has(key)) {
+ return undefined;
+ }
+ const value = this.map.get(key) as V;
+ this.map.delete(key);
+ this.map.set(key, value);
+ return value;
+ }
+
+ set(key: K, value: V): void {
+ this.map.delete(key);
+ this.map.set(key, value);
+ if (!this.max) {
+ return;
+ }
+ while (this.map.size > this.max) {
+ const oldest = this.map.keys().next().value;
+ if (oldest === undefined) {
+ break;
+ }
+ this.map.delete(oldest);
+ }
+ }
+
+ values(): IterableIterator<V> {
+ return this.map.values();
+ }
+}
+
/**
* Per-session, in-memory snapshot of Baileys contacts + chats, fed from `sock.ev` events. Baileys has
* no fetch-all; this data arrives via `contacts.*`/`chats.*`/`messaging-history.set` (a full re-sync on
* each connect) and is mapped to the neutral `Contact`/`ChatSummary` on read. Holds no socket — pure data.
+ *
+ * Every map is LRU-bounded (`BAILEYS_SESSION_STORE_MAX_ENTRIES`, default 5000 per map, 0 = unbounded)
+ * because contacts/chats/lastMessages/lidToPn all grow from peer-controlled traffic — without a cap a
+ * chatty account leaks one entry per distinct peer ever seen. Miss paths after an eviction:
+ * `lidToPn` falls back to the contacts map and then the persisted cross-session lid->phone table (all
+ * writes are written through), `lastMessage` reads null (callers treat it as "nothing known"),
+ * `getEphemeralExpiration` falls back to `Chat.ephemeralExpiration` then undefined (never forces a
+ * timer), and contact/name lookups degrade to the raw user-part. `ephemeralByChat` is keyed under both
+ * the raw and neutral JID (two entries per chat), so its cap is doubled to cover the same number of
+ * chats.
*/
export class BaileysSessionStore {
- private readonly contacts = new Map<string, BaileysContact>();
- private readonly chats = new Map<string, Chat>();
- private readonly lastMessages = new Map<string, LastMessage>();
- private readonly lidToPn = new Map<string, string>();
+ private readonly contacts: LruMap<string, BaileysContact>;
+ private readonly chats: LruMap<string, Chat>;
+ private readonly lastMessages: LruMap<string, LastMessage>;
+ private readonly lidToPn: LruMap<string, string>;
/**
* Per-chat disappearing-messages timer (seconds) learned from inbound messages (#473), the reliable
* source for it: `Chat.ephemeralExpiration` (from `chats.*`/history sync) is empirically absent for a
@@ -27,7 +86,7 @@ export class BaileysSessionStore {
* `@s.whatsapp.net` or `@lid`) resolves to the same entry. See {@link extractEphemeralDuration} for
* which message field is read.
*/
- private readonly ephemeralByChat = new Map<string, number>();
+ private readonly ephemeralByChat: LruMap<string, number>;
/**
* @param lidStore optional persisted, cross-session lid->phone table that backs resolution beyond
@@ -37,7 +96,17 @@ export class BaileysSessionStore {
constructor(
private readonly lidStore?: LidMappingStore,
private readonly sessionId?: string,
- ) {}
+ ) {
+ // Mirrors LidMappingStoreService: a finite default, 0 opts back into unbounded, garbage falls back.
+ const parsed = Number(process.env.BAILEYS_SESSION_STORE_MAX_ENTRIES ?? SESSION_STORE_MAP_CAP_DEFAULT);
+ const maxEntries = Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : SESSION_STORE_MAP_CAP_DEFAULT;
+ this.contacts = new LruMap(maxEntries);
+ this.chats = new LruMap(maxEntries);
+ this.lastMessages = new LruMap(maxEntries);
+ this.lidToPn = new LruMap(maxEntries);
+ // Double-keyed (raw + neutral JID per chat), so it needs two slots per chat to cover the same span.
+ this.ephemeralByChat = new LruMap(maxEntries * 2);
+ }
upsertContacts(records: Partial<BaileysContact>[] = []): void {
for (const r of records) {
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 9e1873af8..f7f93f32b 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -1116,6 +1116,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
_limit?: number,
_includeMedia?: boolean,
_mediaMaxBytes?: number,
+ _signal?: AbortSignal,
): Promise<IncomingMessage[]> {
return this.unsupported('getChatHistory');
}
diff --git a/src/engine/adapters/inbound-media-cap.spec.ts b/src/engine/adapters/inbound-media-cap.spec.ts
index 96824b7ac..5ab2a720e 100644
--- a/src/engine/adapters/inbound-media-cap.spec.ts
+++ b/src/engine/adapters/inbound-media-cap.spec.ts
@@ -1,5 +1,6 @@
import {
capInboundMedia,
+ chatHistoryMediaBudgetBytes,
inboundMediaMaxBytes,
inboundMediaConcurrency,
inboundMediaTimeoutMs,
@@ -171,6 +172,30 @@ describe('inbound media cap', () => {
});
});
+ describe('chatHistoryMediaBudgetBytes', () => {
+ const ENV = 'CHAT_HISTORY_MEDIA_BUDGET_BYTES';
+ const orig = process.env[ENV];
+ afterEach(() => {
+ if (orig === undefined) delete process.env[ENV];
+ else process.env[ENV] = orig;
+ });
+
+ it('defaults to 25 MiB', () => {
+ delete process.env[ENV];
+ expect(chatHistoryMediaBudgetBytes()).toBe(25 * 1024 * 1024);
+ });
+ it('honors a positive override', () => {
+ process.env[ENV] = '1024';
+ expect(chatHistoryMediaBudgetBytes()).toBe(1024);
+ });
+ it('falls back to the default for a non-positive/garbage override', () => {
+ process.env[ENV] = '0';
+ expect(chatHistoryMediaBudgetBytes()).toBe(25 * 1024 * 1024);
+ process.env[ENV] = 'abc';
+ expect(chatHistoryMediaBudgetBytes()).toBe(25 * 1024 * 1024);
+ });
+ });
+
describe('capInboundMedia', () => {
it('keeps media within the cap, encoding base64 exactly once', () => {
const toBase64 = jest.fn(() => 'BASE64DATA');
diff --git a/src/engine/adapters/inbound-media-cap.ts b/src/engine/adapters/inbound-media-cap.ts
index 40a6ab040..301af5b56 100644
--- a/src/engine/adapters/inbound-media-cap.ts
+++ b/src/engine/adapters/inbound-media-cap.ts
@@ -71,6 +71,23 @@ export function isMediaDownloadEnabled(): boolean {
return val !== 'false' && val !== '0' && val !== 'no';
}
+/**
+ * Default aggregate base64 budget for one getChatHistory(includeMedia=true) call: 25 MiB of inlined
+ * payload. The per-message cap (MEDIA_DOWNLOAD_MAX_BYTES) bounds ONE blob, but a 100-message history
+ * could otherwise stack ~100 × 50 MiB of base64 into a single response (and its JSON serialisation).
+ */
+const DEFAULT_CHAT_HISTORY_MEDIA_BUDGET_BYTES = 25 * 1024 * 1024;
+
+/**
+ * Aggregate budget (counted in base64 characters, the actual response/heap payload) for media inlined
+ * by one getChatHistory pass. Once the running total crosses it, remaining media messages carry the
+ * usual `omitted` marker instead of a download. A non-positive/garbage override falls back to the default.
+ */
+export function chatHistoryMediaBudgetBytes(): number {
+ const parsed = Number.parseInt(process.env.CHAT_HISTORY_MEDIA_BUDGET_BYTES ?? '', 10);
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_CHAT_HISTORY_MEDIA_BUDGET_BYTES;
+}
+
/**
* Coerce a sender-declared media size (a protobuf `fileLength`, which may be a number, a Long-like
* `{ toNumber() }`, a numeric string, or absent) to a finite byte count. Unknown/garbage → 0, i.e.
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 4661cc369..967a32f61 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -403,6 +403,94 @@ describe('WhatsAppWebJsAdapter.getChatHistory enrichment (parity with the live p
expect(mediaMsg.downloadMedia).not.toHaveBeenCalled();
expect(out[0].media).toMatchObject({ omitted: true, sizeBytes: 12 * 1024 * 1024, mimetype: 'image/jpeg' });
});
+
+ describe('aggregate media budget + abort', () => {
+ const ENV = 'CHAT_HISTORY_MEDIA_BUDGET_BYTES';
+ const orig = process.env[ENV];
+ afterEach(() => {
+ if (orig === undefined) delete process.env[ENV];
+ else process.env[ENV] = orig;
+ });
+
+ const mediaMsg = (id: string, data: string) => ({
+ id: { _serialized: id },
+ to: 'me',
+ body: '',
+ type: 'image',
+ timestamp: 100,
+ fromMe: false,
+ hasMedia: true,
+ hasQuotedMsg: false,
+ _data: { size: data.length, mimetype: 'image/jpeg' },
+ downloadMedia: jest.fn().mockResolvedValue({ data, mimetype: 'image/jpeg' }),
+ });
+ const clientFor = (...msgs: unknown[]) => ({
+ getChatById: jest.fn().mockResolvedValue({ fetchMessages: jest.fn().mockResolvedValue(msgs) }),
+ });
+
+ it('inlines every media payload while the running total stays under the budget (unchanged behaviour)', async () => {
+ process.env[ENV] = '100';
+ const m1 = mediaMsg('M6', 'QUJD');
+ const m2 = mediaMsg('M7', 'QUJDRA');
+
+ const out = await readyAdapter(clientFor(m1, m2)).getChatHistory('[email protected]', 50, true);
+
+ expect(m1.downloadMedia).toHaveBeenCalled();
+ expect(m2.downloadMedia).toHaveBeenCalled();
+ expect(out[0].media).toEqual({ mimetype: 'image/jpeg', data: 'QUJD' });
+ expect(out[1].media).toEqual({ mimetype: 'image/jpeg', data: 'QUJDRA' });
+ });
+
+ it('marks later media omitted once the budget is spent — no download, bounded response', async () => {
+ process.env[ENV] = '4'; // exactly the first payload's base64 length
+ const m1 = mediaMsg('M8', 'QUJD');
+ const m2 = mediaMsg('M9', 'QUJD');
+ const m3 = mediaMsg('M10', 'QUJD');
+
+ const out = await readyAdapter(clientFor(m1, m2, m3)).getChatHistory('[email protected]', 50, true);
+
+ // The message that consumes the last of the budget stays inline (check-then-spend); only the
+ // messages AFTER the budget is exhausted degrade to the declared-only marker.
+ expect(out[0].media).toEqual({ mimetype: 'image/jpeg', data: 'QUJD' });
+ expect(out[1].media).toEqual({ mimetype: 'image/jpeg', omitted: true, sizeBytes: 4 });
+ expect(out[2].media).toEqual({ mimetype: 'image/jpeg', omitted: true, sizeBytes: 4 });
+ expect(m2.downloadMedia).not.toHaveBeenCalled();
+ expect(m3.downloadMedia).not.toHaveBeenCalled();
+ });
+
+ it('stops the read loop when the abort signal fires (client disconnect)', async () => {
+ const controller = new AbortController();
+ const m1 = mediaMsg('M11', 'QUJD');
+ m1.downloadMedia.mockImplementation(() => {
+ controller.abort(); // the disconnect lands while the first download is in flight
+ return Promise.resolve({ data: 'QUJD', mimetype: 'image/jpeg' });
+ });
+ const m2 = mediaMsg('M12', 'QUJD');
+
+ const out = await readyAdapter(clientFor(m1, m2)).getChatHistory(
+ 50,
+ true,
+ undefined,
+ controller.signal,
+ );
+
+ expect(out).toHaveLength(1); // the second message is never processed
+ expect(m2.downloadMedia).not.toHaveBeenCalled();
+ });
+
+ it('returns an empty result without downloading when the signal is already aborted', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const m1 = mediaMsg('M13', 'QUJD');
+
+ const out = await readyAdapter(clientFor(m1)).getChatHistory('[email protected]', 50, true, undefined, controller.signal);
+
+ expect(out).toEqual([]);
+ expect(m1.downloadMedia).not.toHaveBeenCalled();
+ });
+ });
});
describe('WhatsAppWebJsAdapter.sendPollMessage', () => {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index ede45dca4..6c299a1dc 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -78,6 +78,7 @@ import { buildEditedMessage, buildIncomingMessageBase, mapContactFields } from '
import { buildVCard } from './vcard';
import {
capInboundMedia,
+ chatHistoryMediaBudgetBytes,
coerceDeclaredSize,
inboundMediaConcurrency,
inboundMediaMaxBytes,
@@ -172,6 +173,22 @@ export function extractWwebjsCall(msg: Message): { video: boolean; missed: boole
return { video: Boolean(d.isVideoCall), missed: !msg.fromMe && !d.callDuration };
}
+/**
+ * The `media` envelope for a message whose blob is not downloaded: keeps the sender-declared metadata
+ * so the `media` field stays present (n8n/dashboard contract) while carrying the `omitted` marker
+ * instead of base64. Used when downloads are disabled, the size pre-gate trips, the aggregate history
+ * budget is spent, or the download fails/times out.
+ */
+function declaredOnlyMedia(msg: Message): IncomingMessage['media'] {
+ const data = (msg as unknown as { _data?: { size?: number; mimetype?: string; filename?: string } })._data;
+ return {
+ mimetype: data?.mimetype ?? '',
+ filename: data?.filename || undefined,
+ omitted: true,
+ sizeBytes: coerceDeclaredSize(data?.size),
+ };
+}
+
/**
* Whether a per-session proxy URL parses to a supported scheme — defense-in-depth for a stored proxy
* that bypassed DTO validation (e.g. loaded from the DB on restart). The host is NOT SSRF-blocked: a
@@ -372,13 +389,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
maxBytesOverride?: number,
): Promise<IncomingMessage['media'] | undefined> {
if (!isMediaDownloadEnabled()) {
- const data = (msg as unknown as { _data?: { size?: number; mimetype?: string; filename?: string } })._data;
- return {
- mimetype: data?.mimetype ?? '',
- filename: data?.filename || undefined,
- omitted: true,
- sizeBytes: coerceDeclaredSize(data?.size),
- };
+ return declaredOnlyMedia(msg);
}
const maxBytes = maxBytesOverride ?? inboundMediaMaxBytes();
const data = (msg as unknown as { _data?: { size?: number; mimetype?: string; filename?: string } })._data;
@@ -389,12 +400,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
sizeBytes: declared,
maxBytes,
});
- return {
- mimetype: data?.mimetype ?? '',
- filename: data?.filename || undefined,
- omitted: true,
- sizeBytes: declared,
- };
+ return declaredOnlyMedia(msg);
}
// msg.downloadMedia() can't be aborted, so freeing the slot the moment the wall-clock deadline fires
// would admit a fresh download while the abandoned one is still materialising in heap — letting the
@@ -437,12 +443,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
});
const media = await boundedReady;
if (!media) {
- return {
- mimetype: data?.mimetype ?? '',
- filename: data?.filename || undefined,
- omitted: true,
- sizeBytes: declared,
- };
+ return declaredOnlyMedia(msg);
}
const capped = capInboundMedia({
mimetype: media.mimetype,
@@ -2204,12 +2205,22 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
limit: number = 50,
includeMedia: boolean = false,
mediaMaxBytes?: number,
+ signal?: AbortSignal,
): Promise<IncomingMessage[]> {
this.ensureReady();
const chat = await this.client!.getChatById(chatId);
const messages = await chat.fetchMessages({ limit });
const results: IncomingMessage[] = [];
+ // Aggregate base64 budget across the whole pass: the per-message cap bounds ONE blob, but without
+ // an aggregate bound a 100-message history could stack ~100 × 50 MiB into one response. Once the
+ // running total crosses the budget, later media messages get the declared-only `omitted` marker —
+ // no download — while everything already inlined stays inline (a small history is byte-identical
+ // to before). `signal` (client disconnect) stops the loop between messages; partials are returned.
+ let mediaBudget = includeMedia ? chatHistoryMediaBudgetBytes() : 0;
for (const msg of messages) {
+ if (signal?.aborted) {
+ break;
+ }
// Reuse the shared mapper so history messages carry the same author/contact
// enrichment as live incoming messages (#223). The mapper defaults chatId to
// msg.from, which is wrong here (history includes fromMe messages whose `from`
@@ -2242,13 +2253,23 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
}
if (includeMedia && msg.hasMedia) {
- try {
- // Same pre-gate + limiter as live media: a large historical blob shouldn't bloat the
- // response/heap. Callers (the status seed) can tighten the cap below the global default.
- const capped = await this.capInboundMediaFor(msg, mediaMaxBytes);
- if (capped) out.media = capped;
- } catch (error) {
- this.logger.warn(`Failed to download media for ${msg.id._serialized}: ${String(error)}`);
+ if (mediaBudget <= 0) {
+ out.media = declaredOnlyMedia(msg);
+ } else {
+ try {
+ // Same pre-gate + limiter as live media: a large historical blob shouldn't bloat the
+ // response/heap. Callers (the status seed) can tighten the cap below the global default.
+ const capped = await this.capInboundMediaFor(msg, mediaMaxBytes);
+ if (capped) {
+ out.media = capped;
+ // Only an inlined payload spends budget; an omitted marker carries no base64.
+ if (capped.data) {
+ mediaBudget -= capped.data.length;
+ }
+ }
+ } catch (error) {
+ this.logger.warn(`Failed to download media for ${msg.id._serialized}: ${String(error)}`);
+ }
}
}
results.push(out);
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 64fc6b603..4f825a647 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -651,12 +651,17 @@ export interface IWhatsAppEngine {
* Read a chat's recent messages, newest first. When `includeMedia` downloads blobs, an optional
* `mediaMaxBytes` tightens the declared-size pre-gate below the global MEDIA_DOWNLOAD_MAX_BYTES —
* the status seed uses it to skip downloads the store would discard as over-cap anyway.
+ * Inlined media is additionally bounded in aggregate (CHAT_HISTORY_MEDIA_BUDGET_BYTES): once the
+ * running base64 total crosses the budget, later media messages carry the `omitted` marker instead
+ * of a download. An optional `signal` (e.g. client disconnect) stops the read loop early; the
+ * messages collected so far are returned.
*/
getChatHistory(
chatId: string,
limit?: number,
includeMedia?: boolean,
mediaMaxBytes?: number,
+ signal?: AbortSignal,
): Promise<IncomingMessage[]>;
// Calls
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index 7637a6223..5a8b54d96 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -1,5 +1,6 @@
-import { Controller, Post, Get, Param, Body, Query, HttpCode, HttpStatus } from '@nestjs/common';
+import { Controller, Post, Get, Param, Body, Query, Res, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';
+import type { Response } from 'express';
import { MessageService } from './message.service';
import { BulkMessageService } from './bulk-message.service';
import { SendTextMessageDto, SendMediaMessageDto, SendAudioMessageDto, MessageResponseDto } from './dto';
@@ -311,16 +312,23 @@ export class MessageController {
@Query('limit') limit?: string,
@Query('includeMedia') includeMedia?: string,
@Query('deep') deep?: string,
+ @Res({ passthrough: true }) res?: Response,
) {
// Parse the limit defensively: a non-numeric query value (?limit=abc) yields NaN,
// so fall back to undefined and let the service apply its default + clamp.
const parsedLimit = limit ? parseInt(limit, 10) : undefined;
+ // A client that disconnects mid-history (includeMedia can mean dozens of multi-MB downloads) must
+ // stop the loop: `close` fires on premature disconnect AND after a normal finish — aborting then is
+ // a no-op because the loop has already run to completion.
+ const abort = new AbortController();
+ res?.on('close', () => abort.abort());
return this.messageService.getChatHistory(
sessionId,
chatId,
parsedLimit !== undefined && !Number.isNaN(parsedLimit) ? parsedLimit : undefined,
includeMedia === 'true' || includeMedia === '1',
deep === 'true' || deep === '1',
+ abort.signal,
);
}
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index cd610cde2..2e15549b7 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -1178,6 +1178,12 @@ describe('MessageService', () => {
expect(result).toBe(fake);
});
+ it('threads an abort signal through to the engine when one is given', async () => {
+ const { signal } = new AbortController();
+ await service.getChatHistory('sess-1', '[email protected]', 50, true, false, signal);
+ expect(mockEngine.getChatHistory).toHaveBeenCalledWith('[email protected]', 50, true, undefined, signal);
+ });
+
describe('deep mode (#347)', () => {
it('allows a limit above the standard 100 cap when deep=true', async () => {
await service.getChatHistory('sess-1', '[email protected]', 500, false, true);
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index f715ef0f2..75b346197 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -689,12 +689,25 @@ export class MessageService {
* engine to fetch an unbounded number of messages. When `deep` is true the ceiling is raised to 2000
* (for reaching weeks/months back on whatsapp-web.js, which can load earlier messages on demand) and
* media is forced off — downloading base64 for up to 2000 messages would be an enormous, slow payload.
+ *
+ * An optional `signal` (HTTP client disconnect) is threaded to the engine, which checks it between
+ * media downloads. Callers without cancellation keep the exact three-argument engine call shape.
*/
- async getChatHistory(sessionId: string, chatId: string, limit = 50, includeMedia = false, deep = false) {
+ async getChatHistory(
+ sessionId: string,
+ chatId: string,
+ limit = 50,
+ includeMedia = false,
+ deep = false,
+ signal?: AbortSignal,
+ ) {
const engine = this.getEngine(sessionId);
const ceiling = deep ? MessageService.MAX_DEEP_CHAT_HISTORY_LIMIT : MessageService.MAX_CHAT_HISTORY_LIMIT;
const safeLimit = Number.isFinite(limit) ? Math.min(Math.max(Math.trunc(limit), 1), ceiling) : 50;
- return engine.getChatHistory(chatId, safeLimit, deep ? false : includeMedia);
+ const media = deep ? false : includeMedia;
+ return signal
+ ? engine.getChatHistory(chatId, safeLimit, media, undefined, signal)
+ : engine.getChatHistory(chatId, safeLimit, media);
}
// ========== Delete Message ==========