Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions server/src/routes/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Router } from 'express';
import { getDb } from '../db/connection.js';
import { encrypt, decrypt } from '../services/crypto.js';
import { config } from '../config.js';
import { proxyRequest, ProxyConfig, validateUrl } from '../services/proxyService.js';
import { proxyRequest, ProxyConfig, validateUrl, isPrivateOrLoopback } from '../services/proxyService.js';
import { logger } from '../services/logger.js';

function getProxyConfig(): ProxyConfig | null {
Expand Down Expand Up @@ -218,7 +218,7 @@ router.post('/api/proxy/ai', async (req, res) => {
// Warn if API key is transmitted over non-HTTPS connection
try {
const parsed = new URL(baseUrl);
if (parsed.protocol !== 'https:') {
if (parsed.protocol !== 'https:' && !isPrivateOrLoopback(parsed.hostname)) {
logger.warn('proxy.ai', `AI API key transmitted over ${parsed.protocol} (not HTTPS). Consider using HTTPS for security.`);
}
} catch { /* invalid URL, will be caught by validateUrl later */ }
Expand All @@ -236,7 +236,7 @@ router.post('/api/proxy/ai', async (req, res) => {
reasoningEffort = normalizeReasoningEffort(aiConfig.reasoning_effort);
try {
const parsed = new URL(baseUrl);
if (parsed.protocol !== 'https:') {
if (parsed.protocol !== 'https:' && !isPrivateOrLoopback(parsed.hostname)) {
logger.warn('proxy.ai', `AI API key transmitted over ${parsed.protocol} (not HTTPS). Consider using HTTPS for security.`);
}
} catch { /* invalid URL, will be caught by validateUrl later */ }
Expand Down Expand Up @@ -287,6 +287,10 @@ router.post('/api/proxy/ai', async (req, res) => {

const timeout = apiType === 'openai-responses' || !!reasoningEffort ? 600000 : 60000;

// 宽松档(放行回环/私有网段)只用于「用户已保存的 AI 配置」(configId)。
// 内联 config 路径(任意客户端均可携带目标地址)保持严格档,避免 SSRF 放宽被滥用。
const allowPrivate = Boolean(configId);

const proxyConfig = getProxyConfig();
const result = await proxyRequest({
url: targetUrl,
Expand All @@ -295,6 +299,7 @@ router.post('/api/proxy/ai', async (req, res) => {
body: effectiveRequestBody,
timeout,
proxyConfig,
allowPrivate,
});

res.status(result.status).json(result.data);
Expand Down Expand Up @@ -357,6 +362,8 @@ router.post('/api/proxy/webdav', async (req, res) => {
body: requestBody,
timeout: 60000,
proxyConfig,
// 用户自有配置来源的 WebDAV 地址:放行回环/私有网段(局域网 NAS 等)
allowPrivate: true,
});

res.status(result.status).json(result.data);
Expand Down Expand Up @@ -806,9 +813,9 @@ router.post('/api/download/rpc', async (req, res) => {
return;
}

// SSRF protection: validate the download URL
// SSRF protection: validate the download URL (allow user-owned private/loopback targets)
try {
validateUrl(url);
validateUrl(url, { allowPrivate: true });
} catch (e) {
res.status(400).json({ success: false, error: e instanceof Error ? e.message : 'Invalid URL' });
return;
Expand Down
83 changes: 69 additions & 14 deletions server/src/services/proxyService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export interface ProxyRequestOptions {
timeout?: number;
proxyConfig?: ProxyConfig | null;
preserveRawResponse?: boolean;
/** 放行回环/私有网段(仅用于用户自有配置来源的 URL)。 */
allowPrivate?: boolean;
}

export interface ProxyResponse {
Expand All @@ -30,40 +32,93 @@ export interface ProxyResponse {
const BLOCKED_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0', '169.254.169.254']);
const PRIVATE_IP_PATTERNS = [/^10\./, /^172\.(1[6-9]|2\d|3[01])\./, /^192\.168\./];

export function validateUrl(rawUrl: string): void {
export interface ValidateUrlOptions {
/** 宽松模式:放行回环地址与私有网段。仅用于「用户主动保存的自行配置」所来源的 URL
* (如 AI / WebDAV / 下载目标),不应作用于任意或半可信的输入。 */
allowPrivate?: boolean;
}

/** 归一化 hostname:去掉 IPv6 方括号、去掉结尾点号(防 `localhost.`/`127.0.0.1.` 绕过),
* 并把 IPv4 映射型 IPv6(如 [::ffff:169.254.169.254])还原为对应的 IPv4 字符串,
* 使 SSRF 过滤看到真实的目标地址。 */
function normalizeHostname(hostname: string): string {
// Strip trailing dot first to prevent SSRF bypasses (e.g. "localhost." or "127.0.0.1.")
const h = hostname.replace(/\.$/, '').replace(/^\[(.+)\]$/, '$1').toLowerCase();
// Handle hybrid IPv4-mapped IPv6 written with dotted decimals (::ffff:169.254.169.254)
if (h.startsWith('::ffff:') && h.includes('.')) {
return h.slice(7);
}
// Handle IPv4-mapped IPv6 written in hex form (::ffff:a9fe:a9fe)
const mapped = h.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
if (mapped) {
const octets = [mapped[1], mapped[2]].flatMap((hex) => {
const v = parseInt(hex, 16);
return [(v >>> 8) & 0xff, v & 0xff];
});
return octets.join('.');
}
return h;
}
Comment on lines +44 to +61

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

To prevent SSRF bypasses, we should normalize hostnames by stripping trailing dots (e.g., localhost. or 127.0.0.1.) and correctly handling hybrid IPv4-mapped IPv6 addresses (e.g., ::ffff:169.254.169.254). Without this, these patterns can bypass the blocked hosts and private IP checks.

function normalizeHostname(hostname: string): string {
  // Strip trailing dot if present to prevent SSRF bypasses (e.g., "localhost.")
  const h = hostname.replace(/\.$/, '').replace(/^\[(.+)\]$/, '$1').toLowerCase();
  
  // Handle hybrid IPv4-mapped IPv6 (e.g., ::ffff:169.254.169.254)
  if (h.startsWith('::ffff:') && h.includes('.')) {
    return h.slice(7);
  }

  const mapped = h.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
  if (mapped) {
    const octets = [mapped[1], mapped[2]].flatMap((hex) => {
      const v = parseInt(hex, 16);
      return [(v >>> 8) & 0xff, v & 0xff];
    });
    return octets.join('.');
  }
  return h;
}


/** IPv6 私有/本地网段前缀:唯一本地地址 fc00::/7、链路本地 fe80::/10、组播 ff00::/8 */
function isPrivateOrLocalIpv6(h: string): boolean {
if (!h.includes(':')) return false;
return (
h.startsWith('fc') || h.startsWith('fd') ||
h.startsWith('fe8') || h.startsWith('fe9') ||
h.startsWith('fea') || h.startsWith('feb') ||
h.startsWith('ff')
);
}

/** 判断 hostname 是否为回环地址或私有网段(含 IPv6 私有/本地网段)。 */
export function isPrivateOrLoopback(hostname: string): boolean {
const h = normalizeHostname(hostname);
if (BLOCKED_HOSTS.has(h)) return true;
if (PRIVATE_IP_PATTERNS.some(p => p.test(h))) return true;
if (isPrivateOrLocalIpv6(h)) return true;
return false;
}
Comment on lines +75 to +81

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

We should also block IPv6 private and local ranges (Unique Local Addresses fc00::/7, Link-Local fe80::/10, and Multicast ff00::/8) to prevent SSRF via IPv6.

export function isPrivateOrLoopback(hostname: string): boolean {
  const h = normalizeHostname(hostname);
  if (BLOCKED_HOSTS.has(h)) return true;
  if (PRIVATE_IP_PATTERNS.some(p => p.test(h))) return true;
  
  // Block IPv6 private/local ranges (ULA, Link-Local, Multicast)
  if (
    h.startsWith('fc') ||
    h.startsWith('fd') ||
    h.startsWith('fe8') ||
    h.startsWith('fe9') ||
    h.startsWith('fea') ||
    h.startsWith('feb') ||
    h.startsWith('ff')
  ) {
    if (h.includes(':')) return true;
  }
  return false;
}


export function validateUrl(rawUrl: string, opts: ValidateUrlOptions = {}): void {
const parsed = new URL(rawUrl);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
throw new Error(`Blocked proxy request: unsupported protocol '${parsed.protocol}'`);
}
const hostname = parsed.hostname.toLowerCase();

// 检查是否是IP地址
const isIP = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
if (isIP) {
// IP地址直接检查是否在阻止列表中
if (BLOCKED_HOSTS.has(hostname)) {
throw new Error(`Blocked proxy request: IP '${hostname}' is not allowed`);

// 始终拦截 URL 内嵌的用户名/密码(防止凭证泄露到日志)
if (parsed.username || parsed.password) {
throw new Error(`Blocked proxy request: URL containing credentials is not allowed`);
}

// 归一化后可同时覆盖明文 169.254.169.254 与 [::ffff:a9fe:a9fe] 等 IPv4 映射型写法。
const hostname = normalizeHostname(parsed.hostname);

if (opts.allowPrivate) {
// 宽松模式:仍死守云元数据 IMDS 地址——最高危的 SSRF 目标(云厂商密钥)。
if (hostname === '169.254.169.254') {
throw new Error(`Blocked proxy request: IMDS address '169.254.169.254' is not allowed`);
}
return;
}

// 严格模式(默认):拦截回环地址与私有网段(含 IPv6 私有/本地网段)。
if (BLOCKED_HOSTS.has(hostname)) {
throw new Error(`Blocked proxy request: hostname '${hostname}' is not allowed`);
}
if (PRIVATE_IP_PATTERNS.some(p => p.test(hostname))) {
throw new Error(`Blocked proxy request: private IP '${hostname}' is not allowed`);
}

// 阻止URL中的用户名和密码(防止凭证泄露)
if (parsed.username || parsed.password) {
throw new Error(`Blocked proxy request: URL containing credentials is not allowed`);
if (isPrivateOrLocalIpv6(hostname)) {
throw new Error(`Blocked proxy request: private IPv6 address '${hostname}' is not allowed`);
}
}

export async function proxyRequest(options: ProxyRequestOptions): Promise<ProxyResponse> {
const { url, method, headers = {}, body, timeout = 30000, proxyConfig, preserveRawResponse = false } = options;

try {
validateUrl(url);
validateUrl(url, { allowPrivate: options.allowPrivate });
logger.info('proxy.request', `${method} ${redactUrl(url)}`);

const axiosConfig: AxiosRequestConfig = {
Expand Down
Loading
Loading