fix: correct client IP detection behind reverse proxy

This commit is contained in:
kevinsun
2025-02-18 13:15:46 +08:00
parent a771dd5478
commit 7207506240
2 changed files with 7 additions and 5 deletions

View File

@ -11,10 +11,17 @@ export const urlencodedParser = express.urlencoded({ extended: true, limit: '200
* @returns {string} IP address of the client * @returns {string} IP address of the client
*/ */
export function getIpFromRequest(req) { export function getIpFromRequest(req) {
// First check X-Real-IP header
if (req.headers['x-real-ip']) {
return req.headers['x-real-ip'].toString();
}
// Fall back to socket remote address
let clientIp = req.socket.remoteAddress; let clientIp = req.socket.remoteAddress;
if (!clientIp) { if (!clientIp) {
return 'unknown'; return 'unknown';
} }
let ip = ipaddr.parse(clientIp); let ip = ipaddr.parse(clientIp);
// Check if the IP address is IPv4-mapped IPv6 address // Check if the IP address is IPv4-mapped IPv6 address
if (ip.kind() === 'ipv6' && ip instanceof ipaddr.IPv6 && ip.isIPv4MappedAddress()) { if (ip.kind() === 'ipv6' && ip instanceof ipaddr.IPv6 && ip.isIPv4MappedAddress()) {

View File

@ -31,11 +31,6 @@ function getForwardedIp(req) {
return undefined; return undefined;
} }
// Check if X-Real-IP is available
if (req.headers['x-real-ip']) {
return req.headers['x-real-ip'].toString();
}
// Check for X-Forwarded-For and parse if available // Check for X-Forwarded-For and parse if available
if (req.headers['x-forwarded-for']) { if (req.headers['x-forwarded-for']) {
const ipList = req.headers['x-forwarded-for'].toString().split(',').map(ip => ip.trim()); const ipList = req.headers['x-forwarded-for'].toString().split(',').map(ip => ip.trim());