A modern and elegant dashboard for network traffic visualization and analysis.
feat: Refactor GeoIP handling to use structured objects and add GeoIP configuration API with improved chain-flow delimiter support.
luolei8c240b0261b1
diff --git a/CHANGELOG.en.md b/CHANGELOG.en.mdindex 7286c93..f5893fa 100644--- a/CHANGELOG.en.md+++ b/CHANGELOG.en.md@@ -7,6 +7,45 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+## [1.3.0] - 2026-02-16++### Added++- **Chain-flow delimiter compatibility (Issue #34)**+ - Rule/node names containing `|` are now supported in chain-flow graphs without key-splitting conflicts+- **GeoIP config status fields**+ - Added `configuredProvider` and `effectiveProvider` to `/api/db/geoip` responses to clearly separate configured vs. runtime-effective source+- **Regression test coverage**+ - Added `app.geoip-config.test.ts` for GeoIP config API behavior+ - Added `db.geoip-normalization.test.ts` for GeoIP normalization compatibility+ - Added chain-flow test coverage for names containing `|`++### Changed++- **GeoIP normalization moved to shared**+ - Added `packages/shared/src/geo-ip-utils.ts` and unified `normalizeGeoIP` usage across frontend/backend+ - Narrowed `IPStats.geoIP` to a structured object type and removed array-shape dependency+ - Applied normalization consistently in collector IP-related query outputs for backward compatibility+- **Config module refactor**+ - Moved `/api/db/*` routes out of `app.ts` into a dedicated `config.controller`+ - Added `autoListen` option to `createApp` for better testability and controlled startup+- **GeoIP service reliability improvements**+ - Reused MMDB required-file constants to avoid hardcoded filenames+ - Added short TTL cache for MMDB missing-file checks to reduce repeated filesystem probes+ - Added queue-overflow logging and `destroy()` resource cleanup+ - Improved private IPv6 detection (including `::ffff:` mapped IPv4) and failure-cooldown handling++### Fixed++- **Fixed `/api/stats/rules/chain-flow-all` 500 errors**+ - Resolved `Cannot read properties of undefined (reading 'name')` caused by delimiter-based link key parsing+- **Fixed side effects when reading GeoIP config**+ - `GET /api/db/geoip` no longer mutates persisted provider config+ - Settings selection state now follows `effectiveProvider` to avoid UI/runtime mismatch+- **Fixed Windows flag emoji rendering in React Flow chain nodes**+ - Applied `emoji-flag-font` to rule/group/proxy node labels+ - Unified active-link key encoding across backend/frontend to avoid ambiguous link matching+## [1.2.9] - 2026-02-16### Addeddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex f20fe77..906058f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,45 @@## [未发布]+## [1.3.0] - 2026-02-16++### 新增++- **链路图分隔符兼容(Issue #34)**+ - 链路流向图现在支持规则名/节点名中包含 `|` 字符,不再因分隔符冲突导致构图失败+- **GeoIP 配置状态字段增强**+ - `/api/db/geoip` 响应新增 `configuredProvider` 与 `effectiveProvider`,明确“已配置来源”与“实际生效来源”+- **回归测试补充**+ - 新增 `app.geoip-config.test.ts`(GeoIP 配置 API 行为)+ - 新增 `db.geoip-normalization.test.ts`(GeoIP 归一化兼容)+ - 新增规则链分隔符场景测试,覆盖 `|` 名称链路构建++### 变更++- **GeoIP 归一化能力下沉到 shared**+ - 新增 `packages/shared/src/geo-ip-utils.ts`,统一前后端 `normalizeGeoIP`+ - `IPStats.geoIP` 类型收敛为结构化对象,移除数组形态依赖+ - Collector 多个 IP 相关查询统一做 GeoIP 归一化返回,兼容历史数据+- **配置模块工程化重构**+ - 将 `/api/db/*` 路由从 `app.ts` 抽离到独立 `config.controller`+ - `createApp` 新增 `autoListen` 选项,便于集成测试和可控启动+- **GeoIP 服务稳定性增强**+ - MMDB 必需文件名复用配置常量,减少硬编码+ - 增加 MMDB 缺失状态短 TTL 缓存,降低频繁文件系统探测开销+ - 增加队列溢出日志、`destroy()` 资源释放能力+ - 优化私网 IPv6 判断(含 `::ffff:` 映射 IPv4)与失败冷却策略++### 修复++- **修复 `/api/stats/rules/chain-flow-all` 500 错误**+ - 解决 `Cannot read properties of undefined (reading 'name')` 异常,根因是链路 key 使用字符串分隔导致解析错位+- **修复 GeoIP 配置读取副作用**+ - 读取 `/api/db/geoip` 不再隐式改写已保存配置(side-effect free)+ - 设置页按 `effectiveProvider` 显示选中态,避免“配置值”和“实际值”视觉不一致+- **修复 React Flow 规则链节点在 Windows 下国旗 emoji 显示**+ - 规则/分组/代理节点名称补齐 `emoji-flag-font` 适配+ - 前后端 active link key 编码方式统一,避免链路匹配歧义+## [1.2.9] - 2026-02-16### 新增diff --git a/apps/collector/src/app.geoip-config.test.ts b/apps/collector/src/app.geoip-config.test.tsnew file mode 100644index 0000000..b42398a--- /dev/null+++ b/apps/collector/src/app.geoip-config.test.ts@@ -0,0 +1,127 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { createApp } from "./app.js";+import { realtimeStore } from "./realtime.js";+import { createTestBackend, createTestDatabase } from "./__tests__/helpers.js";+import type { StatsDatabase } from "./db.js";+import type { FastifyInstance } from "fastify";++describe("GeoIP config API", () => {+ let db: StatsDatabase;+ let cleanup: () => void;+ let backendId: number;+ let app: FastifyInstance;+ let mmdbDir: string;+ const originalEnv = {+ GEOIP_MMDB_DIR: process.env.GEOIP_MMDB_DIR,+ GEOIP_LOOKUP_PROVIDER: process.env.GEOIP_LOOKUP_PROVIDER,+ GEOIP_ONLINE_API_URL: process.env.GEOIP_ONLINE_API_URL,+ };++ beforeEach(async () => {+ mmdbDir = fs.mkdtempSync(path.join(os.tmpdir(), "geoip-mmdb-"));+ process.env.GEOIP_MMDB_DIR = mmdbDir;+ delete process.env.GEOIP_LOOKUP_PROVIDER;+ delete process.env.GEOIP_ONLINE_API_URL;++ ({ db, cleanup } = createTestDatabase());+ backendId = createTestBackend(db);+ app = await createApp({+ port: 0,+ db,+ realtimeStore,+ logger: false,+ autoListen: false,+ });+ });++ afterEach(async () => {+ if (app) {+ await app.close();+ }+ realtimeStore.clearBackend(backendId);+ cleanup();+ fs.rmSync(mmdbDir, { recursive: true, force: true });++ if (originalEnv.GEOIP_MMDB_DIR === undefined) delete process.env.GEOIP_MMDB_DIR;+ else process.env.GEOIP_MMDB_DIR = originalEnv.GEOIP_MMDB_DIR;+ if (originalEnv.GEOIP_LOOKUP_PROVIDER === undefined) delete process.env.GEOIP_LOOKUP_PROVIDER;+ else process.env.GEOIP_LOOKUP_PROVIDER = originalEnv.GEOIP_LOOKUP_PROVIDER;+ if (originalEnv.GEOIP_ONLINE_API_URL === undefined) delete process.env.GEOIP_ONLINE_API_URL;+ else process.env.GEOIP_ONLINE_API_URL = originalEnv.GEOIP_ONLINE_API_URL;+ });++ it("GET /api/db/geoip is side-effect-free and reports configured/effective providers", async () => {+ db.updateGeoLookupConfig({ provider: "local" });++ const before = db.getGeoLookupConfig();+ expect(before.provider).toBe("local");+ expect(before.localMmdbReady).toBe(false);++ const response = await app.inject({+ method: "GET",+ url: "/api/db/geoip",+ });+ expect(response.statusCode).toBe(200);++ const payload = response.json() as {+ provider: "online" | "local";+ configuredProvider: "online" | "local";+ effectiveProvider: "online" | "local";+ localMmdbReady: boolean;+ };+ expect(payload.provider).toBe("local");+ expect(payload.configuredProvider).toBe("local");+ expect(payload.effectiveProvider).toBe("online");+ expect(payload.localMmdbReady).toBe(false);++ // GET should never mutate stored config.+ const after = db.getGeoLookupConfig();+ expect(after.provider).toBe("local");+ });++ it("PUT /api/db/geoip rejects local provider when required MMDB files are missing", async () => {+ const response = await app.inject({+ method: "PUT",+ url: "/api/db/geoip",+ payload: { provider: "local" },+ });++ expect(response.statusCode).toBe(400);+ const payload = response.json() as {+ error: string;+ missingMmdbFiles?: string[];+ };+ expect(payload.error).toContain("Local MMDB is not ready");+ expect(payload.missingMmdbFiles).toEqual(+ expect.arrayContaining(["GeoLite2-City.mmdb", "GeoLite2-ASN.mmdb"]),+ );+ });++ it("PUT /api/db/geoip accepts local provider when required MMDB files exist", async () => {+ fs.writeFileSync(path.join(mmdbDir, "GeoLite2-City.mmdb"), "");+ fs.writeFileSync(path.join(mmdbDir, "GeoLite2-ASN.mmdb"), "");++ const response = await app.inject({+ method: "PUT",+ url: "/api/db/geoip",+ payload: { provider: "local" },+ });++ expect(response.statusCode).toBe(200);+ const payload = response.json() as {+ config: {+ provider: "online" | "local";+ configuredProvider: "online" | "local";+ effectiveProvider: "online" | "local";+ localMmdbReady: boolean;+ };+ };+ expect(payload.config.provider).toBe("local");+ expect(payload.config.configuredProvider).toBe("local");+ expect(payload.config.effectiveProvider).toBe("local");+ expect(payload.config.localMmdbReady).toBe(true);+ });+});diff --git a/apps/collector/src/app.ts b/apps/collector/src/app.tsindex b117983..ccc5fb4 100644--- a/apps/collector/src/app.ts+++ b/apps/collector/src/app.ts@@ -17,10 +17,13 @@ import { SurgePolicySyncService } from './modules/surge/surge-policy-sync.js';import { BackendService, backendController } from './modules/backend/index.js';import { StatsService, statsController } from './modules/stats/index.js';import { AuthService, authController } from './modules/auth/index.js';+import { configController } from './modules/config/index.js';// Extend Fastify instance to include servicesdeclare module 'fastify' {interface FastifyInstance {+ db: StatsDatabase;+ realtimeStore: RealtimeStore;backendService: BackendService;statsService: StatsService;}@@ -32,10 +35,18 @@ export interface AppOptions {realtimeStore: RealtimeStore;logger?: boolean;policySyncService?: SurgePolicySyncService;+ autoListen?: boolean;}export async function createApp(options: AppOptions) {- const { port, db, realtimeStore, logger = false, policySyncService } = options;+ const {+ port,+ db,+ realtimeStore,+ logger = false,+ policySyncService,+ autoListen = true,+ } = options;// Create Fastify instanceconst app = Fastify({ logger });@@ -71,21 +82,14 @@ export async function createApp(options: AppOptions) {app.decorate('backendService', backendService);app.decorate('statsService', statsService);app.decorate('authService', authService);+ app.decorate('db', db);+ app.decorate('realtimeStore', realtimeStore);const getBackendIdFromQuery = (query: Record<string, unknown>): number | null => {const backendId = typeof query.backendId === 'string' ? query.backendId : undefined;return statsService.resolveBackendId(backendId);};- const isValidHttpUrl = (value: string): boolean => {- try {- const url = new URL(value);- return url.protocol === 'http:' || url.protocol === 'https:';- } catch {- return false;- }- };-// ...// Helper to get headers for backend requests@@ -172,160 +176,6 @@ export async function createApp(options: AppOptions) {// Health check endpoint (not part of any module)app.get('/health', async () => ({ status: 'ok' }));- // Compatibility routes: DB management- app.get('/api/db/stats', async () => {- return {- size: db.getDatabaseSize(),- totalConnectionsCount: db.getTotalConnectionLogsCount(),- };- });-- app.post('/api/db/cleanup', async (request, reply) => {- if (authService.isShowcaseMode()) {- return reply.status(403).send({ error: 'Forbidden' });- }-- const body = request.body as { days?: number; backendId?: number };- const days = body?.days;- const backendId = typeof body?.backendId === 'number' ? body.backendId : undefined;-- if (typeof days !== 'number' || days < 0) {- return reply.status(400).send({ error: 'Valid days parameter required' });- }-- const result = db.cleanupOldData(backendId ?? null, days);-- if (days === 0) {- if (backendId) {- realtimeStore.clearBackend(backendId);- } else {- const backends = db.getAllBackends();- for (const backend of backends) {- realtimeStore.clearBackend(backend.id);- }- }-- return {- message: `Cleaned all data: ${result.deletedConnections} connections, ${result.deletedDomains} domains, ${result.deletedProxies} proxies`,- deleted: result.deletedConnections,- domains: result.deletedDomains,- ips: result.deletedIPs,- proxies: result.deletedProxies,- rules: result.deletedRules,- };- }-- return {- message: `Cleaned ${result.deletedConnections} old connection logs`,- deleted: result.deletedConnections,- };- });-- app.post('/api/db/vacuum', async (request, reply) => {- if (authService.isShowcaseMode()) {- return reply.status(403).send({ error: 'Forbidden' });- }-- db.vacuum();- return { message: 'Database vacuumed successfully' };- });-- app.get('/api/db/retention', async () => {- return db.getRetentionConfig();- });-- app.put('/api/db/retention', async (request, reply) => {- if (authService.isShowcaseMode()) {- return reply.status(403).send({ error: 'Forbidden' });- }-- const body = request.body as {- connectionLogsDays?: number;- hourlyStatsDays?: number;- autoCleanup?: boolean;- };-- if (- body.connectionLogsDays !== undefined &&- (body.connectionLogsDays < 1 || body.connectionLogsDays > 90)- ) {- return reply.status(400).send({ error: 'connectionLogsDays must be between 1 and 90' });- }-- if (- body.hourlyStatsDays !== undefined &&- (body.hourlyStatsDays < 7 || body.hourlyStatsDays > 365)- ) {- return reply.status(400).send({ error: 'hourlyStatsDays must be between 7 and 365' });- }-- const config = db.updateRetentionConfig({- connectionLogsDays: body.connectionLogsDays,- hourlyStatsDays: body.hourlyStatsDays,- autoCleanup: body.autoCleanup,- });-- return { message: 'Retention configuration updated', config };- });-- app.get('/api/db/geoip', async () => {- const current = db.getGeoLookupConfig() as {- provider?: 'online' | 'local';- localMmdbReady?: boolean;- };-- // Auto-fallback persisted config: if local is selected but required MMDB files are gone,- // switch back to online to keep UI/state consistent with effective runtime behavior.- if (current.provider === 'local' && current.localMmdbReady === false) {- return db.updateGeoLookupConfig({ provider: 'online' });- }-- return current;- });-- app.put('/api/db/geoip', async (request, reply) => {- if (authService.isShowcaseMode()) {- return reply.status(403).send({ error: 'Forbidden' });- }-- const body = request.body as {- provider?: 'online' | 'local';- onlineApiUrl?: string;- };-- if (body.provider !== undefined && body.provider !== 'online' && body.provider !== 'local') {- return reply.status(400).send({ error: "provider must be 'online' or 'local'" });- }-- if (body.onlineApiUrl !== undefined) {- const trimmed = body.onlineApiUrl.trim();- if (!trimmed || !isValidHttpUrl(trimmed)) {- return reply.status(400).send({ error: 'onlineApiUrl must be a valid http/https URL' });- }- body.onlineApiUrl = trimmed;- }-- if (body.provider === 'local') {- const current = db.getGeoLookupConfig() as {- localMmdbReady?: boolean;- missingMmdbFiles?: string[];- };- if (!current.localMmdbReady) {- return reply.status(400).send({- error: 'Local MMDB is not ready. Missing required files.',- missingMmdbFiles: current.missingMmdbFiles || [],- });- }- }-- const config = db.updateGeoLookupConfig({- provider: body.provider,- onlineApiUrl: body.onlineApiUrl,- });-- return { message: 'GeoIP configuration updated', config };- });-// Compatibility routes: Gateway APIsapp.get('/api/gateway/providers/proxies', async (request, reply) => {const query = request.query as Record<string, unknown>;@@ -603,13 +453,16 @@ export async function createApp(options: AppOptions) {await app.register(backendController, { prefix: '/api/backends' });await app.register(statsController, { prefix: '/api/stats' });await app.register(authController, { prefix: '/api/auth' });+ await app.register(configController, { prefix: '/api/db' });- // Start server- await app.listen({ port, host: '0.0.0.0' });- console.log(`[API] Server running at http://localhost:${port}`);+ if (autoListen) {+ // Start server+ await app.listen({ port, host: '0.0.0.0' });+ console.log(`[API] Server running at http://localhost:${port}`);- // Start automatic health checks for upstream gateways- backendService.startHealthChecks();+ // Start automatic health checks for upstream gateways+ backendService.startHealthChecks();+ }return app;}diff --git a/apps/collector/src/database/repositories/config.repository.ts b/apps/collector/src/database/repositories/config.repository.tsindex 0917fd4..9f416e3 100644--- a/apps/collector/src/database/repositories/config.repository.ts+++ b/apps/collector/src/database/repositories/config.repository.ts@@ -17,7 +17,7 @@ interface DatabaseRetentionConfig {export type GeoLookupProvider = 'online' | 'local';-interface GeoLookupConfig {+export interface GeoLookupConfig {provider: GeoLookupProvider;mmdbDir: string;onlineApiUrl: string;@@ -27,11 +27,19 @@ interface GeoLookupConfig {export class ConfigRepository extends BaseRepository {private dbPath: string;- private static readonly REQUIRED_MMDB_FILES = [+ private mmdbStatusCache:+ | {+ dir: string;+ checkedAt: number;+ missingMmdbFiles: string[];+ }+ | null = null;+ public static readonly REQUIRED_MMDB_FILES = ['GeoLite2-City.mmdb','GeoLite2-ASN.mmdb',] as const;private static readonly DEFAULT_MMDB_DIR = '/app/data/geoip';+ private static readonly MMDB_STATUS_CACHE_TTL_MS = 5000;constructor(db: Database.Database, dbPath: string) {super(db);@@ -107,9 +115,7 @@ export class ConfigRepository extends BaseRepository {: 'online');const mmdbDirValue = this.resolveMmdbDir();- const missingMmdbFiles = ConfigRepository.REQUIRED_MMDB_FILES.filter(- (file) => !fs.existsSync(path.join(mmdbDirValue, file)),- );+ const missingMmdbFiles = this.getMissingMmdbFiles(mmdbDirValue);return {provider: providerValue,@@ -123,6 +129,30 @@ export class ConfigRepository extends BaseRepository {};}+ private getMissingMmdbFiles(mmdbDir: string): string[] {+ const now = Date.now();+ const cached = this.mmdbStatusCache;+ if (+ cached &&+ cached.dir === mmdbDir &&+ now - cached.checkedAt < ConfigRepository.MMDB_STATUS_CACHE_TTL_MS+ ) {+ return cached.missingMmdbFiles;+ }++ const missingMmdbFiles = ConfigRepository.REQUIRED_MMDB_FILES.filter(+ (file) => !fs.existsSync(path.join(mmdbDir, file)),+ );++ this.mmdbStatusCache = {+ dir: mmdbDir,+ checkedAt: now,+ missingMmdbFiles,+ };++ return missingMmdbFiles;+ }+private resolveMmdbDir(): string {const envMmdbDir = process.env.GEOIP_MMDB_DIR?.trim();const fallbackCandidates = [diff --git a/apps/collector/src/database/repositories/index.ts b/apps/collector/src/database/repositories/index.tsindex fa46e5a..78c8980 100644--- a/apps/collector/src/database/repositories/index.ts+++ b/apps/collector/src/database/repositories/index.ts@@ -16,5 +16,5 @@ export { DeviceRepository } from './device.repository.js';export { ProxyRepository } from './proxy.repository.js';export { RuleRepository } from './rule.repository.js';export { IPRepository } from './ip.repository.js';-export { ConfigRepository } from './config.repository.js';+export { ConfigRepository, type GeoLookupConfig, type GeoLookupProvider } from './config.repository.js';export { TrafficWriterRepository, type TrafficUpdate } from './traffic-writer.repository.js';diff --git a/apps/collector/src/database/repositories/rule.repository.ts b/apps/collector/src/database/repositories/rule.repository.tsindex 1c22f00..5b96ba7 100644--- a/apps/collector/src/database/repositories/rule.repository.ts+++ b/apps/collector/src/database/repositories/rule.repository.ts@@ -20,6 +20,27 @@ export class RuleRepository extends BaseRepository {super(db);}+ private encodeFlowLinkKey(sourceName: string, targetName: string): string {+ return JSON.stringify([sourceName, targetName]);+ }++ private decodeFlowLinkKey(key: string): [sourceName: string, targetName: string] | null {+ try {+ const parsed = JSON.parse(key) as unknown;+ if (+ Array.isArray(parsed) &&+ parsed.length === 2 &&+ typeof parsed[0] === 'string' &&+ typeof parsed[1] === 'string'+ ) {+ return [parsed[0], parsed[1]];+ }+ } catch {+ return null;+ }+ return null;+ }+getRuleStats(backendId: number, start?: string, end?: string): RuleStats[] {const range = this.parseMinuteRange(start, end);if (range) {@@ -335,16 +356,23 @@ export class RuleRepository extends BaseRepository {node.totalConnections += row.totalConnections;}for (let i = 0; i < flowPath.length - 1; i++) {- linkSet.add(`${flowPath[i]}|${flowPath[i + 1]}`);+ linkSet.add(this.encodeFlowLinkKey(flowPath[i], flowPath[i + 1]));}}const nodes = Array.from(nodeMap.values());const nodeIndexMap = new Map(nodes.map((n, i) => [n.name, i]));- const links = Array.from(linkSet).map(linkStr => {- const [sourceName, targetName] = linkStr.split('|');- return { source: nodeIndexMap.get(sourceName)!, target: nodeIndexMap.get(targetName)! };- });+ const links = Array.from(linkSet)+ .map(linkKey => {+ const decoded = this.decodeFlowLinkKey(linkKey);+ if (!decoded) return null;+ const [sourceName, targetName] = decoded;+ const source = nodeIndexMap.get(sourceName);+ const target = nodeIndexMap.get(targetName);+ if (source === undefined || target === undefined) return null;+ return { source, target };+ })+ .filter((link): link is { source: number; target: number } => !!link);return { nodes, links };}@@ -391,6 +419,8 @@ export class RuleRepository extends BaseRepository {const linkMap = new Map<string, Set<string>>();const rulePathNodes = new Map<string, Set<string>>();const rulePathLinks = new Map<string, Set<string>>();+ const outgoingByNode = new Map<string, Set<string>>();+ const incomingByNode = new Map<string, Set<string>>();for (const row of rows) {const rule = row.rule;@@ -417,10 +447,17 @@ export class RuleRepository extends BaseRepository {}for (let i = 0; i < flowPath.length - 1; i++) {- const linkKey = `${flowPath[i]}|${flowPath[i + 1]}`;+ const sourceName = flowPath[i];+ const targetName = flowPath[i + 1];+ const linkKey = this.encodeFlowLinkKey(sourceName, targetName);if (!linkMap.has(linkKey)) linkMap.set(linkKey, new Set());linkMap.get(linkKey)!.add(rule);rulePathLinks.get(rule)!.add(linkKey);++ if (!outgoingByNode.has(sourceName)) outgoingByNode.set(sourceName, new Set());+ outgoingByNode.get(sourceName)!.add(targetName);+ if (!incomingByNode.has(targetName)) incomingByNode.set(targetName, new Set());+ incomingByNode.get(targetName)!.add(sourceName);}}@@ -433,8 +470,8 @@ export class RuleRepository extends BaseRepository {name === 'DIRECT' || name === 'REJECT' || name === 'REJECT-TINY';for (const [name, data] of nodeEntries) {- const hasOutgoing = Array.from(linkMap.keys()).some(k => k.startsWith(name + '|'));- const hasIncoming = Array.from(linkMap.keys()).some(k => k.endsWith('|' + name));+ const hasOutgoing = (outgoingByNode.get(name)?.size ?? 0) > 0;+ const hasIncoming = (incomingByNode.get(name)?.size ?? 0) > 0;if (!hasIncoming) {nodeTypeMap.set(name, 'rule');@@ -472,11 +509,34 @@ export class RuleRepository extends BaseRepository {const nodeIndexMap = new Map(nodes.map((n, i) => [n.name, i]));const links = Array.from(linkMap.entries())- .sort(([keyA], [keyB]) => keyA.localeCompare(keyB)).map(([key, rules]) => {- const [sourceName, targetName] = key.split('|');- return { source: nodeIndexMap.get(sourceName)!, target: nodeIndexMap.get(targetName)!, rules: Array.from(rules) };- });+ const decoded = this.decodeFlowLinkKey(key);+ if (!decoded) return null;+ const [sourceName, targetName] = decoded;+ const source = nodeIndexMap.get(sourceName);+ const target = nodeIndexMap.get(targetName);+ if (source === undefined || target === undefined) return null;+ return {+ sourceName,+ targetName,+ source,+ target,+ rules: Array.from(rules),+ };+ })+ .filter((link): link is {+ sourceName: string;+ targetName: string;+ source: number;+ target: number;+ rules: string[];+ } => !!link)+ .sort((a, b) => {+ const sourceDiff = a.sourceName.localeCompare(b.sourceName);+ if (sourceDiff !== 0) return sourceDiff;+ return a.targetName.localeCompare(b.targetName);+ })+ .map(({ source, target, rules }) => ({ source, target, rules }));const rulePaths: Record<string, { nodeIndices: number[]; linkIndices: number[] }> = {};for (const [rule, nodeNames] of rulePathNodes) {@@ -486,7 +546,7 @@ export class RuleRepository extends BaseRepository {links.forEach((link, idx) => {const sourceName = nodes[link.source].name;const targetName = nodes[link.target].name;- if (linkKeys.has(`${sourceName}|${targetName}`)) linkIndices.push(idx);+ if (linkKeys.has(this.encodeFlowLinkKey(sourceName, targetName))) linkIndices.push(idx);});rulePaths[rule] = { nodeIndices, linkIndices };}diff --git a/apps/collector/src/db.geoip-normalization.test.ts b/apps/collector/src/db.geoip-normalization.test.tsnew file mode 100644index 0000000..93d574e--- /dev/null+++ b/apps/collector/src/db.geoip-normalization.test.ts@@ -0,0 +1,128 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createTestBackend, createTestDatabase } from "./__tests__/helpers.js";+import type { StatsDatabase } from "./db.js";+import type { IPStats } from "@neko-master/shared";++describe("StatsDatabase geoIP normalization", () => {+ let db: StatsDatabase;+ let cleanup: () => void;+ let backendId: number;++ beforeEach(() => {+ ({ db, cleanup } = createTestDatabase());+ backendId = createTestBackend(db);+ });++ afterEach(() => {+ cleanup();+ });++ it("normalizes legacy geoIP array to structured object in getIPStats", () => {+ const repoSpy = vi.spyOn(db.repos.ip, "getIPStats").mockReturnValue([+ {+ ip: "1.1.1.1",+ domains: ["example.com"],+ totalUpload: 1,+ totalDownload: 2,+ totalConnections: 3,+ lastSeen: "2026-02-16T00:00:00.000Z",+ geoIP: ["US", "United States", "Dallas", "IBM Cloud"] as any,+ } as IPStats,+ ]);++ const result = db.getIPStats(backendId, 10);+ expect(result).toHaveLength(1);+ expect(result[0].geoIP).toEqual({+ countryCode: "US",+ countryName: "United States",+ city: "Dallas",+ asOrganization: "IBM Cloud",+ });++ repoSpy.mockRestore();+ });++ it("keeps structured geoIP and normalizes mixed payloads in paginated results", () => {+ const repoSpy = vi.spyOn(db.repos.ip, "getIPStatsPaginated").mockReturnValue({+ data: [+ {+ ip: "2.2.2.2",+ domains: [],+ totalUpload: 10,+ totalDownload: 20,+ totalConnections: 2,+ lastSeen: "2026-02-16T00:00:00.000Z",+ geoIP: {+ countryCode: "JP",+ countryName: "Japan",+ city: "Tokyo",+ asOrganization: "IIJ",+ },+ } as IPStats,+ {+ ip: "3.3.3.3",+ domains: [],+ totalUpload: 11,+ totalDownload: 22,+ totalConnections: 3,+ lastSeen: "2026-02-16T00:00:00.000Z",+ geoIP: ["KR", "South Korea", "", ""] as any,+ } as IPStats,+ ],+ total: 2,+ });++ const result = db.getIPStatsPaginated(backendId, {+ offset: 0,+ limit: 10,+ });++ expect(result.total).toBe(2);+ expect(result.data[0].geoIP).toEqual({+ countryCode: "JP",+ countryName: "Japan",+ city: "Tokyo",+ asOrganization: "IIJ",+ });+ expect(result.data[1].geoIP).toEqual({+ countryCode: "KR",+ countryName: "South Korea",+ city: "",+ asOrganization: "",+ });++ repoSpy.mockRestore();+ });++ it("normalizes geoIP for wrapped detail methods like getRuleDomainIPDetails", () => {+ const repoSpy = vi.spyOn(db.repos.rule, "getRuleDomainIPDetails").mockReturnValue([+ {+ ip: "4.4.4.4",+ domains: ["a.com"],+ totalUpload: 5,+ totalDownload: 6,+ totalConnections: 1,+ lastSeen: "2026-02-16T00:00:00.000Z",+ geoIP: ["SG", "Singapore", "Singapore", "Singtel"] as any,+ } as IPStats,+ ]);++ const result = db.getRuleDomainIPDetails(+ backendId,+ "DOMAIN-SUFFIX(google.com)",+ "google.com",+ undefined,+ undefined,+ 10,+ );++ expect(result[0].geoIP).toEqual({+ countryCode: "SG",+ countryName: "Singapore",+ city: "Singapore",+ asOrganization: "Singtel",+ });++ repoSpy.mockRestore();+ });+});diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.tsindex 4ac394d..06e49e3 100644--- a/apps/collector/src/db.ts+++ b/apps/collector/src/db.ts@@ -1,7 +1,7 @@import Database from 'better-sqlite3';import path from 'path';import fs from 'fs';-import type { Connection, DomainStats, IPStats, HourlyStats, ProxyStats, RuleStats, ProxyTrafficStats, DeviceStats } from '@neko-master/shared';+import { normalizeGeoIP, type Connection, type DomainStats, type IPStats, type HourlyStats, type ProxyStats, type RuleStats, type ProxyTrafficStats, type DeviceStats } from '@neko-master/shared';import { getAllSchemaStatements } from './database/schema.js';import {AuthRepository,@@ -13,6 +13,8 @@ import {RuleRepository,IPRepository,ConfigRepository,+ type GeoLookupConfig,+ type GeoLookupProvider,TrafficWriterRepository,DomainRepository,BackendRepository,@@ -44,6 +46,23 @@ export interface BackendConfig {updated_at: string;}+function normalizeIPStatsGeoIP(items: IPStats[]): IPStats[] {+ return items.map((item) => {+ const normalizedGeoIP = normalizeGeoIP(item.geoIP as unknown);+ return {+ ...item,+ geoIP: normalizedGeoIP ?? undefined,+ };+ });+}++function normalizePaginatedIPStatsGeoIP(result: { data: IPStats[]; total: number }): { data: IPStats[]; total: number } {+ return {+ ...result,+ data: normalizeIPStatsGeoIP(result.data),+ };+}+export class StatsDatabase {private db: Database.Database;private dbPath: string;@@ -548,7 +567,11 @@ export class StatsDatabase {() => this.repos.domain.getDomainStatsPaginated(backendId, opts),);}- getDomainIPDetails(backendId: number, domain: string, start?: string, end?: string, limit?: number, sourceIP?: string, sourceChain?: string) { return this.repos.ip.getDomainIPDetails(backendId, domain, start, end, limit, sourceIP, sourceChain); }+ getDomainIPDetails(backendId: number, domain: string, start?: string, end?: string, limit?: number, sourceIP?: string, sourceChain?: string) {+ return normalizeIPStatsGeoIP(+ this.repos.ip.getDomainIPDetails(backendId, domain, start, end, limit, sourceIP, sourceChain),+ );+ }getDomainProxyStats(backendId: number, domain: string, start?: string, end?: string, sourceIP?: string, sourceChain?: string) { return this.repos.domain.getDomainProxyStats(backendId, domain, start, end, sourceIP, sourceChain); }// ==================== IP ====================@@ -558,10 +581,12 @@ export class StatsDatabase {[backendId, limit, start || '', end || ''],start,end,- () => this.repos.ip.getIPStats(backendId, limit, start, end),+ () => normalizeIPStatsGeoIP(this.repos.ip.getIPStats(backendId, limit, start, end)),);}- getIPStatsByIPs(backendId: number, ips: string[]) { return this.repos.ip.getIPStatsByIPs(backendId, ips); }+ getIPStatsByIPs(backendId: number, ips: string[]) {+ return normalizeIPStatsGeoIP(this.repos.ip.getIPStatsByIPs(backendId, ips));+ }getIPStatsPaginated(backendId: number,opts: { offset?: number; limit?: number; sortBy?: string; sortOrder?: string; search?: string; start?: string; end?: string } = {},@@ -571,7 +596,7 @@ export class StatsDatabase {[backendId, opts.offset || 0, opts.limit || 50, opts.sortBy || '', opts.sortOrder || '', opts.search || '', opts.start || '', opts.end || ''],opts.start,opts.end,- () => this.repos.ip.getIPStatsPaginated(backendId, opts),+ () => normalizePaginatedIPStatsGeoIP(this.repos.ip.getIPStatsPaginated(backendId, opts)),);}getIPDomainDetails(backendId: number, ip: string, start?: string, end?: string, limit?: number, sourceIP?: string, sourceChain?: string) { return this.repos.ip.getIPDomainDetails(backendId, ip, start, end, limit, sourceIP, sourceChain); }@@ -583,7 +608,7 @@ export class StatsDatabase {[backendId, limit, start || '', end || ''],start,end,- () => this.repos.ip.getTopIPsLight(backendId, limit, start, end),+ () => normalizeIPStatsGeoIP(this.repos.ip.getTopIPsLight(backendId, limit, start, end)),);}updateASNInfo(ip: string, asn: string, org: string) { this.repos.ip.updateASNInfo(ip, asn, org); }@@ -655,7 +680,9 @@ export class StatsDatabase {);}getDeviceDomains(backendId: number, sourceIP: string, limit?: number, start?: string, end?: string) { return this.repos.device.getDeviceDomains(backendId, sourceIP, limit, start, end); }- getDeviceIPs(backendId: number, sourceIP: string, limit?: number, start?: string, end?: string) { return this.repos.device.getDeviceIPs(backendId, sourceIP, limit, start, end); }+ getDeviceIPs(backendId: number, sourceIP: string, limit?: number, start?: string, end?: string) {+ return normalizeIPStatsGeoIP(this.repos.device.getDeviceIPs(backendId, sourceIP, limit, start, end));+ }// ==================== Proxy ====================getProxyStats(backendId: number, start?: string, end?: string) {@@ -668,7 +695,9 @@ export class StatsDatabase {);}getProxyDomains(backendId: number, chain: string, limit?: number, start?: string, end?: string) { return this.repos.proxy.getProxyDomains(backendId, chain, limit, start, end); }- getProxyIPs(backendId: number, chain: string, limit?: number, start?: string, end?: string) { return this.repos.proxy.getProxyIPs(backendId, chain, limit, start, end); }+ getProxyIPs(backendId: number, chain: string, limit?: number, start?: string, end?: string) {+ return normalizeIPStatsGeoIP(this.repos.proxy.getProxyIPs(backendId, chain, limit, start, end));+ }// ==================== Rule ====================getRuleStats(backendId: number, start?: string, end?: string) {@@ -682,9 +711,13 @@ export class StatsDatabase {}getRuleProxyMap(backendId: number) { return this.repos.rule.getRuleProxyMap(backendId); }getRuleDomains(backendId: number, rule: string, limit?: number, start?: string, end?: string) { return this.repos.rule.getRuleDomains(backendId, rule, limit, start, end); }- getRuleIPs(backendId: number, rule: string, limit?: number, start?: string, end?: string) { return this.repos.rule.getRuleIPs(backendId, rule, limit, start, end); }+ getRuleIPs(backendId: number, rule: string, limit?: number, start?: string, end?: string) {+ return normalizeIPStatsGeoIP(this.repos.rule.getRuleIPs(backendId, rule, limit, start, end));+ }getRuleDomainProxyStats(backendId: number, rule: string, domain: string, start?: string, end?: string) { return this.repos.rule.getRuleDomainProxyStats(backendId, rule, domain, start, end); }- getRuleDomainIPDetails(backendId: number, rule: string, domain: string, start?: string, end?: string, limit?: number) { return this.repos.rule.getRuleDomainIPDetails(backendId, rule, domain, start, end, limit); }+ getRuleDomainIPDetails(backendId: number, rule: string, domain: string, start?: string, end?: string, limit?: number) {+ return normalizeIPStatsGeoIP(this.repos.rule.getRuleDomainIPDetails(backendId, rule, domain, start, end, limit));+ }getRuleIPProxyStats(backendId: number, rule: string, ip: string, start?: string, end?: string) { return this.repos.rule.getRuleIPProxyStats(backendId, rule, ip, start, end); }getRuleIPDomainDetails(backendId: number, rule: string, ip: string, start?: string, end?: string, limit?: number) { return this.repos.rule.getRuleIPDomainDetails(backendId, rule, ip, start, end, limit); }getRuleChainFlow(backendId: number, rule: string, start?: string, end?: string) { return this.repos.rule.getRuleChainFlow(backendId, rule, start, end); }@@ -886,8 +919,8 @@ export class StatsDatabase {getTotalConnectionLogsCount() { return this.repos.config.getTotalConnectionLogsCount(); }getRetentionConfig() { return this.repos.config.getRetentionConfig(); }updateRetentionConfig(updates: { connectionLogsDays?: number; hourlyStatsDays?: number; autoCleanup?: boolean }) { return this.repos.config.updateRetentionConfig(updates); }- getGeoLookupConfig() { return this.repos.config.getGeoLookupConfig(); }- updateGeoLookupConfig(updates: { provider?: 'online' | 'local'; onlineApiUrl?: string }) {+ getGeoLookupConfig(): GeoLookupConfig { return this.repos.config.getGeoLookupConfig(); }+ updateGeoLookupConfig(updates: { provider?: GeoLookupProvider; onlineApiUrl?: string }): GeoLookupConfig {return this.repos.config.updateGeoLookupConfig(updates);}vacuum() { this.repos.config.vacuum(); }@@ -924,4 +957,6 @@ export class StatsDatabase {}}+export type { GeoLookupConfig, GeoLookupProvider };+export default StatsDatabase;diff --git a/apps/collector/src/geo-service.ts b/apps/collector/src/geo-service.tsindex ea94106..9865be7 100644--- a/apps/collector/src/geo-service.ts+++ b/apps/collector/src/geo-service.ts@@ -7,6 +7,7 @@ import maxmind, {type Reader,} from "maxmind";import type { StatsDatabase } from "./db.js";+import { ConfigRepository, type GeoLookupConfig } from "./database/repositories/config.repository.js";export interface GeoLocation {country: string;@@ -19,13 +20,6 @@ export interface GeoLocation {continent_name: string;}-interface GeoLookupConfig {- provider: "online" | "local";- mmdbDir: string;- onlineApiUrl: string;- localMmdbReady?: boolean;-}-interface GeoIPApiResponse {country?: unknown;country_name?: unknown;@@ -72,6 +66,7 @@ export class GeoIPService {private static FAILED_IPS_CLEANUP_INTERVAL_MS = 10 * 60 * 1000;private static ONLINE_MIN_REQUEST_INTERVAL_MS = 100;private static LOCAL_MMDB_RECHECK_INTERVAL_MS = 60 * 1000;+ private static COUNTRY_MMDB_FILE = "GeoLite2-Country.mmdb";constructor(db: StatsDatabase) {this.db = db;@@ -91,13 +86,10 @@ export class GeoIPService {};}- const failedAt = this.failedIPs.get(ip);- if (failedAt && Date.now() - failedAt < GeoIPService.FAIL_COOLDOWN_MS) {- return null;- }-const cached = this.db.getIPGeolocation(ip);if (cached) {+ // Cache hit should always win over previous transient failures.+ this.failedIPs.delete(ip);return {country: cached.country,country_name: cached.country_name,@@ -110,6 +102,11 @@ export class GeoIPService {};}+ const failedAt = this.failedIPs.get(ip);+ if (failedAt && Date.now() - failedAt < GeoIPService.FAIL_COOLDOWN_MS) {+ return null;+ }+const pending = this.pendingQueries.get(ip);if (pending) {return pending;@@ -127,6 +124,9 @@ export class GeoIPService {private async queryWithQueue(ip: string): Promise<GeoLocation | null> {if (this.queue.length >= GeoIPService.MAX_QUEUE_SIZE) {+ console.warn(+ `[GeoIP] Queue overflow, dropping lookup for ${ip}. Max queue size: ${GeoIPService.MAX_QUEUE_SIZE}`,+ );return null;}return new Promise((resolve) => {@@ -148,7 +148,7 @@ export class GeoIPService {private getRequestIntervalMs(): number {try {- const config = this.db.getGeoLookupConfig() as GeoLookupConfig;+ const config = this.db.getGeoLookupConfig();const useLocal = config.provider === "local" && config.localMmdbReady !== false;return useLocal ? 0 : GeoIPService.ONLINE_MIN_REQUEST_INTERVAL_MS;} catch {@@ -190,7 +190,7 @@ export class GeoIPService {}private async queryGeo(ip: string): Promise<GeoLocation | null> {- const config = this.db.getGeoLookupConfig() as GeoLookupConfig;+ const config = this.db.getGeoLookupConfig();const useLocal = config.provider === "local" && config.localMmdbReady !== false;if (useLocal) {const localResult = await this.queryLocalMMDB(ip, config);@@ -253,6 +253,7 @@ export class GeoIPService {};this.db.saveIPGeolocation(ip, geo);+ this.failedIPs.delete(ip);return geo;} finally {clearTimeout(timeout);@@ -329,6 +330,7 @@ export class GeoIPService {};this.db.saveIPGeolocation(ip, geo);+ this.failedIPs.delete(ip);return geo;} catch (err) {console.error(`[GeoIP] Local MMDB query failed for ${ip}:`, err);@@ -378,13 +380,14 @@ export class GeoIPService {}private async loadLocalMmdbReaders(mmdbDir: string): Promise<LocalMmdbReaders | null> {- const cityPath = path.join(mmdbDir, "GeoLite2-City.mmdb");- const asnPath = path.join(mmdbDir, "GeoLite2-ASN.mmdb");- const countryPath = path.join(mmdbDir, "GeoLite2-Country.mmdb");+ const [cityMmdbFile, asnMmdbFile] = ConfigRepository.REQUIRED_MMDB_FILES;+ const cityPath = path.join(mmdbDir, cityMmdbFile);+ const asnPath = path.join(mmdbDir, asnMmdbFile);+ const countryPath = path.join(mmdbDir, GeoIPService.COUNTRY_MMDB_FILE);if (!fs.existsSync(cityPath) || !fs.existsSync(asnPath)) {console.error(- `[GeoIP] Missing MMDB file(s) in ${mmdbDir}. Required: GeoLite2-City.mmdb, GeoLite2-ASN.mmdb`,+ `[GeoIP] Missing MMDB file(s) in ${mmdbDir}. Required: ${ConfigRepository.REQUIRED_MMDB_FILES.join(", ")}`,);return null;}@@ -474,17 +477,23 @@ export class GeoIPService {/^100\.(6[4-9]|[7-9][0-9]|1[0-1][0-9]|12[0-7])\./,];- if (ip.includes(":")) {+ const normalized = ip.toLowerCase();+ if (normalized.includes(":")) {+ if (normalized === "::1") {+ return true;+ }+ if (normalized.startsWith("::ffff:")) {+ const mappedIPv4 = normalized.slice("::ffff:".length);+ return privateRanges.some((range) => range.test(mappedIPv4));+ }return (- ip.startsWith("fc") ||- ip.startsWith("fd") ||- ip.startsWith("fe80") ||- ip.startsWith("::1") ||- ip === "::1"+ normalized.startsWith("fc") ||+ normalized.startsWith("fd") ||+ normalized.startsWith("fe80"));}- return privateRanges.some((range) => range.test(ip));+ return privateRanges.some((range) => range.test(normalized));}private sleep(ms: number): Promise<void> {@@ -493,7 +502,7 @@ export class GeoIPService {async bulkQueryIPs(ips: string[]): Promise<void> {const uniqueIPs = [...new Set(ips)].filter((ip) => !this.isPrivateIP(ip));- const config = this.db.getGeoLookupConfig() as GeoLookupConfig;+ const config = this.db.getGeoLookupConfig();const useLocal = config.provider === "local" && config.localMmdbReady !== false;const delayMs = useLocal ? 0 : 150;@@ -507,4 +516,22 @@ export class GeoIPService {}}}++ destroy(): void {+ if (this.processorTimer) {+ clearTimeout(this.processorTimer);+ this.processorTimer = null;+ }++ for (const item of this.queue) {+ item.resolve(null);+ }+ this.queue = [];++ this.pendingQueries.clear();+ this.failedIPs.clear();+ this.localMmdbLoadPromise = null;+ this.localMmdbReaders = null;+ this.isProcessing = false;+ }}diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.tsindex 2c048ea..5ee42d3 100644--- a/apps/collector/src/index.ts+++ b/apps/collector/src/index.ts@@ -241,6 +241,7 @@ function shutdown() {// Stop serverswsServer?.stop();apiServer?.stop();+ geoService?.destroy();// Close databasedb?.close();diff --git a/apps/collector/src/modules/config/config.controller.ts b/apps/collector/src/modules/config/config.controller.tsnew file mode 100644index 0000000..aa28d2a--- /dev/null+++ b/apps/collector/src/modules/config/config.controller.ts@@ -0,0 +1,180 @@+import type { FastifyInstance, FastifyPluginAsync } from "fastify";+import type { StatsDatabase, GeoLookupConfig, GeoLookupProvider } from "../../db.js";+import type { RealtimeStore } from "../../realtime.js";++declare module "fastify" {+ interface FastifyInstance {+ db: StatsDatabase;+ realtimeStore: RealtimeStore;+ }+}++function isValidHttpUrl(value: string): boolean {+ try {+ const url = new URL(value);+ return url.protocol === "http:" || url.protocol === "https:";+ } catch {+ return false;+ }+}++function toGeoLookupResponse(config: GeoLookupConfig) {+ const configuredProvider = config.provider;+ const effectiveProvider =+ configuredProvider === "local" && config.localMmdbReady === false+ ? "online"+ : configuredProvider;++ return {+ ...config,+ configuredProvider,+ effectiveProvider,+ };+}++const configController: FastifyPluginAsync = async (fastify: FastifyInstance): Promise<void> => {+ // Compatibility routes: DB management+ fastify.get("/stats", async () => {+ return {+ size: fastify.db.getDatabaseSize(),+ totalConnectionsCount: fastify.db.getTotalConnectionLogsCount(),+ };+ });++ fastify.post("/cleanup", async (request, reply) => {+ if (fastify.authService.isShowcaseMode()) {+ return reply.status(403).send({ error: "Forbidden" });+ }++ const body = request.body as { days?: number; backendId?: number };+ const days = body?.days;+ const backendId = typeof body?.backendId === "number" ? body.backendId : undefined;++ if (typeof days !== "number" || days < 0) {+ return reply.status(400).send({ error: "Valid days parameter required" });+ }++ const result = fastify.db.cleanupOldData(backendId ?? null, days);++ if (days === 0) {+ if (backendId) {+ fastify.realtimeStore.clearBackend(backendId);+ } else {+ const backends = fastify.db.getAllBackends();+ for (const backend of backends) {+ fastify.realtimeStore.clearBackend(backend.id);+ }+ }++ return {+ message: `Cleaned all data: ${result.deletedConnections} connections, ${result.deletedDomains} domains, ${result.deletedProxies} proxies`,+ deleted: result.deletedConnections,+ domains: result.deletedDomains,+ ips: result.deletedIPs,+ proxies: result.deletedProxies,+ rules: result.deletedRules,+ };+ }++ return {+ message: `Cleaned ${result.deletedConnections} old connection logs`,+ deleted: result.deletedConnections,+ };+ });++ fastify.post("/vacuum", async (_request, reply) => {+ if (fastify.authService.isShowcaseMode()) {+ return reply.status(403).send({ error: "Forbidden" });+ }++ fastify.db.vacuum();+ return { message: "Database vacuumed successfully" };+ });++ fastify.get("/retention", async () => {+ return fastify.db.getRetentionConfig();+ });++ fastify.put("/retention", async (request, reply) => {+ if (fastify.authService.isShowcaseMode()) {+ return reply.status(403).send({ error: "Forbidden" });+ }++ const body = request.body as {+ connectionLogsDays?: number;+ hourlyStatsDays?: number;+ autoCleanup?: boolean;+ };++ if (+ body.connectionLogsDays !== undefined &&+ (body.connectionLogsDays < 1 || body.connectionLogsDays > 90)+ ) {+ return reply.status(400).send({ error: "connectionLogsDays must be between 1 and 90" });+ }++ if (+ body.hourlyStatsDays !== undefined &&+ (body.hourlyStatsDays < 7 || body.hourlyStatsDays > 365)+ ) {+ return reply.status(400).send({ error: "hourlyStatsDays must be between 7 and 365" });+ }++ const config = fastify.db.updateRetentionConfig({+ connectionLogsDays: body.connectionLogsDays,+ hourlyStatsDays: body.hourlyStatsDays,+ autoCleanup: body.autoCleanup,+ });++ return { message: "Retention configuration updated", config };+ });++ fastify.get("/geoip", async () => {+ return toGeoLookupResponse(fastify.db.getGeoLookupConfig());+ });++ fastify.put("/geoip", async (request, reply) => {+ if (fastify.authService.isShowcaseMode()) {+ return reply.status(403).send({ error: "Forbidden" });+ }++ const body = request.body as {+ provider?: GeoLookupProvider;+ onlineApiUrl?: string;+ };++ if (body.provider !== undefined && body.provider !== "online" && body.provider !== "local") {+ return reply.status(400).send({ error: "provider must be 'online' or 'local'" });+ }++ if (body.onlineApiUrl !== undefined) {+ const trimmed = body.onlineApiUrl.trim();+ if (!trimmed || !isValidHttpUrl(trimmed)) {+ return reply.status(400).send({ error: "onlineApiUrl must be a valid http/https URL" });+ }+ body.onlineApiUrl = trimmed;+ }++ if (body.provider === "local") {+ const current = fastify.db.getGeoLookupConfig();+ if (!current.localMmdbReady) {+ return reply.status(400).send({+ error: "Local MMDB is not ready. Missing required files.",+ missingMmdbFiles: current.missingMmdbFiles || [],+ });+ }+ }++ const config = fastify.db.updateGeoLookupConfig({+ provider: body.provider,+ onlineApiUrl: body.onlineApiUrl,+ });++ return {+ message: "GeoIP configuration updated",+ config: toGeoLookupResponse(config),+ };+ });+};++export default configController;diff --git a/apps/collector/src/modules/config/index.ts b/apps/collector/src/modules/config/index.tsnew file mode 100644index 0000000..ce36826--- /dev/null+++ b/apps/collector/src/modules/config/index.ts@@ -0,0 +1,5 @@+/**+ * Config Module+ */++export { default as configController } from "./config.controller.js";diff --git a/apps/collector/src/modules/stats/stats.service.test.ts b/apps/collector/src/modules/stats/stats.service.test.tsindex 5cdaeb2..d209565 100644--- a/apps/collector/src/modules/stats/stats.service.test.ts+++ b/apps/collector/src/modules/stats/stats.service.test.ts@@ -150,6 +150,36 @@ describe('StatsService', () => {});});+ describe('getAllRuleChainFlows', () => {+ it('should handle node names containing "|" in chain flow links', () => {+ db.batchUpdateTrafficStats(backendId, [+ {+ domain: 'video.example.com',+ ip: '203.0.113.10',+ chain: 'JP-Sakura|IEPL',+ chains: ['JP-Sakura|IEPL', 'Manual|Select', 'YouTube|Media'],+ rule: 'RULE-SET',+ rulePayload: 'YouTube',+ upload: 123,+ download: 456,+ sourceIP: '192.168.1.88',+ timestampMs: Date.now(),+ },+ ]);++ const result = service.getAllRuleChainFlows(backendId, { active: false });++ expect(result.nodes.some((node: { name: string }) => node.name === 'YouTube|Media')).toBe(true);+ expect(result.links.length).toBeGreaterThan(0);+ for (const link of result.links) {+ expect(result.nodes[link.source]).toBeDefined();+ expect(result.nodes[link.target]).toBeDefined();+ }+ expect(result.rulePaths['YouTube|Media']).toBeDefined();+ expect(result.rulePaths['YouTube|Media'].linkIndices.length).toBeGreaterThan(0);+ });+ });+describe('shouldIncludeRealtime', () => {it('should return true when no time range is active', () => {expect(service.shouldIncludeRealtime({ active: false })).toBe(true);diff --git a/apps/web/components/common/index.ts b/apps/web/components/common/index.tsindex 2cf75e5..4867681 100644--- a/apps/web/components/common/index.ts+++ b/apps/web/components/common/index.ts@@ -9,3 +9,4 @@ export { TimeRangePicker } from "./time-range-picker";export { TopListItem } from "./top-list-item";export { OverviewCard } from "./overview-card";export { ClientOnly } from "./client-only";+export { CopyIconButton } from "./copy-icon-button";diff --git a/apps/web/components/features/backend/backend-config-dialog.tsx b/apps/web/components/features/backend/backend-config-dialog.tsxindex 3e84859..22a119a 100644--- a/apps/web/components/features/backend/backend-config-dialog.tsx+++ b/apps/web/components/features/backend/backend-config-dialog.tsx@@ -344,6 +344,8 @@ export function BackendConfigDialog({const [updatingRetention, setUpdatingRetention] = useState(false);const [geoLookupConfig, setGeoLookupConfig] = useState<GeoLookupConfig>({provider: "online",+ configuredProvider: "online",+ effectiveProvider: "online",mmdbDir: "/app/data/geoip",onlineApiUrl: "https://api.ipinfo.es/ipinfo",localMmdbReady: false,@@ -509,6 +511,9 @@ export function BackendConfigDialog({handleUpdateGeoLookupConfig({ provider });};+ const selectedGeoLookupProvider =+ geoLookupConfig.effectiveProvider ?? geoLookupConfig.provider;+const handleUpdateRetention = async (key: keyof RetentionConfig,value: number | boolean,@@ -1447,14 +1452,14 @@ export function BackendConfigDialog({</p><RadioGroup- value={geoLookupConfig.provider}+ value={selectedGeoLookupProvider}onValueChange={handleGeoLookupProviderChange}className="space-y-2"disabled={updatingGeoLookup || isShowcase}><divclassName={cn("flex items-center gap-2 rounded-md border p-3 transition-all",- geoLookupConfig.provider === "online"+ selectedGeoLookupProvider === "online"? "border-primary bg-primary/5": "border-border hover:bg-muted/50",!(updatingGeoLookup || isShowcase) && "cursor-pointer",@@ -1471,7 +1476,7 @@ export function BackendConfigDialog({<divclassName={cn("flex items-center gap-2 rounded-md border p-3 transition-all",- geoLookupConfig.provider === "local"+ selectedGeoLookupProvider === "local"? "border-primary bg-primary/5": "border-border hover:bg-muted/50",!geoLookupConfig.localMmdbReady &&diff --git a/apps/web/components/features/rules/interactive-rule-stats.tsx b/apps/web/components/features/rules/interactive-rule-stats.tsxindex 3e70e83..9cdfce8 100644--- a/apps/web/components/features/rules/interactive-rule-stats.tsx+++ b/apps/web/components/features/rules/interactive-rule-stats.tsx@@ -42,6 +42,7 @@ import { DomainExpandedDetails, IPExpandedDetails } from "@/components/features/import { useIsWindows } from "@/lib/hooks/use-is-windows";import { ExpandReveal } from "@/components/ui/expand-reveal";import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";+import { normalizeGeoIP } from "@neko-master/shared";import { UnifiedRuleChainFlow } from "@/components/features/rules/rule-chain-flow";import { InsightChartSkeleton, InsightDetailSectionSkeleton, InsightTableSkeleton, InsightThreePanelSkeleton } from "@/components/ui/insight-skeleton";import type { RuleStats, DomainStats, IPStats, StatsSummary } from "@neko-master/shared";@@ -1586,6 +1587,8 @@ export function InteractiveRuleStats({const isDesktopExpanded = expandedIP === ip.ip;const isMobileActive = mobileIPDetailsOpen && mobileIPDetail?.ip === ip.ip;const ipColor = getIPColor(ip.ip);+ const geo = normalizeGeoIP(ip.geoIP);+ const locationName = geo?.countryName || geo?.countryCode || null;return (<div key={ip.ip} className="group">@@ -1613,10 +1616,10 @@ export function InteractiveRuleStats({{/* Location */}<div className="col-span-2 flex items-center gap-1.5 min-w-0">- {ip.geoIP && ip.geoIP.length > 0 ? (+ {locationName ? (<>- <CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" title={ip.geoIP[1] || ip.geoIP[0]} />- <span className="text-xs whitespace-nowrap">{ip.geoIP[1] || ip.geoIP[0]}</span>+ <CountryFlag country={geo?.countryCode || "UN"} className="h-3.5 w-5" title={locationName} />+ <span className="text-xs whitespace-nowrap">{locationName}</span></>) : (<span className="text-xs text-muted-foreground">-</span>@@ -1682,10 +1685,10 @@ export function InteractiveRuleStats({</div><div className="flex-1 min-w-0"><code className="text-sm font-medium truncate block">{ip.ip}</code>- {ip.geoIP && ip.geoIP.length > 0 && (+ {locationName && (<div className="flex items-center gap-1.5 text-xs text-muted-foreground">- <CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" />- <span className="truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>+ <CountryFlag country={geo?.countryCode || "UN"} className="h-3.5 w-5" />+ <span className="truncate">{locationName}</span></div>)}</div>diff --git a/apps/web/components/features/rules/rule-chain-flow.tsx b/apps/web/components/features/rules/rule-chain-flow.tsxindex cadf5b0..36ba5cf 100644--- a/apps/web/components/features/rules/rule-chain-flow.tsx+++ b/apps/web/components/features/rules/rule-chain-flow.tsx@@ -35,7 +35,8 @@ import { useTheme } from "next-themes";import { api, type TimeRange } from "@/lib/api";import { useStatsWebSocket } from "@/lib/websocket";import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";-import { resolveActiveChains, type ActiveChainInfo } from "@/lib/active-chain";+import { useIsWindows } from "@/lib/hooks/use-is-windows";+import { resolveActiveChains, encodeActiveLinkKey, type ActiveChainInfo } from "@/lib/active-chain";import { useTranslations } from "next-intl";import type { StatsSummary } from "@neko-master/shared";import { useGatewayProviders, useGatewayProxies } from "@/hooks/api/use-gateway";@@ -186,6 +187,7 @@ const MergedChainNodeComponent = memo(function MergedChainNodeComponent({}: {data: MergedChainNode & { dimmed?: boolean };}) {+ const isWindows = useIsWindows();const dimmed = data.dimmed;const zeroTraffic = data._zeroTraffic;const wrapStyle: React.CSSProperties = {@@ -211,7 +213,11 @@ const MergedChainNodeComponent = memo(function MergedChainNodeComponent({<div className="w-7 h-7 rounded-lg flex items-center justify-center text-white bg-gradient-to-br from-emerald-400 to-emerald-600 shadow-sm"><Server className="h-4 w-4" /></div>- <span className="text-xs font-semibold truncate flex-1 text-emerald-800 dark:text-emerald-200 max-w-[120px]">+ <span+ className={cn(+ "text-xs font-semibold truncate flex-1 text-emerald-800 dark:text-emerald-200 max-w-[120px]",+ isWindows && "emoji-flag-font",+ )}>{data.name}</span></div>@@ -237,7 +243,11 @@ const MergedChainNodeComponent = memo(function MergedChainNodeComponent({<div className="w-7 h-7 rounded-lg flex items-center justify-center text-white bg-violet-500 shadow-sm"><Workflow className="h-4 w-4" /></div>- <span className="text-xs font-medium truncate flex-1 max-w-[120px]">+ <span+ className={cn(+ "text-xs font-medium truncate flex-1 max-w-[120px]",+ isWindows && "emoji-flag-font",+ )}>{data.name}</span></div>@@ -275,7 +285,11 @@ const MergedChainNodeComponent = memo(function MergedChainNodeComponent({<div className="w-7 h-7 rounded-lg flex items-center justify-center text-white bg-blue-500 shadow-sm"><Layers className="h-4 w-4" /></div>- <span className="text-xs font-medium truncate flex-1 max-w-[120px]">+ <span+ className={cn(+ "text-xs font-medium truncate flex-1 max-w-[120px]",+ isWindows && "emoji-flag-font",+ )}>{data.name}</span></div>@@ -1174,7 +1188,7 @@ function UnifiedRuleChainFlowInner({activePolicyOnly ||isRuleLink ||isServerKnownLink ||- activeLinkKeys.has(`${srcNode.name}|${tgtNode.name}`);+ activeLinkKeys.has(encodeActiveLinkKey(srcNode.name, tgtNode.name));if (shouldKeepLink) {const key = `${newSrc}-${newTgt}`;diff --git a/apps/web/components/features/stats/table/expanded-details.tsx b/apps/web/components/features/stats/table/expanded-details.tsxindex 549238b..b10d94c 100644--- a/apps/web/components/features/stats/table/expanded-details.tsx+++ b/apps/web/components/features/stats/table/expanded-details.tsx@@ -7,6 +7,7 @@ import { Favicon } from "@/components/common";import { DomainPreview } from "@/components/features/domains";import { getDomainColor, getIPGradient } from "@/lib/stats-utils";import { formatBytes, formatNumber } from "@/lib/utils";+import { normalizeGeoIP } from "@neko-master/shared";import type { DomainStats, IPStats, ProxyTrafficStats } from "@neko-master/shared";interface DomainExpandedDetailsProps {@@ -384,11 +385,9 @@ export function DomainExpandedDetails({) : ipDetails.length > 0 ? (<div className="space-y-2">{ipDetails.map((ipStat) => {- const country = ipStat.geoIP?.[0];- const location =- ipStat.geoIP && ipStat.geoIP.length > 1- ? ipStat.geoIP[1]- : ipStat.geoIP?.[0] || null;+ const geo = normalizeGeoIP(ipStat.geoIP);+ const country = geo?.countryCode;+ const location = geo?.countryName || geo?.countryCode || null;const ipTraffic = ipStat.totalDownload + ipStat.totalUpload;const percent = totalIPTraffic > 0 ? (ipTraffic / totalIPTraffic) * 100 : 0;const downloadPercent = ipTraffic > 0 ? (ipStat.totalDownload / ipTraffic) * 100 : 0;@@ -460,10 +459,11 @@ export function IPExpandedDetails({const domainsT = useTranslations("domains");const ipsT = useTranslations("ips");- const countryCode = ip.geoIP?.[0];- const countryName = ip.geoIP?.[1];- const city = ip.geoIP?.[2] || ipsT("unknown");- const asOrganization = ip.geoIP?.[3] || ipsT("unknown");+ const geo = normalizeGeoIP(ip.geoIP);+ const countryCode = geo?.countryCode;+ const countryName = geo?.countryName;+ const city = geo?.city || ipsT("unknown");+ const asOrganization = geo?.asOrganization || ipsT("unknown");const asnValue = ip.asn || ipsT("unknown");const hasLocation = Boolean(countryCode || countryName);const displayLocation = countryName || countryCode || ipsT("unknown");diff --git a/apps/web/components/features/stats/table/ip-preview.tsx b/apps/web/components/features/stats/table/ip-preview.tsxindex 1e1c9a8..f55b179 100644--- a/apps/web/components/features/stats/table/ip-preview.tsx+++ b/apps/web/components/features/stats/table/ip-preview.tsx@@ -7,10 +7,11 @@ import { Button } from "@/components/ui/button";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { CountryFlag } from "@/components/features/countries/country-flag";import { cn } from "@/lib/utils";+import { normalizeGeoIP, type GeoIPInfo } from "@neko-master/shared";interface IPPreviewProps {ip?: string | null;- geoIP?: string[] | null;+ geoIP?: GeoIPInfo | null;asn?: string | null;unknownLabel: string;unavailableLabel: string;@@ -45,10 +46,11 @@ export function IPPreview({const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const ipText = ip || unknownLabel;- const countryCode = geoIP?.[0];- const countryName = geoIP?.[1];- const city = geoIP?.[2] || unavailableLabel;- const asOrganization = geoIP?.[3] || unavailableLabel;+ const geo = normalizeGeoIP(geoIP);+ const countryCode = geo?.countryCode;+ const countryName = geo?.countryName;+ const city = geo?.city || unavailableLabel;+ const asOrganization = geo?.asOrganization || unavailableLabel;const asnValue = asn || unavailableLabel;const hasLocation = Boolean(countryCode || countryName);const displayLocation = countryName || countryCode || unavailableLabel;@@ -149,7 +151,7 @@ export function IPPreview({</p>{hasLocation ? (<span className="mt-1.5 flex min-w-0 items-center gap-1.5">- <CountryFlag country={countryCode || countryName || "UN"} className="h-3.5 w-5" />+ <CountryFlag country={countryCode || "UN"} className="h-3.5 w-5" /><span className="truncate text-sm font-medium leading-5">{displayLocation}</span></span>) : (diff --git a/apps/web/components/features/stats/table/ip-stats-table.tsx b/apps/web/components/features/stats/table/ip-stats-table.tsxindex 88e9110..b9c3feb 100644--- a/apps/web/components/features/stats/table/ip-stats-table.tsx+++ b/apps/web/components/features/stats/table/ip-stats-table.tsx@@ -49,6 +49,7 @@ import {type IPSortKey,type SortOrder,} from "@/lib/stats-utils";+import { normalizeGeoIP } from "@neko-master/shared";import type { IPStats } from "@neko-master/shared";const DETAIL_QUERY_STALE_MS = 30_000;@@ -333,6 +334,8 @@ export function IPStatsTable({{paginatedIPs.map((ip) => {const isDesktopExpanded = expandedIP === ip.ip;const isMobileActive = mobileDetailsOpen && mobileDetailIP?.ip === ip.ip;+ const geo = normalizeGeoIP(ip.geoIP);+ const locationName = geo?.countryName || geo?.countryCode || null;return (<div key={ip.ip} className="group">@@ -371,10 +374,10 @@ export function IPStatsTable({)}<div className={cn(locationColumnClass, "flex items-center gap-1.5 min-w-0")}>- {ip.geoIP && ip.geoIP.length > 0 ? (+ {locationName ? (<>- <CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" title={ip.geoIP[1] || ip.geoIP[0]} />- <span className="text-xs whitespace-nowrap">{ip.geoIP[1] || ip.geoIP[0]}</span>+ <CountryFlag country={geo?.countryCode || "UN"} className="h-3.5 w-5" title={locationName} />+ <span className="text-xs whitespace-nowrap">{locationName}</span></>) : (<span className="text-xs text-muted-foreground">-</span>@@ -467,10 +470,10 @@ export function IPStatsTable({</div><div className="flex items-center gap-2 mb-2 pl-[30px] flex-wrap">- {ip.geoIP && ip.geoIP.length > 0 && (+ {locationName && (<span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground">- <CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" />- <span className="truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>+ <CountryFlag country={geo?.countryCode || "UN"} className="h-3.5 w-5" />+ <span className="truncate">{locationName}</span></span>)}{showProxyColumn && ip.chains && ip.chains.length > 0 && (diff --git a/apps/web/components/features/stats/table/ip-table.tsx b/apps/web/components/features/stats/table/ip-table.tsxindex d657b12..645672c 100644--- a/apps/web/components/features/stats/table/ip-table.tsx+++ b/apps/web/components/features/stats/table/ip-table.tsx@@ -33,6 +33,7 @@ import type { IPStats, StatsSummary } from "@neko-master/shared";import { api, type TimeRange } from "@/lib/api";import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";import { useStatsWebSocket } from "@/lib/websocket";+import { normalizeGeoIP } from "@neko-master/shared";import {getIPDomainDetailsQueryKey,getIPProxyStatsQueryKey,@@ -430,6 +431,8 @@ export function IPsTable({const ipColor = getIPColor(ip.ip);const isDesktopExpanded = expandedIP === ip.ip;const isMobileActive = mobileDetailsOpen && mobileDetailIP?.ip === ip.ip;+ const geo = normalizeGeoIP(ip.geoIP);+ const locationName = geo?.countryName || geo?.countryCode || null;return (<div key={ip.ip} className="group">@@ -471,11 +474,11 @@ export function IPsTable({{/* Location */}<div className="col-span-2 flex items-center min-w-0">- {ip.geoIP && ip.geoIP.length > 0 ? (+ {locationName ? (<div className="flex items-center gap-1.5 min-w-0">- <CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" title={ip.geoIP[1] || ip.geoIP[0]} />+ <CountryFlag country={geo?.countryCode || "UN"} className="h-3.5 w-5" title={locationName} /><span className="text-xs whitespace-nowrap">- {ip.geoIP[1] || ip.geoIP[0]}+ {locationName}</span></div>) : (@@ -585,11 +588,11 @@ export function IPsTable({{/* Row 2: Location + Proxy tag */}<div className="flex items-center gap-2 mb-2 pl-[30px] flex-wrap">- {ip.geoIP && ip.geoIP.length > 0 && (+ {locationName && (<span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground">- <CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" />+ <CountryFlag country={geo?.countryCode || "UN"} className="h-3.5 w-5" /><span className="truncate">- {ip.geoIP[1] || ip.geoIP[0]}+ {locationName}</span></span>)}diff --git a/apps/web/lib/active-chain.ts b/apps/web/lib/active-chain.tsindex ac45379..4fd758d 100644--- a/apps/web/lib/active-chain.ts+++ b/apps/web/lib/active-chain.ts@@ -1,10 +1,14 @@import type { GatewayProvidersResponse, GatewayRulesResponse, GatewayProxiesResponse } from "./api";import { parseGatewayRule } from "@neko-master/shared";+export function encodeActiveLinkKey(sourceName: string, targetName: string): string {+ return JSON.stringify([sourceName, targetName]);+}+export interface ActiveChainInfo {/** Set of node names that are part of active chains */activeNodeNames: Set<string>;- /** Set of "sourceName|targetName" keys for active links */+ /** Set of encoded [sourceName, targetName] keys for active links */activeLinkKeys: Set<string>;/** Map from proxy group name to its full active chain path */activeChains: Map<string, string[]>;@@ -89,7 +93,7 @@ export function resolveActiveChains(activeNodeNames.add(name);}for (let i = 0; i < chain.length - 1; i++) {- activeLinkKeys.add(`${chain[i]}|${chain[i+1]}`);+ activeLinkKeys.add(encodeActiveLinkKey(chain[i], chain[i + 1]));}return chain;};@@ -121,7 +125,7 @@ export function resolveActiveChains(activeNodeNames.add(ruleName);if (groupChain.length > 0) {- activeLinkKeys.add(`${ruleName}|${groupChain[0]}`);+ activeLinkKeys.add(encodeActiveLinkKey(ruleName, groupChain[0]));}}}diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.tsindex 20bfd96..b8d4881 100644--- a/apps/web/lib/api.ts+++ b/apps/web/lib/api.ts@@ -175,6 +175,8 @@ export type GeoLookupProvider = "online" | "local";export interface GeoLookupConfig {provider: GeoLookupProvider;+ configuredProvider: GeoLookupProvider;+ effectiveProvider: GeoLookupProvider;mmdbDir: string;onlineApiUrl: string;localMmdbReady: boolean;@@ -194,6 +196,8 @@ const DEFAULT_RETENTION_CONFIG = {const DEFAULT_GEO_LOOKUP_CONFIG: GeoLookupConfig = {provider: "online",+ configuredProvider: "online",+ effectiveProvider: "online",mmdbDir: "geoip",onlineApiUrl: "https://api.ipinfo.es/ipinfo",localMmdbReady: false,diff --git a/package.json b/package.jsonindex 053b823..cf8fef5 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "neko-master",- "version": "1.2.9",+ "version": "1.3.0","description": "Modern traffic analytics for edge gateways","private": true,"workspaces": [diff --git a/packages/shared/src/geo-ip-utils.ts b/packages/shared/src/geo-ip-utils.tsnew file mode 100644index 0000000..734843b--- /dev/null+++ b/packages/shared/src/geo-ip-utils.ts@@ -0,0 +1,72 @@+export interface GeoIPInfo {+ countryCode: string;+ countryName: string;+ city: string;+ asOrganization: string;+}++type GeoIPLike =+ | GeoIPInfo+ | readonly unknown[]+ | Record<string, unknown>+ | null+ | undefined;++export function normalizeGeoIP(geoIP: unknown): GeoIPInfo | null {+ const value = geoIP as GeoIPLike;+ if (!value) return null;++ if (Array.isArray(value)) {+ const [countryCode, countryName, city, asOrganization] = value;+ const code = typeof countryCode === "string" ? countryCode : "";+ const name = typeof countryName === "string" ? countryName : code;+ const cityName = typeof city === "string" ? city : "";+ const org = typeof asOrganization === "string" ? asOrganization : "";+ if (!code && !name && !cityName && !org) {+ return null;+ }+ return {+ countryCode: code,+ countryName: name,+ city: cityName,+ asOrganization: org,+ };+ }++ const row = value as Partial<GeoIPInfo> & {+ country?: unknown;+ country_name?: unknown;+ as_name?: unknown;+ };++ const countryCode =+ typeof row.countryCode === "string"+ ? row.countryCode+ : typeof row.country === "string"+ ? row.country+ : "";+ const countryName =+ typeof row.countryName === "string"+ ? row.countryName+ : typeof row.country_name === "string"+ ? row.country_name+ : countryCode;+ const city = typeof row.city === "string" ? row.city : "";+ const asOrganization =+ typeof row.asOrganization === "string"+ ? row.asOrganization+ : typeof row.as_name === "string"+ ? row.as_name+ : "";++ if (!countryCode && !countryName && !city && !asOrganization) {+ return null;+ }++ return {+ countryCode,+ countryName,+ city,+ asOrganization,+ };+}diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex f1343b5..382300b 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -1,3 +1,5 @@+import type { GeoIPInfo } from "./geo-ip-utils.js";+// Gateway Connection Metadataexport interface ConnectionMetadata {network: string;@@ -65,7 +67,7 @@ export interface IPStats {totalConnections: number;lastSeen: string;asn?: string;- geoIP?: string[];+ geoIP?: GeoIPInfo;chains?: string[];}@@ -316,3 +318,4 @@ export type BackendType = 'clash' | 'surge';// Gateway utilitiesexport * from './gateway-utils.js';+export * from './geo-ip-utils.js';