Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/api/src/trusted-client-ip.ts
T
2026-07-08 16:15:37 +02:00

24 lines
1.1 KiB
TypeScript

// Trusted, proxy-set client-IP headers in order of preference. These are set
// by the edge/proxy and OVERWRITE any client-supplied value, so — unlike the
// leftmost X-Forwarded-For entry or X-Client-IP — they cannot be spoofed by the
// client. Every public request in this estate passes through Cloudflare
// (proxied), which sets CF-Connecting-IP; X-Real-IP is the immediate reverse
// proxy (Traefik) hop as a fallback for non-Cloudflare paths.
const TRUSTED_IP_HEADERS = ["cf-connecting-ip", "true-client-ip", "x-real-ip"] as const;
/**
* Read the client IP from a trusted header only. Use for security-sensitive
* decisions (rate limiting, abuse throttles) where an attacker must not be able
* to rotate their apparent IP by forging X-Forwarded-For. Returns the empty
* string when no trusted header is present so callers can key a shared bucket.
*/
export function getTrustedClientIp(request: Request): string {
for (const headerName of TRUSTED_IP_HEADERS) {
const value = request.headers.get(headerName)?.trim();
if (value) {
return value;
}
}
return "";
}