mirror of
https://github.com/vastxie/99AI.git
synced 2025-11-14 04:33:41 +08:00
v3.5.0
This commit is contained in:
51
dist/common/utils/getClientIp.js
vendored
51
dist/common/utils/getClientIp.js
vendored
@@ -1,43 +1,22 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getClientIp = void 0;
|
||||
function getClientIp(request) {
|
||||
let ipAddress = '';
|
||||
const headerList = [
|
||||
'X-Client-IP',
|
||||
'X-Real-IP',
|
||||
'X-Forwarded-For',
|
||||
'CF-Connecting-IP',
|
||||
'True-Client-IP',
|
||||
'X-Cluster-Client-IP',
|
||||
'Proxy-Client-IP',
|
||||
'WL-Proxy-Client-IP',
|
||||
'HTTP_CLIENT_IP',
|
||||
'HTTP_X_FORWARDED_FOR',
|
||||
];
|
||||
for (const header of headerList) {
|
||||
const value = request.headers[header];
|
||||
if (value && typeof value === 'string') {
|
||||
const ips = value.split(',');
|
||||
ipAddress = ips[0].trim();
|
||||
break;
|
||||
}
|
||||
function getFirstValidIp(ipString) {
|
||||
const ips = ipString.split(',').map(ip => ip.trim());
|
||||
return ips.find(ip => isValidIp(ip)) || '';
|
||||
}
|
||||
function isValidIp(ip) {
|
||||
return /^\d{1,3}(\.\d{1,3}){3}$/.test(ip) || /^::ffff:\d{1,3}(\.\d{1,3}){3}$/.test(ip);
|
||||
}
|
||||
function getClientIp(req) {
|
||||
const forwardedFor = req.header('x-forwarded-for');
|
||||
let clientIp = forwardedFor ? getFirstValidIp(forwardedFor) : '';
|
||||
if (!clientIp) {
|
||||
clientIp = req.connection.remoteAddress || req.socket.remoteAddress || '';
|
||||
}
|
||||
if (!ipAddress) {
|
||||
ipAddress = request.connection.remoteAddress || '';
|
||||
if (clientIp.startsWith('::ffff:')) {
|
||||
clientIp = clientIp.substring(7);
|
||||
}
|
||||
if (ipAddress && ipAddress.includes('::')) {
|
||||
const isLocal = /^(::1|fe80(:1)?::1(%.*)?)$/i.test(ipAddress);
|
||||
if (isLocal) {
|
||||
ipAddress = '';
|
||||
}
|
||||
else if (ipAddress.includes('::ffff:')) {
|
||||
ipAddress = ipAddress.split(':').pop() || '';
|
||||
}
|
||||
}
|
||||
if (!ipAddress || !/\d+\.\d+\.\d+\.\d+/.test(ipAddress)) {
|
||||
ipAddress = '';
|
||||
}
|
||||
return ipAddress;
|
||||
return clientIp;
|
||||
}
|
||||
exports.getClientIp = getClientIp;
|
||||
|
||||
Reference in New Issue
Block a user