Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(web-crawler): cap response body size to prevent serverless OOM (#14660)

Arvin Xuca873e3c348e
diff --git a/packages/ssrf-safe-fetch/index.browser.ts b/packages/ssrf-safe-fetch/index.browser.ts
index bff68e5c10e..8d3017ab467 100644
--- a/packages/ssrf-safe-fetch/index.browser.ts
+++ b/packages/ssrf-safe-fetch/index.browser.ts
@@ -13,6 +13,8 @@ export interface SSRFOptions {
allowIPAddressList?: string[];
/** Whether to allow private/local IP addresses */
allowPrivateIPAddress?: boolean;
+ /** Maximum response body size in bytes (server-only; ignored in browser) */
+ maxContentLength?: number;
}
/**
diff --git a/packages/ssrf-safe-fetch/index.test.ts b/packages/ssrf-safe-fetch/index.test.ts
index 50bea302cfe..24e42caa768 100644
--- a/packages/ssrf-safe-fetch/index.test.ts
+++ b/packages/ssrf-safe-fetch/index.test.ts
@@ -280,6 +280,182 @@ describe('ssrfSafeFetch', () => {
});
});
+ describe('maxContentLength (response body cap)', () => {
+ const buildBodyResponse = (chunks: Buffer[]) => ({
+ // arrayBuffer should NOT be called when maxContentLength is set;
+ // make it throw so the test fails loudly if the cap path falls through.
+ arrayBuffer: vi.fn().mockImplementation(async () => {
+ throw new Error('arrayBuffer should not be called when maxContentLength is set');
+ }),
+ body: (async function* () {
+ for (const chunk of chunks) yield chunk;
+ })(),
+ headers: new Map([['content-type', 'text/html']]),
+ status: 200,
+ statusText: 'OK',
+ });
+
+ it('returns the full body when it fits within the cap', async () => {
+ mockFetch.mockResolvedValue(buildBodyResponse([Buffer.from('hello '), Buffer.from('world')]));
+
+ const response = await ssrfSafeFetch('https://example.com', {}, { maxContentLength: 1024 });
+
+ expect(await response.text()).toBe('hello world');
+ });
+
+ it('truncates the body once the cap is reached and stops reading further chunks', async () => {
+ const chunks = [
+ Buffer.from('a'.repeat(60)),
+ Buffer.from('b'.repeat(60)),
+ Buffer.from('c'.repeat(60)),
+ ];
+ mockFetch.mockResolvedValue(buildBodyResponse(chunks));
+
+ const response = await ssrfSafeFetch('https://example.com', {}, { maxContentLength: 100 });
+
+ const text = await response.text();
+ expect(text).toHaveLength(100);
+ expect(text).toBe('a'.repeat(60) + 'b'.repeat(40));
+ });
+
+ it('returns an empty body when the response stream is null', async () => {
+ mockFetch.mockResolvedValue({
+ arrayBuffer: vi.fn(),
+ body: null,
+ headers: new Map(),
+ status: 200,
+ statusText: 'OK',
+ });
+
+ const response = await ssrfSafeFetch('https://example.com', {}, { maxContentLength: 1024 });
+
+ expect(await response.text()).toBe('');
+ });
+
+ it('falls back to arrayBuffer when maxContentLength is not set', async () => {
+ const mockResponse = createMockResponse({
+ arrayBuffer: new TextEncoder().encode('legacy path').buffer as ArrayBuffer,
+ });
+ mockFetch.mockResolvedValue(mockResponse);
+
+ const response = await ssrfSafeFetch('https://example.com');
+
+ expect(mockResponse.arrayBuffer).toHaveBeenCalledTimes(1);
+ expect(await response.text()).toBe('legacy path');
+ });
+ });
+
+ /*
+ * Regression tests for the production SIGABRT crashes on /trpc/tools/search.webSearch
+ * (rss=2889MB heap=2473MB β†’ V8 "allocation failed" β†’ SIGABRT). These verify the cap
+ * actually prevents unbounded buffering even when the source body is huge.
+ */
+ describe('OOM regression: bounded memory under oversized response bodies', () => {
+ const ONE_MB = 1024 * 1024;
+ const SIXTY_FOUR_KB = 64 * 1024;
+
+ /**
+ * Builds a mock response whose body generator tracks how many bytes it has
+ * yielded into a shared counter. Lets us assert that we did not drain the
+ * full source β€” the whole point of the cap is to stop pulling early.
+ */
+ const buildHugeBodyResponse = (
+ counter: { bytesYielded: number },
+ totalAvailableBytes: number,
+ ) => {
+ const chunk = Buffer.alloc(SIXTY_FOUR_KB, 0x61);
+ const totalChunks = Math.ceil(totalAvailableBytes / chunk.length);
+
+ async function* gen() {
+ for (let i = 0; i < totalChunks; i++) {
+ counter.bytesYielded += chunk.length;
+ yield chunk;
+ }
+ }
+
+ return {
+ arrayBuffer: vi.fn().mockImplementation(async () => {
+ throw new Error('arrayBuffer should not be called when maxContentLength is set');
+ }),
+ body: gen(),
+ headers: new Map([['content-type', 'text/html']]),
+ status: 200,
+ statusText: 'OK',
+ };
+ };
+
+ it('stops pulling chunks from the source once the cap is reached', async () => {
+ // Source has 200 MB available; cap at 1 MB. Pre-fix would buffer all 200 MB
+ // before the downstream truncation could apply.
+ const counter = { bytesYielded: 0 };
+ mockFetch.mockResolvedValue(buildHugeBodyResponse(counter, 200 * ONE_MB));
+
+ const response = await ssrfSafeFetch(
+ 'https://huge.example.com',
+ {},
+ { maxContentLength: ONE_MB },
+ );
+ const body = await response.arrayBuffer();
+
+ expect(body.byteLength).toBe(ONE_MB);
+ // We should have pulled at most CAP + one chunk of slack (the last chunk
+ // that triggered the break). Definitely not the full 200 MB.
+ expect(counter.bytesYielded).toBeLessThanOrEqual(ONE_MB + SIXTY_FOUR_KB);
+ });
+
+ it('keeps total source pull bounded under CRAWL_CONCURRENCY=3 (production scenario)', async () => {
+ // Three concurrent oversized fetches β€” matches the production setup where
+ // pMap with concurrency=3 over 3 large search results triggered SIGABRT.
+ const counter = { bytesYielded: 0 };
+ mockFetch
+ .mockResolvedValueOnce(buildHugeBodyResponse(counter, 100 * ONE_MB))
+ .mockResolvedValueOnce(buildHugeBodyResponse(counter, 100 * ONE_MB))
+ .mockResolvedValueOnce(buildHugeBodyResponse(counter, 100 * ONE_MB));
+
+ const responses = await Promise.all([
+ ssrfSafeFetch('https://a.example.com', {}, { maxContentLength: ONE_MB }),
+ ssrfSafeFetch('https://b.example.com', {}, { maxContentLength: ONE_MB }),
+ ssrfSafeFetch('https://c.example.com', {}, { maxContentLength: ONE_MB }),
+ ]);
+
+ for (const r of responses) {
+ expect((await r.arrayBuffer()).byteLength).toBe(ONE_MB);
+ }
+ // Without the cap we would have pulled 300 MB. With cap=1 MB Γ— 3 fetches,
+ // expect ≀ 3 Γ— (cap + one chunk slack).
+ expect(counter.bytesYielded).toBeLessThanOrEqual(3 * (ONE_MB + SIXTY_FOUR_KB));
+ });
+
+ /*
+ * Real heap-pressure test β€” only runs when --expose-gc is available
+ * (e.g. `NODE_OPTIONS=--expose-gc bunx vitest run`). Skipped otherwise so CI
+ * doesn't false-fail due to GC timing.
+ */
+ const itIfGc = typeof globalThis.gc === 'function' ? it : it.skip;
+ itIfGc('heap delta stays bounded when a 50 MB body is fetched with a 1 MB cap', async () => {
+ const counter = { bytesYielded: 0 };
+ mockFetch.mockResolvedValue(buildHugeBodyResponse(counter, 50 * ONE_MB));
+
+ globalThis.gc!();
+ const before = process.memoryUsage().heapUsed;
+
+ const response = await ssrfSafeFetch(
+ 'https://heavy.example.com',
+ {},
+ { maxContentLength: ONE_MB },
+ );
+ await response.arrayBuffer();
+
+ globalThis.gc!();
+ const after = process.memoryUsage().heapUsed;
+ const deltaMB = (after - before) / ONE_MB;
+
+ // Without the cap, delta would be β‰₯ 50 MB. With cap=1 MB, we expect
+ // a few MB of overhead at most.
+ expect(deltaMB).toBeLessThan(10);
+ });
+ });
+
describe('integration scenarios', () => {
it('should work with complex request configurations', async () => {
process.env.SSRF_ALLOW_IP_ADDRESS_LIST = '127.0.0.1';
diff --git a/packages/ssrf-safe-fetch/index.ts b/packages/ssrf-safe-fetch/index.ts
index 9e30836c7af..c1c02bc9715 100644
--- a/packages/ssrf-safe-fetch/index.ts
+++ b/packages/ssrf-safe-fetch/index.ts
@@ -10,8 +10,48 @@ export interface SSRFOptions {
allowIPAddressList?: string[];
/** Whether to allow private/local IP addresses */
allowPrivateIPAddress?: boolean;
+ /**
+ * Maximum response body size in bytes. When set, the body is consumed
+ * incrementally and reading stops as soon as the cap is reached. The returned
+ * Response contains only the bytes received up to that point (soft truncation β€”
+ * still considered a successful response).
+ *
+ * Use this for any fetch that downloads untrusted content (e.g. web crawlers)
+ * to prevent unbounded buffering of large or malicious responses from blowing
+ * up serverless function memory.
+ */
+ maxContentLength?: number;
}
+/**
+ * Consume a node-fetch Response body up to `cap` bytes, then stop. Breaking out
+ * of `for await` closes the async iterator, which destroys the underlying stream
+ * and releases the HTTP connection.
+ */
+const readBodyWithCap = async (
+ body: NodeJS.ReadableStream | null,
+ cap: number,
+): Promise<Uint8Array> => {
+ if (!body) return new Uint8Array(0);
+
+ const chunks: Buffer[] = [];
+ let total = 0;
+
+ for await (const chunk of body as AsyncIterable<Uint8Array>) {
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ const remaining = cap - total;
+ if (buf.length >= remaining) {
+ chunks.push(buf.subarray(0, remaining));
+ total = cap;
+ break;
+ }
+ chunks.push(buf);
+ total += buf.length;
+ }
+
+ return Buffer.concat(chunks, total);
+};
+
/**
* SSRF-safe fetch implementation for server-side use
* Uses request-filtering-agent to prevent requests to private IP addresses
@@ -54,8 +94,16 @@ export const ssrfSafeFetch = async (
agent: (parsedURL: URL) => (parsedURL.protocol === 'https:' ? httpsAgent : httpAgent),
} as any);
+ const cap = ssrfOptions?.maxContentLength;
+ const body: BodyInit =
+ cap && cap > 0
+ ? // Buffer is a Uint8Array subclass; the Response constructor accepts it at
+ // runtime even though the BodyInit lib type doesn't list Uint8Array.
+ ((await readBodyWithCap(response.body as NodeJS.ReadableStream | null, cap)) as any)
+ : await response.arrayBuffer();
+
// Convert node-fetch Response to standard Response
- return new Response(await response.arrayBuffer(), {
+ return new Response(body, {
headers: response.headers as any,
status: response.status,
statusText: response.statusText,
diff --git a/packages/web-crawler/src/crawImpl/naive.ts b/packages/web-crawler/src/crawImpl/naive.ts
index 05f780b06e3..a28e66f417b 100755
--- a/packages/web-crawler/src/crawImpl/naive.ts
+++ b/packages/web-crawler/src/crawImpl/naive.ts
@@ -2,7 +2,7 @@ import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
import type { CrawlImpl, CrawlSuccessResult } from '../type';
import { PageNotFoundError, toFetchError } from '../utils/errorType';
-import { htmlToMarkdown } from '../utils/htmlToMarkdown';
+import { htmlToMarkdown, MAX_HTML_SIZE } from '../utils/htmlToMarkdown';
import { createHTTPStatusError } from '../utils/response';
import { DEFAULT_TIMEOUT, withTimeout } from '../utils/withTimeout';
@@ -41,10 +41,14 @@ export const naive: CrawlImpl = async (url, { filterOptions }) => {
try {
res = await withTimeout(
(signal) =>
- ssrfSafeFetch(url, {
- headers: mixinHeaders,
- signal,
- }),
+ ssrfSafeFetch(
+ url,
+ {
+ headers: mixinHeaders,
+ signal,
+ },
+ { maxContentLength: MAX_HTML_SIZE },
+ ),
DEFAULT_TIMEOUT,
);
} catch (e) {
diff --git a/packages/web-crawler/src/utils/htmlToMarkdown.ts b/packages/web-crawler/src/utils/htmlToMarkdown.ts
index d4a55edcd4a..da95c40476e 100644
--- a/packages/web-crawler/src/utils/htmlToMarkdown.ts
+++ b/packages/web-crawler/src/utils/htmlToMarkdown.ts
@@ -6,7 +6,7 @@ import { NodeHtmlMarkdown } from 'node-html-markdown';
import type { FilterOptions } from '../type';
/** Truncate HTML to 1 MB before DOM parsing to prevent CPU spikes on large pages */
-const MAX_HTML_SIZE = 1024 * 1024;
+export const MAX_HTML_SIZE = 1024 * 1024;
const cleanObj = <T extends object>(
obj: T,
@@ -36,53 +36,60 @@ export const htmlToMarkdown = (
url,
});
- const document = window.document;
- document.body.innerHTML = html;
-
- let parsedContent: ReturnType<Readability<string>['parse']> = null;
try {
- // @ts-expect-error reason: Readability expects a Document type
- parsedContent = new Readability(document).parse();
- } catch {
- // happy-dom may throw on pages with invalid CSS selectors β€” fall back to raw HTML
- }
+ const document = window.document;
+ document.body.innerHTML = html;
- const useReadability = filterOptions.enableReadability ?? true;
+ let parsedContent: ReturnType<Readability<string>['parse']> = null;
+ try {
+ // @ts-expect-error reason: Readability expects a Document type
+ parsedContent = new Readability(document).parse();
+ } catch {
+ // happy-dom may throw on pages with invalid CSS selectors β€” fall back to raw HTML
+ }
- let htmlNode = html;
+ const useReadability = filterOptions.enableReadability ?? true;
- if (useReadability && parsedContent?.content) {
- htmlNode = parsedContent?.content;
- }
+ let htmlNode = html;
- const customTranslators = (
- filterOptions.pureText
- ? {
- a: {
- postprocess: (_: string, content: string) => content,
- },
- img: {
- ignore: true,
- },
- }
- : {}
- ) as TranslatorConfigObject;
+ if (useReadability && parsedContent?.content) {
+ htmlNode = parsedContent?.content;
+ }
- const nodeHtmlMarkdown = new NodeHtmlMarkdown({}, customTranslators);
+ const customTranslators = (
+ filterOptions.pureText
+ ? {
+ a: {
+ postprocess: (_: string, content: string) => content,
+ },
+ img: {
+ ignore: true,
+ },
+ }
+ : {}
+ ) as TranslatorConfigObject;
- const content = nodeHtmlMarkdown.translate(htmlNode);
+ const nodeHtmlMarkdown = new NodeHtmlMarkdown({}, customTranslators);
- const result = {
- author: parsedContent?.byline,
- content,
- description: parsedContent?.excerpt,
- dir: parsedContent?.dir,
- lang: parsedContent?.lang,
- length: parsedContent?.length,
- publishedTime: parsedContent?.publishedTime,
- siteName: parsedContent?.siteName,
- title: parsedContent?.title,
- };
+ const content = nodeHtmlMarkdown.translate(htmlNode);
- return cleanObj(result) as HtmlToMarkdownOutput;
+ const result = {
+ author: parsedContent?.byline,
+ content,
+ description: parsedContent?.excerpt,
+ dir: parsedContent?.dir,
+ lang: parsedContent?.lang,
+ length: parsedContent?.length,
+ publishedTime: parsedContent?.publishedTime,
+ siteName: parsedContent?.siteName,
+ title: parsedContent?.title,
+ };
+
+ return cleanObj(result) as HtmlToMarkdownOutput;
+ } finally {
+ // Release the happy-dom Window so its DOM tree is GC-able immediately, instead
+ // of waiting for the function scope to drop. JS evaluation is disabled so the
+ // returned promise resolves synchronously in practice β€” fire and forget.
+ void window.happyDOM.close();
+ }
};