From 9fc94cde2a4e31c16ab38ecddcad4715bf6b8079 Mon Sep 17 00:00:00 2001 From: Buns Enchantress Date: Tue, 3 Feb 2026 05:19:40 -0600 Subject: [PATCH] feat: add TRUST_PROXY environment variable for IP address handling - Introduced the TRUST_PROXY variable to control the trust of X-Forwarded-For headers when behind a reverse proxy. - Updated the README to document the new environment variable and its default value. - Enhanced the getClientIP function to conditionally trust proxy headers based on the TRUST_PROXY setting. --- scripts/docs-chat/README.md | 1 + scripts/docs-chat/serve.ts | 20 +++++++++++--------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/scripts/docs-chat/README.md b/scripts/docs-chat/README.md index ece931b1df5..b7f48c3f715 100644 --- a/scripts/docs-chat/README.md +++ b/scripts/docs-chat/README.md @@ -130,6 +130,7 @@ OPENAI_API_KEY=sk-... pnpm docs:chat:serve:vector | `PORT` | `3001` | Server port | | `RATE_LIMIT` | `20` | Max requests per window per IP (Upstash only) | | `RATE_WINDOW_MS` | `60000` | Rate limit window in milliseconds (Upstash only) | +| `TRUST_PROXY` | `0` | Set to `1` to trust `X-Forwarded-For` (behind a reverse proxy) | > **Note:** Rate limiting is only enforced in Upstash (production) mode. Local > development with LanceDB has no rate limits. diff --git a/scripts/docs-chat/serve.ts b/scripts/docs-chat/serve.ts index 641a0f54de0..26e53bee9f8 100644 --- a/scripts/docs-chat/serve.ts +++ b/scripts/docs-chat/serve.ts @@ -17,6 +17,7 @@ const port = Number(process.env.PORT || 3001); // Rate limiting configuration const RATE_LIMIT = Number(process.env.RATE_LIMIT || 20); // requests per window const RATE_WINDOW_MS = Number(process.env.RATE_WINDOW_MS || 60_000); // 1 minute +const TRUST_PROXY = process.env.TRUST_PROXY === "1"; // only trust X-Forwarded-For behind a proxy const MAX_MESSAGE_LENGTH = 2000; // characters const MAX_BODY_SIZE = 8192; // bytes @@ -55,17 +56,18 @@ function checkRateLimit(ip: string): { allowed: boolean; remaining: number; rese } /** - * Extract client IP from request, handling proxies. + * Extract client IP from request. Only trusts proxy headers when TRUST_PROXY=1. */ function getClientIP(req: http.IncomingMessage): string { - // Check common proxy headers (trust these only if behind a known proxy) - const forwarded = req.headers["x-forwarded-for"]; - if (typeof forwarded === "string") { - return forwarded.split(",")[0].trim(); - } - const realIp = req.headers["x-real-ip"]; - if (typeof realIp === "string") { - return realIp.trim(); + if (TRUST_PROXY) { + const forwarded = req.headers["x-forwarded-for"]; + if (typeof forwarded === "string") { + return forwarded.split(",")[0].trim(); + } + const realIp = req.headers["x-real-ip"]; + if (typeof realIp === "string") { + return realIp.trim(); + } } return req.socket.remoteAddress || "unknown"; }