mirror of
https://github.com/shuaiplus/nodewarden.git
synced 2026-06-20 21:00:41 +00:00
feat: improve client IP identification logic for rate limiting
This commit is contained in:
+13
-25
@@ -300,34 +300,22 @@ function normalizeClientIpForRateLimit(rawIp: string): string | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getClientIdentifier(request: Request): string | null {
|
export function getClientIdentifier(request: Request): string | null {
|
||||||
const cfIp = request.headers.get('CF-Connecting-IP');
|
// Strict fallback order:
|
||||||
if (cfIp) {
|
// 1) CF-Connecting-IP
|
||||||
return normalizeClientIpForRateLimit(cfIp);
|
// 2) X-Real-IP
|
||||||
}
|
// 3) first item of X-Forwarded-For
|
||||||
|
// If none are present/valid, treat client IP as unavailable.
|
||||||
|
const candidates: Array<string | null> = [
|
||||||
|
request.headers.get('CF-Connecting-IP'),
|
||||||
|
request.headers.get('X-Real-IP'),
|
||||||
|
request.headers.get('X-Forwarded-For')?.split(',')[0]?.trim() || null,
|
||||||
|
];
|
||||||
|
|
||||||
// Local development fallback:
|
for (const raw of candidates) {
|
||||||
// wrangler dev may not provide CF-Connecting-IP. Allow localhost requests
|
if (!raw) continue;
|
||||||
// to resolve an identifier from X-Forwarded-For or loopback.
|
const normalized = normalizeClientIpForRateLimit(raw);
|
||||||
try {
|
|
||||||
const hostname = new URL(request.url).hostname.toLowerCase();
|
|
||||||
const isLocalHost =
|
|
||||||
hostname === 'localhost' ||
|
|
||||||
hostname === '127.0.0.1' ||
|
|
||||||
hostname === '::1' ||
|
|
||||||
hostname === '[::1]';
|
|
||||||
if (!isLocalHost) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const forwardedFor = request.headers.get('X-Forwarded-For');
|
|
||||||
if (forwardedFor) {
|
|
||||||
const first = forwardedFor.split(',')[0].trim();
|
|
||||||
const normalized = normalizeClientIpForRateLimit(first);
|
|
||||||
if (normalized) return normalized;
|
if (normalized) return normalized;
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'ip4:127.0.0.1';
|
|
||||||
} catch {
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user