Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(media): add SSRF-guarded loadRemoteMediaBuffer (neutral URL->Buffer)
rmyndharisa68167323bb4
diff --git a/.gitignore b/.gitignoreindex f89de7af7..5ba7187f5 100644--- a/.gitignore+++ b/.gitignore@@ -46,6 +46,7 @@ Thumbs.db# Data and storagedata/media/+!src/**/media/uploads/.wwebjs_auth/.wwebjs_cache/diff --git a/src/common/media/load-remote-media.spec.ts b/src/common/media/load-remote-media.spec.tsnew file mode 100644index 000000000..757909b5a--- /dev/null+++ b/src/common/media/load-remote-media.spec.ts@@ -0,0 +1,55 @@+import { loadRemoteMediaBuffer } from './load-remote-media';+import { SsrfBlockedError } from '../security/ssrf-guard';++describe('loadRemoteMediaBuffer', () => {+ const realFetch = global.fetch;+ afterEach(() => {+ global.fetch = realFetch;+ delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;+ });++ // Build a Response-like with a single-chunk body stream.+ const fakeResponse = (bytes: number[], headers: Record<string, string>) => ({+ ok: true,+ status: 200,+ headers: { get: (k: string) => headers[k.toLowerCase()] ?? null },+ body: {+ getReader: () => {+ let done = false;+ return {+ read: () =>+ done+ ? Promise.resolve({ done: true, value: undefined })+ : ((done = true), Promise.resolve({ done: false, value: new Uint8Array(bytes) })),+ cancel: () => Promise.resolve(),+ };+ },+ },+ });++ it('blocks an internal URL via the SSRF guard before any fetch', async () => {+ const fetchMock = jest.fn();+ global.fetch = fetchMock as typeof fetch;+ await expect(loadRemoteMediaBuffer('http://127.0.0.1/x.png')).rejects.toBeInstanceOf(SsrfBlockedError);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('fetches a public URL and returns the bytes + content-type', async () => {+ const fetchMock = jest+ .fn()+ .mockResolvedValue(fakeResponse([1, 2, 3], { 'content-type': 'image/png', 'content-length': '3' }));+ global.fetch = fetchMock as typeof fetch;+ const res = await loadRemoteMediaBuffer('http://8.8.8.8/x.png');+ expect(res.mimetype).toBe('image/png');+ expect(Array.from(res.data)).toEqual([1, 2, 3]);+ // Never follow redirects (a 3xx could reach an internal host the guard never validated).+ expect(fetchMock).toHaveBeenCalledWith('http://8.8.8.8/x.png', expect.objectContaining({ redirect: 'error' }));+ });++ it('rejects a body that exceeds the byte cap', async () => {+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '2';+ const fetchMock = jest.fn().mockResolvedValue(fakeResponse([1, 2, 3], { 'content-type': 'image/png' }));+ global.fetch = fetchMock as typeof fetch;+ await expect(loadRemoteMediaBuffer('http://8.8.8.8/x.png')).rejects.toThrow(/exceeds/i);+ });+});diff --git a/src/common/media/load-remote-media.ts b/src/common/media/load-remote-media.tsnew file mode 100644index 000000000..4f0573d45--- /dev/null+++ b/src/common/media/load-remote-media.ts@@ -0,0 +1,60 @@+import { assertSafeFetchUrl } from '../security/ssrf-guard';++/** Default cap on a server-side media download: 50 MiB (overridable via MEDIA_DOWNLOAD_MAX_BYTES). */+const DEFAULT_MEDIA_MAX_BYTES = 50 * 1024 * 1024;+/** Default timeout for a server-side media download: 30s (overridable via MEDIA_DOWNLOAD_TIMEOUT_MS). */+const DEFAULT_MEDIA_TIMEOUT_MS = 30_000;++function positiveIntFromEnv(name: string, fallback: number): number {+ const parsed = Number.parseInt(process.env[name] ?? '', 10);+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;+}++/**+ * Fetch remote media as a Buffer for sending, with an SSRF host guard, a byte cap, and a timeout.+ * The guard runs BEFORE any network call, so an internal/reserved URL throws `SsrfBlockedError`+ * and no outbound socket is opened. `redirect: 'error'` is used because the guard only validated+ * the original host — a followed 3xx could reach an internal target. The cap is enforced while+ * streaming (Content-Length may be absent or wrong) to bound memory use.+ *+ * Engine-neutral: returns raw bytes + the response content-type, so any engine adapter can use it.+ */+export async function loadRemoteMediaBuffer(url: string): Promise<{ data: Buffer; mimetype: string }> {+ await assertSafeFetchUrl(url);++ const maxBytes = positiveIntFromEnv('MEDIA_DOWNLOAD_MAX_BYTES', DEFAULT_MEDIA_MAX_BYTES);+ const timeoutMs = positiveIntFromEnv('MEDIA_DOWNLOAD_TIMEOUT_MS', DEFAULT_MEDIA_TIMEOUT_MS);++ const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });+ if (!response.ok) {+ throw new Error(`Media fetch failed with status ${response.status}`);+ }++ const declaredLength = Number(response.headers.get('content-length') ?? '');+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {+ throw new Error(`Media exceeds the ${maxBytes}-byte limit`);+ }++ const reader = response.body?.getReader();+ if (!reader) {+ throw new Error('Media response has no body');+ }++ const chunks: Buffer[] = [];+ let total = 0;+ for (;;) {+ const { done, value } = await reader.read();+ if (done) {+ break;+ }+ total += value.byteLength;+ if (total > maxBytes) {+ await reader.cancel();+ throw new Error(`Media exceeds the ${maxBytes}-byte limit`);+ }+ chunks.push(Buffer.from(value));+ }++ const mimetype = (response.headers.get('content-type') ?? '').split(';')[0].trim();+ return { data: Buffer.concat(chunks), mimetype };+}