refactor: 移除查询日志地区解析

This commit is contained in:
Nixevol
2026-07-03 03:23:44 +08:00
parent 70a8528f41
commit a78b5aa47a
22 changed files with 54 additions and 90 deletions
+6 -2
View File
@@ -19,8 +19,12 @@ describe('parseUserAgent', () => {
});
describe('extractIp', () => {
it('优先取 x-forwarded-for 首个', () => {
expect(extractIp({ 'x-forwarded-for': '1.2.3.4, 5.6.7.8' })).toBe('1.2.3.4');
it('优先取 x-forwarded-for 首个公网 IP', () => {
expect(extractIp({ 'x-forwarded-for': '10.0.0.1, 1.2.3.4, 5.6.7.8' })).toBe('1.2.3.4');
});
it('x-forwarded-for 无公网 IP 时回退首个地址', () => {
expect(extractIp({ 'x-forwarded-for': '10.0.0.1, 192.168.1.2' })).toBe('10.0.0.1');
});
it('回退到 fallback 并去除 ipv6 前缀', () => {
+21 -4
View File
@@ -31,15 +31,32 @@ export function parseUserAgent(ua?: string): DeviceInfo {
return { deviceType, os, browser };
}
// 从请求中提取真实客户端 IP(兼容反向代理)。
function normalizeIp(ip?: string): string {
return (ip || '').trim().replace(/^::ffff:/, '');
}
function isPrivateIp(ip: string): boolean {
if (!ip || ip === 'unknown') return true;
if (ip === '::1' || ip === '127.0.0.1' || ip === 'localhost') return true;
if (/^10\./.test(ip) || /^192\.168\./.test(ip)) return true;
const m = ip.match(/^172\.(\d+)\./);
if (m) {
const n = Number(m[1]);
if (n >= 16 && n <= 31) return true;
}
return false;
}
// 从请求中提取真实客户端公网 IP(兼容反向代理)。
export function extractIp(headers: Record<string, unknown>, fallback?: string): string {
const xff = headers['x-forwarded-for'];
if (typeof xff === 'string' && xff.length > 0) {
return xff.split(',')[0].trim();
const ips = xff.split(',').map(normalizeIp).filter(Boolean);
return ips.find((ip) => !isPrivateIp(ip)) || ips[0] || 'unknown';
}
const real = headers['x-real-ip'];
if (typeof real === 'string' && real.length > 0) {
return real;
return normalizeIp(real);
}
return (fallback || '').replace('::ffff:', '') || 'unknown';
return normalizeIp(fallback) || 'unknown';
}