Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

feat(proxy): honor TRUST_PROXY for reverse-proxied client IPs (#1041)

suantea (asuan_suan)46ea0de09733
diff --git a/.env.example b/.env.example
index 7f1e63b7..b34a16d7 100644
--- a/.env.example
+++ b/.env.example
@@ -297,6 +297,17 @@ REQUEST_ANALYTICS_MAX_ROWS=100000
# false: force it off even behind HTTPS (e.g. mixed-content reverse proxies).
# CSP_UPGRADE_INSECURE_REQUESTS=false
+# Trust forwarded headers (X-Forwarded-For / X-Forwarded-Proto) from a reverse
+# proxy so Analytics and IP-based rate limiting see the real client (#1024).
+# Default (unset or false): do NOT trust forwarded headers — direct callers
+# cannot spoof the client IP.
+# true: trust every proxy hop (only use on a fully trusted network).
+# A number: trust that many hops in front of the server (TRUST_PROXY=1 for a
+# single reverse proxy such as Caddy, nginx or Traefik on the same host).
+# Otherwise: a comma-separated list of proxy addresses/CIDRs to trust, e.g.
+# TRUST_PROXY=100.64.0.0/10,192.168.1.10
+# TRUST_PROXY=false
+
# Per-model routing score multipliers (#738), JSON object of model id → 0..2.
# 1.0 leaves a model unchanged, below 1 demotes it, above 1 promotes it, and 0
# means the automatic router never picks it (Manual priority still can).
diff --git a/server/src/__tests__/lib/client-context.test.ts b/server/src/__tests__/lib/client-context.test.ts
index 5d9b0acc..002059b7 100644
--- a/server/src/__tests__/lib/client-context.test.ts
+++ b/server/src/__tests__/lib/client-context.test.ts
@@ -2,9 +2,12 @@ import { afterEach, describe, expect, it } from 'vitest';
import type { NextFunction, Request, Response } from 'express';
import { clientContextMiddleware, getClientContext } from '../../lib/client-context.js';
-// Minimal fake req: the middleware only touches headers, socket, and app.
-function fakeReq(headers: Record<string, string | string[]>, remoteAddress?: string, trustProxy?: boolean): Request {
- return { headers, socket: { remoteAddress }, app: { get: () => trustProxy ?? false } } as unknown as Request;
+// Minimal fake req: the middleware only touches headers, socket, and req.ip.
+// `ip` is what Express resolves from the socket peer address (or from the
+// X-Forwarded-For chain when `trust proxy` is enabled) — the middleware reads
+// req.ip rather than re-implementing the trust chain itself (#1024).
+function fakeReq(headers: Record<string, string | string[]>, remoteAddress?: string, ip?: string): Request {
+ return { headers, socket: { remoteAddress }, ip } as unknown as Request;
}
// Run the middleware and capture the context visible to downstream code
@@ -25,15 +28,26 @@ describe('clientContextMiddleware', () => {
expect(ctx).toEqual({ ip: '192.168.0.42', userAgent: 'curl/8.6.0', agent: 'unknown' });
});
- it('prefers the first X-Forwarded-For hop when trust proxy is enabled', () => {
+ it('uses Express-resolved req.ip (trust-proxy chain) when available', () => {
+ // With TRUST_PROXY enabled, Express resolves req.ip to the first untrusted
+ // hop of the X-Forwarded-For chain; the middleware trusts that resolution.
const ctx = contextFor(fakeReq(
{ 'x-forwarded-for': '10.1.2.3, 172.16.0.1', 'user-agent': 'ua' },
'127.0.0.1',
- true,
+ '10.1.2.3',
));
expect(ctx.ip).toBe('10.1.2.3');
});
+ it('falls back to the socket peer address when req.ip is absent', () => {
+ const ctx = contextFor(fakeReq(
+ { 'x-forwarded-for': '10.1.2.3, 172.16.0.1', 'user-agent': 'ua' },
+ '127.0.0.1',
+ ));
+ // trust proxy disabled → spoofed header ignored, socket address used.
+ expect(ctx.ip).toBe('127.0.0.1');
+ });
+
it('normalizes IPv4-mapped IPv6 addresses', () => {
const ctx = contextFor(fakeReq({}, '::ffff:192.168.0.5'));
expect(ctx.ip).toBe('192.168.0.5');
diff --git a/server/src/__tests__/lib/config.test.ts b/server/src/__tests__/lib/config.test.ts
index b434dc3c..a7ee64a6 100644
--- a/server/src/__tests__/lib/config.test.ts
+++ b/server/src/__tests__/lib/config.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, afterEach } from 'vitest';
import { loadConfig } from '../../lib/config.js';
-const ENV_KEYS = ['PORT', 'HOST', 'FREEAPI_DB_PATH', 'DASHBOARD_ORIGINS', 'CLIENT_DIST', 'PROXY_RATE_LIMIT_RPM', 'NODE_ENV'];
+const ENV_KEYS = ['PORT', 'HOST', 'FREEAPI_DB_PATH', 'DASHBOARD_ORIGINS', 'CLIENT_DIST', 'PROXY_RATE_LIMIT_RPM', 'NODE_ENV', 'TRUST_PROXY'];
afterEach(() => {
ENV_KEYS.forEach(k => delete process.env[k]);
@@ -65,4 +65,32 @@ describe('loadConfig', () => {
process.env.NODE_ENV = 'production';
expect(loadConfig().nodeEnv).toBe('production');
});
+
+ it('defaults TRUST_PROXY to false (do not trust forwarded headers)', () => {
+ expect(loadConfig().trustProxy).toBe(false);
+ });
+
+ it('parses TRUST_PROXY=true as trust-all', () => {
+ process.env.TRUST_PROXY = 'true';
+ expect(loadConfig().trustProxy).toBe(true);
+ });
+
+ it('parses TRUST_PROXY=false as untrusted', () => {
+ process.env.TRUST_PROXY = 'false';
+ expect(loadConfig().trustProxy).toBe(false);
+ });
+
+ it('parses an integer TRUST_PROXY as a hop count, not trust-all', () => {
+ process.env.TRUST_PROXY = '1';
+ expect(loadConfig().trustProxy).toBe(1);
+ process.env.TRUST_PROXY = '2';
+ expect(loadConfig().trustProxy).toBe(2);
+ process.env.TRUST_PROXY = '0';
+ expect(loadConfig().trustProxy).toBe(false);
+ });
+
+ it('parses TRUST_PROXY as a comma-separated proxy list', () => {
+ process.env.TRUST_PROXY = '100.64.0.0/10, 192.168.1.10 , ';
+ expect(loadConfig().trustProxy).toEqual(['100.64.0.0/10', '192.168.1.10']);
+ });
});
diff --git a/server/src/app.ts b/server/src/app.ts
index ba8c8147..86a05e0f 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -96,6 +96,12 @@ function isTrustworthyOrigin(req: express.Request): boolean {
export function createApp(config?: Config) {
const cfg = config ?? loadConfig();
const app = express();
+ // TRUST_PROXY (#1024): opt-in trust of X-Forwarded-* from a reverse proxy.
+ // false (default) ignores forwarded headers so direct callers cannot spoof
+ // the client IP; true trusts every hop; a comma-separated list of addresses
+ // /CIDRs trusts only those proxies. Must be set before client-context and
+ // the rate-limit middleware, which both resolve the client IP.
+ app.set('trust proxy', cfg.trustProxy);
const allowedCorsOrigins = new Set([
...DEFAULT_DASHBOARD_ORIGINS,
...cfg.dashboardOrigins,
diff --git a/server/src/lib/client-context.ts b/server/src/lib/client-context.ts
index ebfed8d9..e5c3fc6e 100644
--- a/server/src/lib/client-context.ts
+++ b/server/src/lib/client-context.ts
@@ -13,19 +13,14 @@ export interface ClientContext {
// proxy, responses, anthropic, fusion, embeddings and media paths all log).
const storage = new AsyncLocalStorage<ClientContext>();
-// Resolve the client IP from the socket peer address. The X-Forwarded-For
-// header is only trusted when Express's "trust proxy" setting is enabled
-// (opt-in via app.set('trust proxy', ...) or the TRUST_PROXY env var in
-// run.ts). Without that, a spoofed header from a LAN client is ignored.
+// Resolve the client IP. With Express's `trust proxy` disabled (the default),
+// this is the socket peer address and a spoofed X-Forwarded-For from a LAN
+// client is ignored. When TRUST_PROXY (#1024) opts into trusting a reverse
+// proxy, `req.ip` walks the configured trusted-proxy chain and returns the
+// first untrusted address — instead of trusting the leftmost caller-supplied
+// X-Forwarded-For value, which would let any direct caller spoof it.
function resolveClientIp(req: Request): string | null {
- const trustProxy = req.app?.get('trust proxy') ?? false;
- let raw: string | null;
- if (trustProxy) {
- const xff = req.headers['x-forwarded-for'];
- raw = (Array.isArray(xff) ? xff[0] : xff)?.split(',')[0]?.trim() || req.socket.remoteAddress || null;
- } else {
- raw = req.socket.remoteAddress || null;
- }
+ const raw = req.ip ?? req.socket.remoteAddress ?? null;
// Normalize IPv4-mapped IPv6 ("::ffff:192.168.0.5" -> "192.168.0.5").
return raw?.replace(/^::ffff:/i, '') ?? null;
}
diff --git a/server/src/lib/config.ts b/server/src/lib/config.ts
index d595b7df..ed5e9937 100644
--- a/server/src/lib/config.ts
+++ b/server/src/lib/config.ts
@@ -47,6 +47,16 @@ export interface Config {
requestBodyLimitBytes: number;
nodeEnv: string;
serveStaticAssets: boolean;
+ /**
+ * Express `trust proxy` setting, parsed from TRUST_PROXY (#1024).
+ * - false: do not trust forwarded headers (default; direct callers
+ * cannot spoof X-Forwarded-For).
+ * - true: trust all proxies (with a security warning).
+ * - number: trust that many hops counted from the socket peer
+ * (Express's `trust proxy: 1` idiom for one proxy in front).
+ * - string[]: trust only these proxy addresses/CIDRs.
+ */
+ trustProxy: boolean | number | string[];
/**
* Tri-state override for the CSP `upgrade-insecure-requests` directive (#682).
* - undefined: auto — emit the directive only when the request arrived over
@@ -74,6 +84,7 @@ export function loadConfig(): Config {
requestBodyLimitBytes: parseRequestBodyLimitBytes(),
nodeEnv: process.env.NODE_ENV ?? 'development',
serveStaticAssets: true,
+ trustProxy: parseTrustProxy(),
// CSP_UPGRADE_INSECURE_REQUESTS: true|false forces the directive on/off;
// unset (the default) leaves it on auto — emit only when the request is
// already TLS or forwarded as https, so HTTP LAN installs still render.
@@ -81,6 +92,25 @@ export function loadConfig(): Config {
};
}
+// Parse TRUST_PROXY (#1024). unset/empty/false → false (do not trust forwarded
+// headers); true → trust all proxies; a non-negative integer → that many hops
+// from the socket peer (so `TRUST_PROXY=1` means "one proxy in front", the
+// Express idiom, not "trust everything"); otherwise a comma-separated list of
+// proxy addresses/CIDRs → trust only those hops.
+function parseTrustProxy(): boolean | number | string[] {
+ const raw = process.env.TRUST_PROXY;
+ if (raw === undefined || raw.trim() === '') return false;
+ const lower = raw.trim().toLowerCase();
+ if (lower === 'true' || lower === 'yes') return true;
+ if (lower === 'false' || lower === 'no') return false;
+ if (/^\d+$/.test(lower)) {
+ const hops = Number(lower);
+ return hops > 0 ? hops : false;
+ }
+ const addrs = raw.split(',').map(s => s.trim()).filter(Boolean);
+ return addrs.length > 0 ? addrs : false;
+}
+
function parseCspUpgradeInsecureRequests(): boolean | undefined {
const raw = process.env.CSP_UPGRADE_INSECURE_REQUESTS;
if (raw === undefined || raw.trim() === '') return undefined;