Skip to content

Commit 738628c

Browse files
committed
refactor: improve IP handling in backend and frontend
- Fixed logging to correctly display split IP in backend middleware. - Added `isPrivateIP` utility in frontend for private IP detection. - Updated frontend logic to filter out private IPs when determining public IPs.
1 parent 2d2a1d6 commit 738628c

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

backend/app/api/middlewares.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def get_ip_address(self, request: Request) -> ipaddress.IPv4Address | ipaddress.
2626
validated_ip = validate_ip_address(split_ip)
2727
if validated_ip is not None:
2828
if validated_ip.is_private:
29-
logging.warning(f"Forwarded Private IP address: {ip}, maybe behind proxy/docker?")
29+
logging.warning(f"Forwarded Private IP address: {split_ip}, maybe behind proxy/docker?")
3030
ip = validated_ip
3131
if validated_ip is None and request.client and request.client.host:
3232
try:

frontend/src/lib/utils/ip.ts

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,32 @@
1+
function isPrivateIP(ip: string): boolean {
2+
// IPv4 private ranges
3+
const ipv4PrivateRanges = [
4+
/^10\./, // 10.0.0.0/8
5+
/^172\.(1[6-9]|2[0-9]|3[0-1])\./, // 172.16.0.0/12
6+
/^192\.168\./, // 192.168.0.0/16
7+
/^127\./, // 127.0.0.0/8 (loopback)
8+
/^169\.254\./, // 169.254.0.0/16 (link-local)
9+
];
10+
11+
// IPv6 private/special addresses
12+
const ipv6PrivatePatterns = [
13+
/^::1$/i, // loopback
14+
/^fc[0-9a-f]{2}:/i, // fc00::/7 (unique local)
15+
/^fd[0-9a-f]{2}:/i, // fd00::/8 (unique local)
16+
/^fe[89ab][0-9a-f]:/i, // fe80::/10 (link-local)
17+
];
18+
19+
return ipv4PrivateRanges.some(r => r.test(ip)) || ipv6PrivatePatterns.some(r => r.test(ip));
20+
}
21+
22+
function getPublicIP(ip: string | null | undefined): string | null {
23+
if (!ip) return null;
24+
return isPrivateIP(ip) ? null : ip;
25+
}
26+
127
export function getUserIpAddress(request: Request, getClientAddress: () => string) {
2-
return request.headers.get("cf-connecting-ip") ||
3-
request.headers.get("x-real-ip") ||
4-
request.headers.get("x-forwarded-for")?.split(",")[0].trim() ||
28+
return getPublicIP(request.headers.get("cf-connecting-ip")) ||
29+
getPublicIP(request.headers.get("x-real-ip")) ||
30+
getPublicIP(request.headers.get("x-forwarded-for")?.split(",")[0].trim()) ||
531
getClientAddress();
6-
}
32+
}

0 commit comments

Comments
 (0)