Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): bound SSRF DNS resolution by a deadline; detect media URLs case-insensitively (#404)
Yudhi Armyndhariscae5e00aa18e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bfbb91496..81dfc38ba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -48,9 +48,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0non-integer value (e.g. `RATE_LIMIT_SHORT_LIMIT=abc`) became `NaN` and silently disabled thecorresponding limit. Startup now rejects a non-negative-integer violation with a clear message,consistent with the existing port validation. (#402)+- **The whatsapp-web.js engine now detects remote media URLs case-insensitively.** A media `data`+ string was treated as a URL only with a lowercase `http://`/`https://` prefix, so a mixed-case+ scheme (e.g. `HTTPS://…`) was mistaken for base64 instead of being fetched through the SSRF-guarded+ path — diverging from the Baileys engine. Both engines now use the same case-insensitive check. (#404)### Security+- **DNS resolution in the SSRF guard is now bounded by a deadline.** The guard resolved a hostname+ with an unbounded lookup, so a hanging or very slow resolver could pin a worker indefinitely. The+ lookup now races a deadline (default 10s, overridable via `SSRF_DNS_TIMEOUT_MS`) and fails closed+ with a clear error on expiry. Healthy resolvers are unaffected. (#404)- **Custom webhook headers are now validated as a flat, control-character-free string map.** The`headers` field accepted any object shape with no per-value checks, so a value containing `CR`/`LF`could attempt header injection into the outbound webhook request, and non-string values silentlydiff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.tsindex d7e31e9c2..40ec4c85a 100644--- a/src/common/security/ssrf-guard.spec.ts+++ b/src/common/security/ssrf-guard.spec.ts@@ -197,6 +197,23 @@ describe('resolveSafeFetchTarget', () => {(dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '10.0.0.5', family: 4 }]);await expect(resolveSafeFetchTarget('https://rebind.example/hook')).rejects.toThrow(SsrfBlockedError);});++ it('propagates a DNS lookup failure (rejection) rather than hanging', async () => {+ (dnsPromises.lookup as jest.Mock).mockRejectedValueOnce(new Error('ENOTFOUND'));+ await expect(resolveSafeFetchTarget('https://nxdomain.example/hook')).rejects.toThrow(/ENOTFOUND/);+ });++ it('rejects when DNS resolution exceeds the deadline (a hanging resolver cannot pin a worker)', async () => {+ const prev = process.env.SSRF_DNS_TIMEOUT_MS;+ process.env.SSRF_DNS_TIMEOUT_MS = '30';+ (dnsPromises.lookup as jest.Mock).mockReturnValueOnce(new Promise(() => undefined)); // never resolves+ try {+ await expect(resolveSafeFetchTarget('https://slow.example/hook')).rejects.toThrow(/timed out resolving/i);+ } finally {+ if (prev === undefined) delete process.env.SSRF_DNS_TIMEOUT_MS;+ else process.env.SSRF_DNS_TIMEOUT_MS = prev;+ }+ }, 1000);});describe('withSafeFetch (guarded + pinned fetch)', () => {diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.tsindex 2e85cc8d6..dd432fce9 100644--- a/src/common/security/ssrf-guard.ts+++ b/src/common/security/ssrf-guard.ts@@ -170,6 +170,35 @@ export function assertNoRedirect(response: { status: number; type?: string }, ur}}+/** Default DNS resolution deadline (ms) — generous for healthy resolvers; bounds a hang. */+const DEFAULT_DNS_TIMEOUT_MS = 10000;++function resolveDnsTimeoutMs(): number {+ const raw = process.env.SSRF_DNS_TIMEOUT_MS;+ const n = raw !== undefined ? Number(raw) : NaN;+ return Number.isInteger(n) && n > 0 ? n : DEFAULT_DNS_TIMEOUT_MS;+}++/**+ * Resolve a host with `{ all: true }`, bounded by a deadline so a hanging/slow DNS resolver cannot+ * pin a worker indefinitely (the lookup is otherwise unbounded). The default deadline is generous+ * and overridable via SSRF_DNS_TIMEOUT_MS. On expiry it throws SsrfBlockedError; the in-flight lookup+ * is left to settle with its late result swallowed (no unhandledRejection).+ */+async function lookupWithDeadline(host: string): Promise<LookupAddress[]> {+ const lookupPromise = lookup(host, { all: true });+ lookupPromise.catch(() => undefined); // swallow a late rejection if the deadline already fired+ let timer: NodeJS.Timeout | undefined;+ const deadline = new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new SsrfBlockedError(`Timed out resolving host: ${host}`)), resolveDnsTimeoutMs());+ });+ try {+ return await Promise.race([lookupPromise, deadline]);+ } finally {+ if (timer) clearTimeout(timer);+ }+}+/*** Validate an outbound URL and resolve its host ONCE. Throws SsrfBlockedError if the scheme is not* http(s) or if the host (literal or any DNS-resolved address) is internal/reserved. Guards both@@ -207,7 +236,7 @@ export async function resolveSafeFetchTarget(rawUrl: string): Promise<LookupAddrreturn null; // literal IP — fetch connects directly, nothing to rebind}- const resolved = await lookup(host, { all: true });+ const resolved = await lookupWithDeadline(host);if (resolved.length === 0) {throw new SsrfBlockedError(`Could not resolve host: ${host}`);}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex d0235fe55..ccd4c812c 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -2,6 +2,7 @@ import { MessageMedia } from 'whatsapp-web.js';import {WhatsAppWebJsAdapter,extractLinkedParentJID,+ isHttpUrl,isSupportedProxyUrl,loadRemoteMedia,resolveAuthTimeoutMs,@@ -36,6 +37,22 @@ describe('wwebjsAckToDeliveryStatus (engine ack-int -> neutral DeliveryStatus bo});});+describe('isHttpUrl (remote-media detection, case-insensitive like Baileys)', () => {+ it.each(['http://x/y.png', 'https://x/y.png', 'HTTP://X/Y.PNG', 'Https://x/y.png', 'hTtPs://x'])(+ 'treats %s as a remote URL',+ url => {+ expect(isHttpUrl(url)).toBe(true);+ },+ );++ it.each(['data:image/png;base64,iVBOR', 'iVBORw0KGgoAAAANSU', 'ftp://x/y', 'httpserver-not-a-url'])(+ 'treats %s as non-URL (base64 / other)',+ s => {+ expect(isHttpUrl(s)).toBe(false);+ },+ );+});+describe('isSupportedProxyUrl', () => {it.each(['http://proxy:8080', 'https://proxy:8443', 'socks4://proxy:1080', 'socks5://user:pass@proxy:1080'])('accepts %s',diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 5eadfcc48..5a7b196ee 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -74,6 +74,15 @@ export function isSupportedProxyUrl(url: string): boolean {}}+/**+ * Whether a MediaInput's string `data` is an http(s) URL (to be fetched through the SSRF-guarded+ * loadRemoteMedia) rather than base64. Case-insensitive, matching the Baileys adapter — a mixed-case+ * scheme like `HTTPS://` must still route through the guarded fetch, not be treated as base64.+ */+export function isHttpUrl(value: string): boolean {+ return /^https?:\/\//i.test(value);+}+/*** Fetch remote media 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`@@ -564,7 +573,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginlet messageMedia: MessageMedia;if (typeof media.data === 'string') {- if (media.data.startsWith('http://') || media.data.startsWith('https://')) {+ if (isHttpUrl(media.data)) {// URLmessageMedia = await loadRemoteMedia(media.data);} else {@@ -715,7 +724,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginlet messageMedia: MessageMedia;if (typeof media.data === 'string') {- if (media.data.startsWith('http://') || media.data.startsWith('https://')) {+ if (isHttpUrl(media.data)) {messageMedia = await loadRemoteMedia(media.data);} else {messageMedia = new MessageMedia(media.mimetype, media.data, media.filename);