Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(ssrf): cancel unread withSafeFetch bodies before dispatcher teardown
waldyrlimaverdecfc58cb72c15
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fdb25c32b..02337fa80 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- **Outbound `withSafeFetch` no longer crashes the process on unread webhook response bodies.**+ Status-only callers (queued webhook delivery, webhook test, deprecated direct delivery) left the+ undici response body unread; when the peer reset the TLS socket — or the per-request dispatcher+ was destroyed — undici could emit `TypeError: terminated` / `ECONNRESET` on the body stream with+ no listener, becoming a fatal `uncaughtException` that took every WhatsApp session offline (#887).+ `withSafeFetch` now cancels unread bodies before tearing down the connection; callers that already+ stream the body (media / plugin downloads) are unchanged.+## [0.10.8] - 2026-07-23### Addeddiff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.tsindex 61fad01a7..41f2a5f65 100644--- a/src/common/security/ssrf-guard.spec.ts+++ b/src/common/security/ssrf-guard.spec.ts@@ -310,6 +310,64 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {);expect(use).not.toHaveBeenCalled();});++ it('cancels an unread response body before tearing down the dispatcher (#887)', async () => {+ // Status-only callers leave the body unread; if we destroy the Agent while the stream is still+ // open, undici can emit TypeError: terminated / ECONNRESET as an uncaughtException. Cancelling+ // the unread body before destroy closes that path.+ const cancel = jest.fn().mockResolvedValue(undefined);+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);+ (undiciFetch as jest.Mock).mockResolvedValue({+ status: 200,+ type: 'basic',+ bodyUsed: false,+ body: { cancel },+ });+ const use = jest.fn(() => ({ ok: true, status: 200 }));++ await expect(withSafeFetch('https://example.com/hook', {}, use, { guard: true })).resolves.toEqual({+ ok: true,+ status: 200,+ });+ expect(cancel).toHaveBeenCalledTimes(1);+ });++ it('does not cancel a body the caller already consumed', async () => {+ const cancel = jest.fn().mockResolvedValue(undefined);+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);+ (undiciFetch as jest.Mock).mockResolvedValue({+ status: 200,+ type: 'basic',+ bodyUsed: true,+ body: { cancel },+ });++ await withSafeFetch('https://example.com/hook', {}, () => 'consumed', { guard: true });+ expect(cancel).not.toHaveBeenCalled();+ });++ it('still cancels an unread body when use throws', async () => {+ const cancel = jest.fn().mockResolvedValue(undefined);+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);+ (undiciFetch as jest.Mock).mockResolvedValue({+ status: 500,+ type: 'basic',+ bodyUsed: false,+ body: { cancel },+ });++ await expect(+ withSafeFetch(+ 'https://example.com/hook',+ {},+ () => {+ throw new Error('HTTP 500');+ },+ { guard: true },+ ),+ ).rejects.toThrow('HTTP 500');+ expect(cancel).toHaveBeenCalledTimes(1);+ });});describe('validatingLookup (per-hop redirect guard)', () => {diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.tsindex 411f8a48a..5e9b1cb18 100644--- a/src/common/security/ssrf-guard.ts+++ b/src/common/security/ssrf-guard.ts@@ -377,6 +377,31 @@ export function validatingLookup(): LookupFunction {return fn as unknown as LookupFunction;}+/**+ * Cancel an unread response body before the per-request dispatcher is destroyed.+ *+ * Status-only callers (webhook delivery) often leave `response.body` unread. When undici then+ * tears down the socket — or the peer resets it mid-flight — the body stream can emit an `error`+ * (`TypeError: terminated` / `ECONNRESET`) with no listener, which becomes a process-fatal+ * `uncaughtException` (see #887). Cancelling here drains that path safely; already-consumed+ * bodies (`bodyUsed`) are left alone so streaming readers (media / plugin downloads) are unaffected.+ */+async function settleUnreadResponseBody(response: Response): Promise<void> {+ if (response.bodyUsed || !response.body) return;+ await response.body.cancel().catch(() => undefined);+}++/**+ * Run `use(response)` and always settle an unread body afterwards, even if `use` throws.+ */+async function useAndSettleBody<T>(response: Response, use: (response: Response) => Promise<T> | T): Promise<T> {+ try {+ return await use(response);+ } finally {+ await settleUnreadResponseBody(response);+ }+}+/*** Perform an SSRF-safe fetch and hand the response to `use`, then tear down the per-request* connection. The host is validated and resolved ONCE; the connection is pinned to the vetted IP(s)@@ -386,7 +411,9 @@ export function validatingLookup(): LookupFunction {* so A-record failover still works. Redirects are refused (the guard only validated the original host).** `use` must read everything it needs from the response before returning — the dispatcher (and its- * sockets) is destroyed once `use` settles, so a still-streaming body would be cut off.+ * sockets) is destroyed once `use` settles, so a still-streaming body would be cut off. Unread+ * bodies are cancelled automatically before teardown so status-only callers cannot crash the process+ * when the peer resets the connection (#887).** @param opts.guard - when false (the WEBHOOK_SSRF_PROTECT opt-out), skips validation/pinning and* performs a plain redirect-following fetch. Defaults to true (always guard).@@ -399,7 +426,7 @@ export async function withSafeFetch<T>(): Promise<T> {const guard = opts.guard ?? true;if (!guard) {- return use(await undiciFetch(rawUrl, { ...init, redirect: 'follow' }));+ return useAndSettleBody(await undiciFetch(rawUrl, { ...init, redirect: 'follow' }), use);}if (opts.followRedirects) {@@ -411,7 +438,7 @@ export async function withSafeFetch<T>(await resolveSafeFetchTarget(rawUrl);const dispatcher = new Agent({ connect: { lookup: validatingLookup() } });try {- return await use(await undiciFetch(rawUrl, { ...init, redirect: 'follow', dispatcher }));+ return await useAndSettleBody(await undiciFetch(rawUrl, { ...init, redirect: 'follow', dispatcher }), use);} finally {await dispatcher.destroy().catch(() => undefined);}@@ -422,7 +449,7 @@ export async function withSafeFetch<T>(try {const response = await undiciFetch(rawUrl, { ...init, redirect: 'manual', dispatcher });assertNoRedirect(response, rawUrl);- return await use(response);+ return await useAndSettleBody(response, use);} finally {if (dispatcher) await dispatcher.destroy().catch(() => undefined);}