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(security): guard server-side requests to user-supplied AI provider endpoints (T-03) (#23692)

Bryanf44156f39637
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yaml
index b25212fea6f..64b9b3825ce 100644
--- a/apps/desktop/pnpm-lock.yaml
+++ b/apps/desktop/pnpm-lock.yaml
@@ -681,6 +681,9 @@ importers:
request-filtering-agent:
specifier: ^3.2.1
version: 3.2.1
+ undici:
+ specifier: ^7.29.0
+ version: 7.30.0
devDependencies:
vitest:
specifier: 5.0.3
@@ -5084,6 +5087,7 @@ packages:
resolution: {integrity: sha512-jI22jzTf7x3GAcUoZARwuxKBPotb3PFkemVWqxlF2qV55FhRytRJrn95HeLoUMq2vkIbY3aQqNYytvZKqUoMaQ==}
+ deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
@@ -15915,8 +15919,7 @@ snapshots:
- optional: true
diff --git a/apps/server/src/modules/ModelRuntime/index.ts b/apps/server/src/modules/ModelRuntime/index.ts
index 90848187a5f..ad75441a516 100644
--- a/apps/server/src/modules/ModelRuntime/index.ts
+++ b/apps/server/src/modules/ModelRuntime/index.ts
@@ -43,6 +43,7 @@ import { ensureFreshOAuthToken } from '@/server/services/oauthDeviceFlow/refresh
import { KeyVaultsGateKeeper } from '../KeyVaultsEncrypt';
import apiKeyManager from './apiKeyManager';
import { sharpInlineImageNormalizer } from './inlineImageNormalizer';
+import { createUserEndpointGuardedRuntime } from './userEndpointGuard';
// Server requests can re-encode oversized images instead of dropping them.
setInlineImageNormalizer(sharpInlineImageNormalizer);
@@ -447,6 +448,14 @@ const buildVertexOptions = (
(useServerConfig ? process.env.VERTEXAI_LOCATION : undefined) ||
undefined;
+ // The region is interpolated into `<region>-aiplatform.googleapis.com` by the
+ // SDK; reject anything that could change the resulting host.
+ if (location && !/^[a-z0-9-]+$/.test(location)) {
+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidVertexCredentials, {
+ message: 'Invalid VertexAI region',
+ });
+ }
+
const googleAuthOptions = params.googleAuthOptions || (credentials ? { credentials } : undefined);
// Without explicit user credentials Google auth would load the server's ambient credentials.
@@ -492,25 +501,32 @@ export const initModelRuntimeWithUserPayload = (
});
}
- if (runtimeProvider === ModelProvider.VertexAI) {
- const vertexOptions = buildVertexOptions(
- payload,
- params,
- canUseServerProviderConfig(provider, payload),
- );
- const runtime = LobeVertexAI.initFromVertexAI(vertexOptions);
-
- return new ModelRuntime(runtime, hooks);
- }
+ /**
+ * Endpoints in the payload are user-supplied (keyVaults or the client), so
+ * requests to them are SSRF-guarded. Env-configured `*_PROXY_URL` endpoints
+ * are operator-trusted and stay unguarded. The LobeHub provider is
+ * platform-owned and routes through server config only.
+ */
+ const userEndpoints =
+ runtimeProvider === ModelProvider.LobeHub
+ ? []
+ : [payload.baseURL, payload.cloudflareBaseURLOrAccountID];
+
+ const runtime = createUserEndpointGuardedRuntime({
+ create: () =>
+ runtimeProvider === ModelProvider.VertexAI
+ ? LobeVertexAI.initFromVertexAI(
+ buildVertexOptions(payload, params, canUseServerProviderConfig(provider, payload)),
+ )
+ : ModelRuntime.createProviderRuntime(runtimeProvider, {
+ ...getParamsFromPayload(provider, payload),
+ ...params,
+ }),
+ endpoints: userEndpoints,
+ provider,
+ });
- return ModelRuntime.initializeWithProvider(
- runtimeProvider,
- {
- ...getParamsFromPayload(provider, payload),
- ...params,
- },
- hooks,
- );
+ return new ModelRuntime(runtime, hooks);
};
/**
diff --git a/apps/server/src/modules/ModelRuntime/userEndpointGuard.test.ts b/apps/server/src/modules/ModelRuntime/userEndpointGuard.test.ts
new file mode 100644
index 00000000000..cb81e8d67a2
--- /dev/null
+++ b/apps/server/src/modules/ModelRuntime/userEndpointGuard.test.ts
@@ -0,0 +1,354 @@
+// @vitest-environment node
+import http from 'node:http';
+import type { AddressInfo } from 'node:net';
+
+import { SSRFBlockedError, validateSsrfAddress } from '@lobechat/ssrf-safe-fetch';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { ModelProvider } from 'model-bank';
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { initModelRuntimeWithUserPayload } from './index';
+import {
+ createProviderBaseURLBlockedError,
+ createUserEndpointGuardedRuntime,
+ resolveUserEndpointSsrfPolicy,
+} from './userEndpointGuard';
+
+const edition = vi.hoisted(() => ({ cloud: false }));
+
+vi.mock('@lobechat/business-const', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ get ENABLE_BUSINESS_FEATURES() {
+ return edition.cloud;
+ },
+}));
+
+vi.mock('@/envs/llm', () => ({ getLLMConfig: vi.fn(() => ({ OPENAI_API_KEY: 'env-key' })) }));
+vi.mock('@/server/globalConfig', () => ({ getServerAiProviderConfig: vi.fn() }));
+
+/**
+ * A stand-in for a model server on the loopback interface — exactly what a
+ * user-supplied `http://127.0.0.1:…` / `http://localhost:11434` baseURL hits.
+ */
+let hits: string[] = [];
+let server: http.Server;
+let baseURL: string;
+
+const sseCompletion = [
+ 'data: {"id":"1","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"hi from loopback"},"finish_reason":null}]}',
+ 'data: {"id":"1","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
+ 'data: [DONE]',
+ '',
+].join('\n\n');
+
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ hits.push(`${req.method} ${req.url}`);
+
+ if (req.url?.startsWith('/redirect')) {
+ res.writeHead(307, { location: 'http://169.254.169.254/latest/meta-data/' });
+ return res.end();
+ }
+
+ if (req.url?.endsWith('/models')) {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ return res.end(JSON.stringify({ data: [{ id: 'local-model', object: 'model' }] }));
+ }
+
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
+ res.end(sseCompletion);
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ baseURL = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`;
+});
+
+afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())));
+
+afterEach(() => {
+ hits = [];
+ edition.cloud = false;
+ vi.unstubAllEnvs();
+});
+
+const chat = (provider: string, endpoint: string) =>
+ initModelRuntimeWithUserPayload(provider, { apiKey: 'user-key', baseURL: endpoint }).chat({
+ messages: [{ content: 'hello', role: 'user' }],
+ model: 'local-model',
+ stream: true,
+ temperature: 0,
+ });
+
+describe('resolveUserEndpointSsrfPolicy', () => {
+ it('cloud always blocks private addresses, even when the env asks to allow them', () => {
+ edition.cloud = true;
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', '1');
+
+ expect(resolveUserEndpointSsrfPolicy().allowPrivateIPAddress).toBe(false);
+ });
+
+ it('self-hosted allows private addresses by default and blocks with SSRF_ALLOW_PRIVATE_IP_ADDRESS=0', () => {
+ expect(resolveUserEndpointSsrfPolicy().allowPrivateIPAddress).toBe(true);
+
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', '0');
+ expect(resolveUserEndpointSsrfPolicy().allowPrivateIPAddress).toBe(false);
+ });
+
+ it('reads the allow list from SSRF_ALLOW_IP_ADDRESS_LIST', () => {
+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', '10.0.0.5, 192.168.0.0/16,');
+
+ expect(resolveUserEndpointSsrfPolicy().allowIPAddressList).toEqual([
+ '10.0.0.5',
+ '192.168.0.0/16',
+ ]);
+ });
+
+ it.each(['169.254.169.254', 'fe80::1', '64:ff9b::a9fe:a9fe', '::ffff:a9fe:a9fe'])(
+ 'denies %s under the self-host policy even though private addresses are allowed',
+ (address) => {
+ expect(validateSsrfAddress(address, resolveUserEndpointSsrfPolicy())).toBeInstanceOf(
+ SSRFBlockedError,
+ );
+ },
+ );
+
+ it('still allows a plain private address under the self-host policy', () => {
+ expect(validateSsrfAddress('10.0.0.1', resolveUserEndpointSsrfPolicy())).toBeUndefined();
+ });
+});
+
+describe('initModelRuntimeWithUserPayload SSRF guard', () => {
+ describe('cloud', () => {
+ it('refuses a loopback baseURL for chat with ProviderBaseURLBlocked; the server is never contacted', async () => {
+ edition.cloud = true;
+
+ await expect(chat(ModelProvider.OpenAI, baseURL)).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ provider: ModelProvider.OpenAI,
+ });
+ expect(hits).toEqual([]);
+ });
+
+ it('refuses the model list request (models()) too', async () => {
+ edition.cloud = true;
+ const runtime = initModelRuntimeWithUserPayload(ModelProvider.OpenAI, {
+ apiKey: 'user-key',
+ baseURL,
+ });
+
+ await expect(runtime.models()).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ });
+ expect(hits).toEqual([]);
+ });
+
+ it('refuses embeddings', async () => {
+ edition.cloud = true;
+ const runtime = initModelRuntimeWithUserPayload(ModelProvider.OpenAI, {
+ apiKey: 'user-key',
+ baseURL,
+ });
+
+ await expect(
+ runtime.embeddings({ input: 'hello', model: 'text-embedding-3-small' }),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked });
+ expect(hits).toEqual([]);
+ });
+
+ it('covers non-OpenAI SDKs (Ollama) and custom providers', async () => {
+ edition.cloud = true;
+ const ollamaRuntime = initModelRuntimeWithUserPayload(ModelProvider.Ollama, {
+ baseURL: baseURL.replace('/v1', ''),
+ });
+
+ await expect(ollamaRuntime.models()).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ });
+
+ await expect(
+ initModelRuntimeWithUserPayload('my-custom-provider', {
+ apiKey: 'user-key',
+ baseURL,
+ runtimeProvider: ModelProvider.OpenAI,
+ }).models(),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked });
+
+ expect(hits).toEqual([]);
+ });
+
+ it('blocks an allow-listed endpoint that redirects (3xx) to a private address', async () => {
+ edition.cloud = true;
+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', '127.0.0.1');
+
+ const redirecting = baseURL.replace('/v1', '/redirect/v1');
+ await expect(chat(ModelProvider.OpenAI, redirecting)).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ });
+ // The allow-listed first hop was served, the private redirect target was refused
+ expect(hits).toEqual(['POST /redirect/v1/chat/completions']);
+ });
+
+ it('lets an allow-listed private endpoint stream normally', async () => {
+ edition.cloud = true;
+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', '127.0.0.1');
+
+ const response = await chat(ModelProvider.OpenAI, baseURL);
+ expect(await response.text()).toContain('hi from loopback');
+ expect(hits).toEqual(['POST /v1/chat/completions']);
+ });
+ });
+
+ describe('self-hosted', () => {
+ it('keeps reaching a private endpoint by default (docker-network Ollama / LM Studio)', async () => {
+ const response = await chat(ModelProvider.OpenAI, baseURL);
+
+ expect(await response.text()).toContain('hi from loopback');
+ expect(hits).toEqual(['POST /v1/chat/completions']);
+ });
+
+ it('blocks private endpoints when the operator sets SSRF_ALLOW_PRIVATE_IP_ADDRESS=0', async () => {
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', '0');
+
+ await expect(chat(ModelProvider.OpenAI, baseURL)).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ });
+ expect(hits).toEqual([]);
+ });
+
+ it('blocks link-local metadata endpoints even though private addresses are allowed', async () => {
+ await expect(
+ chat(ModelProvider.OpenAI, 'http://169.254.169.254/latest'),
+ ).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ });
+ });
+ });
+
+ it('does not guard an operator-configured env proxy URL (no user baseURL in the payload)', async () => {
+ edition.cloud = true;
+ vi.stubEnv('OPENAI_PROXY_URL', baseURL);
+
+ const response = await initModelRuntimeWithUserPayload(ModelProvider.OpenAI, {}).chat({
+ messages: [{ content: 'hello', role: 'user' }],
+ model: 'local-model',
+ stream: true,
+ temperature: 0,
+ });
+
+ expect(await response.text()).toContain('hi from loopback');
+ });
+});
+
+describe('createUserEndpointGuardedRuntime', () => {
+ it('only guards hosts of the user endpoints; other requests made inside the call pass through', async () => {
+ edition.cloud = true;
+ const otherOrigin = baseURL.replace('/v1', '');
+
+ const runtime = createUserEndpointGuardedRuntime({
+ create: () => ({
+ // e.g. a platform hook or another service reached during the call
+ fetchOther: () => fetch(`${otherOrigin}/v1/models`).then((res) => res.json()),
+ fetchUserEndpoint: () => fetch(`http://localhost:11434/v1/models`),
+ }),
+ endpoints: ['http://localhost:11434/v1'],
+ provider: 'openai',
+ });
+
+ await expect(runtime.fetchOther()).resolves.toEqual({
+ data: [{ id: 'local-model', object: 'model' }],
+ });
+ await expect(runtime.fetchUserEndpoint()).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ });
+ });
+
+ it('returns the bare runtime when no endpoint is user-supplied', () => {
+ edition.cloud = true;
+ const bare = { chat: vi.fn() };
+
+ expect(
+ createUserEndpointGuardedRuntime({ create: () => bare, endpoints: [], provider: 'openai' }),
+ ).toBe(bare);
+ });
+
+ describe('node:http transports', () => {
+ /**
+ * `@azure-rest/ai-inference` (via `@typespec/ts-http-runtime`) and similar
+ * SDKs drive `node:http(s)` directly instead of `fetch`; the guard must
+ * cover them by injecting a filtering agent.
+ */
+ const nodeTransport = () => ({
+ probe: () =>
+ new Promise<number>((resolve, reject) => {
+ http
+ .get(`${baseURL}/models`, (res) => {
+ res.resume();
+ resolve(res.statusCode ?? 0);
+ })
+ .on('error', reject);
+ }),
+ });
+
+ it('blocks node:http requests to a private endpoint host in cloud mode', async () => {
+ edition.cloud = true;
+ const runtime = createUserEndpointGuardedRuntime({
+ create: nodeTransport,
+ endpoints: [baseURL],
+ provider: 'azureai',
+ });
+
+ await expect(runtime.probe()).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ });
+ expect(hits).toEqual([]);
+ });
+
+ it('still reaches a private endpoint over node:http when the policy allows private addresses', async () => {
+ const runtime = createUserEndpointGuardedRuntime({
+ create: nodeTransport,
+ endpoints: [baseURL],
+ provider: 'azureai',
+ });
+
+ await expect(runtime.probe()).resolves.toBe(200);
+ expect(hits).toEqual(['GET /v1/models']);
+ });
+ });
+});
+
+describe('vertexAIRegion', () => {
+ it.each(['us-central1.evil.com', 'evil.com/x', 'a b', 'a?b=1', '[email protected]'])(
+ 'rejects a region that could corrupt the derived aiplatform host: %s',
+ (region) => {
+ try {
+ initModelRuntimeWithUserPayload(ModelProvider.VertexAI, {
+ apiKey: JSON.stringify({ project_id: 'p' }),
+ vertexAIRegion: region,
+ });
+ expect.unreachable(`region ${region} should be rejected`);
+ } catch (error) {
+ expect(error).toMatchObject({
+ errorType: AgentRuntimeErrorType.InvalidVertexCredentials,
+ });
+ }
+ },
+ );
+});
+
+describe('createProviderBaseURLBlockedError', () => {
+ it('does not leak the resolved address to the client', () => {
+ const blocked = new SSRFBlockedError(
+ 'SSRF blocked: DNS lookup 10.1.2.3(family:4, host:internal.corp) is not allowed.',
+ );
+ blocked.address = '10.1.2.3';
+ blocked.hostname = 'internal.corp';
+
+ const error = createProviderBaseURLBlockedError('openai', blocked);
+
+ expect(error).toMatchObject({
+ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ provider: 'openai',
+ });
+ expect(JSON.stringify(error)).not.toContain('10.1.2.3');
+ expect(JSON.stringify(error)).not.toContain('DNS lookup');
+ });
+});
diff --git a/apps/server/src/modules/ModelRuntime/userEndpointGuard.ts b/apps/server/src/modules/ModelRuntime/userEndpointGuard.ts
new file mode 100644
index 00000000000..c7aa5bbd536
--- /dev/null
+++ b/apps/server/src/modules/ModelRuntime/userEndpointGuard.ts
@@ -0,0 +1,374 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+import http from 'node:http';
+import https from 'node:https';
+import net from 'node:net';
+
+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
+import { AgentRuntimeError } from '@lobechat/model-runtime';
+import type { SSRFOptions } from '@lobechat/ssrf-safe-fetch';
+import {
+ createSsrfSafeFetch,
+ findSSRFBlockedError,
+ SSRF_BLOCKED_PREFIX,
+ SSRF_DOCS_URL,
+ SSRFBlockedError,
+ ssrfSafeAgent,
+} from '@lobechat/ssrf-safe-fetch';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import debug from 'debug';
+
+const log = debug('model-runtime:user-endpoint-guard');
+
+/**
+ * SSRF guard for model requests sent to user-supplied endpoints (a provider
+ * `baseURL` from keyVaults or the client payload).
+ *
+ * Provider SDKs and the providers' own raw `fetch` calls all go through
+ * `globalThis.fetch`, so rather than threading a `fetch` option through ~90
+ * provider implementations, every method call on a guarded runtime runs inside
+ * an AsyncLocalStorage scope. A one-time wrapper around `globalThis.fetch`
+ * routes requests whose host matches one of the user's endpoints through an
+ * SSRF-safe fetch that validates the resolved address of every connection,
+ * redirect hops included. Requests to any other host are untouched.
+ *
+ * Platform-configured endpoints (`*_PROXY_URL` env, built-in provider URLs) are
+ * operator-trusted and never guarded.
+ */
+
+/**
+ * Cloud is multi-tenant, so user endpoints may never reach private networks.
+ * Self-hosted deployments keep reaching private endpoints by default — a
+ * LobeHub container talking to `http://ollama:11434` on the same docker
+ * network is a common, legitimate setup — and opt in to blocking with
+ * `SSRF_ALLOW_PRIVATE_IP_ADDRESS=0`. `SSRF_ALLOW_IP_ADDRESS_LIST` allow-lists
+ * specific addresses / CIDRs in both cases.
+ */
+export const resolveUserEndpointSsrfPolicy = (): SSRFOptions => ({
+ allowIPAddressList:
+ process.env.SSRF_ALLOW_IP_ADDRESS_LIST?.split(',')
+ .map((item) => item.trim())
+ .filter(Boolean) ?? [],
+ allowPrivateIPAddress: ENABLE_BUSINESS_FEATURES
+ ? false
+ : process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS !== '0',
+ /**
+ * Link-local stays denied even when a self-hosted deployment allows private
+ * endpoints: an open-registration instance must not hand every user a path
+ * to the cloud metadata service (169.254.169.254). The NAT64 prefixes cover
+ * the same destinations in translated form on NAT64 networks.
+ * `SSRF_ALLOW_IP_ADDRESS_LIST` still wins for an operator who genuinely
+ * needs such an endpoint.
+ */
+ denyIPAddressList: ['169.254.0.0/16', 'fe80::/10', '64:ff9b::/96', '64:ff9b:1::/48'],
+});
+
+interface GuardScope {
+ agents: { http: http.Agent; https: https.Agent };
+ blocked?: SSRFBlockedError;
+ fetch: typeof fetch;
+ hosts: ReadonlySet<string>;
+ provider: string;
+}
+
+const scopeStorage = new AsyncLocalStorage<GuardScope>();
+
+const normalizeHostname = (hostname: string) => hostname.replaceAll(/^\[|\]$/g, '').toLowerCase();
+
+const getEndpointHostname = (endpoint: string | undefined) => {
+ if (!endpoint) return;
+ try {
+ return normalizeHostname(new URL(endpoint).hostname);
+ } catch {
+ // Not a URL, e.g. a Cloudflare account id in `cloudflareBaseURLOrAccountID`
+ }
+};
+
+const getRequestHostname = (input: RequestInfo | URL) => {
+ try {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ return normalizeHostname(new URL(url).hostname);
+ } catch {
+ return;
+ }
+};
+
+/**
+ * The hostname a `http(s).request(url[, options][, cb])` /
+ * `http(s).request(options[, cb])` call targets. `options.host` may carry a
+ * port, `options.hostname` never does.
+ */
+type NodeRequestCallback = (res: http.IncomingMessage) => void;
+
+const getNodeRequestHostname = (args: unknown[]) => {
+ const [urlOrOptions, options] = args as [
+ string | URL | http.RequestOptions | undefined,
+ (http.RequestOptions | NodeRequestCallback) | undefined,
+ ];
+ if (typeof urlOrOptions === 'string' || urlOrOptions instanceof URL) {
+ try {
+ return normalizeHostname(new URL(urlOrOptions).hostname);
+ } catch {
+ return;
+ }
+ }
+ const host =
+ (urlOrOptions as http.RequestOptions | undefined)?.hostname ??
+ (urlOrOptions as http.RequestOptions | undefined)?.host ??
+ (options as http.RequestOptions | undefined)?.hostname ??
+ (options as http.RequestOptions | undefined)?.host;
+ if (typeof host !== 'string') return;
+ // A bare IP never carries a port; only strip `:port` from names and
+ // bracketed IPv6 so `::1` is not mangled into a bypass.
+ if (net.isIP(host) !== 0) return normalizeHostname(host);
+ return normalizeHostname(host.replace(/:\d+$/, ''));
+};
+
+/** request-filtering-agent refuses with an "… is not allowed" message. */
+const toBlockedFromAgentError = (error: Error) =>
+ error.message.includes('is not allowed') || error instanceof SSRFBlockedError
+ ? new SSRFBlockedError(`${SSRF_BLOCKED_PREFIX}: ${error.message}. See: ${SSRF_DOCS_URL}`, {
+ cause: error,
+ })
+ : undefined;
+
+/**
+ * SDKs retry a rejected fetch as a connection error (the OpenAI SDK twice, with
+ * backoff), which would re-send the request to an allowed first hop on every
+ * attempt. A non-retryable 403 ends the attempt immediately; the guarded call
+ * then reports `ProviderBaseURLBlocked` from `scope.blocked`, whatever error
+ * the provider derived from this response.
+ */
+const createBlockedResponse = (blocked: SSRFBlockedError) =>
+ Response.json(
+ { error: { code: 'provider_base_url_blocked', message: blocked.message } },
+ { status: 403, statusText: 'Forbidden' },
+ );
+
+let originalFetch: typeof fetch | undefined;
+let nodeRequestsWrapped = false;
+
+/**
+ * Wrap `http.request` / `https.request` once. Some SDK transports bypass
+ * `fetch` entirely (e.g. `@typespec/ts-http-runtime` used by
+ * `@azure-rest/ai-inference` calls `node:https` directly), so endpoint-host
+ * requests made inside a guard scope get a request-filtering agent injected
+ * that applies the same connect-time policy — redirects included.
+ */
+const wrapNodeRequest = (
+ module: typeof http | typeof https,
+ agent: 'http' | 'https',
+ method: 'request' | 'get',
+) => {
+ const original = module[method] as (...args: unknown[]) => http.ClientRequest;
+
+ module[method] = function (this: unknown, ...args: unknown[]) {
+ const scope = scopeStorage.getStore();
+ const hostname = scope && getNodeRequestHostname(args);
+
+ if (!scope || !hostname || !scope.hosts.has(hostname)) {
+ return original.apply(this, args as []);
+ }
+
+ if (scope.blocked) {
+ // Return a pre-failed request — a bare `new ClientRequest({})` would
+ // still open a socket to localhost:80.
+ const request = new http.ClientRequest({ createConnection: () => new net.Socket() });
+ queueMicrotask(() => request.destroy(scope.blocked));
+ return request;
+ }
+
+ const [urlOrOptions, options, callback] = args as [
+ string | URL | http.RequestOptions | undefined,
+ (http.RequestOptions | NodeRequestCallback) | undefined,
+ NodeRequestCallback | undefined,
+ ];
+ const filteringAgent = scope.agents[agent];
+
+ const wrappedArgs =
+ typeof urlOrOptions === 'string' || urlOrOptions instanceof URL
+ ? typeof options === 'function'
+ ? [urlOrOptions, { agent: filteringAgent }, options]
+ : [urlOrOptions, { ...(options as http.RequestOptions), agent: filteringAgent }, callback]
+ : typeof options === 'function'
+ ? [{ ...(urlOrOptions as http.RequestOptions), agent: filteringAgent }, options]
+ : [
+ { ...(urlOrOptions as http.RequestOptions), agent: filteringAgent },
+ options === undefined ? undefined : (options as NodeRequestCallback),
+ ];
+
+ const request = original.apply(this, wrappedArgs as []);
+ request.on('error', (error) => {
+ if (scope.blocked) return;
+ const blocked = toBlockedFromAgentError(error);
+ if (blocked) {
+ log(
+ 'blocked %s request to %s for provider %s: %s',
+ agent,
+ hostname,
+ scope.provider,
+ blocked.message,
+ );
+ scope.blocked = blocked;
+ }
+ });
+ return request;
+ } as typeof module.request;
+};
+
+const wrapNodeRequests = () => {
+ if (nodeRequestsWrapped) return;
+ nodeRequestsWrapped = true;
+ // `get` calls an internal `request`, not `module.request`, so both are wrapped.
+ wrapNodeRequest(http, 'http', 'request');
+ wrapNodeRequest(http, 'http', 'get');
+ wrapNodeRequest(https, 'https', 'request');
+ wrapNodeRequest(https, 'https', 'get');
+};
+
+/**
+ * Wrap `globalThis.fetch` once. SDKs capture the global fetch when a client is
+ * constructed, so this must run before the guarded runtime is created.
+ */
+const installScopedFetch = () => {
+ if (originalFetch) return originalFetch;
+
+ const baseFetch = globalThis.fetch;
+ originalFetch = baseFetch;
+
+ const scopedFetch = ((input: RequestInfo | URL, init?: RequestInit) => {
+ const scope = scopeStorage.getStore();
+ const hostname = scope && getRequestHostname(input);
+
+ if (!scope || !hostname || !scope.hosts.has(hostname)) return baseFetch(input, init);
+
+ if (scope.blocked) return Promise.resolve(createBlockedResponse(scope.blocked));
+
+ return scope.fetch(input, init).catch((error: unknown) => {
+ const blocked = findSSRFBlockedError(error);
+ if (!blocked) throw error;
+
+ log('blocked fetch to %s for provider %s: %s', hostname, scope.provider, blocked.message);
+ scope.blocked = blocked;
+ return createBlockedResponse(blocked);
+ });
+ }) as typeof fetch;
+
+ // Keep markers that frameworks put on fetch (e.g. Next.js `__nextPatched`) so
+ // they do not wrap it a second time.
+ Object.assign(scopedFetch, baseFetch);
+ globalThis.fetch = scopedFetch;
+ wrapNodeRequests();
+
+ return baseFetch;
+};
+
+const guardedFetchCache = new Map<string, typeof fetch>();
+
+const getGuardedFetch = (policy: SSRFOptions, baseFetch: typeof fetch) => {
+ const key = JSON.stringify(policy);
+ let guardedFetch = guardedFetchCache.get(key);
+ if (!guardedFetch) {
+ guardedFetch = createSsrfSafeFetch(policy, { fetch: baseFetch });
+ guardedFetchCache.set(key, guardedFetch);
+ }
+ return guardedFetch;
+};
+
+const guardedAgentCache = new Map<string, GuardScope['agents']>();
+
+const getGuardedAgents = (policy: SSRFOptions): GuardScope['agents'] => {
+ const key = JSON.stringify(policy);
+ let agents = guardedAgentCache.get(key);
+ if (!agents) {
+ agents = {
+ http: ssrfSafeAgent('http://endpoint.invalid', policy) as http.Agent,
+ https: ssrfSafeAgent('https://endpoint.invalid', policy) as https.Agent,
+ };
+ guardedAgentCache.set(key, agents);
+ }
+ return agents;
+};
+
+export const createProviderBaseURLBlockedError = (provider: string, blocked: SSRFBlockedError) =>
+ AgentRuntimeError.chat({
+ error: {
+ hostname: blocked.hostname,
+ // Never return the resolved address — that would leak internal DNS
+ // results to whoever configured the endpoint.
+ message:
+ 'The provider endpoint resolves to a private or reserved network address that the server is not allowed to reach.',
+ },
+ errorType: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ provider,
+ });
+
+const toBlockedError = (provider: string, scope: GuardScope, error: unknown) => {
+ const blocked = scope.blocked ?? findSSRFBlockedError(error);
+ return blocked ? createProviderBaseURLBlockedError(provider, blocked) : error;
+};
+
+const isPromise = (value: unknown): value is Promise<unknown> =>
+ !!value && typeof (value as PromiseLike<unknown>).then === 'function';
+
+const runInScope = <T>(provider: string, scope: GuardScope, fn: () => T): T =>
+ scopeStorage.run(scope, () => {
+ try {
+ const result = fn();
+
+ if (isPromise(result)) {
+ return result.then(
+ (value) => {
+ // Some providers swallow a non-OK response (e.g. `models()` falling
+ // back to an empty list); a blocked request must still fail loudly
+ if (scope.blocked) throw createProviderBaseURLBlockedError(provider, scope.blocked);
+ return value;
+ },
+ (error: unknown) => {
+ throw toBlockedError(provider, scope, error);
+ },
+ ) as T;
+ }
+
+ return result;
+ } catch (error) {
+ throw toBlockedError(provider, scope, error);
+ }
+ });
+
+/**
+ * Build a provider runtime whose requests to the given user endpoints are
+ * SSRF-guarded. Returns the plain runtime when no endpoint is user-supplied.
+ * Self-hosted deployments still go through the guard: the policy allows
+ * private addresses there but keeps link-local (metadata) denied.
+ *
+ * A blocked connection surfaces as `ProviderBaseURLBlocked` instead of the
+ * SDK's generic `Connection error.`.
+ */
+export const createUserEndpointGuardedRuntime = <T extends object>(params: {
+ create: () => T;
+ endpoints: (string | undefined)[];
+ provider: string;
+}): T => {
+ const { create, endpoints, provider } = params;
+ const policy = resolveUserEndpointSsrfPolicy();
+ const hosts = new Set(endpoints.map(getEndpointHostname).filter((host) => !!host) as string[]);
+
+ if (hosts.size === 0) return create();
+
+ const baseFetch = installScopedFetch();
+ const guardedFetch = getGuardedFetch(policy, baseFetch);
+ const agents = getGuardedAgents(policy);
+ const runtime = create();
+
+ return new Proxy(runtime, {
+ get(target, property) {
+ const value = Reflect.get(target, property, target);
+ if (typeof value !== 'function' || property === 'constructor') return value;
+
+ return (...args: unknown[]) =>
+ runInScope(provider, { agents, fetch: guardedFetch, hosts, provider }, () =>
+ value.apply(target, args),
+ );
+ },
+ });
+};
diff --git a/apps/server/src/services/memory/userMemory/extract/runtime.ts b/apps/server/src/services/memory/userMemory/extract/runtime.ts
index d24c60ed936..4e6844b12be 100644
--- a/apps/server/src/services/memory/userMemory/extract/runtime.ts
+++ b/apps/server/src/services/memory/userMemory/extract/runtime.ts
@@ -10,6 +10,7 @@ import { getBusinessModelRuntimeHooks } from '@/business/server/model-runtime';
import { AiInfraRepos } from '@/database/repositories/aiInfra';
import type { MemoryAgentConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { createUserEndpointGuardedRuntime } from '@/server/modules/ModelRuntime/userEndpointGuard';
import { getUserScopedAiProviderRuntimeState } from '@/server/services/aiProviderAccess';
import type { GlobalMemoryLayer } from '@/types/serverConfig';
import type { LayersEnum } from '@/types/userMemory';
@@ -110,11 +111,18 @@ export const resolveRuntimeAgentConfig = (
// Only use the user baseURL if we are also using their API key; otherwise fall back entirely
// to system config to avoid mixing credentials.
- return ModelRuntime.initializeWithProvider(provider, {
- apiKey: userApiKey,
- baseURL: userBaseURL,
- userId: options?.userId,
- });
+ return new ModelRuntime(
+ createUserEndpointGuardedRuntime({
+ create: () =>
+ ModelRuntime.createProviderRuntime(provider, {
+ apiKey: userApiKey,
+ baseURL: userBaseURL,
+ userId: options?.userId,
+ }),
+ endpoints: [userBaseURL],
+ provider,
+ }),
+ );
}
debugRuntimeInit(agent, {
diff --git a/docs/self-hosting/environment-variables/basic.mdx b/docs/self-hosting/environment-variables/basic.mdx
index 084b6948258..6c130b0e6d9 100644
--- a/docs/self-hosting/environment-variables/basic.mdx
+++ b/docs/self-hosting/environment-variables/basic.mdx
@@ -209,6 +209,8 @@ LobeHub performs SSRF security checks in the following scenarios:
4. **HTTP MCP Servers and Connectors**: When the server connects to a Streamable HTTP MCP server or connector, including its OAuth discovery and token requests. The check uses the IP address the host actually resolves to, on every request and redirect. A self-hosted deployment without a device gateway that runs MCP servers on its own network must allow them with `SSRF_ALLOW_PRIVATE_IP_ADDRESS` or `SSRF_ALLOW_IP_ADDRESS_LIST`; MCP servers that run through the desktop app on the user's machine are not affected.
+5. **AI Provider Endpoints**: When the server calls an AI provider `baseURL` that a user supplied (provider settings / keyVaults), the endpoint host is checked on every request and redirect. On LobeHub Cloud, user-supplied endpoints can never reach private addresses. Self-hosted deployments allow private provider endpoints by default — a container reaching `http://ollama:11434` on its own docker network is a common, legitimate setup — and can opt in to blocking with `SSRF_ALLOW_PRIVATE_IP_ADDRESS=0` (note the inverted meaning for this surface), or allow only specific addresses with `SSRF_ALLOW_IP_ADDRESS_LIST`. Link-local addresses (`169.254.0.0/16`, `fe80::/10`, and their NAT64 translations) stay blocked on self-hosted deployments even when private endpoints are allowed, so an open-registration instance cannot reach cloud metadata services; `SSRF_ALLOW_IP_ADDRESS_LIST` can still allow a specific link-local address if truly needed. Endpoints configured by the operator (`*_PROXY_URL` env, built-in provider URLs) are trusted and not checked.
+
**Configuration Examples**:
```bash
diff --git a/docs/self-hosting/environment-variables/basic.zh-CN.mdx b/docs/self-hosting/environment-variables/basic.zh-CN.mdx
index 3e328e6dc58..edfbcf26eaf 100644
--- a/docs/self-hosting/environment-variables/basic.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables/basic.zh-CN.mdx
@@ -204,6 +204,8 @@ LobeHub 会在以下场景执行 SSRF 安全检查:
4. **HTTP MCP 服务器与连接器**:服务端连接 Streamable HTTP 类型的 MCP 服务器或连接器时(包括其 OAuth 发现与令牌请求)。检查基于域名实际解析出的 IP,每次请求和重定向都会检查。未配置设备网关、需要直连本地网络中 MCP 服务器的自部署实例,需通过 `SSRF_ALLOW_PRIVATE_IP_ADDRESS` 或 `SSRF_ALLOW_IP_ADDRESS_LIST` 放行;经桌面端在用户本机运行的 MCP 服务器不受影响。
+5. **AI 提供商端点**:服务端调用用户填写的 AI 提供商 `baseURL`(提供商设置 /keyVaults)时,该端点域名在每次请求和重定向都会检查。LobeHub Cloud 上用户端点永远不能访问私有地址。自部署默认允许私有提供商端点 —— 容器访问同一 docker 网络中的 `http://ollama:11434` 是常见的正当用法 —— 可用 `SSRF_ALLOW_PRIVATE_IP_ADDRESS=0` 开启拦截(注意此处语义相反),或用 `SSRF_ALLOW_IP_ADDRESS_LIST` 只放行特定地址。即使自部署放行了私网,链路本地地址(`169.254.0.0/16`、`fe80::/10` 及其 NAT64 转换前缀)依然被拦截,避免开放注册的实例被用来访问云元数据服务;如确有需求可用 `SSRF_ALLOW_IP_ADDRESS_LIST` 单独放行。运维配置的端点(`*_PROXY_URL` 环境变量、内置提供商地址)视为可信,不做检查。
+
**配置示例**:
```bash
diff --git a/locales/en-US/modelRuntime.json b/locales/en-US/modelRuntime.json
index eb79ff22182..4660b419db9 100644
--- a/locales/en-US/modelRuntime.json
+++ b/locales/en-US/modelRuntime.json
@@ -40,6 +40,7 @@
"OllamaServiceUnavailable": "Ollama service is unavailable. Please check if Ollama is running properly or if the cross-origin configuration of Ollama is set correctly.",
"OperationInactivityTimeout": "The agent operation was idle for too long and was terminated. Please retry the request.",
"PermissionDenied": "Sorry, you do not have permission to access this service. Please check if your key has the necessary access rights.",
+ "ProviderBaseURLBlocked": "The {{provider}} endpoint points to a private or local network address, which the server is not allowed to reach for security reasons. This address only works from your own device — use a publicly reachable endpoint instead.",
"ProviderBizError": "Error requesting {{provider}} service, please troubleshoot or retry based on the following information",
"ProviderContentPolicyViolation": "The provider blocked this request or its output due to content policy. Please revise your prompt and try again.",
"ProviderNetworkError": "Connection to the provider timed out or was dropped. Please check your network and try again.",
diff --git a/locales/zh-CN/modelRuntime.json b/locales/zh-CN/modelRuntime.json
index b406d1f9288..8392bd2fc35 100644
--- a/locales/zh-CN/modelRuntime.json
+++ b/locales/zh-CN/modelRuntime.json
@@ -40,6 +40,7 @@
"OllamaServiceUnavailable": "Ollama服务不可用。请检查Ollama是否正常运行或Ollama的跨域配置是否正确设置。",
"OperationInactivityTimeout": "代理操作闲置时间过长,已被终止。请重试请求。",
"PermissionDenied": "抱歉,您没有权限访问此服务。请检查您的密钥是否具有必要的访问权限。",
+ "ProviderBaseURLBlocked": "{{provider}} 的服务地址指向私有或本地网络,出于安全原因服务端不允许访问。该地址只能从你自己的设备访问,请改用可公网访问的服务地址。",
"ProviderBizError": "请求{{provider}}服务时发生错误,请根据以下信息进行排查或重试。",
"ProviderContentPolicyViolation": "供应商因内容政策拦截了此请求或其输出。请修改提示词后重试。",
"ProviderNetworkError": "与提供商的连接超时或被中断。请检查您的网络并重试。",
diff --git a/packages/locales/src/default/modelRuntime.ts b/packages/locales/src/default/modelRuntime.ts
index 9321501dc7e..c91c2c78421 100644
--- a/packages/locales/src/default/modelRuntime.ts
+++ b/packages/locales/src/default/modelRuntime.ts
@@ -79,6 +79,8 @@ export default {
'The agent operation was idle for too long and was terminated. Please retry the request.',
PermissionDenied:
'Sorry, you do not have permission to access this service. Please check if your key has the necessary access rights.',
+ ProviderBaseURLBlocked:
+ 'The {{provider}} endpoint points to a private or local network address, which the server is not allowed to reach for security reasons. This address only works from your own device — use a publicly reachable endpoint instead.',
ProviderBizError:
'Error requesting {{provider}} service, please troubleshoot or retry based on the following information',
ProviderContentPolicyViolation:
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index 338ad5cfe3a..cb827884b49 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -887,13 +887,23 @@ export class ModelRuntime {
>,
hooks?: ModelRuntimeHooks,
) {
+ return new ModelRuntime(ModelRuntime.createProviderRuntime(provider, params), hooks);
+ }
+
+ /**
+ * Construct the bare provider implementation without wrapping it in a
+ * ModelRuntime, so callers can decorate it (e.g. the server's SSRF guard)
+ * before attaching hooks.
+ */
+ static createProviderRuntime(
+ provider: string,
+ params: Parameters<typeof ModelRuntime.initializeWithProvider>[1],
+ ): LobeRuntimeAI {
// runtime map does not include every provider id (e.g. vertex), so index loosely
const runtimeMap: Partial<Record<string, new (params: any) => LobeRuntimeAI>> =
providerRuntimeMap;
const providerAI = runtimeMap[provider] ?? LobeOpenAI;
- const runtimeModel: LobeRuntimeAI = new providerAI(params);
-
- return new ModelRuntime(runtimeModel, hooks);
+ return new providerAI(params);
}
}
diff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.ts
index a4aef26f5d2..7d379a9cc05 100644
--- a/packages/model-runtime/src/errors/specs.ts
+++ b/packages/model-runtime/src/errors/specs.ts
@@ -792,6 +792,18 @@ export const ERROR_CODE_SPECS: SpecMap = {
countAsFailure: false,
description: 'Provider connection check failed during setup.',
},
+ [AgentRuntimeErrorType.ProviderBaseURLBlocked]: {
+ code: AgentRuntimeErrorType.ProviderBaseURLBlocked,
+ numericId: 9006,
+ category: 'config',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description:
+ 'User-supplied provider base URL resolves to a private / reserved address the server may not reach (SSRF protection).',
+ },
[AgentRuntimeErrorType.ClientLlmExecutorUnavailable]: {
code: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,
numericId: 9007,
diff --git a/packages/ssrf-safe-fetch/guardedFetch.network.test.ts b/packages/ssrf-safe-fetch/guardedFetch.network.test.ts
new file mode 100644
index 00000000000..bcd732371f1
--- /dev/null
+++ b/packages/ssrf-safe-fetch/guardedFetch.network.test.ts
@@ -0,0 +1,434 @@
+import dns from 'node:dns';
+import http from 'node:http';
+import type { AddressInfo } from 'node:net';
+
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ createSsrfSafeFetch,
+ findSSRFBlockedError,
+ SSRFBlockedError,
+ validateSsrfAddress,
+} from './index';
+
+const expectBlocked = async (promise: Promise<unknown>) => {
+ const error = await promise.then(
+ () => undefined,
+ (e) => e,
+ );
+ expect(error).toBeDefined();
+ expect(findSSRFBlockedError(error)).toBeInstanceOf(SSRFBlockedError);
+};
+
+let server: http.Server;
+let origin: string;
+let hits: string[] = [];
+
+/** A second origin (same host, different port) for cross-origin redirect cases. */
+let crossServer: http.Server;
+let crossOrigin: string;
+let crossRequests: { authorization?: string; cookie?: string; url?: string }[] = [];
+
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ hits.push(req.url!);
+
+ if (req.url === '/redirect-to-metadata') {
+ res.writeHead(302, { location: 'http://169.254.169.254/latest/meta-data/' });
+ return res.end();
+ }
+
+ if (req.url === '/redirect-to-loopback-name') {
+ res.writeHead(307, {
+ location: `http://localhost:${(server.address() as AddressInfo).port}/ok`,
+ });
+ return res.end();
+ }
+
+ if (req.url === '/redirect-to-ok') {
+ res.writeHead(302, { location: '/ok' });
+ return res.end();
+ }
+
+ if (req.url === '/redirect-cross-origin') {
+ res.writeHead(307, { location: `${crossOrigin}/echo` });
+ return res.end();
+ }
+
+ if (req.url === '/redirect-post-307') {
+ res.writeHead(307, { location: '/echo' });
+ return res.end();
+ }
+
+ if (req.url === '/echo') {
+ let body = '';
+ req.on('data', (chunk) => (body += chunk));
+ req.on('end', () => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify({
+ authorization: req.headers.authorization ?? null,
+ body,
+ method: req.method,
+ }),
+ );
+ });
+ return;
+ }
+
+ if (req.url === '/stream') {
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
+ res.write('data: first\n\n');
+ setTimeout(() => res.end('data: second\n\n'), 300);
+ return;
+ }
+
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+
+ crossServer = http.createServer((req, res) => {
+ crossRequests.push({
+ authorization: req.headers.authorization,
+ cookie: req.headers.cookie,
+ url: req.url,
+ });
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ await new Promise<void>((resolve) => crossServer.listen(0, '127.0.0.1', resolve));
+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ crossOrigin = `http://127.0.0.1:${(crossServer.address() as AddressInfo).port}`;
+});
+
+afterAll(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ await new Promise<void>((resolve) => crossServer.close(() => resolve()));
+});
+
+afterEach(() => {
+ hits = [];
+ crossRequests = [];
+ vi.restoreAllMocks();
+});
+
+describe('validateSsrfAddress', () => {
+ it.each([
+ '127.0.0.1',
+ '10.1.2.3',
+ '172.16.0.1',
+ '192.168.1.1',
+ '169.254.169.254',
+ '100.64.0.1',
+ '0.0.0.0',
+ '::1',
+ '::',
+ 'fd00::1',
+ 'fe80::1',
+ '::ffff:127.0.0.1',
+ '::ffff:10.0.0.1',
+ // IPv4-mapped IPv6 is judged by its own `ipv4Mapped` range, not the mapped
+ // IPv4's — the same rule `assertSsrfSafeUrl` enforces.
+ '::ffff:8.8.8.8',
+ ])('blocks %s by default', (address) => {
+ expect(validateSsrfAddress(address, {})).toBeInstanceOf(SSRFBlockedError);
+ });
+
+ it.each(['8.8.8.8', '1.1.1.1', '2606:4700:4700::1111'])('allows public %s', (address) => {
+ expect(validateSsrfAddress(address, {})).toBeUndefined();
+ });
+
+ it('honours allowPrivateIPAddress and the allow list (address and CIDR)', () => {
+ expect(validateSsrfAddress('10.0.0.1', { allowPrivateIPAddress: true })).toBeUndefined();
+ expect(validateSsrfAddress('10.0.0.1', { allowIPAddressList: ['10.0.0.1'] })).toBeUndefined();
+ expect(
+ validateSsrfAddress('10.0.0.9', { allowIPAddressList: ['10.0.0.0/24'] }),
+ ).toBeUndefined();
+ expect(validateSsrfAddress('10.0.1.9', { allowIPAddressList: ['10.0.0.0/24'] })).toBeInstanceOf(
+ SSRFBlockedError,
+ );
+ });
+
+ it('deny list wins over allowPrivateIPAddress but loses to the allow list', () => {
+ const policy = {
+ allowPrivateIPAddress: true,
+ denyIPAddressList: ['169.254.0.0/16', 'fe80::/10'],
+ };
+
+ expect(validateSsrfAddress('169.254.169.254', policy)).toBeInstanceOf(SSRFBlockedError);
+ expect(validateSsrfAddress('fe80::1', policy)).toBeInstanceOf(SSRFBlockedError);
+ // IPv4-mapped IPv6 forms of the same link-local destination
+ expect(validateSsrfAddress('::ffff:a9fe:a9fe', policy)).toBeInstanceOf(SSRFBlockedError);
+ expect(validateSsrfAddress('::ffff:169.254.169.254', policy)).toBeInstanceOf(SSRFBlockedError);
+ expect(validateSsrfAddress('10.0.0.1', policy)).toBeUndefined();
+ expect(
+ validateSsrfAddress('169.254.169.254', {
+ ...policy,
+ allowIPAddressList: ['169.254.169.254'],
+ }),
+ ).toBeUndefined();
+ });
+});
+
+describe('createSsrfSafeFetch', () => {
+ it('blocks a loopback baseURL before any request reaches the server', async () => {
+ await expectBlocked(createSsrfSafeFetch()(`${origin}/v1/chat/completions`));
+ expect(hits).toHaveLength(0);
+ });
+
+ it.each([
+ 'http://2130706433/',
+ 'http://0x7f.1/',
+ 'http://127.1/',
+ 'http://[::1]/',
+ 'http://[::ffff:127.0.0.1]/',
+ 'http://[fd00::1]/',
+ 'http://169.254.169.254/latest/meta-data/',
+ ])('blocks the obfuscated private address %s', async (url) => {
+ await expectBlocked(createSsrfSafeFetch()(url));
+ });
+
+ it('blocks a hostname that resolves to a private address (DNS rebinding)', async () => {
+ vi.spyOn(dns, 'lookup').mockImplementation(((
+ _hostname: string,
+ options: dns.LookupOptions,
+ callback: (...args: unknown[]) => void,
+ ) => {
+ if (options?.all) return callback(null, [{ address: '10.0.0.7', family: 4 }]);
+ callback(null, '10.0.0.7', 4);
+ }) as any);
+
+ await expectBlocked(createSsrfSafeFetch()('http://rebind.example.com/v1/models'));
+ expect(dns.lookup).toHaveBeenCalled();
+ });
+
+ it('blocks localhost because the resolved loopback address is checked', async () => {
+ const port = (server.address() as AddressInfo).port;
+ await expectBlocked(createSsrfSafeFetch()(`http://localhost:${port}/ok`));
+ expect(hits).toHaveLength(0);
+ });
+
+ it('re-validates every redirect hop: an allowed host redirecting to a private address is blocked', async () => {
+ const guardedFetch = createSsrfSafeFetch({ allowIPAddressList: ['127.0.0.1'] });
+
+ await expectBlocked(guardedFetch(`${origin}/redirect-to-metadata`));
+ // The first hop was allowed and served; only the redirect target was refused
+ expect(hits).toEqual(['/redirect-to-metadata']);
+ });
+
+ it('blocks a redirect to a hostname resolving to loopback even when the IP literal is allow-listed', async () => {
+ vi.spyOn(dns, 'lookup').mockImplementation(((
+ _hostname: string,
+ options: dns.LookupOptions,
+ callback: (...args: unknown[]) => void,
+ ) => {
+ if (options?.all) return callback(null, [{ address: '::1', family: 6 }]);
+ callback(null, '::1', 6);
+ }) as any);
+
+ const guardedFetch = createSsrfSafeFetch({ allowIPAddressList: ['127.0.0.1'] });
+
+ await expectBlocked(guardedFetch(`${origin}/redirect-to-loopback-name`));
+ expect(hits).toEqual(['/redirect-to-loopback-name']);
+ });
+
+ it('allows private targets when the policy allows them', async () => {
+ const res = await createSsrfSafeFetch({ allowPrivateIPAddress: true })(`${origin}/ok`);
+ expect(await res.json()).toEqual({ ok: true });
+ });
+
+ it('allows an allow-listed address and streams the body without buffering it', async () => {
+ const res = await createSsrfSafeFetch({ allowIPAddressList: ['127.0.0.1'] })(
+ `${origin}/stream`,
+ );
+ expect(res).toBeInstanceOf(Response);
+
+ const reader = res.body!.getReader();
+ const first = await reader.read();
+
+ // The server sends the first SSE event immediately and the second only
+ // after a delay, so a body buffered to completion would deliver both
+ // events in the first chunk.
+ const firstEvent = new TextDecoder().decode(first.value);
+ expect(firstEvent).toContain('data: first');
+ expect(firstEvent).not.toContain('data: second');
+
+ let rest = '';
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
+ rest += new TextDecoder().decode(chunk.value);
+ }
+ expect(rest).toContain('data: second');
+ });
+
+ it('works as an SDK fetch with POST bodies and abort signals', async () => {
+ const controller = new AbortController();
+ const res = await createSsrfSafeFetch({ allowIPAddressList: ['127.0.0.1'] })(`${origin}/ok`, {
+ body: JSON.stringify({ model: 'x' }),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ signal: controller.signal,
+ });
+ expect(res.status).toBe(200);
+ });
+
+ it('falls back to application-layer checks on Bun, whose fetch ignores dispatchers', async () => {
+ const baseFetch = vi.fn((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init));
+ (process.versions as Record<string, string | undefined>).bun = '1.4.4';
+ try {
+ // private targets are still refused — at resolution time rather than connect time
+ await expectBlocked(createSsrfSafeFetch({}, { fetch: baseFetch })(`${origin}/ok`));
+ expect(baseFetch).not.toHaveBeenCalled();
+ expect(hits).toHaveLength(0);
+
+ // allowed targets go through the base fetch with no dispatcher attached
+ const res = await createSsrfSafeFetch(
+ { allowIPAddressList: ['127.0.0.1'] },
+ { fetch: baseFetch },
+ )(`${origin}/ok`);
+ expect(res.status).toBe(200);
+ expect((baseFetch.mock.calls[0][1] as RequestInit).dispatcher).toBeUndefined();
+ } finally {
+ delete (process.versions as Record<string, string | undefined>).bun;
+ }
+ });
+});
+
+describe('createSsrfSafeFetch with an environment proxy (NODE_USE_ENV_PROXY=1)', () => {
+ // The env vars only select the proxy code path; the injected base fetch
+ // connects directly, standing in for the proxied global fetch.
+ const proxiedFetch = vi.fn((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init));
+
+ beforeEach(() => {
+ vi.stubEnv('NODE_USE_ENV_PROXY', '1');
+ vi.stubEnv('HTTPS_PROXY', 'http://proxy.example.com:3128');
+ proxiedFetch.mockClear();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ const createProxyModeFetch = () =>
+ createSsrfSafeFetch({ allowIPAddressList: ['127.0.0.1'] }, { fetch: proxiedFetch });
+
+ it('blocks a private target before handing it to the proxy', async () => {
+ await expectBlocked(createSsrfSafeFetch({}, { fetch: proxiedFetch })(`${origin}/ok`));
+ expect(proxiedFetch).not.toHaveBeenCalled();
+ expect(hits).toHaveLength(0);
+ });
+
+ it('re-validates redirect hops: an allowed endpoint redirecting to the metadata address is blocked', async () => {
+ await expectBlocked(createProxyModeFetch()(`${origin}/redirect-to-metadata`));
+
+ expect(hits).toEqual(['/redirect-to-metadata']);
+ expect(proxiedFetch).toHaveBeenCalledTimes(1);
+ expect(proxiedFetch.mock.calls[0][1]).toMatchObject({ redirect: 'manual' });
+ });
+
+ it('re-resolves redirect hostnames: a redirect to a name resolving to loopback is blocked', async () => {
+ vi.spyOn(dns.promises, 'lookup').mockResolvedValue([{ address: '::1', family: 6 }] as any);
+
+ await expectBlocked(createProxyModeFetch()(`${origin}/redirect-to-loopback-name`));
+ expect(hits).toEqual(['/redirect-to-loopback-name']);
+ });
+
+ it('still follows redirects between allowed targets', async () => {
+ const res = await createProxyModeFetch()(`${origin}/redirect-to-ok`);
+
+ expect(await res.json()).toEqual({ ok: true });
+ expect(hits).toEqual(['/redirect-to-ok', '/ok']);
+ });
+
+ it("preserves a Request input's abort signal across hops", async () => {
+ const request = new Request(`${origin}/redirect-post-307`, {
+ body: 'payload',
+ method: 'POST',
+ signal: AbortSignal.abort(),
+ });
+
+ await expect(createProxyModeFetch()(request)).rejects.toThrowError(/abort/i);
+ expect(hits).toHaveLength(0);
+ });
+
+ it('strips credentials when a redirect crosses origins', async () => {
+ const res = await createProxyModeFetch()(`${origin}/redirect-cross-origin`, {
+ headers: { authorization: 'Bearer secret', cookie: 'session=private' },
+ });
+
+ expect(res.status).toBe(200);
+ expect(crossRequests).toEqual([{ authorization: undefined, cookie: undefined, url: '/echo' }]);
+ });
+
+ it("keeps a Request input's method, headers and body across a same-origin redirect", async () => {
+ const request = new Request(`${origin}/redirect-post-307`, {
+ body: 'payload',
+ headers: { authorization: 'Bearer keep-me' },
+ method: 'POST',
+ });
+
+ const res = await createProxyModeFetch()(request);
+
+ expect(await res.json()).toEqual({
+ authorization: 'Bearer keep-me',
+ body: 'payload',
+ method: 'POST',
+ });
+ });
+});
+
+describe('createSsrfSafeFetch with an installed global proxy dispatcher', () => {
+ // The dev server installs EnvHttpProxyAgent via setGlobalDispatcher when
+ // HTTP(S)_PROXY is set, WITHOUT NODE_USE_ENV_PROXY. A per-request dispatcher
+ // would bypass that proxy entirely.
+ let proxyHits = 0;
+ let proxy: http.Server;
+
+ beforeAll(async () => {
+ proxy = http.createServer((_req, res) => {
+ res.writeHead(502).end();
+ });
+ // undici's proxy agents CONNECT-tunnel everything; answer the tunnel and
+ // serve the wrapped request ourselves, proving the request took the proxy.
+ proxy.on('connect', (_req, sock) => {
+ proxyHits++;
+ sock.write('HTTP/1.1 200 Connection Established\r\n\r\n');
+ sock.once('data', () => {
+ sock.end(
+ 'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 16\r\n\r\n{"proxied":true}',
+ );
+ });
+ });
+ await new Promise<void>((resolve) => proxy.listen(0, '127.0.0.1', resolve));
+ });
+
+ afterAll(async () => {
+ await new Promise<void>((resolve) => proxy.close(() => resolve()));
+ });
+
+ afterEach(() => {
+ proxyHits = 0;
+ });
+
+ it('routes through the global proxy dispatcher instead of bypassing it', async () => {
+ const { EnvHttpProxyAgent, getGlobalDispatcher, setGlobalDispatcher } = await import('undici');
+ const previous = getGlobalDispatcher();
+ const proxyUrl = `http://127.0.0.1:${(proxy.address() as AddressInfo).port}`;
+ // `noProxy` overrides any NO_PROXY inherited from the test environment
+ setGlobalDispatcher(
+ new EnvHttpProxyAgent({ httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy: '' }),
+ );
+
+ try {
+ const res = await createSsrfSafeFetch({ allowIPAddressList: ['127.0.0.1'] })(`${origin}/ok`);
+
+ expect(await res.json()).toEqual({ proxied: true });
+ expect(proxyHits).toBe(1);
+ // the request never reached the target directly
+ expect(hits).toHaveLength(0);
+ } finally {
+ setGlobalDispatcher(previous);
+ }
+ });
+});
diff --git a/packages/ssrf-safe-fetch/guardedFetch.ts b/packages/ssrf-safe-fetch/guardedFetch.ts
new file mode 100644
index 00000000000..69303fb9f85
--- /dev/null
+++ b/packages/ssrf-safe-fetch/guardedFetch.ts
@@ -0,0 +1,246 @@
+import dns from 'node:dns';
+import net from 'node:net';
+
+import { Agent, buildConnector, EnvHttpProxyAgent, getGlobalDispatcher, ProxyAgent } from 'undici';
+
+import type { SSRFOptions } from './policy';
+import { assertAddressAllowed, SSRFBlockedError } from './policy';
+
+/**
+ * A WHATWG-compatible `fetch` that refuses connections to private or reserved
+ * addresses, built on Node's undici stack instead of node-fetch.
+ *
+ * Unlike `ssrfSafeFetch` (which swaps in a node-fetch response), the response
+ * here is the undici `Response` streaming untouched, so the returned function
+ * can be handed to SDK clients (`new OpenAI({ fetch })`, `new Anthropic({ fetch
+ * })`) for streaming chat completions without changing body semantics.
+ */
+
+/** Check one resolved address against the policy. Returns the block, if any. */
+export const validateSsrfAddress = (
+ address: string,
+ policy: SSRFOptions,
+ hostname?: string,
+): SSRFBlockedError | undefined => {
+ try {
+ assertAddressAllowed(address, hostname ?? address, undefined, {
+ allowIPAddressList: policy.allowIPAddressList ?? [],
+ allowMetaIPAddress: policy.allowPrivateIPAddress ?? false,
+ allowPrivateIPAddress: policy.allowPrivateIPAddress ?? false,
+ denyIPAddressList: policy.denyIPAddressList ?? [],
+ });
+ return undefined;
+ } catch (error) {
+ return error instanceof SSRFBlockedError ? error : new SSRFBlockedError(String(error));
+ }
+};
+
+type LookupCallback = (
+ error: NodeJS.ErrnoException | null,
+ address: string | dns.LookupAddress[],
+ family?: number,
+) => void;
+
+/**
+ * A `dns.lookup` replacement that rejects the connection when any resolved
+ * address is blocked. Because the socket connects to exactly what this
+ * returned, there is no window for DNS rebinding between check and use.
+ */
+const createGuardedLookup =
+ (policy: SSRFOptions) =>
+ (hostname: string, options: dns.LookupOptions, callback: LookupCallback) => {
+ dns.lookup(hostname, options, (error, address, family) => {
+ if (error) return callback(error, address, family);
+
+ const resolved = Array.isArray(address) ? address : [{ address, family }];
+ for (const entry of resolved) {
+ const blocked = validateSsrfAddress(entry.address, policy, hostname);
+ if (blocked) return callback(blocked, address, family);
+ }
+
+ callback(null, address, family);
+ });
+ };
+
+const stripBrackets = (hostname: string) => hostname.replaceAll(/^\[|\]$/g, '');
+
+/**
+ * An undici dispatcher whose every connection — including each redirect hop —
+ * is validated against the policy after DNS resolution and before connecting.
+ */
+export const createSsrfSafeDispatcher = (policy: SSRFOptions) => {
+ const connector = buildConnector({ lookup: createGuardedLookup(policy) } as any);
+
+ return new Agent({
+ connect: (options, callback) => {
+ // IP literals never reach `lookup`, so validate them here
+ const host = stripBrackets(options.hostname);
+ if (net.isIP(host)) {
+ const blocked = validateSsrfAddress(host, policy);
+ if (blocked) return callback(blocked, null);
+ }
+
+ connector(options, callback);
+ },
+ });
+};
+
+const PROXY_ENV_KEYS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'];
+
+/** Node only routes fetch through `HTTP(S)_PROXY` when `NODE_USE_ENV_PROXY=1` */
+const isEnvProxyActive = () =>
+ process.env.NODE_USE_ENV_PROXY === '1' && PROXY_ENV_KEYS.some((key) => !!process.env[key]);
+
+/**
+ * Whether the process proxies requests through a global dispatcher installed
+ * with `setGlobalDispatcher` (the dev server installs an `EnvHttpProxyAgent`
+ * when `HTTP(S)_PROXY` is set — see `libs/better-auth/define-config.ts`). A
+ * per-request `dispatcher` would silently bypass that proxy and break
+ * connectivity for deployments that need it to reach the outside, so those
+ * requests take the application-layer path instead — same as env-proxy mode.
+ */
+const globalDispatcherIsProxy = () => {
+ const dispatcher = getGlobalDispatcher();
+ return dispatcher instanceof ProxyAgent || dispatcher instanceof EnvHttpProxyAgent;
+};
+
+/**
+ * Bun's fetch — and the `undici` shim it maps the package specifier to —
+ * ignores `init.dispatcher`, so connect-time filtering is impossible there.
+ * `dev:bun` is a supported server runtime, so fall back to resolving and
+ * vetting every target at the application layer, as with proxy transports.
+ */
+const isBunRuntime = () => !!process.versions.bun;
+
+const resolveRequestUrl = (input: RequestInfo | URL) =>
+ new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
+
+/**
+ * With an egress proxy the socket goes to the proxy, so connection-time checks
+ * would validate the proxy's address instead of the target. Fall back to an
+ * application-layer resolution check. This leaves a DNS-rebinding window;
+ * deployments with a proxy should enforce a private-network ACL on the proxy
+ * itself.
+ */
+const assertResolvedTargetAllowed = async (url: URL, policy: SSRFOptions) => {
+ const hostname = stripBrackets(url.hostname);
+ const addresses = net.isIP(hostname)
+ ? [{ address: hostname, family: undefined }]
+ : await dns.promises.lookup(hostname, { all: true });
+
+ for (const { address } of addresses) {
+ const blocked = validateSsrfAddress(address, policy, hostname);
+ if (blocked) throw new TypeError('fetch failed', { cause: blocked });
+ }
+};
+
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+const SENSITIVE_HEADERS = ['authorization', 'proxy-authorization', 'cookie', 'cookie2'];
+const MAX_REDIRECTS = 5;
+
+/**
+ * Proxy mode cannot rely on the dispatcher to vet redirect hops, so follow
+ * redirects manually and re-check every target before requesting it.
+ */
+const fetchThroughEnvProxy = async (
+ input: RequestInfo | URL,
+ init: RequestInit | undefined,
+ policy: SSRFOptions,
+ baseFetch: typeof fetch,
+) => {
+ /**
+ * Flatten a `Request` input into `init`: the loop below re-issues every hop
+ * from a string URL, which would otherwise drop the request's method,
+ * headers and body after the first redirect. Explicit `init` fields win.
+ */
+ let requestInit: RequestInit;
+ if (input instanceof Request) {
+ const headers = new Headers(input.headers);
+ if (init?.headers) new Headers(init.headers).forEach((v, k) => headers.set(k, v));
+ requestInit = {
+ ...init,
+ // `input.body` is locked to the Request; read it once so every hop can resend it
+ body: init?.body ?? (input.body ? await input.arrayBuffer() : undefined),
+ headers,
+ method: init?.method ?? input.method,
+ redirect: init?.redirect ?? input.redirect,
+ signal: init?.signal ?? input.signal,
+ };
+ } else {
+ requestInit = { ...init };
+ }
+
+ const followRedirects = (requestInit.redirect ?? 'follow') === 'follow';
+ if (followRedirects) requestInit.redirect = 'manual';
+
+ let url = resolveRequestUrl(input);
+ let method = (requestInit.method ?? 'GET').toUpperCase();
+
+ for (let hop = 0; ; hop++) {
+ await assertResolvedTargetAllowed(url, policy);
+
+ const response = await baseFetch(url.href, requestInit);
+ const location = response.headers.get('location');
+ if (!followRedirects || !REDIRECT_STATUSES.has(response.status) || !location) return response;
+
+ await response.body?.cancel();
+ if (hop >= MAX_REDIRECTS) {
+ throw new TypeError('fetch failed', { cause: new Error('Too many redirects') });
+ }
+
+ const next = new URL(location, url);
+ if (next.origin !== url.origin && requestInit.headers) {
+ // Native fetch strips credentials when a redirect crosses origins
+ const headers = new Headers(requestInit.headers);
+ for (const name of SENSITIVE_HEADERS) headers.delete(name);
+ requestInit = { ...requestInit, headers };
+ }
+
+ // Mirror fetch's redirect semantics: 303, and 301/302 after a POST, become a body-less GET
+ const switchToGet =
+ (response.status === 303 && method !== 'HEAD') ||
+ ((response.status === 301 || response.status === 302) && method === 'POST');
+ if (switchToGet) {
+ method = 'GET';
+ requestInit = { ...requestInit, body: undefined, method };
+ }
+
+ url = next;
+ }
+};
+
+export interface CreateSsrfSafeFetchOptions {
+ /** The fetch to wrap; defaults to the global fetch at call time */
+ fetch?: typeof fetch;
+}
+
+/**
+ * Build a WHATWG-compatible `fetch` that refuses to connect to private or
+ * reserved addresses. Unlike `ssrfSafeFetch`, the response body is streamed
+ * untouched, so it can be handed to SDKs (`new OpenAI({ fetch })`) for
+ * streaming chat completions.
+ *
+ * `maxContentLength` in {@link SSRFOptions} does not apply here: the undici
+ * response streams straight through.
+ */
+export const createSsrfSafeFetch = (
+ policy: SSRFOptions = {},
+ options: CreateSsrfSafeFetchOptions = {},
+): typeof fetch => {
+ const getBaseFetch = () => options.fetch ?? globalThis.fetch;
+
+ // Passthrough only when nothing can still be denied; a deny list applies
+ // even when private addresses are allowed.
+ if (policy.allowPrivateIPAddress && !policy.denyIPAddressList?.length)
+ return ((input, init) => getBaseFetch()(input, init)) as typeof fetch;
+
+ const dispatcher = createSsrfSafeDispatcher(policy);
+
+ return (async (input: RequestInfo | URL, init?: RequestInit) => {
+ if (isEnvProxyActive() || globalDispatcherIsProxy() || isBunRuntime()) {
+ return fetchThroughEnvProxy(input, init, policy, getBaseFetch());
+ }
+
+ return getBaseFetch()(input, { ...init, dispatcher } as RequestInit);
+ }) as typeof fetch;
+};
diff --git a/packages/ssrf-safe-fetch/index.browser.ts b/packages/ssrf-safe-fetch/index.browser.ts
index 8c8a93e943f..7739cc47a1e 100644
--- a/packages/ssrf-safe-fetch/index.browser.ts
+++ b/packages/ssrf-safe-fetch/index.browser.ts
@@ -13,12 +13,17 @@ export interface SSRFOptions {
allowIPAddressList?: string[];
/** Whether to allow private/local IP addresses */
allowPrivateIPAddress?: boolean;
+ /** List of IP addresses to deny (browser parity; unused) */
+ denyIPAddressList?: string[];
/** Maximum response body size in bytes (server-only; ignored in browser) */
maxContentLength?: number;
}
/** Kept for API parity with the server version; the browser fetch never throws it. */
export class SSRFBlockedError extends Error {
+ address?: string;
+ hostname?: string;
+
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SSRFBlockedError';
@@ -26,18 +31,21 @@ export class SSRFBlockedError extends Error {
}
/** Kept for API parity with the server version. */
-export const isSSRFBlockedError = (error: unknown): boolean => {
+export const findSSRFBlockedError = (error: unknown): SSRFBlockedError | undefined => {
const seen = new Set<unknown>();
let current: unknown = error;
while (current instanceof Error && !seen.has(current)) {
if (current instanceof SSRFBlockedError || current.message.startsWith('SSRF blocked'))
- return true;
+ return current as SSRFBlockedError;
seen.add(current);
current = current.cause;
}
- return false;
+ return undefined;
};
+/** Kept for API parity with the server version. */
+export const isSSRFBlockedError = (error: unknown): boolean => !!findSSRFBlockedError(error);
+
/**
* Browser-safe fetch implementation
* Uses native fetch API in browser environments
@@ -68,3 +76,32 @@ export const assertSsrfSafeUrl = async (url: string, _ssrfOptions?: SSRFOptions)
* never constructs one, so this always returns `undefined`.
*/
export const ssrfSafeAgent = (_url: string, _ssrfOptions?: SSRFOptions) => undefined;
+
+export interface CreateSsrfSafeFetchOptions {
+ fetch?: typeof fetch;
+}
+
+/**
+ * Browser parity stub. Browser requests are not server-side egress, so the
+ * returned fetch validates nothing and delegates to the base fetch.
+ */
+export const createSsrfSafeFetch = (
+ _policy?: SSRFOptions,
+ options: CreateSsrfSafeFetchOptions = {},
+): typeof fetch => ((input, init) => (options.fetch ?? fetch)(input, init)) as typeof fetch;
+
+/**
+ * Browser parity stub. Dispatchers are an undici (Node.js) transport concept;
+ * the browser never constructs one, so this always returns `undefined`.
+ */
+export const createSsrfSafeDispatcher = (_policy?: SSRFOptions) => undefined;
+
+/**
+ * Browser parity stub. In the browser the origin enforces connectivity, so no
+ * address is ever blocked.
+ */
+export const validateSsrfAddress = (
+ _address: string,
+ _policy: SSRFOptions,
+ _hostname?: string,
+): SSRFBlockedError | undefined => undefined;
diff --git a/packages/ssrf-safe-fetch/index.ts b/packages/ssrf-safe-fetch/index.ts
index 2060becf704..a61204e02d4 100644
--- a/packages/ssrf-safe-fetch/index.ts
+++ b/packages/ssrf-safe-fetch/index.ts
@@ -1,71 +1,37 @@
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';
-/**
- * Options for per-call SSRF configuration overrides
- */
-export interface SSRFOptions {
- /** List of IP addresses to allow */
- allowIPAddressList?: string[];
- /** Whether to allow private/local IP addresses */
- allowPrivateIPAddress?: boolean;
- /**
- * Maximum response body size in bytes. When set, the body stream ends as soon as
- * the cap is reached and the upstream connection is closed. Readers get 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)
- * so a large or malicious response cannot be buffered without bound by
- * callers that read the whole body.
- */
- maxContentLength?: number;
-}
+import {
+ assertAddressAllowed,
+ blockedError,
+ resolveAgentOptions,
+ SSRF_BLOCKED_PREFIX,
+ SSRF_DOCS_URL,
+ SSRFBlockedError,
+ type SSRFOptions,
+} from './policy';
+
+export type { CreateSsrfSafeFetchOptions } from './guardedFetch';
+export { createSsrfSafeDispatcher, createSsrfSafeFetch, validateSsrfAddress } from './guardedFetch';
+export type { SSRFOptions } from './policy';
+export {
+ findSSRFBlockedError,
+ isSSRFBlockedError,
+ matchIPAddressList,
+ resolveAgentOptions,
+ SSRF_BLOCKED_PREFIX,
+ SSRF_DOCS_URL,
+ SSRFBlockedError,
+} from './policy';
/** Statuses whose Response must have a null body (Fetch standard "null body status"). */
const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
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
- * keeps its `SSRF blocked:` prefix so callers matching on it keep working.
- */
-export class SSRFBlockedError extends Error {
- constructor(message: string, options?: ErrorOptions) {
- super(message, options);
- this.name = 'SSRFBlockedError';
- }
-}
-
-/**
- * Whether `error`, or any error in its `cause` chain, is an SSRF block. Callers that wrap
- * fetch errors (an SDK transport, a retry helper) keep the original as `cause`, so the
- * chain is walked instead of checking only the outermost error.
- */
-export const isSSRFBlockedError = (error: unknown): boolean => {
- const seen = new Set<unknown>();
- let current: unknown = error;
- while (current instanceof Error && !seen.has(current)) {
- if (current instanceof SSRFBlockedError || current.message.startsWith(SSRF_BLOCKED_PREFIX))
- return true;
- seen.add(current);
- current = current.cause;
- }
- return false;
-};
-
/** A URL inside an error message (node-fetch puts the full request URL in its errors). */
const URL_IN_TEXT = /\b[a-z][\d+.a-z-]*:\/\/[^\s"'<>]+/gi;
@@ -184,26 +150,6 @@ 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,
@@ -245,71 +191,6 @@ export const ssrfSafeFetch = async (
}
};
-/** 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
diff --git a/packages/ssrf-safe-fetch/package.json b/packages/ssrf-safe-fetch/package.json
index c79f9dcdca0..b78cc86429a 100644
--- a/packages/ssrf-safe-fetch/package.json
+++ b/packages/ssrf-safe-fetch/package.json
@@ -18,7 +18,8 @@
"dependencies": {
"ipaddr.js": "^2.5.0",
"node-fetch": "^3.3.2",
- "request-filtering-agent": "^3.2.1"
+ "request-filtering-agent": "^3.2.1",
+ "undici": "^7.29.0"
},
"devDependencies": {
"vitest": "5.0.0"
diff --git a/packages/ssrf-safe-fetch/policy.ts b/packages/ssrf-safe-fetch/policy.ts
new file mode 100644
index 00000000000..dca4328a99a
--- /dev/null
+++ b/packages/ssrf-safe-fetch/policy.ts
@@ -0,0 +1,220 @@
+import net from 'node:net';
+
+import ipaddr from 'ipaddr.js';
+import type { RequestFilteringAgentOptions } from 'request-filtering-agent';
+
+/**
+ * Options for per-call SSRF configuration overrides
+ */
+export interface SSRFOptions {
+ /** List of IP addresses to allow */
+ allowIPAddressList?: string[];
+ /** Whether to allow private/local IP addresses */
+ allowPrivateIPAddress?: boolean;
+ /** List of IP addresses to deny, checked even when private addresses are allowed */
+ denyIPAddressList?: string[];
+ /**
+ * Maximum response body size in bytes. When set, the body stream ends as soon as
+ * the cap is reached and the upstream connection is closed. Readers get 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)
+ * so a large or malicious response cannot be buffered without bound by
+ * callers that read the whole body.
+ */
+ maxContentLength?: number;
+}
+
+export const SSRF_BLOCKED_PREFIX = 'SSRF blocked';
+
+export 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
+ * keeps its `SSRF blocked:` prefix so callers matching on it keep working.
+ */
+export class SSRFBlockedError extends Error {
+ /** The resolved address that tripped the policy, when known. */
+ address?: string;
+ /** The hostname that resolved to `address`, when known. */
+ hostname?: string;
+
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = 'SSRFBlockedError';
+ }
+}
+
+/**
+ * Return the first `SSRFBlockedError` in `error`'s `cause` chain, if any. SDKs and
+ * transports wrap fetch errors (undici raises `TypeError: fetch failed` with the
+ * connect error as `cause`), so the chain is walked instead of checking only the
+ * outermost error.
+ */
+export const findSSRFBlockedError = (error: unknown): SSRFBlockedError | undefined => {
+ const seen = new Set<unknown>();
+ let current: unknown = error;
+ while (current instanceof Error && !seen.has(current)) {
+ if (current instanceof SSRFBlockedError || current.message.startsWith(SSRF_BLOCKED_PREFIX))
+ return current as SSRFBlockedError;
+ seen.add(current);
+ current = current.cause;
+ }
+ return undefined;
+};
+
+/**
+ * Whether `error`, or any error in its `cause` chain, is an SSRF block. Callers that wrap
+ * fetch errors (an SDK transport, a retry helper) keep the original as `cause`, so the
+ * chain is walked instead of checking only the outermost error.
+ */
+export const isSSRFBlockedError = (error: unknown): boolean => !!findSSRFBlockedError(error);
+
+/**
+ * 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.
+ */
+export const resolveAgentOptions = (ssrfOptions?: SSRFOptions): RequestFilteringAgentOptions => {
+ const allowPrivate = ssrfOptions?.allowPrivateIPAddress ?? envAllowPrivate();
+ const options: RequestFilteringAgentOptions = {
+ allowIPAddressList: ssrfOptions?.allowIPAddressList ?? envAllowIPAddressList(),
+ allowMetaIPAddress: allowPrivate,
+ allowPrivateIPAddress: allowPrivate,
+ denyIPAddressList: ssrfOptions?.denyIPAddressList ?? [],
+ // The agent's built-in list matching never unwraps an IPv4-mapped IPv6
+ // target, so `::ffff:169.254.169.254` would sidestep the deny list. The
+ // filter receives the normalized (unwrapped) address and re-runs the same
+ // policy on it.
+ filter: (address, { host, family }) => {
+ try {
+ assertAddressAllowed(address, host ?? address, family, options);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ };
+ return options;
+};
+
+export const envAllowPrivate = () => process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS === '1';
+
+export const envAllowIPAddressList = () =>
+ process.env.SSRF_ALLOW_IP_ADDRESS_LIST?.split(',').filter(Boolean) ?? [];
+
+// Mirrors request-filtering-agent's toParsableAddress: the OS reads "::8.8.8.8"
+// as the IPv4-compatible address ::808:808 while ipaddr.js reads it as the
+// IPv4-mapped ::ffff:808:808 — rewrite the notation so the checked address is
+// the address actually connected to.
+const IPV4_COMPATIBLE_DOTTED_NOTATION = /^::(?=\d+\.\d+\.\d+\.\d+(?:%.*)?$)/;
+const toParsableAddress = (address: string) =>
+ address.replace(IPV4_COMPATIBLE_DOTTED_NOTATION, '0:0:0:0:0:0:');
+
+// Mirrors request-filtering-agent's getRange: IANA allocates only 2000::/3 as
+// IPv6 global unicast, so an IPv6 address ipaddr.js reports as "unicast"
+// outside it (e.g. deprecated ranges, NAT64 64:ff9b::/96) is not public.
+const IPV6_GLOBAL_UNICAST_RANGE = ipaddr.parseCIDR('2000::/3');
+const getRange = (parsed: ipaddr.IPv4 | ipaddr.IPv6) => {
+ const range = parsed.range();
+ if (
+ range === 'unicast' &&
+ parsed.kind() === 'ipv6' &&
+ // eslint-disable-next-line unicorn/prefer-regexp-test -- ipaddr.js API, not String.prototype.match
+ !parsed.match(IPV6_GLOBAL_UNICAST_RANGE)
+ ) {
+ return 'reserved';
+ }
+ return range;
+};
+
+/** `parsed` when it is an IPv4-mapped IPv6 address, unwrapped to its IPv4 form. */
+const unwrappedIPv4 = (parsed: ipaddr.IPv4 | ipaddr.IPv6) =>
+ parsed instanceof ipaddr.IPv6 && parsed.isIPv4MappedAddress()
+ ? parsed.toIPv4Address()
+ : undefined;
+
+/** Whether `address` (raw or parsed) matches an IP or CIDR entry of `ipAddressList`. */
+export const matchIPAddressList = (
+ address: string,
+ parsed: ipaddr.IPv4 | ipaddr.IPv6,
+ ipAddressList: string[],
+) => {
+ for (const ipOrCIDR of ipAddressList) {
+ if (net.isIP(ipOrCIDR) !== 0) {
+ // An IPv4-mapped IPv6 literal is the same destination as its IPv4 form;
+ // match both so `::ffff:169.254.169.254` cannot sidestep the list.
+ if (ipOrCIDR === address || unwrappedIPv4(parsed)?.toString() === ipOrCIDR) return true;
+ continue;
+ }
+ try {
+ const cidr = ipaddr.parseCIDR(ipOrCIDR);
+ // `parsed.match` throws on a family mismatch, so pick the comparison
+ // target first: an IPv4-mapped IPv6 target matches IPv4 entries in its
+ // unwrapped form.
+ const target = cidr[0].kind() === parsed.kind() ? parsed : unwrappedIPv4(parsed);
+ if (target?.match(cidr)) return true;
+ } catch {
+ // Invalid CIDR entries are ignored, matching request-filtering-agent behavior.
+ }
+ }
+ return false;
+};
+
+export const blockedError = (
+ detail: string,
+ cause?: unknown,
+ fields?: Pick<SSRFBlockedError, 'address' | 'hostname'>,
+) => {
+ const error = new SSRFBlockedError(`${SSRF_BLOCKED_PREFIX}: ${detail}. See: ${SSRF_DOCS_URL}`, {
+ cause,
+ });
+ if (fields?.address) error.address = fields.address;
+ if (fields?.hostname) error.hostname = fields.hostname;
+ return error;
+};
+
+/**
+ * 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.
+ */
+export const assertAddressAllowed = (
+ address: string,
+ host: string,
+ family: number | undefined,
+ options: RequestFilteringAgentOptions,
+): void => {
+ if (net.isIP(address) === 0) return;
+
+ const parsed = ipaddr.parse(toParsableAddress(address));
+
+ if (
+ options.allowIPAddressList?.length &&
+ matchIPAddressList(address, parsed, options.allowIPAddressList)
+ ) {
+ return;
+ }
+
+ const range = getRange(parsed);
+ const where = `DNS lookup ${address}(family:${family}, host:${host}) is not allowed`;
+ const fields = { address, hostname: host };
+
+ if (!options.allowMetaIPAddress && range === 'unspecified') {
+ throw blockedError(`${where}. Because, It is meta IP address.`, undefined, fields);
+ }
+
+ if (!options.allowPrivateIPAddress && range !== 'unicast') {
+ throw blockedError(`${where}. Because, It is private IP address.`, undefined, fields);
+ }
+
+ if (
+ options.denyIPAddressList?.length &&
+ matchIPAddressList(address, parsed, options.denyIPAddressList)
+ ) {
+ throw blockedError(`${where}. Because It is defined in denyIPAddressList.`, undefined, fields);
+ }
+};
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 6e9534a43ad..de8a6b257db 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -305,6 +305,12 @@ export const AgentRuntimeErrorType = {
OperationInactivityTimeout: 'OperationInactivityTimeout',
InvalidOllamaArgs: 'InvalidOllamaArgs',
+ /**
+ * The provider base URL resolves to a private / reserved network address that
+ * the server is not allowed to reach (SSRF protection). The endpoint is only
+ * reachable from the user's own device.
+ */
+ ProviderBaseURLBlocked: 'ProviderBaseURLBlocked',
/**
* The model can only be reached from the user's own device, and no open
* LobeHub client picked up the request (no client declared it can run this