π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(security): route user-controlled image and ComfyUI requests through SSRF policy (T-07) (#23676)
Bryan2e4589b71bbf
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex 650b17960e5..d062a248ac0 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -672,6 +672,9 @@ importers:../../packages/ssrf-safe-fetch:dependencies:+ ipaddr.js:+ specifier: ^2.5.0+ version: 2.5.0node-fetch:specifier: ^3.3.2version: 3.3.2@@ -2496,6 +2499,7 @@ packages:'@opentelemetry/[email protected]':resolution: {integrity: sha512-H19x/TX/LZdqiYOjM7fqtSxwlplC5pgelavqbQdHbhdq0q/AI/TGkM2dfGuuynTXmJPeF2HoZVoPDu+TGoW78A==}engines: {node: ^18.19.0 || >=20.6.0}+ deprecated: Use @opentelemetry/sdk-trace packagepeerDependencies:'@opentelemetry/api': '>=1.3.0 <1.10.0'@@ -9827,7 +9831,7 @@ snapshots:dependencies:'@hono/node-server': 2.1.3([email protected])ajv: 8.20.0- ajv-formats: 3.0.1([email protected])+ ajv-formats: 3.0.1content-type: 1.0.5cors: 2.8.6cross-spawn: 7.0.6@@ -11178,8 +11182,8 @@ snapshots:dependencies:humanize-ms: 1.2.1- optionalDependencies:+ dependencies:ajv: 8.20.0@@ -11652,7 +11656,7 @@ snapshots:dependencies:ajv: 8.20.0- ajv-formats: 3.0.1([email protected])+ ajv-formats: 3.0.1atomically: 2.1.1debounce-fn: 6.0.0dot-prop: 9.0.0@@ -11664,7 +11668,7 @@ snapshots:dependencies:ajv: 8.20.0- ajv-formats: 3.0.1([email protected])+ ajv-formats: 3.0.1atomically: 2.1.1debounce-fn: 6.0.0dot-prop: 10.2.0diff --git a/apps/server/src/services/comfyui/__tests__/core/comfyUIConnectionService.test.ts b/apps/server/src/services/comfyui/__tests__/core/comfyUIConnectionService.test.tsindex 7c689cdc49d..8ca2b4264b9 100644--- a/apps/server/src/services/comfyui/__tests__/core/comfyUIConnectionService.test.ts+++ b/apps/server/src/services/comfyui/__tests__/core/comfyUIConnectionService.test.ts@@ -1,14 +1,21 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import type * as SSRFSafeFetchModule from '@lobechat/ssrf-safe-fetch';+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ComfyUIConnectionService } from '@/server/services/comfyui/core/comfyUIConnectionService';import { ServicesError } from '@/server/services/comfyui/errors';-// Mock global fetch-global.fetch = vi.fn();+vi.mock('@lobechat/ssrf-safe-fetch', async (importOriginal) => {+ const mod = await importOriginal<typeof SSRFSafeFetchModule>();+ return { ...mod, ssrfSafeFetch: vi.fn() };+});++const realSsrfSafeFetch = async () =>+ (await vi.importActual<typeof SSRFSafeFetchModule>('@lobechat/ssrf-safe-fetch')).ssrfSafeFetch;describe('ComfyUIConnectionService', () => {let service: ComfyUIConnectionService;- const mockFetch = vi.mocked(fetch);+ const mockFetch = vi.mocked(ssrfSafeFetch);beforeEach(() => {service = new ComfyUIConnectionService();@@ -284,4 +291,28 @@ describe('ComfyUIConnectionService', () => {});});});++ describe('SSRF boundary', () => {+ beforeEach(async () => {+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', undefined);+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', undefined);+ mockFetch.mockImplementation(await realSsrfSafeFetch());+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it.each([+ 'http://169.254.169.254:8188',+ 'http://127.0.0.1:8188',+ 'http://10.0.0.1:8188',+ 'http://192.168.1.1:8188',+ 'http://[::1]:8188',+ ])('rejects validation against %s', async (blockedBaseURL) => {+ await expect(service.validateConnection(blockedBaseURL)).rejects.toThrow(/SSRF blocked/);+ expect(service.isValidated()).toBe(false);+ });+ });});diff --git a/apps/server/src/services/comfyui/__tests__/core/comfyuiClient.redirect.test.ts b/apps/server/src/services/comfyui/__tests__/core/comfyuiClient.redirect.test.tsnew file mode 100644index 00000000000..e9d1b6522de--- /dev/null+++ b/apps/server/src/services/comfyui/__tests__/core/comfyuiClient.redirect.test.ts@@ -0,0 +1,47 @@+import { createServer, type Server } from 'node:http';+import type { AddressInfo } from 'node:net';++import { afterEach, describe, expect, it } from 'vitest';++import { ComfyUIClientService } from '@/server/services/comfyui/core/comfyUIClientService';++/**+ * T-07 redirect-bypass regression (found in review): the ComfyUI SDK's HTTP+ * calls must stay behind the SSRF policy after the baseURL check passes. A+ * hostile ComfyUI endpoint can answer any request with a redirect to an+ * internal address, and the runtime fetch would follow it unfiltered.+ *+ * This test runs the real chain β no SDK or fetch mocks: a local server+ * stands in for the hostile ComfyUI host and 302s to the instance-metadata+ * address. `127.0.0.1` is allow-listed so the baseURL itself passes the+ * policy while the redirect target does not.+ */+describe('ComfyUIClientService redirect bypass', () => {+ let server: Server;++ afterEach(() => {+ server.close();+ delete process.env.SSRF_ALLOW_IP_ADDRESS_LIST;+ });++ it('blocks an SDK fetchApi redirect to the metadata address', async () => {+ server = createServer((_, res) => {+ res.writeHead(302, { location: 'http://169.254.169.254/latest/meta-data' });+ res.end();+ });+ await new Promise<void>((resolve) => {+ server.listen(0, '127.0.0.1', resolve);+ });+ const { port } = server.address() as AddressInfo;+ process.env.SSRF_ALLOW_IP_ADDRESS_LIST = '127.0.0.1';++ const service = new ComfyUIClientService({ baseURL: `http://127.0.0.1:${port}` });+ const client = await (service as any).clientReady;++ try {+ await expect(client.fetchApi('/object_info')).rejects.toThrow(/SSRF blocked|not allowed/);+ } finally {+ client.destroy();+ }+ });+});diff --git a/apps/server/src/services/comfyui/__tests__/core/comfyuiClient.test.ts b/apps/server/src/services/comfyui/__tests__/core/comfyuiClient.test.tsindex 7f9355ccf3c..81b68e93300 100644--- a/apps/server/src/services/comfyui/__tests__/core/comfyuiClient.test.ts+++ b/apps/server/src/services/comfyui/__tests__/core/comfyuiClient.test.ts@@ -1,3 +1,5 @@+import type * as SSRFSafeFetchModule from '@lobechat/ssrf-safe-fetch';+import { assertSsrfSafeUrl, ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';import { ComfyApi } from '@saintno/comfyui-sdk';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -17,6 +19,18 @@ vi.mock('@saintno/comfyui-sdk', () => ({vi.mock('@/server/services/comfyui/core/comfyUIAuthService');vi.mock('@/server/services/comfyui/core/comfyUIConnectionService');+// The baseURL gate is stubbed to resolve by default; the SSRF describe+// overrides it with the real implementation.+vi.mock('@lobechat/ssrf-safe-fetch', async (importOriginal) => {+ const mod = await importOriginal<typeof SSRFSafeFetchModule>();+ return {+ ...mod,+ assertSsrfSafeUrl: vi.fn().mockResolvedValue(undefined),+ ssrfSafeAgent: vi.fn(),+ ssrfSafeFetch: vi.fn(),+ };+});+const workflowCallWrapper = () => ({onFailed: vi.fn().mockReturnThis(),onFinished: vi.fn().mockReturnThis(),@@ -76,21 +90,30 @@ describe('ComfyUIClientService', () => {afterEach(() => {Date.now = originalDateNow;+ vi.unstubAllEnvs();});describe('constructor', () => {- it('should initialize with default settings', () => {+ it('should initialize with default settings', async () => {service = new ComfyUIClientService();+ // The SDK client is created asynchronously once the baseURL passes the+ // SSRF policy.+ await vi.waitFor(() => expect(ComfyApi).toHaveBeenCalled());+expect(ComfyUIAuthService).toHaveBeenCalledWith({});expect(ComfyUIConnectionService).toHaveBeenCalled();- expect(ComfyApi).toHaveBeenCalledWith(expect.stringContaining('http'), undefined, {- credentials: undefined,- });+ expect(ComfyApi).toHaveBeenCalledWith(+ expect.stringContaining('http'),+ undefined,+ expect.objectContaining({+ customWebSocketImpl: expect.any(Function),+ }),+ );expect(mockClient.init).toHaveBeenCalled();});- it('should initialize with custom options', () => {+ it('should initialize with custom options', async () => {const options: ComfyUIKeyVault = {authType: 'basic',baseURL: 'http://custom:8188',@@ -100,11 +123,17 @@ describe('ComfyUIClientService', () => {service = new ComfyUIClientService(options);+ await vi.waitFor(() => expect(ComfyApi).toHaveBeenCalled());+expect(ComfyUIAuthService).toHaveBeenCalledWith(options);expect(ComfyUIConnectionService).toHaveBeenCalled();- expect(ComfyApi).toHaveBeenCalledWith('http://custom:8188', undefined, {- credentials: undefined,- });+ expect(ComfyApi).toHaveBeenCalledWith(+ 'http://custom:8188',+ undefined,+ expect.objectContaining({+ customWebSocketImpl: expect.any(Function),+ }),+ );expect(mockClient.init).toHaveBeenCalled();});@@ -669,3 +698,118 @@ describe('ComfyUIClientService', () => {});});});++describe('ComfyUIClientService SSRF boundary', () => {+ let service: ComfyUIClientService;+ let ssrfMockClient: any;++ beforeEach(async () => {+ vi.clearAllMocks();+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', undefined);+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', undefined);++ const { assertSsrfSafeUrl: realAssert } = await vi.importActual<typeof SSRFSafeFetchModule>(+ '@lobechat/ssrf-safe-fetch',+ );+ vi.mocked(assertSsrfSafeUrl).mockImplementation(realAssert);++ // Fresh SDK client including the internals hardenComfyApi touches.+ ssrfMockClient = {+ apiURL: vi.fn((route: string) => `http://custom:8188${route}`),+ fetchApi: vi.fn(),+ getCheckpoints: vi.fn(),+ getCredentialHeaders: vi.fn(() => ({})),+ init: vi.fn(),+ testCredentials: vi.fn().mockResolvedValue(true),+ };+ vi.mocked(ComfyApi).mockImplementation(function () {+ return ssrfMockClient;+ } as any);+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ vi.mocked(assertSsrfSafeUrl).mockResolvedValue(undefined);+ });++ it.each([+ 'http://169.254.169.254:8188',+ 'http://127.0.0.1:8188',+ 'http://10.0.0.1:8188',+ 'http://192.168.1.1:8188',+ 'http://172.16.0.1:8188',+ 'http://[::1]:8188',+ ])('refuses to create an SDK client for %s', async (baseURL) => {+ service = new ComfyUIClientService({ baseURL });++ await expect(service.getCheckpoints()).rejects.toThrow(/SSRF blocked/);++ // No SDK client or connection is created for a refused baseURL.+ expect(ComfyApi).not.toHaveBeenCalled();+ expect(assertSsrfSafeUrl).toHaveBeenCalledWith(baseURL);+ });++ it('refuses a baseURL hostname that resolves to loopback', async () => {+ service = new ComfyUIClientService({ baseURL: 'http://localhost:8188' });++ await expect(service.getCheckpoints()).rejects.toThrow(/SSRF blocked/);+ expect(ComfyApi).not.toHaveBeenCalled();+ });++ it.each(['uploadImage', 'executeWorkflow', 'getLoras', 'getNodeDefs', 'getSamplerInfo'] as const)(+ 'gates %s on the baseURL check',+ async (method) => {+ service = new ComfyUIClientService({ baseURL: 'http://169.254.169.254:8188' });++ const calls = {+ executeWorkflow: () => service.executeWorkflow({} as any),+ getLoras: () => service.getLoras(),+ getNodeDefs: () => service.getNodeDefs(),+ getSamplerInfo: () => service.getSamplerInfo(),+ uploadImage: () => service.uploadImage(Buffer.from('x'), 'x.png'),+ };++ await expect(calls[method]()).rejects.toThrow(/SSRF blocked/);+ expect(ComfyApi).not.toHaveBeenCalled();+ },+ );++ it('routes SDK fetchApi calls through ssrfSafeFetch so redirect hops are filtered', async () => {+ vi.mocked(assertSsrfSafeUrl).mockResolvedValue(undefined);+ vi.mocked(ssrfSafeFetch).mockResolvedValue(new Response('{}'));++ service = new ComfyUIClientService({ baseURL: 'http://custom:8188' });+ // Resolves clientReady: client is constructed and fetchApi is patched.+ await service.getCheckpoints();++ ssrfMockClient.getCredentialHeaders.mockReturnValue({ Authorization: 'Bearer token' });++ const response = await ssrfMockClient.fetchApi('/object_info');++ expect(vi.mocked(ssrfSafeFetch)).toHaveBeenCalledWith(+ 'http://custom:8188/object_info',+ expect.objectContaining({+ headers: { Authorization: 'Bearer token' },+ mode: 'cors',+ }),+ );+ expect(response).toBeInstanceOf(Response);+ });++ it('applies credentials after patching instead of passing them to the constructor', async () => {+ vi.mocked(assertSsrfSafeUrl).mockResolvedValue(undefined);++ const credentials = { token: 'secret', type: 'bearer_token' as const };++ service = new ComfyUIClientService({ baseURL: 'http://custom:8188' });+ const authService = vi.mocked(ComfyUIAuthService).mock.results.at(-1)!.value as any;+ authService.getCredentials.mockReturnValue(credentials);++ await service.getCheckpoints();++ const constructorOptions = vi.mocked(ComfyApi).mock.calls.at(-1)![2];+ expect(constructorOptions).not.toHaveProperty('credentials');+ expect(ssrfMockClient.credentials).toEqual(credentials);+ expect(ssrfMockClient.testCredentials).toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/comfyui/__tests__/core/imageService.test.ts b/apps/server/src/services/comfyui/__tests__/core/imageService.test.tsindex 3897abc51b2..ffac6212d87 100644--- a/apps/server/src/services/comfyui/__tests__/core/imageService.test.ts+++ b/apps/server/src/services/comfyui/__tests__/core/imageService.test.ts@@ -1,5 +1,7 @@import { type CreateImagePayload } from '@lobechat/model-runtime';import { AgentRuntimeErrorType } from '@lobechat/model-runtime';+import type * as SSRFSafeFetchModule from '@lobechat/ssrf-safe-fetch';+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';import { beforeEach, describe, expect, it, vi } from 'vitest';import { ComfyUIClientService } from '@/server/services/comfyui/core/comfyUIClientService';@@ -16,6 +18,11 @@ vi.mock('@/server/services/comfyui/core/workflowBuilderService');vi.mock('@/server/services/comfyui/core/errorHandlerService');vi.mock('@/server/services/comfyui/utils/workflowDetector');+vi.mock('@lobechat/ssrf-safe-fetch', async (importOriginal) => {+ const mod = await importOriginal<typeof SSRFSafeFetchModule>();+ return { ...mod, ssrfSafeFetch: vi.fn() };+});+// Mock sharp module for image processingvi.mock('sharp', () => ({default: vi.fn(function (buffer) {@@ -58,9 +65,8 @@ describe('ImageService', () => {handleError: vi.fn(),};- // Mock global fetch- mockFetch = vi.fn();- global.fetch = mockFetch;+ // Mock the SSRF-safe fetch used for image downloads+ mockFetch = vi.mocked(ssrfSafeFetch);// Setup mocks for constructorvi.mocked(ComfyUIClientService, true).mockImplementation(function () {@@ -533,4 +539,45 @@ describe('ImageService', () => {expect(mockErrorHandler.handleError).toHaveBeenCalledWith(testError);});});++ describe('SSRF boundary', () => {+ beforeEach(async () => {+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', undefined);+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', undefined);++ const { ssrfSafeFetch: realImpl } = await vi.importActual<typeof SSRFSafeFetchModule>(+ '@lobechat/ssrf-safe-fetch',+ );+ mockFetch.mockImplementation(realImpl);+ vi.spyOn(console, 'error').mockImplementation(() => {});++ mockModelResolverService.validateModel.mockResolvedValue({+ actualFileName: 'flux1-schnell-fp8.safetensors',+ exists: true,+ });+ mockErrorHandler.handleError.mockImplementation(function (error: any) {+ throw error;+ });+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it.each([+ 'http://169.254.169.254/latest/meta-data/image.png',+ 'http://127.0.0.1:8188/image.png',+ 'http://10.0.0.1/image.png',+ 'http://192.168.1.1/image.png',+ 'http://[::1]/image.png',+ ])('rejects imageUrl pointing at %s', async (imageUrl) => {+ const payload: CreateImagePayload = {+ model: 'flux-schnell',+ params: { imageUrl, prompt: 'test prompt' },+ };++ await expect(imageService.createImage(payload)).rejects.toThrow(/SSRF blocked/);+ expect(mockClientService.uploadImage).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/server/src/services/comfyui/core/comfyUIClientService.ts b/apps/server/src/services/comfyui/core/comfyUIClientService.tsindex d03618cb5d5..f15df963b29 100644--- a/apps/server/src/services/comfyui/core/comfyUIClientService.ts+++ b/apps/server/src/services/comfyui/core/comfyUIClientService.ts@@ -5,10 +5,19 @@* Provides unified error handling and abstraction over SDK* Uses modular services for authentication, connection, and caching*/+import { assertSsrfSafeUrl, ssrfSafeAgent, ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';import { type ComfyUIKeyVault } from '@lobechat/types';-import { type PromptBuilder } from '@saintno/comfyui-sdk';+import {+ type BasicCredentials,+ type BearerTokenCredentials,+ type CustomCredentials,+ type FetchOptions,+ type PromptBuilder,+ type WebSocketInterface,+} from '@saintno/comfyui-sdk';import { CallWrapper, ComfyApi } from '@saintno/comfyui-sdk';import debug from 'debug';+import WebSocket, { type ClientOptions } from 'ws';import { COMFYUI_DEFAULTS } from '@/server/services/comfyui/config/constants';import { ComfyUIAuthService } from '@/server/services/comfyui/core/comfyUIAuthService';@@ -19,6 +28,30 @@ import { TTLCacheManager } from '@/server/services/comfyui/utils/cacheManager';const log = debug('lobe-image:comfyui:client');+/**+ * WebSocket transport for the ComfyUI SDK that applies the SSRF policy at+ * connect time: `ws` runs its handshake through the supplied agent, and the+ * request-filtering agent checks the host on every connect.+ */+class SsrfSafeComfyUIWebSocket extends WebSocket {+ constructor(+ url: string | URL,+ protocolsOrOptions?: string | string[] | ClientOptions,+ options?: ClientOptions,+ ) {+ const agent = ssrfSafeAgent(String(url));+ if (+ protocolsOrOptions &&+ typeof protocolsOrOptions === 'object' &&+ !Array.isArray(protocolsOrOptions)+ ) {+ super(url, { ...protocolsOrOptions, agent } as ClientOptions);+ } else {+ super(url, protocolsOrOptions, { ...options, agent });+ }+ }+}+/*** Workflow execution result*/@@ -45,8 +78,16 @@ export type ProgressCallback = (info: any) => void;* Encapsulates all SDK interactions using modular services*/export class ComfyUIClientService {- private client: ComfyApi;+ private client?: ComfyApi;private baseURL: string;+ /**+ * Resolves once the ComfyUI `baseURL` has passed the SSRF policy and the SDK+ * client exists. The baseURL is user-configurable, so nothing may reach the+ * SDK β its internal `fetchApi` calls do not go through `ssrfSafeFetch` β+ * until the host is checked (T-07). The WebSocket transport is additionally+ * guarded at connect time by {@link SsrfSafeComfyUIWebSocket}.+ */+ private readonly clientReady!: Promise<ComfyApi>;// Modular services for separation of concernsprivate cacheManager: TTLCacheManager;@@ -69,11 +110,27 @@ export class ComfyUIClientService {this.baseURL =options.baseURL || process.env.COMFYUI_DEFAULT_URL || COMFYUI_DEFAULTS.BASE_URL;- // Initialize client with credentials from AuthService- this.client = new ComfyApi(this.baseURL, undefined, {- credentials: this.authService.getCredentials(),+ // Create the SDK client only after the baseURL passes the SSRF policy.+ this.clientReady = assertSsrfSafeUrl(this.baseURL).then(() => {+ this.client = new ComfyApi(this.baseURL, undefined, {+ // Credentials are applied by hardenComfyApi, not here: the constructor+ // would fire testCredentials() synchronously, ahead of the fetchApi+ // patch, and that probe would reach the network unfiltered.+ // The SDK types the impl against the DOM WebSocket, but only uses the+ // members `ws` implements (onopen/onclose/onmessage/onerror, send,+ // close, readyState, ready-state constants).+ customWebSocketImpl: SsrfSafeComfyUIWebSocket as unknown as WebSocketInterface,+ });+ this.hardenComfyApi(this.client, this.authService.getCredentials());+ this.client.init();+ return this.client;+ });++ // Callers observe the rejection when they await clientReady; this branch+ // only keeps an unused service from producing an unhandled rejection.+ this.clientReady.catch((error) => {+ log('β ComfyUI client initialization failed:', error);});- this.client.init();log('β ComfyUI Client Service initialized with baseURL:', this.baseURL);} catch (error) {@@ -82,6 +139,43 @@ export class ComfyUIClientService {}}+ /**+ * Route the SDK's HTTP traffic through the SSRF policy (T-07).+ *+ * Every SDK HTTP call funnels through `fetchApi` β global `fetch`. The+ * constructor-time `assertSsrfSafeUrl` check cannot cover what happens once+ * it has passed: a hostile ComfyUI endpoint (the baseURL is user-supplied)+ * can answer any request with a redirect to an internal address, which the+ * runtime fetch follows unchecked, and a hostname can re-resolve to a+ * private address after the check (DNS rebinding). `fetchApi` is+ * re-implemented 1:1 β credential headers plus `mode: 'cors'` β on top of+ * `ssrfSafeFetch`, so every connect, including redirect hops, is filtered.+ */+ private hardenComfyApi(+ client: ComfyApi,+ credentials: BasicCredentials | BearerTokenCredentials | CustomCredentials | undefined,+ ): void {+ const api = client as unknown as {+ apiURL: (route: string) => string;+ credentials: typeof credentials;+ getCredentialHeaders: () => Record<string, string>;+ testCredentials?: () => Promise<boolean>;+ };++ client.fetchApi = async (route: string, options?: FetchOptions): Promise<Response> => {+ // Same init the SDK builds: credential headers, `mode: 'cors'`.+ const init: FetchOptions = {+ ...options,+ headers: { ...api.getCredentialHeaders() },+ mode: 'cors',+ };+ return ssrfSafeFetch(api.apiURL(route), init);+ };++ api.credentials = credentials;+ void api.testCredentials?.();+ }+/*** Get authentication headers for image download* This method provides auth headers to framework layer without exposing credentials@@ -96,6 +190,12 @@ export class ComfyUIClientService {* Get the path for an image result*/getPathImage(imageInfo: any): string {+ if (!this.client) {+ throw new ServicesError(+ 'ComfyUI client is not initialized',+ ServicesError.Reasons.CONNECTION_FAILED,+ );+ }return this.client.getPathImage(imageInfo);}@@ -108,7 +208,8 @@ export class ComfyUIClientService {async uploadImage(file: Buffer | Blob, fileName: string): Promise<string> {log('π€ Uploading image to ComfyUI:', fileName);- const result = await this.client.uploadImage(file, fileName);+ const client = await this.clientReady;+ const result = await client.uploadImage(file, fileName);if (!result) {throw new ServicesError(@@ -131,8 +232,10 @@ export class ComfyUIClientService {): Promise<WorkflowResult> {log('π Executing workflow...');+ const client = await this.clientReady;+return new Promise<WorkflowResult>((resolve, reject) => {- new CallWrapper(this.client, workflow)+ new CallWrapper(client, workflow).onFinished((result: any) => {log('β Workflow execution finished successfully');log('π Raw workflow result structure:', {@@ -161,8 +264,9 @@ export class ComfyUIClientService {* Uses unified TTL cache for performance optimization*/async getCheckpoints(): Promise<string[]> {+ const client = await this.clientReady;return await this.cacheManager.get('checkpoints', async () => {- return await this.client.getCheckpoints();+ return await client.getCheckpoints();});}@@ -172,8 +276,9 @@ export class ComfyUIClientService {* Uses unified TTL cache for performance optimization*/async getLoras(): Promise<string[]> {+ const client = await this.clientReady;return await this.cacheManager.get('loras', async () => {- return await this.client.getLoras();+ return await client.getLoras();});}@@ -184,8 +289,9 @@ export class ComfyUIClientService {* @param nodeName - Optional specific node name to query*/async getNodeDefs(nodeName?: string): Promise<any> {+ const client = await this.clientReady;const allNodeDefs = await this.cacheManager.get('nodeDefs', async () => {- return await this.client.getNodeDefs();+ return await client.getNodeDefs();});// Return specific node or all nodes@@ -197,7 +303,8 @@ export class ComfyUIClientService {* Wraps SDK method to avoid Law of Demeter violation*/async getSamplerInfo(): Promise<{ samplerName: string[]; scheduler: string[] }> {- const info = await this.client.getSamplerInfo();+ const client = await this.clientReady;+ const info = await client.getSamplerInfo();return {samplerName: this.extractStrings(info.sampler),diff --git a/apps/server/src/services/comfyui/core/comfyUIConnectionService.ts b/apps/server/src/services/comfyui/core/comfyUIConnectionService.tsindex 559bad67bbf..a96c33c30e5 100644--- a/apps/server/src/services/comfyui/core/comfyUIConnectionService.ts+++ b/apps/server/src/services/comfyui/core/comfyUIConnectionService.ts@@ -4,6 +4,7 @@* Handles connection validation and state management for ComfyUI server* Provides TTL-based connection validation caching*/+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';import debug from 'debug';import { ServicesError } from '@/server/services/comfyui/errors';@@ -72,7 +73,9 @@ export class ComfyUIConnectionService {log('π Validating connection to:', url);- const response = await fetch(url, {+ // The ComfyUI baseURL is user-configurable, so the health check must go+ // through the SSRF policy (T-07).+ const response = await ssrfSafeFetch(url, {headers: {...headers,'Content-Type': 'application/json',diff --git a/apps/server/src/services/comfyui/core/imageService.ts b/apps/server/src/services/comfyui/core/imageService.tsindex 0152a72d4f4..294fbc6a40e 100644--- a/apps/server/src/services/comfyui/core/imageService.ts+++ b/apps/server/src/services/comfyui/core/imageService.ts@@ -5,6 +5,7 @@* and workflow execution*/import { type CreateImagePayload, type CreateImageResponse } from '@lobechat/model-runtime';+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';import { type PromptBuilder } from '@saintno/comfyui-sdk';import debug from 'debug';@@ -115,8 +116,9 @@ export class ImageService {}// Fetch image from URL (both S3 and Desktop static server use HTTP)+ // The URL is user-supplied, so the download goes through the SSRF policy (T-07).log('Fetching image from URL:', imageUrl);- const response = await fetch(imageUrl);+ const response = await ssrfSafeFetch(imageUrl);if (!response.ok) {throw new ServicesError(diff --git a/apps/server/src/services/generation/video.ssrf.test.ts b/apps/server/src/services/generation/video.ssrf.test.tsnew file mode 100644index 00000000000..431784752ff--- /dev/null+++ b/apps/server/src/services/generation/video.ssrf.test.ts@@ -0,0 +1,44 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { VideoGenerationService } from './video';++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return {};+ }),+}));++/**+ * `processVideoForGeneration` downloads `videoUrl` server-side. The download+ * must go through the SSRF policy; a raw fetch would reach intranet and+ * instance metadata endpoints (T-07).+ */+describe('VideoGenerationService SSRF boundary', () => {+ beforeEach(() => {+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', undefined);+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', undefined);+ // A stubbed native fetch keeps the unguarded path deterministic so this+ // suite fails fast if the SSRF guard is ever bypassed.+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('x')));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it.each([+ 'http://169.254.169.254/latest/meta-data/v.mp4',+ 'http://127.0.0.1/v.mp4',+ 'http://10.0.0.1/v.mp4',+ 'http://192.168.1.1/v.mp4',+ 'http://[::1]/v.mp4',+ ])('blocks the video download to %s', async (videoUrl) => {+ const service = new VideoGenerationService({} as any, 'user-1');++ await expect(service.processVideoForGeneration(videoUrl)).rejects.toThrow(/SSRF blocked/);+ expect(fetch).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/generation/video.ts b/apps/server/src/services/generation/video.tsindex 662e391b3c3..61705285723 100644--- a/apps/server/src/services/generation/video.ts+++ b/apps/server/src/services/generation/video.ts@@ -9,6 +9,7 @@ import { promisify } from 'node:util';import { type LobeChatDatabase } from '@lobechat/database';import { parseDataUri } from '@lobechat/model-runtime';+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';import debug from 'debug';import { nanoid } from 'nanoid';import sharp from 'sharp';@@ -197,7 +198,7 @@ export class VideoGenerationService {return tempVideoPath;}- const response = await fetch(url, {+ const response = await ssrfSafeFetch(url, {headers: options?.headers,signal: AbortSignal.timeout(VideoGenerationService.DOWNLOAD_TIMEOUT_MS),});diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ssrf.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.ssrf.test.tsnew file mode 100644index 00000000000..a3f23c873a2--- /dev/null+++ b/packages/model-runtime/src/core/contextBuilders/openai.ssrf.test.ts@@ -0,0 +1,69 @@+// @vitest-environment node+import type * as SSRFSafeFetchModule from '@lobechat/ssrf-safe-fetch';+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { clearReferenceImageCache } from '../../utils/referenceImageCache';+import { convertImageUrlToFile } from './openai';++// Wrap the real ssrfSafeFetch so call-through can be asserted while the real+// request-filtering policy still applies.+vi.mock('@lobechat/ssrf-safe-fetch', async (importOriginal) => {+ const mod = await importOriginal<typeof SSRFSafeFetchModule>();+ return { ...mod, ssrfSafeFetch: vi.fn(mod.ssrfSafeFetch) };+});++/**+ * `image.createImage` forwards user-supplied `imageUrls` to+ * `convertImageUrlToFile`, which downloads them server-side. The download must+ * go through the SSRF policy; a raw fetch would reach intranet and instance+ * metadata endpoints (T-07).+ */+describe('convertImageUrlToFile SSRF boundary', () => {+ beforeEach(() => {+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', undefined);+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', undefined);+ // A stubbed native fetch keeps the unguarded path deterministic so this+ // suite fails fast if the SSRF guard is ever bypassed.+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(new Uint8Array([1]))));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ clearReferenceImageCache();+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ vi.clearAllMocks();+ });++ it.each([+ 'http://169.254.169.254/latest/meta-data/image.png',+ 'http://127.0.0.1:8188/image.png',+ 'http://10.0.0.1/image.png',+ 'http://192.168.1.1/image.png',+ 'http://172.16.0.1/image.png',+ 'http://[::1]/image.png',+ ])('blocks the reference image download to %s', async (url) => {+ await expect(convertImageUrlToFile(url)).rejects.toThrow(/SSRF blocked/);++ expect(ssrfSafeFetch).toHaveBeenCalledWith(url, undefined, undefined);+ expect(fetch).not.toHaveBeenCalled();+ });++ it('routes remote image downloads through ssrfSafeFetch', async () => {+ vi.mocked(ssrfSafeFetch).mockResolvedValueOnce(+ new Response(new Uint8Array([1, 2, 3]), {+ headers: { 'content-type': 'image/png' },+ }),+ );++ const result = await convertImageUrlToFile('https://example.com/reference.png');++ expect(ssrfSafeFetch).toHaveBeenCalledWith(+ 'https://example.com/reference.png',+ undefined,+ undefined,+ );+ expect(result).toHaveProperty('type', 'image/png');+ });+});diff --git a/packages/model-runtime/src/core/contextBuilders/openai.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.test.tsindex e3a4d74b757..0a16c8135cb 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.test.ts@@ -369,7 +369,7 @@ describe('convertImageUrlToFile', () => {const result = await convertImageUrlToFile('https://example.com/image.jpg');- expect(mockFetch).toHaveBeenCalledWith('https://example.com/image.jpg');+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/image.jpg', undefined);expect(result).toBeDefined();expect(result).toHaveProperty('name', 'image.jpeg');expect(result).toHaveProperty('type', 'image/jpeg');@@ -433,7 +433,7 @@ describe('convertImageUrlToFile', () => {'Failed to fetch image from https://example.com/nonexistent.jpg: Not Found',);- expect(mockFetch).toHaveBeenCalledWith('https://example.com/nonexistent.jpg');+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/nonexistent.jpg', undefined);});it('should throw error when network request fails', async () => {@@ -443,7 +443,7 @@ describe('convertImageUrlToFile', () => {'Network error',);- expect(mockFetch).toHaveBeenCalledWith('https://example.com/image.jpg');+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/image.jpg', undefined);});});diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ts b/packages/model-runtime/src/core/contextBuilders/openai.tsindex 7e8d8cdded0..0a726da7c5f 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts@@ -7,6 +7,7 @@ import type { ChatStreamPayload, OpenAIChatMessage, UserMessageContentPart } froimport { imageUrlToBase64 } from '../../utils/imageToBase64';import { fetchReferenceImageBytes } from '../../utils/referenceImageCache';import { type SignatureScope } from '../../utils/signatureScope';+import { ssrfFetch } from '../../utils/ssrfFetch';import { parseDataUri } from '../../utils/uriParser';import { videoUrlToBase64 } from '../../utils/videoToBase64';@@ -220,7 +221,7 @@ export const convertImageUrlToFile = async (imageUrl: string) => {} else {// a http url; generation retries and batch siblings reuse the same download({ buffer, mimeType } = await fetchReferenceImageBytes(imageUrl, async (url) => {- const response = await fetch(url);+ const response = await ssrfFetch(url);if (!response.ok) {throw new Error(`Failed to fetch image from ${url}: ${response.statusText}`);}diff --git a/packages/model-runtime/src/core/openaiCompatible/createImage.test.ts b/packages/model-runtime/src/core/openaiCompatible/createImage.test.tsindex ecdb1aa3459..5148dc8cf75 100644--- a/packages/model-runtime/src/core/openaiCompatible/createImage.test.ts+++ b/packages/model-runtime/src/core/openaiCompatible/createImage.test.ts@@ -1,4 +1,6 @@// @vitest-environment node+import type * as SSRFSafeFetchModule from '@lobechat/ssrf-safe-fetch';+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';import type OpenAI from 'openai';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -13,6 +15,11 @@ vi.mock('@lobechat/business-model-bank/model-config', () => ({loadModels: vi.fn().mockResolvedValue([]),}));+vi.mock('@lobechat/ssrf-safe-fetch', async (importOriginal) => {+ const mod = await importOriginal<typeof SSRFSafeFetchModule>();+ return { ...mod, ssrfSafeFetch: vi.fn() };+});+// Polyfill File for Node environmentif (typeof File === 'undefined') {// @ts-ignore@@ -608,9 +615,9 @@ describe('createOpenAICompatibleImage', () => {],};- // Mock fetch for image download+ // Mock the SSRF-safe download for the input imageconst mockArrayBuffer = new Uint8Array([0xff, 0xd8, 0xff, 0xe0]).buffer;- global.fetch = vi.fn().mockResolvedValue({+ vi.mocked(ssrfSafeFetch).mockResolvedValue({ok: true,arrayBuffer: async () => mockArrayBuffer,headers: {diff --git a/packages/model-runtime/src/utils/imageToBase64.ts b/packages/model-runtime/src/utils/imageToBase64.tsindex 12d11702b6f..5dcda3ac04f 100644--- a/packages/model-runtime/src/utils/imageToBase64.ts+++ b/packages/model-runtime/src/utils/imageToBase64.ts@@ -2,6 +2,7 @@ import { Buffer } from 'buffer.js';import { resolveMimeTypeFromBytes } from './imageMimeType';import { readBlobWithLimit } from './readBlobWithLimit';+import { ssrfFetch } from './ssrfFetch';export { readBlobWithLimit } from './readBlobWithLimit';@@ -61,19 +62,14 @@ export const imageUrlToBase64 = async (try {const isServer = typeof window === 'undefined';- // Use SSRF-safe fetch on server-side to prevent SSRF attacksconst init = options.signal ? { signal: options.signal } : undefined;// Also cap the stream inside ssrfSafeFetch. It truncates silently, so allow one extra// byte for readBlobWithLimit to detect the overflow and reject.- const res = isServer- ? await import('@lobechat/ssrf-safe-fetch').then((m) =>- m.ssrfSafeFetch(- imageUrl,- init,- options.maxBytes ? { maxContentLength: options.maxBytes + 1 } : undefined,- ),- )- : await fetch(imageUrl, init);+ const res = await ssrfFetch(+ imageUrl,+ init,+ options.maxBytes ? { maxContentLength: options.maxBytes + 1 } : undefined,+ );const blob = options.maxBytes? await readBlobWithLimit(res, options.maxBytes)diff --git a/packages/model-runtime/src/utils/ssrfFetch.ts b/packages/model-runtime/src/utils/ssrfFetch.tsnew file mode 100644index 00000000000..3586bce7e20--- /dev/null+++ b/packages/model-runtime/src/utils/ssrfFetch.ts@@ -0,0 +1,16 @@+import type { SSRFOptions } from '@lobechat/ssrf-safe-fetch';++/**+ * Fetch that applies the server-side SSRF policy to caller-supplied URLs.+ * Every outbound download of a user- or provider-controlled URL must go+ * through this instead of bare `fetch`, so intranet and instance-metadata+ * endpoints stay unreachable (see `SSRF_ALLOW_PRIVATE_IP_ADDRESS` /+ * `SSRF_ALLOW_IP_ADDRESS_LIST` for self-host overrides).+ *+ * Browser builds fall back to native `fetch`: SSRF does not apply+ * client-side, and `@lobechat/ssrf-safe-fetch` degrades to native fetch there.+ */+export const ssrfFetch = (url: string, init?: RequestInit, ssrfOptions?: SSRFOptions) =>+ typeof window === 'undefined'+ ? import('@lobechat/ssrf-safe-fetch').then((m) => m.ssrfSafeFetch(url, init, ssrfOptions))+ : fetch(url, init);diff --git a/packages/model-runtime/src/utils/videoToBase64.ts b/packages/model-runtime/src/utils/videoToBase64.tsindex 54417e6a13b..ea39510c2ac 100644--- a/packages/model-runtime/src/utils/videoToBase64.ts+++ b/packages/model-runtime/src/utils/videoToBase64.ts@@ -1,3 +1,5 @@+import { ssrfFetch } from './ssrfFetch';+/*** Convert video URL to base64 data URL with SSRF protection* Uses SSRF-safe fetch to prevent SSRF attacks@@ -8,14 +10,10 @@ export const videoUrlToBase64 = async (try {const isServer = typeof window === 'undefined';- // Use SSRF-safe fetch to prevent SSRF attacks- const response = isServer- ? await import('@lobechat/ssrf-safe-fetch').then((m) =>- m.ssrfSafeFetch(videoUrl, {- signal: AbortSignal.timeout(30_000), // 30 seconds- }),- )- : await fetch(videoUrl);+ const response = await ssrfFetch(+ videoUrl,+ isServer ? { signal: AbortSignal.timeout(30_000) } : undefined, // 30 seconds+ );if (!response.ok) {throw new Error(`Failed to fetch video: ${response.status} ${response.statusText}`);diff --git a/packages/ssrf-safe-fetch/index.browser.ts b/packages/ssrf-safe-fetch/index.browser.tsindex b90ad42bff6..8c8a93e943f 100644--- a/packages/ssrf-safe-fetch/index.browser.ts+++ b/packages/ssrf-safe-fetch/index.browser.ts@@ -54,3 +54,17 @@ export const ssrfSafeFetch = async (): Promise<Response> => {return fetch(url, options);};++/**+ * Browser parity stub. In the browser the origin enforces connectivity, so+ * this only validates that the URL parses.+ */+export const assertSsrfSafeUrl = async (url: string, _ssrfOptions?: SSRFOptions): Promise<void> => {+ if (!URL.canParse(url)) throw new TypeError(`Invalid URL: ${url}`);+};++/**+ * Browser parity stub. Agents are a Node.js transport concept; the browser+ * never constructs one, so this always returns `undefined`.+ */+export const ssrfSafeAgent = (_url: string, _ssrfOptions?: SSRFOptions) => undefined;diff --git a/packages/ssrf-safe-fetch/index.test.ts b/packages/ssrf-safe-fetch/index.test.tsindex 93db9d6fb71..e1c1ec58215 100644--- a/packages/ssrf-safe-fetch/index.test.ts+++ b/packages/ssrf-safe-fetch/index.test.ts@@ -1,8 +1,16 @@// @ts-ignore+import dns from 'node:dns';+import fetch from 'node-fetch';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { isSSRFBlockedError, SSRFBlockedError, ssrfSafeFetch } from './index';+import {+ assertSsrfSafeUrl,+ isSSRFBlockedError,+ SSRFBlockedError,+ ssrfSafeAgent,+ ssrfSafeFetch,+} from './index';// Mock node-fetch to avoid actual network requestsvi.mock('node-fetch', () => ({@@ -573,3 +581,119 @@ describe('ssrfSafeFetch', () => {});});});++describe('assertSsrfSafeUrl', () => {+ beforeEach(() => {+ delete process.env.SSRF_ALLOW_IP_ADDRESS_LIST;+ delete process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS;+ vi.restoreAllMocks();+ });++ describe('literal IP hostnames', () => {+ const blockedUrls = [+ 'http://127.0.0.1:8188/system_stats',+ 'http://169.254.169.254/latest/meta-data/',+ 'http://10.0.0.1/internal',+ 'http://192.168.1.1/admin',+ 'http://172.16.0.1/',+ 'http://0.0.0.0:80',+ 'http://[::1]:8188/',+ 'http://[fe80::1]/',+ ];++ blockedUrls.forEach((url) => {+ it(`rejects ${url} with an SSRF blocked error`, async () => {+ const error = await assertSsrfSafeUrl(url).catch((e) => e);+ expect(error).toBeInstanceOf(SSRFBlockedError);+ expect(error.message).toMatch(/^SSRF blocked: /);+ expect(isSSRFBlockedError(error)).toBe(true);+ });+ });++ it('resolves for a public unicast IP', async () => {+ await expect(assertSsrfSafeUrl('http://93.184.215.14/')).resolves.toBeUndefined();+ });+ });++ describe('hostnames', () => {+ it('rejects a hostname resolving to a private address', async () => {+ vi.spyOn(dns.promises, 'lookup').mockResolvedValue([+ { address: '10.1.2.3', family: 4 },+ ] as dns.LookupAddress[]);++ await expect(assertSsrfSafeUrl('http://comfy.intranet.example:8188')).rejects.toThrow(+ /SSRF blocked: .*10\.1\.2\.3.*private IP address/,+ );+ });++ it('rejects when any resolved address is private', async () => {+ vi.spyOn(dns.promises, 'lookup').mockResolvedValue([+ { address: '93.184.215.14', family: 4 },+ { address: '127.0.0.1', family: 4 },+ ] as dns.LookupAddress[]);++ await expect(assertSsrfSafeUrl('http://mixed.example')).rejects.toThrow(/SSRF blocked/);+ });++ it('resolves when every resolved address is public', async () => {+ vi.spyOn(dns.promises, 'lookup').mockResolvedValue([+ { address: '93.184.215.14', family: 4 },+ { address: '93.184.215.15', family: 4 },+ ] as dns.LookupAddress[]);++ await expect(assertSsrfSafeUrl('http://public.example')).resolves.toBeUndefined();+ });++ it('rejects localhost, which resolves to loopback', async () => {+ await expect(assertSsrfSafeUrl('http://localhost:8188')).rejects.toThrow(/SSRF blocked/);+ });+ });++ describe('policy overrides', () => {+ it('allows private addresses when SSRF_ALLOW_PRIVATE_IP_ADDRESS is set', async () => {+ process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS = '1';+ await expect(assertSsrfSafeUrl('http://127.0.0.1:8188')).resolves.toBeUndefined();+ });++ it('allows a literal IP listed in SSRF_ALLOW_IP_ADDRESS_LIST', async () => {+ process.env.SSRF_ALLOW_IP_ADDRESS_LIST = '127.0.0.1';+ await expect(assertSsrfSafeUrl('http://127.0.0.1/')).resolves.toBeUndefined();+ });++ it('allows addresses inside an allow-listed CIDR', async () => {+ await expect(+ assertSsrfSafeUrl('http://10.20.30.40/', { allowIPAddressList: ['10.0.0.0/8'] }),+ ).resolves.toBeUndefined();+ });++ it('respects a per-call allowPrivateIPAddress override', async () => {+ await expect(+ assertSsrfSafeUrl('http://192.168.1.1/', { allowPrivateIPAddress: true }),+ ).resolves.toBeUndefined();+ });+ });++ describe('invalid input', () => {+ it('rejects malformed URLs', async () => {+ const error = await assertSsrfSafeUrl('not a url').catch((e) => e);+ expect(error).toBeInstanceOf(SSRFBlockedError);+ expect(error.message).toContain('Invalid URL');+ });+ });+});++describe('ssrfSafeAgent', () => {+ it('returns an HTTP agent for http and ws URLs', () => {+ expect(ssrfSafeAgent('http://example.com').constructor.name).toBe('RequestFilteringHttpAgent');+ expect(ssrfSafeAgent('ws://example.com:8188').constructor.name).toBe(+ 'RequestFilteringHttpAgent',+ );+ });++ it('returns an HTTPS agent for https and wss URLs', () => {+ expect(ssrfSafeAgent('https://example.com').constructor.name).toBe(+ 'RequestFilteringHttpsAgent',+ );+ expect(ssrfSafeAgent('wss://example.com').constructor.name).toBe('RequestFilteringHttpsAgent');+ });+});diff --git a/packages/ssrf-safe-fetch/index.ts b/packages/ssrf-safe-fetch/index.tsindex 0cdcd2fba11..2060becf704 100644--- a/packages/ssrf-safe-fetch/index.ts+++ b/packages/ssrf-safe-fetch/index.ts@@ -1,3 +1,7 @@+import dns from 'node:dns';+import net from 'node:net';++import ipaddr from 'ipaddr.js';import fetch from 'node-fetch';import type { RequestFilteringAgentOptions } from 'request-filtering-agent';import { RequestFilteringHttpAgent, RequestFilteringHttpsAgent } from 'request-filtering-agent';@@ -30,6 +34,9 @@ type NodeBody = NodeJS.ReadableStream & { destroy?: (error?: Error) => void };const SSRF_BLOCKED_PREFIX = 'SSRF blocked';+const SSRF_DOCS_URL =+ 'https://lobehub.com/docs/self-hosting/environment-variables/basic#ssrf-allow-private-ip-address';+/*** Thrown when the request (or one of its redirect hops) resolves to a private, loopback,* link-local or otherwise reserved address that the SSRF policy does not allow. The message@@ -93,11 +100,9 @@ const toFetchError = (error: unknown): Error => {if (isSSRFBlock) {console.error('SSRF protection blocked request:', toErrorLog(error));- return new SSRFBlockedError(- `${SSRF_BLOCKED_PREFIX}: ${errorMessage}. ` +- 'See: https://lobehub.com/docs/self-hosting/environment-variables/basic#ssrf-allow-private-ip-address',- { cause: error },- );+ return new SSRFBlockedError(`${SSRF_BLOCKED_PREFIX}: ${errorMessage}. See: ${SSRF_DOCS_URL}`, {+ cause: error,+ });}console.error('Fetch error:', toErrorLog(error));@@ -179,6 +184,26 @@ const abandonedBodies = new FinalizationRegistry<ReadableStream<Uint8Array>>((bo* @param ssrfOptions - Optional per-call SSRF configuration overrides* @see https://lobehub.com/docs/self-hosting/environment-variables/basic#ssrf-allow-private-ip-address*/+/**+ * Resolve the effective request-filtering policy for a call: explicit+ * `ssrfOptions` win over the `SSRF_ALLOW_PRIVATE_IP_ADDRESS` /+ * `SSRF_ALLOW_IP_ADDRESS_LIST` environment variables.+ */+const resolveAgentOptions = (ssrfOptions?: SSRFOptions): RequestFilteringAgentOptions => {+ const allowPrivate = ssrfOptions?.allowPrivateIPAddress ?? envAllowPrivate();+ return {+ allowIPAddressList: ssrfOptions?.allowIPAddressList ?? envAllowIPAddressList(),+ allowMetaIPAddress: allowPrivate,+ allowPrivateIPAddress: allowPrivate,+ denyIPAddressList: [],+ };+};++const envAllowPrivate = () => process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS === '1';++const envAllowIPAddressList = () =>+ process.env.SSRF_ALLOW_IP_ADDRESS_LIST?.split(',').filter(Boolean) ?? [];+export const ssrfSafeFetch = async (url: string,@@ -186,23 +211,9 @@ export const ssrfSafeFetch = async (ssrfOptions?: SSRFOptions,): Promise<Response> => {try {- // Configure SSRF protection options with proper precedence using nullish coalescing- const envAllowPrivate = process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS === '1';- const allowPrivate = ssrfOptions?.allowPrivateIPAddress ?? envAllowPrivate;-- const agentOptions: RequestFilteringAgentOptions = {- allowIPAddressList:- ssrfOptions?.allowIPAddressList ??- process.env.SSRF_ALLOW_IP_ADDRESS_LIST?.split(',').filter(Boolean) ??- [],- allowMetaIPAddress: allowPrivate,- allowPrivateIPAddress: allowPrivate,- denyIPAddressList: [],- };-// Create agents for both protocols- const httpAgent = new RequestFilteringHttpAgent(agentOptions);- const httpsAgent = new RequestFilteringHttpsAgent(agentOptions);+ const httpAgent = new RequestFilteringHttpAgent(resolveAgentOptions(ssrfOptions));+ const httpsAgent = new RequestFilteringHttpsAgent(resolveAgentOptions(ssrfOptions));// Use node-fetch with SSRF protection agent// Pass a function to dynamically select agent based on URL protocol@@ -233,3 +244,129 @@ export const ssrfSafeFetch = async (throw toFetchError(error);}};++/** Whether `address` (raw or parsed) matches an IP or CIDR entry of `ipAddressList`. */+const matchIPAddressList = (+ address: string,+ parsed: ipaddr.IPv4 | ipaddr.IPv6,+ ipAddressList: string[],+) => {+ for (const ipOrCIDR of ipAddressList) {+ if (net.isIP(ipOrCIDR) !== 0) {+ if (ipOrCIDR === address) return true;+ continue;+ }+ try {+ // eslint-disable-next-line unicorn/prefer-regexp-test -- ipaddr.js API, not String.prototype.match+ if (parsed.match(ipaddr.parseCIDR(ipOrCIDR))) return true;+ } catch {+ // Invalid CIDR entries are ignored, matching request-filtering-agent behavior.+ }+ }+ return false;+};++const blockedError = (detail: string, cause?: unknown) =>+ new SSRFBlockedError(`${SSRF_BLOCKED_PREFIX}: ${detail}. See: ${SSRF_DOCS_URL}`, { cause });++/**+ * Apply the same address policy `request-filtering-agent` enforces at connect+ * time to a resolved `address`. The messages keep the agent's wording so the+ * `SSRF blocked:` contract is identical whichever check trips.+ */+const assertAddressAllowed = (+ address: string,+ host: string,+ family: number | undefined,+ options: RequestFilteringAgentOptions,+): void => {+ if (net.isIP(address) === 0) return;++ const parsed = ipaddr.parse(address);++ if (+ options.allowIPAddressList?.length &&+ matchIPAddressList(address, parsed, options.allowIPAddressList)+ ) {+ return;+ }++ const range = parsed.range();+ const where = `DNS lookup ${address}(family:${family}, host:${host}) is not allowed`;++ if (!options.allowMetaIPAddress && range === 'unspecified') {+ throw blockedError(`${where}. Because, It is meta IP address.`);+ }++ if (!options.allowPrivateIPAddress && range !== 'unicast') {+ throw blockedError(`${where}. Because, It is private IP address.`);+ }++ if (+ options.denyIPAddressList?.length &&+ matchIPAddressList(address, parsed, options.denyIPAddressList)+ ) {+ throw blockedError(`${where}. Because It is defined in denyIPAddressList.`);+ }+};++/**+ * Assert that `url` does not point at a private, loopback, link-local or+ * otherwise reserved address: every address its hostname resolves to is checked+ * against the same policy `ssrfSafeFetch` enforces, including the+ * `SSRF_ALLOW_PRIVATE_IP_ADDRESS` / `SSRF_ALLOW_IP_ADDRESS_LIST` overrides.+ *+ * Use this for transports `ssrfSafeFetch` cannot cover β WebSocket clients or+ * third-party SDKs that manage their own connections β as a pre-flight check on+ * the base URL. Note the resolution happens once, ahead of the connection;+ * where the transport accepts a custom agent, prefer {@link ssrfSafeAgent}+ * which filters at connect time instead.+ *+ * @param url - The URL whose host is resolved and checked+ * @param ssrfOptions - Optional per-call SSRF configuration overrides+ * @throws {SSRFBlockedError} when any resolved address is refused by the policy+ */+export const assertSsrfSafeUrl = async (url: string, ssrfOptions?: SSRFOptions): Promise<void> => {+ const options = resolveAgentOptions(ssrfOptions);++ let hostname: string;+ try {+ // `new URL` keeps the brackets on IPv6 literals (`[::1]`); strip them for the+ // IP checks and the DNS lookup below.+ hostname = new URL(url).hostname.replaceAll(/^\[|\]$/g, '');+ } catch (error) {+ throw blockedError(`Invalid URL: ${url}`, error);+ }++ if (!hostname) {+ throw blockedError(`Invalid URL: ${url}`);+ }++ // Literal IP hostnames skip DNS and are checked directly.+ if (net.isIP(hostname) !== 0) {+ assertAddressAllowed(hostname, hostname, undefined, options);+ return;+ }++ const addresses = await dns.promises.lookup(hostname, { all: true });+ for (const { address, family } of addresses) {+ assertAddressAllowed(address, hostname, family, options);+ }+};++/**+ * Create a request-filtering agent for `url`, so transports that accept a+ * Node.js `http.Agent` / `https.Agent` (for example `ws`, which uses the agent+ * for its handshake connection) get the same connect-time SSRF policy as+ * `ssrfSafeFetch` β including DNS filtering on every connect, with no+ * resolution-vs-connect race.+ *+ * `https`/`wss` URLs get a TLS-capable agent; anything else gets the plain one.+ *+ * @param url - The URL the agent will connect to+ * @param ssrfOptions - Optional per-call SSRF configuration overrides+ */+export const ssrfSafeAgent = (url: string, ssrfOptions?: SSRFOptions) =>+ url.startsWith('https') || url.startsWith('wss')+ ? new RequestFilteringHttpsAgent(resolveAgentOptions(ssrfOptions))+ : new RequestFilteringHttpAgent(resolveAgentOptions(ssrfOptions));diff --git a/packages/ssrf-safe-fetch/package.json b/packages/ssrf-safe-fetch/package.jsonindex 95db4446245..c79f9dcdca0 100644--- a/packages/ssrf-safe-fetch/package.json+++ b/packages/ssrf-safe-fetch/package.json@@ -16,6 +16,7 @@"test:coverage": "vitest --coverage --silent='passed-only'"},"dependencies": {+ "ipaddr.js": "^2.5.0","node-fetch": "^3.3.2","request-filtering-agent": "^3.2.1"},