Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): only fetch inbound Baileys media from WhatsApp hosts

Yudhi Armyndharise430a183d48c
diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.ts
index cf2f5d648..cb167a16b 100644
--- a/src/engine/adapters/baileys-events.spec.ts
+++ b/src/engine/adapters/baileys-events.spec.ts
@@ -77,8 +77,16 @@ const normalizeMessageContent = (content: Record<string, unknown> | null | undef
return current;
};
+// Baileys' own picks for the node downloadMediaMessage fetches: unwrap, then the first content key.
+const extractMessageContent = (content: Record<string, unknown> | null | undefined): unknown =>
+ normalizeMessageContent(content);
+const getContentType = (content: Record<string, unknown> | undefined): string | undefined =>
+ Object.keys(content ?? {}).find(k => k === 'conversation' || k.endsWith('Message'));
+
const libStub = {
normalizeMessageContent,
+ extractMessageContent,
+ getContentType,
downloadMediaMessage,
} as unknown as Awaited<ReturnType<BaileysEventsHost['loadLib']>>;
@@ -489,6 +497,87 @@ describe('BaileysEvents.mapMessage', () => {
});
});
+describe('BaileysEvents inbound media source', () => {
+ const download = (message: Record<string, unknown>) =>
+ new BaileysEvents(makeHost()).mapMessage(
+ {
+ key: { id: 'wamid.src', remoteJid: '[email protected]', fromMe: false },
+ messageTimestamp: 1_700_000_000,
+ message,
+ },
+ 'imageMessage',
+ );
+
+ beforeEach(() => downloadMediaMessage.mockReset());
+
+ it.each([
+ ['a plain-http url', { url: 'http://127.0.0.1/latest/meta-data/' }],
+ ['a url outside whatsapp.net', { url: 'https://internal.example/x' }],
+ ['a whatsapp.net url on another port', { url: 'https://mmg.whatsapp.net:8080/x' }],
+ ['a directPath that rewrites the host', { url: 'https://mmg.whatsapp.net/x', directPath: '@internal.example/x' }],
+ ['a directPath under a foreign url host', { url: 'https://internal.example/x', directPath: '/v/t62/x' }],
+ ])('does not fetch media whose address is %s', async (_name, source) => {
+ const incoming = await download({ imageMessage: { mimetype: 'image/jpeg', fileLength: 7, ...source } });
+ expect(downloadMediaMessage).not.toHaveBeenCalled();
+ expect(incoming.media).toEqual({ mimetype: 'image/jpeg', filename: undefined, omitted: true, sizeBytes: 7 });
+ });
+
+ it('checks the node Baileys downloads, not the first media type this file looks for', async () => {
+ await download({
+ documentMessage: { mimetype: 'application/pdf', fileLength: 7, url: 'http://127.0.0.1/' },
+ imageMessage: { mimetype: 'image/jpeg', fileLength: 7, url: 'https://mmg.whatsapp.net/x' },
+ });
+ expect(downloadMediaMessage).not.toHaveBeenCalled();
+ });
+
+ it('still downloads media served from WhatsApp hosts', async () => {
+ const buf = Buffer.from('IMGDATA');
+ downloadMediaMessage.mockResolvedValueOnce(streamOf(buf));
+ const incoming = await download({
+ imageMessage: {
+ mimetype: 'image/jpeg',
+ fileLength: buf.byteLength,
+ url: 'https://mmg.whatsapp.net/v/t62/x.enc',
+ directPath: '/v/t62/x.enc',
+ },
+ });
+ expect(downloadMediaMessage).toHaveBeenCalledTimes(1);
+ expect(incoming.media).toEqual({ mimetype: 'image/jpeg', filename: undefined, data: buf.toString('base64') });
+ });
+
+ it('refuses a re-upload answer that points outside WhatsApp hosts', async () => {
+ downloadMediaMessage.mockImplementationOnce(
+ async (
+ _m: WAMessage,
+ _t: string,
+ _o: unknown,
+ ctx: { reuploadRequest: (m: WAMessage) => Promise<WAMessage> },
+ ) => {
+ await ctx.reuploadRequest(_m);
+ return streamOf(Buffer.from('x'));
+ },
+ );
+ const updateMediaMessage = jest.fn((m: WAMessage) =>
+ Promise.resolve({
+ ...m,
+ message: { imageMessage: { url: 'https://mmg.whatsapp.net', directPath: '@internal.example/x' } },
+ }),
+ );
+ const incoming = await new BaileysEvents(
+ makeHost({ getSocket: () => ({ updateMediaMessage }) as unknown as WASocket }),
+ ).mapMessage(
+ {
+ key: { id: 'wamid.re', remoteJid: '[email protected]', fromMe: false },
+ messageTimestamp: 1_700_000_000,
+ message: { imageMessage: { mimetype: 'image/jpeg', fileLength: 1, url: 'https://mmg.whatsapp.net/x' } },
+ },
+ 'imageMessage',
+ );
+ expect(updateMediaMessage).toHaveBeenCalledTimes(1);
+ expect(incoming.media).toEqual({ mimetype: 'image/jpeg', filename: undefined, omitted: true, sizeBytes: 1 });
+ });
+});
+
describe('BaileysEvents record of messages deleted for everyone', () => {
it('forgets the oldest id once it holds its limit', () => {
const events = new BaileysEvents(makeHost());
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index 09ec5bcf6..2b3945899 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -116,6 +116,46 @@ export function differentWaIds(
return !lidGap(x, y) && !lidGap(y, x);
}
+/**
+ * Whether the media node Baileys' downloadMediaMessage would fetch is served from WhatsApp's media
+ * hosts. Baileys builds the address from the message as the sender composed it (`url`, or
+ * `https://<host of url>` + `directPath`) and fetches it with no host check of its own, so anything
+ * outside https://*.whatsapp.net on the default port is refused here. The node and the address are
+ * resolved exactly as rc14's downloadMediaMessage and downloadContentFromMessage resolve them.
+ */
+export function isWhatsAppMediaSource(
+ b: Pick<typeof BaileysLib, 'extractMessageContent' | 'getContentType'>,
+ message: WAMessage['message'],
+): boolean {
+ const content = b.extractMessageContent(message);
+ const type = content ? b.getContentType(content) : undefined;
+ const media: unknown = type ? content?.[type] : undefined;
+ // Baileys refuses a node like this itself, before any fetch.
+ if (!media || typeof media !== 'object') return true;
+ const node = media as { url?: string | null; directPath?: string | null; thumbnailDirectPath?: string | null };
+ const thumbnailOnly = 'thumbnailDirectPath' in media && !('url' in media);
+ const url = thumbnailOnly ? undefined : node.url;
+ const directPath = thumbnailOnly ? node.thumbnailDirectPath : node.directPath;
+ let host = 'mmg.whatsapp.net';
+ try {
+ if (url) host = new URL(url).host;
+ } catch {
+ // Baileys falls back to its default host for an unparsable url.
+ }
+ const target = directPath ? `https://${host}${directPath}` : url;
+ if (!target) return true;
+ try {
+ const parsed = new URL(target);
+ return (
+ parsed.protocol === 'https:' &&
+ parsed.port === '' &&
+ (parsed.hostname === 'whatsapp.net' || parsed.hostname.endsWith('.whatsapp.net'))
+ );
+ } catch {
+ return false;
+ }
+}
+
export interface BaileysEventsHost {
/** Live socket handle for media re-upload requests (inbound media download). */
getSocket(): WASocket;
@@ -1188,13 +1228,23 @@ export class BaileysEvents {
return Buffer.alloc(0);
}
const b = await this.host.loadLib();
+ // The address comes from the sender, and so does a re-upload answer (encrypted with the
+ // sender's own media key): both are checked before Baileys fetches them.
+ const assertWhatsAppSource = (m: WAMessage): WAMessage => {
+ if (!isWhatsAppMediaSource(b, m.message)) {
+ throw new Error('Inbound media address is not a WhatsApp media host; not fetched');
+ }
+ return m;
+ };
+ assertWhatsAppSource(msg);
+ const sock = this.host.getSocket();
stream = (await b.downloadMediaMessage(
msg,
'stream',
dispatcher ? { options: { dispatcher } as RequestInit } : {},
{
logger: createSilentLogger(),
- reuploadRequest: this.host.getSocket().updateMediaMessage,
+ reuploadRequest: async m => assertWhatsAppSource(await sock.updateMediaMessage(m)),
},
)) as AsyncIterable<Buffer> & { destroy?: () => void };
if (timedOut) {
diff --git a/src/engine/adapters/baileys-media-abort.spec.ts b/src/engine/adapters/baileys-media-abort.spec.ts
index 46d438fa3..f4fad5254 100644
--- a/src/engine/adapters/baileys-media-abort.spec.ts
+++ b/src/engine/adapters/baileys-media-abort.spec.ts
@@ -30,7 +30,13 @@ function build(dispatcher?: object): { events: BaileysEvents; warns: string[] }
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 }),
+ loadLib: () =>
+ Promise.resolve({
+ normalizeMessageContent: (c: unknown) => c,
+ extractMessageContent: (c: unknown) => c,
+ getContentType: (c: Record<string, unknown> | undefined) => Object.keys(c ?? {})[0],
+ downloadMediaMessage,
+ }),
getFetchDispatcher: () => dispatcher,
toNeutralJid: (jid: string) => jid,
normalizedSelfJid: () => '[email protected]',
diff --git a/src/engine/adapters/baileys-quote-on-receipt.spec.ts b/src/engine/adapters/baileys-quote-on-receipt.spec.ts
index f6381c5aa..5f3ec086c 100644
--- a/src/engine/adapters/baileys-quote-on-receipt.spec.ts
+++ b/src/engine/adapters/baileys-quote-on-receipt.spec.ts
@@ -91,6 +91,7 @@ describe('quoting a Baileys message the moment it is announced', () => {
loadLib: () =>
Promise.resolve({
normalizeMessageContent: (c: unknown) => c,
+ extractMessageContent: (c: unknown) => c,
getContentType: (c: Record<string, unknown> | undefined) => Object.keys(c ?? {})[0],
proto: { Message: { ProtocolMessage: { Type: { REVOKE: 0, MESSAGE_EDIT: 14 } } } },
BufferJSON: { replacer: (_k: string, v: unknown) => v, reviver: (_k: string, v: unknown) => v },
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index a62b7edc8..ecf03fa60 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -135,6 +135,7 @@ jest.mock('@whiskeysockets/baileys', () => ({
),
// Identity passthrough by default; individual tests may override to simulate unwrapping.
normalizeMessageContent: jest.fn((c: unknown) => c),
+ extractMessageContent: jest.fn((c: unknown) => c),
// The pinned protocol node targets this JID; exported from the real module's WABinary surface.
S_WHATSAPP_NET: '@s.whatsapp.net',
ALL_WA_PATCH_NAMES: ['critical_block', 'critical_unblock_low', 'regular_high', 'regular_low', 'regular'],
diff --git a/src/engine/adapters/inbound-media-cap.spec.ts b/src/engine/adapters/inbound-media-cap.spec.ts
index 864d746fb..2f604664c 100644
--- a/src/engine/adapters/inbound-media-cap.spec.ts
+++ b/src/engine/adapters/inbound-media-cap.spec.ts
@@ -409,7 +409,13 @@ describe('process-wide inbound media gate (INBOUND_MEDIA_GLOBAL_CONCURRENCY)', (
getSocket: () => ({ updateMediaMessage: jest.fn() }) as unknown as WASocket,
getSocketOrNull: () => null,
logger: { ...createLogger('InboundMediaGateSpec'), warn: () => undefined },
- loadLib: () => Promise.resolve({ normalizeMessageContent: (c: unknown) => c, downloadMediaMessage }),
+ loadLib: () =>
+ Promise.resolve({
+ normalizeMessageContent: (c: unknown) => c,
+ extractMessageContent: (c: unknown) => c,
+ getContentType: (c: Record<string, unknown> | undefined) => Object.keys(c ?? {})[0],
+ downloadMediaMessage,
+ }),
getFetchDispatcher: () => undefined,
toNeutralJid: (jid: string) => jid,
normalizedSelfJid: () => '[email protected]',