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.
This commit is contained in:
Buns Enchantress
2026-02-03 05:19:40 -06:00
parent 5f13a98a84
commit 9fc94cde2a
2 changed files with 12 additions and 9 deletions

View File

@@ -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.

View File

@@ -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";
}