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
+1 -1
View File
@@ -286,7 +286,7 @@
},
"queryLog": {
"result": "Result",
"ip": "IP / Region",
"ip": "IP",
"device": "Device",
"queriedAt": "Time",
"startTime": "Start",
+1 -1
View File
@@ -286,7 +286,7 @@
},
"queryLog": {
"result": "查询结果",
"ip": "IP / 地区",
"ip": "IP",
"device": "设备信息",
"queriedAt": "查询时间",
"startTime": "开始时间",
+2 -2
View File
@@ -95,8 +95,8 @@ const columns: DataTableColumns<any> = [
{
title: () => t('pages.queryLog.ip'),
key: 'ip',
width: 190,
render: (r) => `${r.ip || '-'} / ${r.region || '-'}`,
width: 160,
render: (r) => r.ip || '-',
},
{
title: () => t('pages.queryLog.device'),
@@ -0,0 +1 @@
ALTER TABLE `query_log` DROP COLUMN `region`;
-1
View File
@@ -305,7 +305,6 @@ model QueryLog {
queriedAt DateTime @default(now()) @map("queried_at")
queryResult QueryResult @map("query_result")
ip String?
region String?
userAgent String? @db.Text @map("user_agent")
deviceType String? @map("device_type")
browser String?
-1
View File
@@ -210,7 +210,6 @@ async function ensureSampleData(): Promise<void> {
firstActivatedAt: new Date(Date.now() - 86400000),
queryResult: i === 0 ? 'FIRST_ACTIVATE' : 'REPEAT',
ip: `120.0.0.${10 + i}`,
region: '未知地区',
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X)',
deviceType: 'Mobile',
browser: 'Safari',
-2
View File
@@ -11,7 +11,6 @@ import { UploadModule } from './upload/upload.module';
import { QueueModule } from './queue/queue.module';
import { JobsModule } from './jobs/jobs.module';
import { BlockchainModule } from './blockchain/blockchain.module';
import { GeoModule } from './geo/geo.module';
import { RedisModule } from './redis/redis.module';
import { TemplateModule } from './template/template.module';
import { ArtworkModule } from './artwork/artwork.module';
@@ -38,7 +37,6 @@ import { SettingsModule } from './settings/settings.module';
QueueModule,
JobsModule,
BlockchainModule,
GeoModule,
AuthModule,
UserModule,
UploadModule,
+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';
}
-2
View File
@@ -26,7 +26,6 @@ export interface AppConfig {
driver: 'mock' | 'tianhe';
tianhe: { baseUrl: string; appId: string; appKey: string };
};
geo: { driver: string };
seedAdmin: { username: string; password: string; name: string };
logRetentionDays: number;
watermarkText: string;
@@ -74,7 +73,6 @@ export default (): AppConfig => {
appKey: process.env.TIANHE_APP_KEY || '',
},
},
geo: { driver: process.env.GEO_DRIVER || 'mock' },
seedAdmin: {
username: process.env.SEED_ADMIN_USERNAME || 'admin',
password: process.env.SEED_ADMIN_PASSWORD || 'Admin@12345',
-9
View File
@@ -1,9 +0,0 @@
import { Global, Module } from '@nestjs/common';
import { GeoService } from './geo.service';
@Global()
@Module({
providers: [GeoService],
exports: [GeoService],
})
export class GeoModule {}
-31
View File
@@ -1,31 +0,0 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
// IP 归属地解析。默认 Mock(本地/内网返回占位),预留接入真实 GeoIP 服务。
@Injectable()
export class GeoService {
constructor(private readonly config: ConfigService) {}
resolveRegion(ip?: string): string {
if (!ip || ip === 'unknown') return '未知';
if (this.isLocal(ip)) return '本地/内网';
// driver=mock:真实 GeoIP 未接入,返回占位。切换真实库后在此实现。
const driver = this.config.get<string>('geo.driver');
if (driver === 'mock') {
return '未知地区';
}
return '未知地区';
}
private isLocal(ip: string): boolean {
const clean = ip.replace('::ffff:', '');
return (
clean === '127.0.0.1' ||
clean === '::1' ||
clean === 'localhost' ||
clean.startsWith('10.') ||
clean.startsWith('192.168.') ||
/^172\.(1[6-9]|2\d|3[0-1])\./.test(clean)
);
}
}
@@ -4,7 +4,6 @@ import { Prisma } from '@prisma/client';
import { ArtworkStatus, AuditStatus, QueryResult, ProofStatus, TraceCodeStatus } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { GeoService } from '../geo/geo.service';
import { REDIS_CLIENT } from '../redis/redis.module';
import { parseUserAgent } from '../common/utils/ua.util';
@@ -24,7 +23,6 @@ export class PublicTraceService {
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly geo: GeoService,
@Inject(REDIS_CLIENT) private readonly redis: Redis,
) {}
@@ -209,7 +207,6 @@ export class PublicTraceService {
firstActivatedAt: code?.firstActivatedAt ?? undefined,
queryResult: result,
ip: ctx.ip,
region: this.geo.resolveRegion(ctx.ip),
userAgent: ctx.userAgent,
deviceType: device.deviceType,
browser: device.browser,