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.

♻️ refactor: refactor a `ssrf-safe-fetch` module (#9474)

Arvin Xu92da716028f3
diff --git a/package.json b/package.json
index 4decf4017f6..625d95fa6eb 100644
--- a/package.json
+++ b/package.json
@@ -122,7 +122,7 @@
"dependencies": {
"@ant-design/icons": "^5.6.1",
"@ant-design/pro-components": "^2.8.10",
- "@anthropic-ai/sdk": "^0.64.0",
+ "@anthropic-ai/sdk": "^0.65.0",
"@auth/core": "^0.40.0",
"@aws-sdk/client-s3": "~3.893.0",
"@aws-sdk/s3-request-presigner": "~3.893.0",
@@ -262,12 +262,12 @@
"remark": "^15.0.1",
"remark-gfm": "^4.0.1",
"remark-html": "^16.0.1",
- "request-filtering-agent": "^3.0.0",
"resolve-accept-language": "^3.1.13",
"rtl-detect": "^1.1.2",
"semver": "^7.7.2",
"sharp": "^0.34.3",
"shiki": "^3.12.2",
+ "ssrf-safe-fetch": "workspace:*",
"stripe": "^17.7.0",
"superjson": "^2.2.2",
"svix": "^1.76.1",
@@ -301,7 +301,7 @@
"@peculiar/webcrypto": "^1.5.0",
"@prettier/sync": "^0.6.1",
"@semantic-release/exec": "^6.0.3",
- "@testing-library/jest-dom": "^6.8.0",
+ "@testing-library/jest-dom": "~6.8.0",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/chroma-js": "^3.1.1",
@@ -323,7 +323,6 @@
"@types/systemjs": "^6.15.3",
"@types/ua-parser-js": "^0.7.39",
"@types/unist": "^3.0.3",
- "@types/uuid": "^11.0.0",
"@types/ws": "^8.18.1",
"@typescript/native-preview": "7.0.0-dev.20250711.1",
"@vitest/coverage-v8": "^3.2.4",
diff --git a/packages/ssrf-safe-fetch/index.test.ts b/packages/ssrf-safe-fetch/index.test.ts
new file mode 100644
index 00000000000..341b3698520
--- /dev/null
+++ b/packages/ssrf-safe-fetch/index.test.ts
@@ -0,0 +1,343 @@
+// @ts-ignore
+import fetch from 'node-fetch';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ssrfSafeFetch } from './index';
+
+// Mock node-fetch to avoid actual network requests
+vi.mock('node-fetch', () => ({
+ default: vi.fn(),
+}));
+
+const mockFetch = fetch as any;
+
+// Mock console.error to avoid noise in test output
+vi.spyOn(console, 'error').mockImplementation(() => {});
+
+describe('ssrfSafeFetch', () => {
+ const createMockResponse = (
+ options: {
+ arrayBuffer?: ArrayBuffer;
+ headers?: Map<string, string>;
+ status?: number;
+ statusText?: string;
+ } = {},
+ ) => ({
+ arrayBuffer: vi.fn().mockResolvedValue(options.arrayBuffer || new ArrayBuffer(10)),
+ headers: options.headers || new Map(),
+ status: options.status || 200,
+ statusText: options.statusText || 'OK',
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Reset environment variables
+ delete process.env.SSRF_ALLOW_IP_ADDRESS_LIST;
+ delete process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS;
+ });
+
+ describe('successful requests to allowed URLs', () => {
+ it('should make a successful fetch request to external URL', async () => {
+ const mockResponse = createMockResponse({
+ headers: new Map([['content-type', 'application/json']]),
+ });
+
+ mockFetch.mockResolvedValue(mockResponse);
+
+ const response = await ssrfSafeFetch('https://httpbin.org/get');
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://httpbin.org/get',
+ expect.objectContaining({
+ agent: expect.objectContaining({
+ requestFilterOptions: expect.objectContaining({
+ allowIPAddressList: [],
+ allowMetaIPAddress: false,
+ allowPrivateIPAddress: false,
+ denyIPAddressList: [],
+ }),
+ }),
+ }),
+ );
+ expect(response).toBeInstanceOf(Response);
+ expect(response.status).toBe(200);
+ expect(response.statusText).toBe('OK');
+ });
+
+ it('should pass through request options', async () => {
+ const mockResponse = createMockResponse();
+ mockFetch.mockResolvedValue(mockResponse);
+
+ const requestOptions = {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ test: 'data' }),
+ };
+
+ await ssrfSafeFetch('https://httpbin.org/post', requestOptions);
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://httpbin.org/post',
+ expect.objectContaining({
+ ...requestOptions,
+ agent: expect.objectContaining({
+ requestFilterOptions: expect.objectContaining({
+ allowIPAddressList: [],
+ allowMetaIPAddress: false,
+ allowPrivateIPAddress: false,
+ denyIPAddressList: [],
+ }),
+ }),
+ }),
+ );
+ });
+ });
+
+ describe('SSRF protection for private IP addresses', () => {
+ const privateIPs = [
+ 'http://127.0.0.1:8080',
+ 'http://localhost:3000',
+ 'http://192.168.1.1/api',
+ 'http://10.0.0.1/internal',
+ 'http://172.16.0.1/admin',
+ 'http://0.0.0.0:80',
+ ];
+
+ privateIPs.forEach((url) => {
+ it(`should block requests to private IP: ${url}`, async () => {
+ // The request-filtering-agent should throw an error for private IPs
+ mockFetch.mockImplementation(() => {
+ throw new Error('getaddrinfo ENOTFOUND');
+ });
+
+ await expect(ssrfSafeFetch(url)).rejects.toThrow(/SSRF-safe fetch failed/);
+
+ expect(console.error).toHaveBeenCalledWith('SSRF-safe fetch error:', expect.any(Error));
+ });
+ });
+
+ it('should allow private IPs when SSRF_ALLOW_PRIVATE_IP_ADDRESS is true', async () => {
+ process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS = 'true';
+
+ const mockResponse = createMockResponse();
+ mockFetch.mockResolvedValue(mockResponse);
+
+ const response = await ssrfSafeFetch('http://127.0.0.1:8080/api');
+
+ expect(response).toBeInstanceOf(Response);
+ expect(response.status).toBe(200);
+ });
+
+ it('should allow specific IPs in SSRF_ALLOW_IP_ADDRESS_LIST', async () => {
+ process.env.SSRF_ALLOW_IP_ADDRESS_LIST = '127.0.0.1,192.168.1.100';
+
+ const mockResponse = createMockResponse();
+ mockFetch.mockResolvedValue(mockResponse);
+
+ const response = await ssrfSafeFetch('http://127.0.0.1:8080/api');
+
+ expect(response).toBeInstanceOf(Response);
+ expect(response.status).toBe(200);
+ });
+ });
+
+ describe('SSRF protection for malicious URLs', () => {
+ const maliciousUrls = [
+ 'http://169.254.169.254/latest/meta-data/', // AWS metadata service
+ 'http://169.254.169.254:80/computeMetadata/v1/', // GCP metadata
+ 'http://metadata.google.internal/computeMetadata/v1/',
+ 'file:///etc/passwd', // File protocol
+ 'ftp://internal.company.com/secrets', // FTP protocol
+ ];
+
+ maliciousUrls.forEach((url) => {
+ it(`should block malicious URL: ${url}`, async () => {
+ mockFetch.mockImplementation(() => {
+ throw new Error('Request blocked by SSRF protection');
+ });
+
+ await expect(ssrfSafeFetch(url)).rejects.toThrow(/SSRF-safe fetch failed/);
+ });
+ });
+ });
+
+ describe('environment variable configuration', () => {
+ it('should respect empty SSRF_ALLOW_IP_ADDRESS_LIST', async () => {
+ process.env.SSRF_ALLOW_IP_ADDRESS_LIST = '';
+
+ mockFetch.mockImplementation(() => {
+ throw new Error('getaddrinfo ENOTFOUND');
+ });
+
+ await expect(ssrfSafeFetch('http://127.0.0.1:8080')).rejects.toThrow(
+ /SSRF-safe fetch failed/,
+ );
+ });
+
+ it('should handle invalid environment variable values gracefully', async () => {
+ process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS = 'invalid-value';
+
+ mockFetch.mockImplementation(() => {
+ throw new Error('getaddrinfo ENOTFOUND');
+ });
+
+ // Should default to false when env var is not 'true'
+ await expect(ssrfSafeFetch('http://127.0.0.1:8080')).rejects.toThrow(
+ /SSRF-safe fetch failed/,
+ );
+ });
+ });
+
+ describe('error handling', () => {
+ it('should throw error with descriptive message when fetch fails', async () => {
+ const originalError = new Error('Network error');
+ mockFetch.mockRejectedValue(originalError);
+
+ await expect(ssrfSafeFetch('https://example.com')).rejects.toThrow(
+ 'SSRF-safe fetch failed: Network error',
+ );
+
+ expect(console.error).toHaveBeenCalledWith('SSRF-safe fetch error:', originalError);
+ });
+
+ it('should handle non-Error thrown values', async () => {
+ const nonErrorValue = 'String error';
+ mockFetch.mockRejectedValue(nonErrorValue);
+
+ await expect(ssrfSafeFetch('https://example.com')).rejects.toThrow(
+ 'SSRF-safe fetch failed: String error',
+ );
+ });
+
+ it('should handle null/undefined error values', async () => {
+ mockFetch.mockRejectedValue(null);
+
+ await expect(ssrfSafeFetch('https://example.com')).rejects.toThrow(
+ 'SSRF-safe fetch failed: null',
+ );
+ });
+ });
+
+ describe('response conversion', () => {
+ it('should convert node-fetch Response to standard Response', async () => {
+ const mockArrayBuffer = new ArrayBuffer(10);
+ const mockHeaders = new Map([
+ ['content-type', 'application/json'],
+ ['content-length', '10'],
+ ]);
+
+ const mockResponse = createMockResponse({
+ arrayBuffer: mockArrayBuffer,
+ headers: mockHeaders,
+ status: 201,
+ statusText: 'Created',
+ });
+
+ mockFetch.mockResolvedValue(mockResponse);
+
+ const response = await ssrfSafeFetch('https://httpbin.org/status/201');
+
+ expect(response).toBeInstanceOf(Response);
+ expect(response.status).toBe(201);
+ expect(response.statusText).toBe('Created');
+ expect(response.headers.get('content-type')).toBe('application/json');
+ expect(response.headers.get('content-length')).toBe('10');
+ expect(mockResponse.arrayBuffer).toHaveBeenCalled();
+ });
+
+ it('should handle response with different status codes', async () => {
+ const mockResponse = createMockResponse({
+ arrayBuffer: new ArrayBuffer(0),
+ status: 404,
+ statusText: 'Not Found',
+ });
+
+ mockFetch.mockResolvedValue(mockResponse);
+
+ const response = await ssrfSafeFetch('https://httpbin.org/status/404');
+
+ expect(response.status).toBe(404);
+ expect(response.statusText).toBe('Not Found');
+ });
+
+ it('should handle response with empty headers', async () => {
+ const mockResponse = createMockResponse({
+ arrayBuffer: new ArrayBuffer(0),
+ });
+
+ mockFetch.mockResolvedValue(mockResponse);
+
+ const response = await ssrfSafeFetch('https://httpbin.org/get');
+
+ expect(response.headers).toBeDefined();
+ expect([...response.headers.entries()]).toEqual([]);
+ });
+ });
+
+ describe('integration scenarios', () => {
+ it('should work with complex request configurations', async () => {
+ process.env.SSRF_ALLOW_IP_ADDRESS_LIST = '127.0.0.1';
+ process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS = 'true';
+
+ const mockResponse = createMockResponse({
+ // @ts-ignore
+ arrayBuffer: new TextEncoder().encode('{"success": true}'),
+ headers: new Map([['content-type', 'application/json']]),
+ });
+
+ mockFetch.mockResolvedValue(mockResponse);
+
+ const requestOptions = {
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer token123',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ data: 'test' }),
+ };
+
+ const response = await ssrfSafeFetch('https://api.example.com/data', requestOptions);
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://api.example.com/data',
+ expect.objectContaining({
+ ...requestOptions,
+ agent: expect.objectContaining({
+ requestFilterOptions: expect.objectContaining({
+ allowIPAddressList: ['127.0.0.1'],
+ allowMetaIPAddress: true,
+ allowPrivateIPAddress: true,
+ denyIPAddressList: [],
+ }),
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get('content-type')).toBe('application/json');
+ });
+
+ it('should properly handle agent function with HTTPS URLs', async () => {
+ const mockResponse = createMockResponse();
+ mockFetch.mockResolvedValue(mockResponse);
+
+ await ssrfSafeFetch('https://secure.example.com/api');
+
+ // Verify that the agent is properly configured for HTTPS
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://secure.example.com/api',
+ expect.objectContaining({
+ agent: expect.objectContaining({
+ protocol: 'https:',
+ requestFilterOptions: expect.objectContaining({
+ allowIPAddressList: [],
+ allowMetaIPAddress: false,
+ allowPrivateIPAddress: false,
+ denyIPAddressList: [],
+ }),
+ }),
+ }),
+ );
+ });
+ });
+});
diff --git a/packages/ssrf-safe-fetch/index.ts b/packages/ssrf-safe-fetch/index.ts
new file mode 100644
index 00000000000..0d77cc60d7e
--- /dev/null
+++ b/packages/ssrf-safe-fetch/index.ts
@@ -0,0 +1,37 @@
+import fetch from 'node-fetch';
+import { RequestFilteringAgentOptions, useAgent as ssrfAgent } from 'request-filtering-agent';
+
+/**
+ * SSRF-safe fetch implementation for server-side use
+ * Uses request-filtering-agent to prevent requests to private IP addresses
+ */
+// eslint-disable-next-line no-undef
+export const ssrfSafeFetch = async (url: string, options?: RequestInit): Promise<Response> => {
+ try {
+ // Configure SSRF protection options
+ const agentOptions: RequestFilteringAgentOptions = {
+ allowIPAddressList: process.env.SSRF_ALLOW_IP_ADDRESS_LIST?.split(',') || [],
+ allowMetaIPAddress: process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS === '1',
+ allowPrivateIPAddress: process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS === '1',
+ denyIPAddressList: [],
+ };
+
+ // Use node-fetch with SSRF protection agent
+ const response = await fetch(url, {
+ ...options,
+ agent: ssrfAgent(url, agentOptions),
+ } as any);
+
+ // Convert node-fetch Response to standard Response
+ return new Response(await response.arrayBuffer(), {
+ headers: response.headers as any,
+ status: response.status,
+ statusText: response.statusText,
+ });
+ } catch (error) {
+ console.error('SSRF-safe fetch error:', error);
+ throw new Error(
+ `SSRF-safe fetch failed: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+};
diff --git a/packages/ssrf-safe-fetch/package.json b/packages/ssrf-safe-fetch/package.json
new file mode 100644
index 00000000000..ec98738fc38
--- /dev/null
+++ b/packages/ssrf-safe-fetch/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "ssrf-safe-fetch",
+ "version": "1.0.0",
+ "private": true,
+ "description": "",
+ "main": "index.ts",
+ "scripts": {
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "node-fetch": "^3.3.2",
+ "request-filtering-agent": "^3"
+ },
+ "devDependencies": {
+ "vitest": "^3.2.4"
+ }
+}
diff --git a/packages/ssrf-safe-fetch/vitest.config.mts b/packages/ssrf-safe-fetch/vitest.config.mts
new file mode 100644
index 00000000000..78007b7aeb2
--- /dev/null
+++ b/packages/ssrf-safe-fetch/vitest.config.mts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ reporter: ['text', 'json', 'lcov', 'text-summary'],
+ },
+ environment: 'node',
+ },
+});
diff --git a/src/app/(backend)/webapi/proxy/route.ts b/src/app/(backend)/webapi/proxy/route.ts
index 7461a5e5bc5..de2b3f5b0e6 100644
--- a/src/app/(backend)/webapi/proxy/route.ts
+++ b/src/app/(backend)/webapi/proxy/route.ts
@@ -1,8 +1,5 @@
import { NextResponse } from 'next/server';
-import fetch from 'node-fetch';
-import { RequestFilteringAgentOptions, useAgent as ssrfAgent } from 'request-filtering-agent';
-
-import { appEnv } from '@/envs/app';
+import { ssrfSafeFetch } from 'ssrf-safe-fetch';
/**
* just for a proxy
@@ -11,15 +8,7 @@ export const POST = async (req: Request) => {
const url = await req.text();
try {
- // https://www.npmjs.com/package/request-filtering-agent
- const options: RequestFilteringAgentOptions = {
- allowIPAddressList: appEnv.SSRF_ALLOW_IP_ADDRESS_LIST?.split(',') || [],
- allowMetaIPAddress: appEnv.SSRF_ALLOW_PRIVATE_IP_ADDRESS,
- allowPrivateIPAddress: appEnv.SSRF_ALLOW_PRIVATE_IP_ADDRESS,
- denyIPAddressList: [],
- };
- const res = await fetch(url, { agent: ssrfAgent(url, options) });
-
+ const res = await ssrfSafeFetch(url);
return new Response(await res.arrayBuffer(), { headers: { ...res.headers } });
} catch (err) {
console.error(err); // DNS lookup 127.0.0.1(family:4, host:127.0.0.1.nip.io) is not allowed. Because, It is private IP address.