A modern and elegant dashboard for network traffic visualization and analysis.
feat: Implement geo-IP lookup functionality and enhance IP stats table with a mobile-friendly detail drawer.
luolei161454475fc6
diff --git a/.env.example b/.env.exampleindex f8ee285..3e495f3 100644--- a/.env.example+++ b/.env.example@@ -35,6 +35,18 @@ WS_EXTERNAL_PORT=3002# 可使用 openssl rand -hex 32 生成# COOKIE_SECRET=+# -----------------------------------------------------------------------------+# IP 地理查询配置(可选)+# -----------------------------------------------------------------------------+# 可选值:online / local+# online: 使用线上接口(默认)+# local: 使用本地 MMDB 文件查询+# GEOIP_LOOKUP_PROVIDER=online++# 线上 IP 查询接口地址(仅支持与默认 ipinfo.my 响应结构兼容的服务)+# 非兼容接口可能导致查询失败或字段为空+# GEOIP_ONLINE_API_URL=https://api.ipinfo.es/ipinfo+# -----------------------------------------------------------------------------# 高级配置(一般不需要修改)# -----------------------------------------------------------------------------diff --git a/.gitignore b/.gitignoreindex 0d3fa12..bcaed76 100644--- a/.gitignore+++ b/.gitignore@@ -23,6 +23,7 @@ out/*.db-shm*.sqlite*.sqlite3+geoip/# Logslogs/diff --git a/README.en.md b/README.en.mdindex 1334e3d..d5298f5 100644--- a/README.en.md+++ b/README.en.md@@ -112,6 +112,8 @@ services:- "3000:3000" # Web UIvolumes:- ./data:/app/data+ # Local MMDB (optional, files should be downloaded into ./geoip)+ - ./geoip:/app/data/geoip:roenvironment:- NODE_ENV=production- DB_PATH=/app/data/stats.db@@ -137,6 +139,8 @@ services:- "3002:3002" # WebSocket (for Nginx / Tunnel forwarding)volumes:- ./data:/app/data+ # Local MMDB (optional, files should be downloaded into ./geoip)+ - ./geoip:/app/data/geoip:roenvironment:- NODE_ENV=production- DB_PATH=/app/data/stats.db@@ -188,6 +192,9 @@ Open <http://localhost:3000> to get started.> For `docker run`, change external ports using `-p` mappings directly.> Only if you use direct WS access (no reverse proxy) and external WS port is not `3002`, also pass `-e WS_EXTERNAL_PORT=<external-ws-port>`.+>+> Local MMDB lookup mode (optional): mount `-v $(pwd)/geoip:/app/data/geoip:ro`,+> then switch source to Local in `Settings -> Preferences -> IP Lookup Source`.### Option 3: One-Click Script@@ -356,6 +363,8 @@ The script will automatically detect and suggest available ports.| `NEXT_PUBLIC_WS_PORT` | `3002` | WS direct-connection fallback port (build-time exposed) | Direct WS mode needs explicit port || `API_URL` | `http://localhost:3001` | Next.js `/api` rewrite target (mainly source/custom builds) | API listen address changed || `COOKIE_SECRET` | auto-generated | Cookie signing secret; if not fixed, sessions can be invalidated after restart when data dir is not persisted | Strongly recommended in production |+| `GEOIP_LOOKUP_PROVIDER` | `online` | IP geolocation source (`online` / `local`) | Default to local MMDB lookup |+| `GEOIP_ONLINE_API_URL` | `https://api.ipinfo.es/ipinfo` | Online IP geolocation API endpoint (must be compatible with `ipinfo.my` response schema) | Set only when you deploy a compatible endpoint || `FORCE_ACCESS_CONTROL_OFF` | `false` | Force disable access control (emergency recovery) | Temporary use only when token is lost || `SHOWCASE_SITE_MODE` | `false` | Read-only showcase mode (blocks sensitive write operations) | Public demo sites only |@@ -388,6 +397,8 @@ The script will automatically detect and suggest available ports.NODE_ENV=productionDB_PATH=/app/data/stats.dbCOOKIE_SECRET=<at least 32-byte random string>+# Optional: default to local MMDB lookup+# GEOIP_LOOKUP_PROVIDER=local# Keep false in normal operation# FORCE_ACCESS_CONTROL_OFF=false```@@ -399,6 +410,10 @@ Additional recommendations:1. Mount persistent storage (for example `./data:/app/data`) to avoid data and secret loss.2. If using direct WS access and external WS port is not `3002`, set `WS_EXTERNAL_PORT` accordingly.3. If API port/address changes in source deployment, update `API_URL` as well.+4. For local MMDB lookup, mount `./geoip:/app/data/geoip:ro` and switch source in `Settings -> Preferences -> IP Lookup Source`.+5. MMDB files are large and are not bundled in the image. Download and place them in `./geoip` with fixed names:+ `GeoLite2-City.mmdb`, `GeoLite2-ASN.mmdb` (required), and `GeoLite2-Country.mmdb` (optional).+ Recommended source: <https://github.com/P3TERX/GeoLite.mmdb>.## 🌐 Reverse Proxy & Tunnel@@ -601,6 +616,18 @@ docker compose up -d1. Set a fixed `COOKIE_SECRET`2. Mount `./data:/app/data`+### Q: Which files are required for local MMDB lookup?++**A:** Create `./geoip` in your project directory (same level as `docker-compose.yml` is recommended), then place:++1. `GeoLite2-City.mmdb` (required)+2. `GeoLite2-ASN.mmdb` (required)+3. `GeoLite2-Country.mmdb` (optional)++Recommended source: <https://github.com/P3TERX/GeoLite.mmdb>.+Inside the container, the fixed lookup path is `/app/data/geoip`, so keep:+`./geoip:/app/data/geoip:ro`. To update later, just replace files in host `./geoip`.+### Q: Failed to connect OpenClash / gateway?**A:** Check:diff --git a/README.md b/README.mdindex ae89344..c73100b 100644--- a/README.md+++ b/README.md@@ -104,6 +104,8 @@ services:- "3000:3000" # Web UIvolumes:- ./data:/app/data+ # 本地 MMDB(可选,文件需自行下载并放到 ./geoip)+ - ./geoip:/app/data/geoip:roenvironment:- NODE_ENV=production- DB_PATH=/app/data/stats.db@@ -129,6 +131,8 @@ services:- "3002:3002" # WebSocket(供 Nginx / Tunnel 转发)volumes:- ./data:/app/data+ # 本地 MMDB(可选,文件需自行下载并放到 ./geoip)+ - ./geoip:/app/data/geoip:roenvironment:- NODE_ENV=production- DB_PATH=/app/data/stats.db@@ -180,6 +184,9 @@ docker run -d \> `docker run` 修改外部端口时,直接改 `-p` 映射即可。> 仅在“非反代直连 WS 且外部 WS 端口不是 3002”时,额外传入 `-e WS_EXTERNAL_PORT=<外部WS端口>`。+>+> 本地 MMDB 查询模式(可选):额外挂载 `-v $(pwd)/geoip:/app/data/geoip:ro`,+> 并在面板「设置 -> 偏好设置 -> IP 查询来源」切换到本地。### 方式三:一键脚本@@ -347,6 +354,8 @@ curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh || `NEXT_PUBLIC_WS_PORT` | `3002` | WS 直连端口兜底值(构建时注入) | 非反代直连 WS 且需显式指定端口时 || `API_URL` | `http://localhost:3001` | Next.js `/api` rewrite 目标(主要用于源码/自构建) | 你修改了 API 实际监听地址时 || `COOKIE_SECRET` | 自动生成 | Cookie 签名密钥;未固定时会自动生成(数据目录不持久化时重启后会话会失效) | 生产环境强烈建议固定配置 |+| `GEOIP_LOOKUP_PROVIDER` | `online` | IP 地理查询来源(`online`/`local`) | 需要默认走本地 MMDB 查询时 |+| `GEOIP_ONLINE_API_URL` | `https://api.ipinfo.es/ipinfo` | 在线 IP 查询接口地址(需兼容 `ipinfo.my` 的响应结构) | 仅在你部署了兼容接口时设置 || `FORCE_ACCESS_CONTROL_OFF` | `false` | 强制关闭访问控制(紧急恢复) | 仅忘记密码临时使用 || `SHOWCASE_SITE_MODE` | `false` | 演示只读模式(禁用敏感写操作) | 仅公开演示站点 |@@ -379,6 +388,8 @@ curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh |NODE_ENV=productionDB_PATH=/app/data/stats.dbCOOKIE_SECRET=<至少32字节随机字符串>+# 可选:默认切换到本地 MMDB 查询+# GEOIP_LOOKUP_PROVIDER=local# 仅紧急恢复时临时开启,平时不要保留 true# FORCE_ACCESS_CONTROL_OFF=false```@@ -390,6 +401,10 @@ COOKIE_SECRET=<至少32字节随机字符串>1. 挂载持久化目录(如 `./data:/app/data`),避免数据库与自动生成密钥丢失。2. 如果外部直连 WS 且端口非 `3002`,务必同步设置 `WS_EXTERNAL_PORT`。3. 若源码部署修改了 API 端口或地址,记得同步设置 `API_URL`。+4. 如需本地 MMDB 查询:挂载 `./geoip:/app/data/geoip:ro`,并在面板「设置 -> 偏好设置 -> IP 查询来源」切换为本地。+5. MMDB 文件体积较大,项目镜像不内置数据库。请自行下载并放入 `./geoip`,文件名固定为:+ `GeoLite2-City.mmdb`、`GeoLite2-ASN.mmdb`(必需),`GeoLite2-Country.mmdb`(可选)。+ 推荐来源:<https://github.com/P3TERX/GeoLite.mmdb>。## 🌐 反向代理与 Tunnel@@ -592,6 +607,18 @@ docker compose up -d1. 设置固定 `COOKIE_SECRET`2. 挂载 `./data:/app/data`+### Q: 本地 MMDB 查询要准备哪些文件?++**A:** 建议在项目目录创建 `./geoip`(可与 `docker-compose.yml` 同级),然后放置以下文件:++1. `GeoLite2-City.mmdb`(必需)+2. `GeoLite2-ASN.mmdb`(必需)+3. `GeoLite2-Country.mmdb`(可选)++推荐下载源:<https://github.com/P3TERX/GeoLite.mmdb>。+容器内固定读取目录是 `/app/data/geoip`,因此建议保持挂载:+`./geoip:/app/data/geoip:ro`。后续你只需替换宿主机 `./geoip` 里的文件即可完成更新。+### Q: 连接 OpenClash / 网关失败?**A:** 检查以下几点:diff --git a/README_EN.md b/README_EN.mdindex 1334e3d..a94bea4 100644--- a/README_EN.md+++ b/README_EN.md@@ -1,707 +1,5 @@-<p align="center">- <img src="./assets/icon-neko-master.png" width="200" alt="Neko Master Logo" style="margin-bottom: 16px;">- <br>- <b style="font-size: 32px;">Neko Master</b>-</p>+# English README-<p align="center">- <b>See your network traffic clearly.</b><br>- <span>Real-time monitoring · Traffic auditing · Multi-gateway support</span>-</p>+The maintained English documentation is in [`README.en.md`](./README.en.md).-<p align="center">- <b>English</b> | <a href="./README.md">中文</a>-</p>--<p align="center">- <a href="https://github.com/foru17/neko-master/stargazers"><img src="https://img.shields.io/github/stars/foru17/neko-master?style=flat-square&color=yellow" alt="Stars"></a>- <a href="https://hub.docker.com/r/foru17/neko-master"><img src="https://img.shields.io/docker/pulls/foru17/neko-master?style=flat-square&color=blue&logo=docker" alt="Docker Pulls"></a>- <a href="https://hub.docker.com/r/foru17/neko-master"><img src="https://img.shields.io/docker/v/foru17/neko-master?style=flat-square&label=Docker&color=2496ED" alt="Docker Version"></a>- <a href="https://hub.docker.com/r/foru17/neko-master"><img src="https://img.shields.io/docker/image-size/foru17/neko-master/latest?style=flat-square&logo=docker" alt="Image Size"></a>- <a href="https://github.com/foru17/neko-master/blob/main/LICENSE"><img src="https://img.shields.io/github/license/foru17/neko-master?style=flat-square&color=green" alt="License"></a>- <img src="https://img.shields.io/badge/Node.js-22-339933?style=flat-square&logo=node.js">- <a href="https://github.com/foru17/neko-master/actions/workflows/docker-build.yml"><img src="https://img.shields.io/github/actions/workflow/status/foru17/neko-master/docker-build.yml?style=flat-square&label=Docker%20CI" alt="Docker CI"></a>- <a href="./docs/architecture.md"><img src="https://img.shields.io/badge/docs-architecture-0ea5e9?style=flat-square" alt="Architecture Docs"></a>-</p>--> [!IMPORTANT]-> **Disclaimer**->-> This project is a traffic analysis and visualization tool-> for local gateway environments.->-> It does not provide any network access service,-> proxy subscription, or cross-network connectivity.-> All data is collected from the user's own network environment.->-> This project is open-sourced under the MIT License. We assume no responsibility for any consequences resulting from the use of this software. Please use it in compliance with applicable laws and regulations.--<table>- <tr>- <td align="center" width="50%">- <img src="./assets/neko-master-overview-light.png" alt="Neko Master Preview (Light 1)" />- </td>- <td align="center" width="50%">- <img src="./assets/neko-master-regions-light.png" alt="Neko Master Preview (Light 2)" />- </td>- </tr>- <tr>- <td align="center" width="50%">- <img src="./assets/neko-master-rules-dark.png" alt="Neko Master Preview (Dark 1)" />- </td>- <td align="center" width="50%">- <img src="./assets/neko-master-domains-dark.png" alt="Neko Master Preview (Dark 2)" />- </td>- </tr>-</table>--## About the Name--**Neko** (ねこ) means _cat_ in Japanese.-Pronounced **/ˈneɪkoʊ/** (NEH-ko).--Like a cat, Neko Master observes network traffic quietly and precisely.-It is a lightweight analytics dashboard designed for modern gateway environments.--## 📋 Table of Contents--- [✨ Features](#-features)-- [🚀 Quick Start](#-quick-start)-- [📖 First Use](#-first-use)-- [🔧 Port Conflict Resolution](#-port-conflict-resolution)-- [🐳 Docker Configuration](#-docker-configuration)-- [🌐 Reverse Proxy & Tunnel](#-reverse-proxy--tunnel)-- [🔐 Authentication & Security](#-authentication--security)-- [❓ FAQ](#-faq)-- [🏗️ Architecture Guide](#-architecture-guide)-- [🤝 Feedback & Issues](#-feedback--issues)-- [📁 Project Structure](#-project-structure)-- [🛠️ Tech Stack](#-tech-stack)-- [📄 License](#-license)--## ✨ Features--| Feature | Description |-| --------------------------- | ------------------------------------------------------------- |-| 📊 **Real-time Monitoring** | WebSocket real-time collection with millisecond latency |-| 📈 **Trend Analysis** | Multi-dimensional traffic trends: 30min / 1h / 24h |-| 🌐 **Domain Analysis** | View traffic, associated IPs, and connection count per domain |-| 🗺️ **IP Analysis** | ASN, geo-location, and associated domain display |-| 🚀 **Proxy Statistics** | Traffic distribution and connection count per proxy node |-| 📱 **PWA Support** | Install as desktop app for native experience |-| 🌙 **Dark Mode** | Light / Dark / System theme support |-| 🌍 **i18n Support** | English / Chinese seamless switching |-| 🔄 **Multi-Backend** | Monitor multiple OpenClash backend instances simultaneously |--## 🚀 Quick Start--### Option 1: Docker Compose (Recommended)--> The repository's built-in `docker-compose.yml` maps `3000/3001/3002` by default.-> Scenarios A/B below are minimal templates for common deployments.--#### Scenario A: Minimal deployment (only expose 3000)--```yaml-services:- neko-master:- image: foru17/neko-master:latest- container_name: neko-master- restart: unless-stopped- ports:- - "3000:3000" # Web UI- volumes:- - ./data:/app/data- environment:- - NODE_ENV=production- - DB_PATH=/app/data/stats.db- - COOKIE_SECRET=${COOKIE_SECRET}-```--> Recommended in `.env` (same directory as `docker-compose.yml`):-> `COOKIE_SECRET=<at least 32-byte random string>` (generate with `openssl rand -hex 32`)--> This mode is fully upgrade-compatible and works out of the box.-> If WS is not routed, the app falls back to HTTP polling automatically.--#### Scenario B: Real-time WebSocket (recommended with reverse proxy)--```yaml-services:- neko-master:- image: foru17/neko-master:latest- container_name: neko-master- restart: unless-stopped- ports:- - "3000:3000" # Web UI- - "3002:3002" # WebSocket (for Nginx / Tunnel forwarding)- volumes:- - ./data:/app/data- environment:- - NODE_ENV=production- - DB_PATH=/app/data/stats.db- - COOKIE_SECRET=${COOKIE_SECRET}-```--Then run:--```bash-docker compose up -d-```--Open <http://localhost:3000> to get started.--If you use the repository's built-in Compose file (default `3000/3001/3002`), run the same command.--### Option 2: Docker Run--```bash-# Generate a fixed cookie secret first (for session persistence)-export COOKIE_SECRET="$(openssl rand -hex 32)"-```--```bash-# Minimal (only 3000)-docker run -d \- --name neko-master \- -p 3000:3000 \- -v $(pwd)/data:/app/data \- -e COOKIE_SECRET="$COOKIE_SECRET" \- --restart unless-stopped \- foru17/neko-master:latest--# Real-time WS (with reverse proxy)-docker run -d \- --name neko-master \- -p 3000:3000 \- -p 3002:3002 \- -v $(pwd)/data:/app/data \- -e COOKIE_SECRET="$COOKIE_SECRET" \- --restart unless-stopped \- foru17/neko-master:latest-```--Open <http://localhost:3000> to get started.--> The frontend uses same-origin `/api` by default, so port 3001 is usually not required externally.-> For real-time WS, your reverse proxy/tunnel must be able to reach port `3002`. If not, the app falls back to ~5s HTTP polling.--> For `docker run`, change external ports using `-p` mappings directly.-> Only if you use direct WS access (no reverse proxy) and external WS port is not `3002`, also pass `-e WS_EXTERNAL_PORT=<external-ws-port>`.--### Option 3: One-Click Script--Automatically detects port conflicts and configures everything:--```bash-# Using curl-curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash--# Or using wget-wget -qO- https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash-```--The script will automatically:--- ✅ Download `docker-compose.yml`-- ✅ Check if default ports (3000/3001/3002) are in use-- ✅ Suggest available alternative ports-- ✅ Create configuration file and start the service--### Option 4: Source Code--```bash-# 1. Clone the repository-git clone https://github.com/foru17/neko-master.git-cd neko-master--# 2. Install dependencies-pnpm install--# 3. Prepare collector env (source mode reads apps/collector/.env)-cp apps/collector/.env.example apps/collector/.env--# 4. Start development services-pnpm dev-```--Open <http://localhost:3000> to configure.--> In source mode: collector listens on `3001/3002`, web listens on `3000` by default.-> If you changed `API_PORT` (not 3001), set `API_URL` accordingly (for example `API_URL=http://localhost:4001`) so web `/api` rewrite targets the correct API.-> `apps/collector/.env.local` takes precedence over `apps/collector/.env`.--## 📖 First Use----### Connect Clash / Mihomo--1. Open <http://localhost:3000>-2. The **Gateway Configuration** dialog will appear on first visit-3. Fill in your network gateway (e.g., OpenClash) connection info:- - **Name**: Custom name (e.g., "Home Gateway")- - **Type**: Select `Clash / Mihomo`- - **Host**: Gateway backend address (e.g., `192.168.101.1`)- - **Port**: Gateway backend port (e.g., `9090`)- - **Token**: Fill if Secret is configured, otherwise leave empty-4. Click "Add Backend" to save-5. The system will automatically start collecting and analyzing traffic data--> 💡 **Get Gateway Address**: Go to your gateway control panel (e.g., OpenClash) → Enable "External Control" → Copy API address--### Connect Surge----Neko Master supports connecting to Surge gateways for complete rule chain visualization and traffic analysis.--#### 1. Enable Surge HTTP API--Enable HTTP remote API in your Surge configuration:--```ini-[General]-http-api = 127.0.0.1:9091-http-api-tls = false-http-api-web-dashboard = true-```--Or configure via Surge's graphical interface:--- **HTTP Remote API**: `Settings` → `General` → `HTTP Remote API`-- **Port**: Default `9091`-- **Authentication**: Recommended to set a password for enhanced security--#### 2. Add Surge Backend in Neko Master--1. Open Neko Master settings dialog-2. Click "Add Backend"-3. Fill in the connection info:- - **Name**: Custom name (e.g., "Surge Home")- - **Type**: Select `Surge`- - **Host**: IP address where Surge is running (e.g., `192.168.1.1` or `127.0.0.1`)- - **Port**: HTTP API port (default `9091`)- - **Token**: HTTP API password (if configured)-4. Click "Test Connection" to verify the configuration-5. Save the configuration--> 💡 **Note**: Surge uses HTTP polling to fetch data (compared to Clash's WebSocket real-time stream), with a data refresh delay of approximately 2 seconds.--## 🔧 Port Conflict Resolution--If you see "port already in use" error, here are the solutions:--### Solution 1: Use .env File--Create a `.env` file in the same directory as `docker-compose.yml`:--```env-WEB_EXTERNAL_PORT=8080 # Change Web UI port-API_EXTERNAL_PORT=8081 # Change API port-WS_EXTERNAL_PORT=8082 # Change WebSocket external port (only for direct access)-COOKIE_SECRET=your-long-random-secret # Strongly recommended to keep fixed-```--Then restart:--```bash-docker compose down-docker compose up -d-```--Now access <http://localhost:8080>--### Solution 2: Directly Modify docker-compose.yml--```yaml-ports:- - "8080:3000" # External 8080 → Internal 3000- - "8082:3002" # External 8082 → Internal 3002 (for proxy/tunnel WS forwarding)-```--> Note: if you use direct WS access (no reverse proxy) and external WS port is not `3002`, set `WS_EXTERNAL_PORT=<external-ws-port>`.--### Solution 3: Use One-Click Script--```bash-curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash-```--The script will automatically detect and suggest available ports.--## 🐳 Docker Configuration--### Ports--| Port | Purpose | External Required | Description |-| :--: | :-------: | :---------------: | :---------------------------------------------------------------------------------------------------------- |-| 3000 | Web UI | ✅ | Frontend entry point |-| 3001 | API | Optional | Frontend uses same-origin `/api` by default; usually no public exposure needed (default Compose maps it) |-| 3002 | WebSocket | Optional | Real-time push endpoint; recommended for reverse proxy/tunnel forwarding only (default Compose maps it) |--### Environment Variables (Deployment)--| Variable | Default | Purpose | When to set |-| :-- | :-- | :-- | :-- |-| `WEB_PORT` | `3000` | Web listen port (inside container) | Usually unchanged |-| `API_PORT` | `3001` | API listen port (inside container) | Usually unchanged |-| `COLLECTOR_WS_PORT` | `3002` | WS listen port (inside container) | Usually unchanged |-| `DB_PATH` | `/app/data/stats.db` | SQLite data path | Custom data path |-| `WEB_EXTERNAL_PORT` | `3000` | External web port mapping in `docker-compose.yml` | External web port changed |-| `API_EXTERNAL_PORT` | `3001` | External API port mapping in `docker-compose.yml` | Direct external API access needed |-| `WS_EXTERNAL_PORT` | `3002` | External WS port mapping in `docker-compose.yml`; also used for direct WS port inference | Direct WS access without proxy and external WS port changed |-| `NEXT_PUBLIC_API_URL` | empty | Override frontend API base URL (e.g. `https://api.example.com`) | API is not same-origin `/api` |-| `NEXT_PUBLIC_WS_URL` | empty | Override frontend WS URL (absolute URL or `/custom_ws`) | Custom WS path/domain |-| `NEXT_PUBLIC_WS_PORT` | `3002` | WS direct-connection fallback port (build-time exposed) | Direct WS mode needs explicit port |-| `API_URL` | `http://localhost:3001` | Next.js `/api` rewrite target (mainly source/custom builds) | API listen address changed |-| `COOKIE_SECRET` | auto-generated | Cookie signing secret; if not fixed, sessions can be invalidated after restart when data dir is not persisted | Strongly recommended in production |-| `FORCE_ACCESS_CONTROL_OFF` | `false` | Force disable access control (emergency recovery) | Temporary use only when token is lost |-| `SHOWCASE_SITE_MODE` | `false` | Read-only showcase mode (blocks sensitive write operations) | Public demo sites only |--### Advanced Tuning Variables (Optional)--| Variable | Default | Description |-| :-- | :-- | :-- |-| `FLUSH_INTERVAL_MS` | `30000` | Buffer flush interval for collector writes |-| `FLUSH_MAX_BUFFER_SIZE` | `5000` | Max buffer entries before early flush |-| `REALTIME_MAX_MINUTES` | `180` | Realtime in-memory window size (minutes) |-| `REALTIME_RANGE_END_TOLERANCE_MS` | `120000` | End-time tolerance for range queries |-| `SURGE_POLICY_SYNC_INTERVAL_MS` | `600000` | Surge policy sync interval |-| `DB_RANGE_QUERY_CACHE_TTL_MS` | `8000` | Range-query cache TTL |-| `DB_HISTORICAL_QUERY_CACHE_TTL_MS` | `300000` | Historical-query cache TTL |-| `DB_RANGE_QUERY_CACHE_MAX_ENTRIES` | `1024` | Max range-query cache entries |-| `DB_RANGE_QUERY_CACHE_DISABLED` | empty | Set `1` to disable range-query cache |-| `DEBUG_SURGE` | `false` | Enable Surge collector debug logs (`true`) |--### API / WS Resolution Priority--1. API client base: `runtime-config.API_URL` → `NEXT_PUBLIC_API_URL` → same-origin `/api`-2. `/api` server-side rewrite target: `API_URL` (default `http://localhost:3001`, applied in Next.js rewrites)-3. WS URL: `runtime-config.WS_URL` → `NEXT_PUBLIC_WS_URL` → auto candidates (production prefers `/_cm_ws`, then direct port fallback)-4. WS port: `runtime-config.WS_PORT` (from `WS_EXTERNAL_PORT`) → `NEXT_PUBLIC_WS_PORT` → `3002`-5. In normal deployments, `NEXT_PUBLIC_WS_URL` is usually unnecessary unless you use a custom WS path/domain--### Production Environment Baseline (Recommended)--```env-NODE_ENV=production-DB_PATH=/app/data/stats.db-COOKIE_SECRET=<at least 32-byte random string>-# Keep false in normal operation-# FORCE_ACCESS_CONTROL_OFF=false-```--Use `openssl rand -hex 32` to generate `COOKIE_SECRET`.--Additional recommendations:--1. Mount persistent storage (for example `./data:/app/data`) to avoid data and secret loss.-2. If using direct WS access and external WS port is not `3002`, set `WS_EXTERNAL_PORT` accordingly.-3. If API port/address changes in source deployment, update `API_URL` as well.--## 🌐 Reverse Proxy & Tunnel--Recommended approach: keep Web and WS under the same domain, with path routing:-`/` → `3000`, `/_cm_ws` → `3002`.--### Nginx Standard Example--```nginx-server {- listen 443 ssl http2;- server_name neko.example.com;-- location / {- proxy_pass http://<neko-master-host>:3000;- proxy_http_version 1.1;- proxy_set_header Host $host;- proxy_set_header X-Real-IP $remote_addr;- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;- proxy_set_header X-Forwarded-Proto $scheme;- }-- location ^~ /_cm_ws {- proxy_pass http://<neko-master-host>:3002;- proxy_http_version 1.1;- proxy_set_header Upgrade $http_upgrade;- proxy_set_header Connection "upgrade";- proxy_set_header Host $host;- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;- proxy_set_header X-Forwarded-Proto $scheme;- proxy_read_timeout 86400;- proxy_send_timeout 86400;- proxy_buffering off;- }-}-```--Optional env override:--```env-# Not required by default (already /_cm_ws)-# NEXT_PUBLIC_WS_URL=/custom_ws-```--### Cloudflare Tunnel Standard Example--`~/.cloudflared/config.yml`:--```yaml-tunnel: <your-tunnel-name-or-id>-credentials-file: /path/to/<credentials>.json--ingress:- - hostname: neko.example.com- path: /_cm_ws*- service: http://localhost:3002- - hostname: neko.example.com- path: /*- service: http://localhost:3000- - service: http_status:404-```--Run:--```bash-cloudflared tunnel --config ~/.cloudflared/config.yml run <your-tunnel-name-or-id>-```--For Zero Trust dashboard-managed routes (token mode), configure the same two routes and keep `/_cm_ws*` above `/*`.--### Key Notes--1. Do not use `ws` (without leading slash) as WS path; it can overmatch and cause `/_next/static/...` → `426 Upgrade Required`-2. WS route must be above catch-all `/*`-3. `NEXT_PUBLIC_WS_URL` is optional by default; if customized, restart frontend/container after changes-4. Mapping only `3000` still works, but falls back to HTTP polling (~5s), with less real-time responsiveness-5. `beacon.min.js` failures (Cloudflare analytics script) are typically unrelated to app API/WS data flow-6. No extra `/api` reverse-proxy rule is required in most setups; frontend uses same-origin `/api` and app handles internal forwarding to `3001`--> Note: `/_next/static/... 426 Upgrade Required` is common in **misconfigured reverse proxy / tunnel** setups; it is uncommon in direct local access without a proxy.--### Multi-Architecture Support--Docker images support both `linux/amd64` and `linux/arm64`.--### Data Persistence--Data is stored in `/app/data` inside the container. Mount it to host to prevent data loss:--```yaml-volumes:- - ./data:/app/data-```--### Update to Latest--```bash-# Pull the latest image and restart-docker compose pull-docker compose up -d-```--## 🔐 Authentication & Security--Neko Master supports access authentication to protect dashboard data.--### Production Security Baseline--1. Set a fixed `COOKIE_SECRET` (otherwise sessions may be invalidated after restart).-2. Do not keep `FORCE_ACCESS_CONTROL_OFF=true` enabled in normal operation.-3. Use `SHOWCASE_SITE_MODE=true` only for public demo environments (write operations are restricted).--Example:--```env-COOKIE_SECRET=<at least 32-byte random string>-# FORCE_ACCESS_CONTROL_OFF=false-# SHOWCASE_SITE_MODE=false-```--### Enable / Disable Authentication--1. Open dashboard and click "Settings" in the lower-left sidebar.-2. Go to the "Security" tab.-3. Enable/disable access control and set your token.--### Forgot Token (Emergency Reset)--If you forgot the token, temporarily set `FORCE_ACCESS_CONTROL_OFF=true` to enter emergency mode.--#### Docker Compose--1. Add to `docker-compose.yml`:-- ```yaml- environment:- - FORCE_ACCESS_CONTROL_OFF=true- ```--2. Restart:-- ```bash- docker compose up -d- ```--3. Open dashboard and reset token in "Settings -> Security".-4. Remove this env var immediately after reset, then restart again.--#### Docker CLI--1. Stop and remove container:-- ```bash- docker stop neko-master- docker rm neko-master- ```--2. Re-run with emergency flag:-- ```bash- docker run -d \- --name neko-master \- -p 3000:3000 \- -v $(pwd)/data:/app/data \- -e FORCE_ACCESS_CONTROL_OFF=true \- foru17/neko-master:latest- ```--3. Reset token, then remove this flag and restart normally.--## ❓ FAQ--### Q: Can I run normally with only `3000:3000` exposed?--**A:** Yes. Core features still work.-If WS is not routed, the app automatically falls back to HTTP polling.-For full realtime experience, route `/_cm_ws` to `3002`.--### Q: Port conflict or inaccessible after port changes?--**A:** Create/update `.env` (same directory as `docker-compose.yml`):--```env-WEB_EXTERNAL_PORT=8080-API_EXTERNAL_PORT=8081-WS_EXTERNAL_PORT=8082-```--Then restart:--```bash-docker compose down-docker compose up -d-```--### Q: Why does login/session disappear after restart?--**A:** Usually because `COOKIE_SECRET` is not fixed or data directory is not persisted.--1. Set a fixed `COOKIE_SECRET`-2. Mount `./data:/app/data`--### Q: Failed to connect OpenClash / gateway?--**A:** Check:--1. External control is enabled on gateway side-2. Host/port is correct-3. Token/Secret is correct (if configured)-4. Container network can reach gateway--### Q: How to backup and restore data?--**A:** Backup first:--```bash-cp -r ./data ./data-backup-$(date +%Y%m%d)-```--Restore:--```bash-docker compose down-cp -r ./data-backup-YYYYMMDD/. ./data/-docker compose up -d-```--## 🏗️ Architecture Guide--If you want to quickly understand the system design depth, read in this order:--1. **System Architecture Diagram**: end-to-end layering and module responsibilities- Chinese: [`docs/architecture.md`](./docs/architecture.md)- English: [`docs/architecture.en.md`](./docs/architecture.en.md)-2. **Data Flow**: Clash / Surge collection pipelines and aggregation-3. **Data Model & Storage**: SQLite schema, cache tables, retention-4. **Realtime Channel Design**: `RealtimeStore` merge strategy and WS push--> This documentation covers the core design of collection, aggregation, caching, realtime push, and multi-backend management.--## 🤝 Feedback & Issues--This project uses GitHub Issue Templates (Bug / Feature / Support).--Please include at least:--1. Deployment method (Compose / Docker Run / Source)-2. Version info (image tag or commit)-3. Key env vars (masked, e.g. `COOKIE_SECRET=***`)-4. Reproduction steps and expected vs actual behavior-5. Key logs (`docker logs`, browser console, network errors)--## 📁 Project Structure--```-neko-master/-├── docker-compose.yml # Docker Compose config-├── Dockerfile # Docker image build-├── setup.sh # One-click setup script-├── docker-start.sh # Docker container startup script-├── start.sh # Source code dev startup script-├── docs/ # Architecture and design docs-│ ├── architecture.md # Chinese architecture docs-│ └── architecture.en.md # English architecture docs-├── assets/ # Screenshots and icons-├── apps/-│ ├── collector/ # Data collection service (Node.js + WebSocket)-│ └── web/ # Next.js frontend app-└── packages/- └── shared/ # Shared types and utilities-```--## 🛠️ Tech Stack--- **Frontend**: [Next.js 16](https://nextjs.org/) + [React 19](https://react.dev/) + [TypeScript](https://www.typescriptlang.org/)-- **Styling**: [Tailwind CSS](https://tailwindcss.com/) + [shadcn/ui](https://ui.shadcn.com/)-- **Charts**: [Recharts](https://recharts.org/)-- **i18n**: [next-intl](https://next-intl-docs.vercel.app/)-- **Backend**: [Node.js](https://nodejs.org/) + [Fastify](https://www.fastify.io/) + WebSocket-- **Database**: [SQLite](https://www.sqlite.org/) ([better-sqlite3](https://github.com/WiseLibs/better-sqlite3))-- **Build**: [pnpm](https://pnpm.io/) + [Turborepo](https://turbo.build/)--## 🤝 Contributing--Contributions are welcome!--- 🐛 [Submit Bug](https://github.com/foru17/neko-master/issues/new)-- 💡 [Request Feature](https://github.com/foru17/neko-master/issues/new)-- 🔧 [Contribute Code](https://github.com/foru17/neko-master/pulls)--## 📄 License--[MIT](LICENSE) © [foru17](https://github.com/foru17)-------## ⭐ Star History--[](https://www.star-history.com/#foru17/neko-master&type=date&legend=top-left)-------<p align="center">- <sub>Made with ❤️ by <a href="https://github.com/foru17">@foru17</a></sub><br>- <sub>If this project helps you, please consider giving it a ⭐</sub>-</p>+This file is kept as a compatibility entry to avoid broken external links.diff --git a/apps/collector/package.json b/apps/collector/package.jsonindex 879a6bf..0eca181 100644--- a/apps/collector/package.json+++ b/apps/collector/package.json@@ -17,6 +17,7 @@"better-sqlite3": "^11.8.0","dotenv": "^16.6.0","fastify": "^5.7.4",+ "maxmind": "^5.0.5","ws": "^8.19.0"},"devDependencies": {diff --git a/apps/collector/src/app.ts b/apps/collector/src/app.tsindex 8574f96..b117983 100644--- a/apps/collector/src/app.ts+++ b/apps/collector/src/app.ts@@ -77,6 +77,15 @@ export async function createApp(options: AppOptions) {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@@ -259,6 +268,64 @@ export async function createApp(options: AppOptions) {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>;diff --git a/apps/collector/src/database/repositories/config.repository.ts b/apps/collector/src/database/repositories/config.repository.tsindex 332e6b7..0917fd4 100644--- a/apps/collector/src/database/repositories/config.repository.ts+++ b/apps/collector/src/database/repositories/config.repository.ts@@ -6,6 +6,7 @@*/import type Database from 'better-sqlite3';import * as fs from 'node:fs';+import path from 'node:path';import { BaseRepository } from './base.repository.js';interface DatabaseRetentionConfig {@@ -14,8 +15,23 @@ interface DatabaseRetentionConfig {autoCleanup: boolean;}+export type GeoLookupProvider = 'online' | 'local';++interface GeoLookupConfig {+ provider: GeoLookupProvider;+ mmdbDir: string;+ onlineApiUrl: string;+ localMmdbReady: boolean;+ missingMmdbFiles: string[];+}+export class ConfigRepository extends BaseRepository {private dbPath: string;+ private static readonly REQUIRED_MMDB_FILES = [+ 'GeoLite2-City.mmdb',+ 'GeoLite2-ASN.mmdb',+ ] as const;+ private static readonly DEFAULT_MMDB_DIR = '/app/data/geoip';constructor(db: Database.Database, dbPath: string) {super(db);@@ -69,6 +85,89 @@ export class ConfigRepository extends BaseRepository {return this.getRetentionConfig();}+ // Geo lookup config+ getGeoLookupConfig(): GeoLookupConfig {+ const providerRow = this.db.prepare(+ `SELECT value FROM app_config WHERE key = 'geoip.lookup_provider'`,+ ).get() as { value: string } | undefined;++ const onlineApiUrlRow = this.db.prepare(+ `SELECT value FROM app_config WHERE key = 'geoip.online_api_url'`,+ ).get() as { value: string } | undefined;++ const envProviderRaw = process.env.GEOIP_LOOKUP_PROVIDER?.trim();+ const envProvider =+ envProviderRaw === 'online' || envProviderRaw === 'local'+ ? envProviderRaw+ : undefined;+ const providerValue =+ envProvider ||+ (providerRow?.value === 'online' || providerRow?.value === 'local'+ ? (providerRow.value as GeoLookupProvider)+ : 'online');++ const mmdbDirValue = this.resolveMmdbDir();+ const missingMmdbFiles = ConfigRepository.REQUIRED_MMDB_FILES.filter(+ (file) => !fs.existsSync(path.join(mmdbDirValue, file)),+ );++ return {+ provider: providerValue,+ mmdbDir: mmdbDirValue,+ onlineApiUrl:+ process.env.GEOIP_ONLINE_API_URL?.trim() ||+ onlineApiUrlRow?.value ||+ 'https://api.ipinfo.es/ipinfo',+ localMmdbReady: missingMmdbFiles.length === 0,+ missingMmdbFiles,+ };+ }++ private resolveMmdbDir(): string {+ const envMmdbDir = process.env.GEOIP_MMDB_DIR?.trim();+ const fallbackCandidates = [+ path.join(process.cwd(), 'geoip'),+ path.join(process.cwd(), 'geo'),+ path.resolve(process.cwd(), '..', 'geoip'),+ path.resolve(process.cwd(), '..', 'geo'),+ path.resolve(process.cwd(), '..', '..', 'geoip'),+ path.resolve(process.cwd(), '..', '..', 'geo'),+ ConfigRepository.DEFAULT_MMDB_DIR,+ ];++ const candidates = [envMmdbDir, ...fallbackCandidates]+ .filter((dir): dir is string => !!dir)+ .map((dir) => path.resolve(dir));+ const uniqueCandidates = Array.from(new Set(candidates));+ const existing = uniqueCandidates.find((dir) => fs.existsSync(dir));+ if (existing) return existing;++ if (envMmdbDir) {+ return path.resolve(envMmdbDir);+ }+ return ConfigRepository.DEFAULT_MMDB_DIR;+ }++ updateGeoLookupConfig(updates: {+ provider?: GeoLookupProvider;+ onlineApiUrl?: string;+ }): GeoLookupConfig {+ if (updates.provider !== undefined) {+ this.db.prepare(`+ INSERT INTO app_config (key, value) VALUES ('geoip.lookup_provider', ?)+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP+ `).run(updates.provider);+ }+ if (updates.onlineApiUrl !== undefined) {+ this.db.prepare(`+ INSERT INTO app_config (key, value) VALUES ('geoip.online_api_url', ?)+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP+ `).run(updates.onlineApiUrl);+ }++ return this.getGeoLookupConfig();+ }+// Data cleanupcleanupOldData(backendId: number | null, days: number): {deletedConnections: number; deletedLogs: number; deletedDomains: number;diff --git a/apps/collector/src/database/schema.ts b/apps/collector/src/database/schema.tsindex bef1356..f32eca5 100644--- a/apps/collector/src/database/schema.ts+++ b/apps/collector/src/database/schema.ts@@ -468,7 +468,9 @@ export const DEFAULT_APP_CONFIG = `INSERT OR IGNORE INTO app_config (key, value) VALUES('retention.connection_logs_days', '7'),('retention.hourly_stats_days', '30'),- ('retention.auto_cleanup', '1');+ ('retention.auto_cleanup', '1'),+ ('geoip.lookup_provider', 'online'),+ ('geoip.online_api_url', 'https://api.ipinfo.es/ipinfo');`;// Default auth config valuesdiff --git a/apps/collector/src/db.ts b/apps/collector/src/db.tsindex 3960d05..4ac394d 100644--- a/apps/collector/src/db.ts+++ b/apps/collector/src/db.ts@@ -886,6 +886,10 @@ 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 }) {+ return this.repos.config.updateGeoLookupConfig(updates);+ }vacuum() { this.repos.config.vacuum(); }deleteOldMinuteStats(cutoff: string) { return this.repos.config.deleteOldMinuteStats(cutoff); }deleteOldConnectionLogs(cutoff: string) { return this.repos.config.deleteOldConnectionLogs(cutoff); }diff --git a/apps/collector/src/geo-service.ts b/apps/collector/src/geo-service.tsindex 9418ff4..ea94106 100644--- a/apps/collector/src/geo-service.ts+++ b/apps/collector/src/geo-service.ts@@ -1,3 +1,11 @@+import fs from "node:fs";+import path from "node:path";+import maxmind, {+ type AsnResponse,+ type CityResponse,+ type CountryResponse,+ type Reader,+} from "maxmind";import type { StatsDatabase } from "./db.js";export interface GeoLocation {@@ -11,34 +19,65 @@ export interface GeoLocation {continent_name: string;}+interface GeoLookupConfig {+ provider: "online" | "local";+ mmdbDir: string;+ onlineApiUrl: string;+ localMmdbReady?: boolean;+}++interface GeoIPApiResponse {+ country?: unknown;+ country_name?: unknown;+ city?: unknown;+ asn?: unknown;+ as_name?: unknown;+ as_domain?: unknown;+ continent?: unknown;+ continent_name?: unknown;+ reserved?: unknown;+}++interface LocalMmdbReaders {+ mmdbDir: string;+ cityPath: string;+ asnPath: string;+ countryPath: string | null;+ cityMtimeMs: number;+ asnMtimeMs: number;+ countryMtimeMs: number | null;+ cityReader: Reader<CityResponse>;+ asnReader: Reader<AsnResponse>;+ countryReader: Reader<CountryResponse> | null;+}+export class GeoIPService {private db: StatsDatabase;private pendingQueries: Map<string, Promise<GeoLocation | null>> = new Map();- private failedIPs: Map<string, number> = new Map(); // IP -> failure timestamp+ private failedIPs: Map<string, number> = new Map();private lastRequestTime: number = 0;private lastFailedIPsCleanup: number = 0;- private minRequestInterval: number = 100; // Minimum 100ms between requestsprivate queue: {ip: string;resolve: (value: GeoLocation | null) => void;}[] = [];private isProcessing: boolean = false;private processorTimer: NodeJS.Timeout | null = null;+ private localMmdbReaders: LocalMmdbReaders | null = null;+ private localMmdbLoadPromise: Promise<LocalMmdbReaders | null> | null = null;+ private lastLocalMmdbCheckMs: number = 0;- // Failed IPs won't be retried for 30 minutesprivate static FAIL_COOLDOWN_MS = 30 * 60 * 1000;- // Maximum queue size to prevent unbounded memory growthprivate static MAX_QUEUE_SIZE = 100;- // Sweep expired failedIPs entries every 10 minutesprivate 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;constructor(db: StatsDatabase) {this.db = db;}- // Get geolocation for an IP (with caching)async getGeoLocation(ip: string): Promise<GeoLocation | null> {- // Skip private/local IPsif (this.isPrivateIP(ip)) {return {country: "LOCAL",@@ -52,13 +91,11 @@ export class GeoIPService {};}- // Skip recently failed IPs (30 min cooldown)const failedAt = this.failedIPs.get(ip);if (failedAt && Date.now() - failedAt < GeoIPService.FAIL_COOLDOWN_MS) {return null;}- // Check cache firstconst cached = this.db.getIPGeolocation(ip);if (cached) {return {@@ -73,27 +110,22 @@ export class GeoIPService {};}- // Check if there's already a pending query for this IPconst pending = this.pendingQueries.get(ip);if (pending) {return pending;}- // Create new query promiseconst promise = this.queryWithQueue(ip);this.pendingQueries.set(ip, promise);try {- const result = await promise;- return result;+ return await promise;} finally {this.pendingQueries.delete(ip);}}- // Queue-based query to respect rate limitsprivate async queryWithQueue(ip: string): Promise<GeoLocation | null> {- // Drop requests when queue is overloaded to prevent memory buildupif (this.queue.length >= GeoIPService.MAX_QUEUE_SIZE) {return null;}@@ -103,18 +135,27 @@ export class GeoIPService {});}- // Schedule queue processing (on-demand, no idle spinning)private scheduleProcessing() {if (this.processorTimer || this.isProcessing) return;- const delay = Math.max(0, this.minRequestInterval - (Date.now() - this.lastRequestTime));+ const intervalMs = this.getRequestIntervalMs();+ const delay = Math.max(0, intervalMs - (Date.now() - this.lastRequestTime));this.processorTimer = setTimeout(() => {this.processorTimer = null;this.processNext();}, delay);}- // Process the next item in the queue+ private getRequestIntervalMs(): number {+ try {+ const config = this.db.getGeoLookupConfig() as GeoLookupConfig;+ const useLocal = config.provider === "local" && config.localMmdbReady !== false;+ return useLocal ? 0 : GeoIPService.ONLINE_MIN_REQUEST_INTERVAL_MS;+ } catch {+ return GeoIPService.ONLINE_MIN_REQUEST_INTERVAL_MS;+ }+ }+private async processNext() {if (this.isProcessing || this.queue.length === 0) return;@@ -122,7 +163,7 @@ export class GeoIPService {const item = this.queue.shift()!;try {- const result = await this.queryAPI(item.ip);+ const result = await this.queryGeo(item.ip);this.lastRequestTime = Date.now();item.resolve(result);} catch (err) {@@ -130,9 +171,7 @@ export class GeoIPService {item.resolve(null);} finally {this.isProcessing = false;- // Periodically sweep expired failedIPs to prevent unbounded growththis.cleanupFailedIPs();- // Continue processing if more items in queueif (this.queue.length > 0) {this.scheduleProcessing();}@@ -143,81 +182,288 @@ export class GeoIPService {const now = Date.now();if (now - this.lastFailedIPsCleanup < GeoIPService.FAILED_IPS_CLEANUP_INTERVAL_MS) return;this.lastFailedIPsCleanup = now;- let cleaned = 0;for (const [ip, failedAt] of this.failedIPs) {if (now - failedAt > GeoIPService.FAIL_COOLDOWN_MS) {this.failedIPs.delete(ip);- cleaned++;}}- if (cleaned > 0) {- console.log(`[GeoIP] Cleaned ${cleaned} expired failed-IP entries`);+ }++ private async queryGeo(ip: string): Promise<GeoLocation | null> {+ const config = this.db.getGeoLookupConfig() as GeoLookupConfig;+ const useLocal = config.provider === "local" && config.localMmdbReady !== false;+ if (useLocal) {+ const localResult = await this.queryLocalMMDB(ip, config);+ if (localResult) {+ return localResult;+ }+ // Local mode fallback: MMDB missing/invalid or lookup failed, use online API.+ return this.queryOnlineAPI(ip, config);}+ return this.queryOnlineAPI(ip, config);}- // Query the API- private async queryAPI(ip: string): Promise<GeoLocation | null> {- try {- console.log(`[GeoIP] Querying API for: ${ip}`);+ private async queryOnlineAPI(+ ip: string,+ config: GeoLookupConfig,+ ): Promise<GeoLocation | null> {+ const lookupUrl = this.buildLookupUrl(config.onlineApiUrl, ip);+ try {const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), 8000);- const response = await fetch(- `https://api.ipinfo.es/ipinfo?ip=${ip}&meituan=false`,- {+ try {+ const response = await fetch(lookupUrl, {signal: controller.signal,headers: {Accept: "application/json",},- },- );+ });++ if (!response.ok) {+ console.error(`[GeoIP] Online API error for ${ip}: ${response.status}`);+ this.failedIPs.set(ip, Date.now());+ return null;+ }++ const data = (await response.json()) as GeoIPApiResponse;+ const isReserved = data.reserved === true;++ const geo: GeoLocation = isReserved+ ? {+ country: "RESERVED",+ country_name: "Reserved IP",+ city: "",+ asn: "",+ as_name: "Reserved IP",+ as_domain: "",+ continent: "RESERVED",+ continent_name: "Reserved",+ }+ : {+ country: this.toStringValue(data.country, "Unknown"),+ country_name: this.toStringValue(data.country_name, "Unknown"),+ city: this.toStringValue(data.city, ""),+ asn: this.toStringValue(data.asn, ""),+ as_name: this.toStringValue(data.as_name, ""),+ as_domain: this.toStringValue(data.as_domain, ""),+ continent: this.toStringValue(data.continent, "Unknown"),+ continent_name: this.toStringValue(data.continent_name, "Unknown"),+ };++ this.db.saveIPGeolocation(ip, geo);+ return geo;+ } finally {+ clearTimeout(timeout);+ }+ } catch (err) {+ console.error(`[GeoIP] Online API query failed for ${ip}:`, err);+ this.failedIPs.set(ip, Date.now());+ return null;+ }+ }- clearTimeout(timeout);+ private async queryLocalMMDB(+ ip: string,+ config: GeoLookupConfig,+ ): Promise<GeoLocation | null> {+ if (!maxmind.validate(ip)) {+ this.failedIPs.set(ip, Date.now());+ return null;+ }- if (!response.ok) {- console.error(`[GeoIP] API error for ${ip}: ${response.status}`);+ try {+ const readers = await this.ensureLocalMmdbReaders(config.mmdbDir);+ if (!readers) {this.failedIPs.set(ip, Date.now());return null;}- const data = (await response.json()) as {- country?: string;- country_name?: string;- city?: string;- asn?: string;- as_name?: string;- as_domain?: string;- continent?: string;- continent_name?: string;- };+ const cityData = readers.cityReader.get(ip);+ const asnData = readers.asnReader.get(ip);+ const countryData = readers.countryReader?.get(ip) || null;++ const countryCode =+ cityData?.country?.iso_code ||+ countryData?.country?.iso_code ||+ "Unknown";+ const countryName =+ this.pickLocalizedName(cityData?.country?.names) ||+ this.pickLocalizedName(countryData?.country?.names) ||+ countryCode;+ const continentCode =+ cityData?.continent?.code ||+ countryData?.continent?.code ||+ "Unknown";+ const continentName =+ this.pickLocalizedName(cityData?.continent?.names) ||+ this.pickLocalizedName(countryData?.continent?.names) ||+ "Unknown";+ const cityName =+ this.pickLocalizedName(cityData?.city?.names) || "";++ const asnNumber =+ asnData?.autonomous_system_number ??+ cityData?.traits?.autonomous_system_number ??+ countryData?.traits?.autonomous_system_number;+ const asnOrg =+ asnData?.autonomous_system_organization ||+ cityData?.traits?.autonomous_system_organization ||+ countryData?.traits?.autonomous_system_organization ||+ "";+ const asDomain =+ cityData?.traits?.domain ||+ countryData?.traits?.domain ||+ "";const geo: GeoLocation = {- country: data.country || "Unknown",- country_name: data.country_name || "Unknown",- city: data.city || "",- asn: data.asn || "",- as_name: data.as_name || "",- as_domain: data.as_domain || "",- continent: data.continent || "Unknown",- continent_name: data.continent_name || "Unknown",+ country: countryCode,+ country_name: countryName || "Unknown",+ city: cityName,+ asn: typeof asnNumber === "number" ? `AS${asnNumber}` : "",+ as_name: asnOrg,+ as_domain: asDomain,+ continent: continentCode,+ continent_name: continentName,};- // Save to cachethis.db.saveIPGeolocation(ip, geo);- console.log(`[GeoIP] Cached: ${ip} -> ${geo.country_name}`);-return geo;} catch (err) {- console.error(`[GeoIP] Failed to query ${ip}:`, err);+ console.error(`[GeoIP] Local MMDB query failed for ${ip}:`, err);this.failedIPs.set(ip, Date.now());return null;}}- // Check if IP is private/local+ private async ensureLocalMmdbReaders(mmdbDir: string): Promise<LocalMmdbReaders | null> {+ const targetDir = path.resolve(mmdbDir || path.join(process.cwd(), "geoip"));++ const current = this.localMmdbReaders;+ if (current?.mmdbDir === targetDir) {+ const now = Date.now();+ if (now - this.lastLocalMmdbCheckMs < GeoIPService.LOCAL_MMDB_RECHECK_INTERVAL_MS) {+ return current;+ }+ this.lastLocalMmdbCheckMs = now;++ const cityMtimeMs = this.getFileMtimeMs(current.cityPath);+ const asnMtimeMs = this.getFileMtimeMs(current.asnPath);+ const countryMtimeMs = current.countryPath ? this.getFileMtimeMs(current.countryPath) : null;+ const unchanged =+ cityMtimeMs !== null &&+ asnMtimeMs !== null &&+ cityMtimeMs === current.cityMtimeMs &&+ asnMtimeMs === current.asnMtimeMs &&+ countryMtimeMs === current.countryMtimeMs;+ if (unchanged) {+ return current;+ }++ console.log(`[GeoIP] MMDB files changed, reloading from ${targetDir}`);+ this.localMmdbReaders = null;+ }++ if (this.localMmdbLoadPromise) {+ return this.localMmdbLoadPromise;+ }++ this.localMmdbLoadPromise = this.loadLocalMmdbReaders(targetDir)+ .finally(() => {+ this.localMmdbLoadPromise = null;+ });++ return this.localMmdbLoadPromise;+ }++ 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");++ if (!fs.existsSync(cityPath) || !fs.existsSync(asnPath)) {+ console.error(+ `[GeoIP] Missing MMDB file(s) in ${mmdbDir}. Required: GeoLite2-City.mmdb, GeoLite2-ASN.mmdb`,+ );+ return null;+ }++ const cityMtimeMs = this.getFileMtimeMs(cityPath);+ const asnMtimeMs = this.getFileMtimeMs(asnPath);+ const countryMtimeMs = fs.existsSync(countryPath)+ ? this.getFileMtimeMs(countryPath)+ : null;+ if (cityMtimeMs === null || asnMtimeMs === null) {+ console.error(`[GeoIP] Failed to stat required MMDB files under ${mmdbDir}`);+ return null;+ }++ const [cityReader, asnReader, countryReader] = await Promise.all([+ maxmind.open<CityResponse>(cityPath),+ maxmind.open<AsnResponse>(asnPath),+ countryMtimeMs !== null+ ? maxmind.open<CountryResponse>(countryPath)+ : Promise.resolve(null),+ ]);++ this.localMmdbReaders = {+ mmdbDir,+ cityPath,+ asnPath,+ countryPath: countryMtimeMs !== null ? countryPath : null,+ cityMtimeMs,+ asnMtimeMs,+ countryMtimeMs,+ cityReader,+ asnReader,+ countryReader,+ };+ this.lastLocalMmdbCheckMs = Date.now();++ console.log(`[GeoIP] Local MMDB loaded from ${mmdbDir}`);+ return this.localMmdbReaders;+ }++ private getFileMtimeMs(filePath: string): number | null {+ try {+ return fs.statSync(filePath).mtimeMs;+ } catch {+ return null;+ }+ }++ private buildLookupUrl(baseUrl: string, ip: string): string {+ const url = new URL(baseUrl);+ url.searchParams.set("ip", ip);+ if (!url.searchParams.has("meituan")) {+ url.searchParams.set("meituan", "false");+ }+ return url.toString();+ }++ private pickLocalizedName(names: unknown): string {+ if (!names || typeof names !== "object") return "";+ const record = names as Record<string, unknown>;+ if (typeof record.en === "string" && record.en) return record.en;+ if (typeof record["zh-CN"] === "string" && record["zh-CN"]) return record["zh-CN"];+ for (const value of Object.values(record)) {+ if (typeof value === "string" && value) return value;+ }+ return "";+ }++ private toStringValue(value: unknown, fallback: string): string {+ if (typeof value === "string" && value.trim().length > 0) {+ return value.trim();+ }+ if (typeof value === "number") {+ return String(value);+ }+ return fallback;+ }+private isPrivateIP(ip: string): boolean {- // IPv4 private rangesconst privateRanges = [/^10\./,/^172\.(1[6-9]|2[0-9]|3[01])\./,@@ -225,10 +471,9 @@ export class GeoIPService {/^127\./,/^0\./,/^255\./,- /^100\.(6[4-9]|[7-9][0-9]|1[0-1][0-9]|12[0-7])\./, // CGNAT+ /^100\.(6[4-9]|[7-9][0-9]|1[0-1][0-9]|12[0-7])\./,];- // IPv6 privateif (ip.includes(":")) {return (ip.startsWith("fc") ||@@ -246,18 +491,19 @@ export class GeoIPService {return new Promise((resolve) => setTimeout(resolve, ms));}- // Bulk query IPs (for backfill)async bulkQueryIPs(ips: string[]): Promise<void> {const uniqueIPs = [...new Set(ips)].filter((ip) => !this.isPrivateIP(ip));- console.log(`[GeoIP] Bulk querying ${uniqueIPs.length} IPs`);+ const config = this.db.getGeoLookupConfig() as GeoLookupConfig;+ const useLocal = config.provider === "local" && config.localMmdbReady !== false;+ const delayMs = useLocal ? 0 : 150;for (const ip of uniqueIPs) {- // Check if already cachedconst cached = this.db.getIPGeolocation(ip);if (!cached) {await this.getGeoLocation(ip);- // Small delay to respect rate limits- await this.sleep(150);+ if (delayMs > 0) {+ await this.sleep(delayMs);+ }}}}diff --git a/apps/web/components/features/backend/backend-config-dialog.tsx b/apps/web/components/features/backend/backend-config-dialog.tsxindex 88fbb77..ceb311d 100644--- a/apps/web/components/features/backend/backend-config-dialog.tsx+++ b/apps/web/components/features/backend/backend-config-dialog.tsx@@ -56,14 +56,13 @@ import {DialogTitle,} from "@/components/ui/dialog";import { cn, formatBytes, formatNumber } from "@/lib/utils";-import { api } from "@/lib/api";+import { api, type GeoLookupConfig, type GeoLookupProvider } from "@/lib/api";import { toast } from "sonner";import { BackendVerifyAnimation } from "@/components/features/backend/backend-verify-animation";import { BackendListSkeleton } from "@/components/ui/insight-skeleton";import { useSettings, FaviconProvider, getFaviconUrl } from "@/lib/settings";import { Label } from "@/components/ui/label";import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";-import { Separator } from "@/components/ui/separator";import { useAuthState, authKeys } from "@/lib/auth-queries";// Favicon Provider Preview Component@@ -343,6 +342,14 @@ export function BackendConfigDialog({autoCleanup: true,});const [updatingRetention, setUpdatingRetention] = useState(false);+ const [geoLookupConfig, setGeoLookupConfig] = useState<GeoLookupConfig>({+ provider: "online",+ mmdbDir: "/app/data/geoip",+ onlineApiUrl: "https://api.ipinfo.es/ipinfo",+ localMmdbReady: false,+ missingMmdbFiles: [],+ });+ const [updatingGeoLookup, setUpdatingGeoLookup] = useState(false);// Alert Dialog Statesconst [deleteDialogOpen, setDeleteDialogOpen] = useState(false);@@ -421,6 +428,7 @@ export function BackendConfigDialog({loadBackends();loadDbStats();loadRetentionConfig();+ loadGeoLookupConfig();}}, [open]);@@ -459,6 +467,48 @@ export function BackendConfigDialog({}};+ const loadGeoLookupConfig = async () => {+ try {+ const config = await api.getGeoLookupConfig();+ setGeoLookupConfig(config);+ } catch (error) {+ console.error("Failed to load geo lookup config:", error);+ }+ };++ const handleUpdateGeoLookupConfig = async (+ updates: {+ provider?: GeoLookupProvider;+ onlineApiUrl?: string;+ },+ ) => {+ try {+ setUpdatingGeoLookup(true);+ const result = await api.updateGeoLookupConfig(updates);+ setGeoLookupConfig(result.config);+ toast.success(t("geoLookupUpdated"));+ } catch (error: any) {+ toast.error(error.message || t("geoLookupUpdateFailed"));+ } finally {+ setUpdatingGeoLookup(false);+ }+ };++ const handleGeoLookupProviderChange = (value: string) => {+ const provider = value as GeoLookupProvider;+ if (provider !== "online" && provider !== "local") return;+ if (provider === "local" && !geoLookupConfig.localMmdbReady) {+ const missing = geoLookupConfig.missingMmdbFiles.join(", ");+ toast.error(+ t("geoLookupLocalUnavailable", {+ files: missing || "GeoLite2-City.mmdb, GeoLite2-ASN.mmdb",+ }),+ );+ return;+ }+ handleUpdateGeoLookupConfig({ provider });+ };+const handleUpdateRetention = async (key: keyof RetentionConfig,value: number | boolean,@@ -1385,6 +1435,63 @@ export function BackendConfigDialog({t={t}/></div>++ {/* GeoIP Lookup Provider */}+ <div className="p-4 rounded-lg border bg-card space-y-4">+ <h4 className="text-sm font-medium mb-2 flex items-center gap-2">+ <Radio className="w-4 h-4" />+ {t("geoLookupProvider")}+ </h4>+ <p className="text-sm text-muted-foreground">+ {t("geoLookupProviderDescription")}+ </p>++ <RadioGroup+ value={geoLookupConfig.provider}+ onValueChange={handleGeoLookupProviderChange}+ className="space-y-2"+ disabled={updatingGeoLookup || isShowcase}>+ <div className="flex items-center gap-2 rounded-md border p-3">+ <RadioGroupItem value="online" id="geo-provider-online" />+ <Label htmlFor="geo-provider-online" className="cursor-pointer">+ {t("geoLookupOnline")}+ </Label>+ </div>+ <div+ className={cn(+ "flex items-center gap-2 rounded-md border p-3",+ !geoLookupConfig.localMmdbReady &&+ "opacity-60 cursor-not-allowed",+ )}>+ <RadioGroupItem+ value="local"+ id="geo-provider-local"+ disabled={!geoLookupConfig.localMmdbReady}+ />+ <Label+ htmlFor="geo-provider-local"+ className={cn(+ "cursor-pointer",+ !geoLookupConfig.localMmdbReady && "cursor-not-allowed",+ )}>+ {t("geoLookupLocal")}+ </Label>+ </div>+ </RadioGroup>++ <p className="text-xs text-muted-foreground">+ {t("geoLookupFixedPathHint")}+ </p>+ {!geoLookupConfig.localMmdbReady && (+ <p className="text-xs text-amber-600 dark:text-amber-400">+ {t("geoLookupLocalUnavailable", {+ files:+ geoLookupConfig.missingMmdbFiles.join(", ") ||+ "GeoLite2-City.mmdb, GeoLite2-ASN.mmdb",+ })}+ </p>+ )}+ </div></div>) : activeTab === "security" ? (<div className="space-y-6">diff --git a/apps/web/components/features/domains/domain-preview.tsx b/apps/web/components/features/domains/domain-preview.tsxindex 1851dba..95b169a 100644--- a/apps/web/components/features/domains/domain-preview.tsx+++ b/apps/web/components/features/domains/domain-preview.tsx@@ -66,12 +66,13 @@ export function DomainPreview({<PopoverContentalign="start"side="bottom"- sideOffset={8}- className="w-[min(92vw,30rem)] rounded-lg border-border/50 bg-popover p-2.5 shadow-lg"+ sideOffset={6}+ collisionPadding={12}+ className="w-[min(94vw,24rem)] rounded-lg border border-border/60 bg-popover/98 p-2 shadow-lg ring-1 ring-black/5 dark:bg-slate-950/94 dark:border-white/[0.08] dark:ring-0 dark:shadow-[0_14px_30px_rgba(0,0,0,0.46)]"onClick={(event) => event.stopPropagation()}><div className="flex items-start gap-2">- <code className="min-w-0 flex-1 max-h-28 overflow-auto rounded-md border border-border/50 bg-muted/25 px-2.5 py-2 text-[13px] leading-5 break-all">+ <code className="min-w-0 flex-1 max-h-24 overflow-auto rounded-md border border-border/55 bg-muted/35 px-2 py-1.5 text-[13px] leading-5 break-all dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-slate-100">{domainText}</code>{domain ? (@@ -83,10 +84,10 @@ export function DomainPreview({title={copied ? copiedLabel : copyLabel}aria-label={copied ? copiedLabel : copyLabel}className={cn(- "h-8 w-8 shrink-0 rounded-md border border-border/40",+ "h-8 w-8 shrink-0 rounded-md border border-border/55 dark:border-white/[0.08] dark:bg-white/[0.02]",copied? "text-emerald-600 bg-emerald-500/15 hover:bg-emerald-500/20 dark:text-emerald-400"- : "text-muted-foreground hover:text-foreground hover:bg-muted/50",+ : "text-muted-foreground hover:text-foreground hover:bg-muted/60",)}onClick={(event) => {event.preventDefault();diff --git a/apps/web/components/features/proxies/proxy-chain-badge.tsx b/apps/web/components/features/proxies/proxy-chain-badge.tsxindex 11f03a7..81c8bbe 100644--- a/apps/web/components/features/proxies/proxy-chain-badge.tsx+++ b/apps/web/components/features/proxies/proxy-chain-badge.tsx@@ -3,6 +3,7 @@import { ChevronRight, Waypoints } from "lucide-react";import { cn } from "@/lib/utils";import { useIsWindows } from "@/lib/hooks/use-is-windows";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import {Tooltip,TooltipContent,@@ -19,7 +20,15 @@ interface ProxyChainBadgeProps {emptyClassName?: string;}-function ChainFlow({ chain, isWindows }: { chain: string; isWindows: boolean }) {+function ChainFlow({+ chain,+ isWindows,+ mobile = false,+}: {+ chain: string;+ isWindows: boolean;+ mobile?: boolean;+}) {const segments = chain.split(">").map((part) => part.trim())@@ -57,6 +66,31 @@ function ChainFlow({ chain, isWindows }: { chain: string; isWindows: boolean })};};+ if (mobile) {+ return (+ <div className="space-y-1">+ {displaySegments.map((segment, idx) => (+ <div key={`${segment}-${idx}`}>+ <span+ className={cn(+ "block w-full px-2 py-1 rounded-md border text-[11px] font-medium break-words",+ isWindows && "emoji-flag-font",+ getNodeTone(idx, displaySegments.length),+ )}+ >+ {segment}+ </span>+ {idx < displaySegments.length - 1 && (+ <div className="flex justify-center py-0.5">+ <ChevronRight className="h-3.5 w-3.5 rotate-90 text-muted-foreground/70" />+ </div>+ )}+ </div>+ ))}+ </div>+ );+ }+return (<div className="overflow-x-auto pb-0.5"><div className="inline-flex items-center gap-1.5 min-w-max">@@ -111,61 +145,94 @@ export function ProxyChainBadge({const firstChain = chains[0];const landingProxy = firstChain.split(">").map((p) => p.trim()).filter(Boolean)[0] || firstChain;-- return (- <TooltipProvider delayDuration={250}>- <Tooltip>- <TooltipTrigger asChild>- <span className={cn("inline-flex items-center gap-1.5 min-w-0", wrapperClassName)}>- <span- className={cn(- "inline-flex items-center gap-1 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium",- isWindows && "emoji-flag-font",- truncateLabel- ? "px-1.5 py-0.5 truncate max-w-[180px] lg:max-w-[220px]"- : "px-2 py-0.5 whitespace-nowrap",- badgeClassName,- )}- >- <Waypoints className="h-2.5 w-2.5 shrink-0" />- {landingProxy}- </span>+ const triggerClassName = cn(+ "inline-flex items-center gap-1.5 min-w-0",+ wrapperClassName,+ );+ const labelClassName = cn(+ "inline-flex items-center gap-1 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium",+ isWindows && "emoji-flag-font",+ truncateLabel+ ? "px-1.5 py-0.5 truncate max-w-[180px] lg:max-w-[220px]"+ : "px-2 py-0.5 whitespace-nowrap",+ badgeClassName,+ );+ const extraCount = chains.length > 1 ? (+ <span className={cn("text-[11px] text-muted-foreground shrink-0", countClassName)}>+ +{chains.length - 1}+ </span>+ ) : null;+ const renderTrigger = () => (+ <button+ type="button"+ className={triggerClassName}+ onClick={(event) => event.stopPropagation()}+ onPointerDown={(event) => event.stopPropagation()}+ >+ <span className={labelClassName}>+ <Waypoints className="h-2.5 w-2.5 shrink-0" />+ {landingProxy}+ </span>+ {extraCount}+ </button>+ );+ const renderChainDetails = (mobile = false) => (+ <div className="max-h-[280px] overflow-auto pr-1 space-y-1.5">+ {chains.map((chain, idx) => (+ <div+ key={`${chain}-${idx}`}+ className={cn(+ "rounded-md border border-border/70 bg-card/85 text-card-foreground px-2 py-1.5 dark:border-white/[0.08] dark:bg-white/[0.02]",+ idx > 0 && "mt-1",+ )}+ >+ <div className="flex items-center gap-2">{chains.length > 1 && (- <span className={cn("text-[11px] text-muted-foreground shrink-0", countClassName)}>- +{chains.length - 1}+ <span className="inline-flex items-center justify-center h-5 min-w-5 px-1 rounded-full bg-muted/80 text-[10px] font-semibold text-muted-foreground shrink-0 dark:bg-white/[0.06] dark:text-slate-300">+ {idx + 1}</span>)}- </span>- </TooltipTrigger>- <TooltipContent- side="top"- align="start"- className="max-w-[560px] p-2 border border-border bg-popover text-popover-foreground shadow-xl"- >- <div className="max-h-[280px] overflow-auto pr-1 space-y-1.5">- {chains.map((chain, idx) => (- <div- key={`${chain}-${idx}`}- className={cn(- "rounded-md border border-border bg-card text-card-foreground px-2 py-1.5",- idx > 0 && "mt-1",- )}- >- <div className="flex items-center gap-2">- {chains.length > 1 && (- <span className="inline-flex items-center justify-center h-5 min-w-5 px-1 rounded-full bg-muted text-[10px] font-semibold text-muted-foreground shrink-0">- {idx + 1}- </span>- )}- <div className="min-w-0 flex-1">- <ChainFlow chain={chain} isWindows={isWindows} />- </div>- </div>- </div>- ))}+ <div className="min-w-0 flex-1">+ <ChainFlow chain={chain} isWindows={isWindows} mobile={mobile} />+ </div></div>- </TooltipContent>- </Tooltip>- </TooltipProvider>+ </div>+ ))}+ </div>+ );++ return (+ <>+ <span className="hidden sm:inline-flex">+ <TooltipProvider delayDuration={250}>+ <Tooltip>+ <TooltipTrigger asChild>{renderTrigger()}</TooltipTrigger>+ <TooltipContent+ side="top"+ align="start"+ className="max-w-[560px] p-2 border border-border/70 bg-popover/98 text-popover-foreground shadow-xl ring-1 ring-black/5 dark:bg-slate-950/94 dark:border-white/[0.08] dark:ring-0 dark:shadow-[0_14px_30px_rgba(0,0,0,0.46)]"+ >+ {renderChainDetails(false)}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </span>++ <span className="sm:hidden inline-flex">+ <Popover>+ <PopoverTrigger asChild>{renderTrigger()}</PopoverTrigger>+ <PopoverContent+ side="top"+ align="start"+ sideOffset={6}+ collisionPadding={12}+ className="w-[min(94vw,24rem)] p-2 border border-border/70 bg-popover/98 text-popover-foreground shadow-xl ring-1 ring-black/5 dark:bg-slate-950/94 dark:border-white/[0.08] dark:ring-0 dark:shadow-[0_14px_30px_rgba(0,0,0,0.46)]"+ onClick={(event) => event.stopPropagation()}+ >+ {renderChainDetails(true)}+ </PopoverContent>+ </Popover>+ </span>+ </>);}diff --git a/apps/web/components/features/rules/interactive-rule-stats.tsx b/apps/web/components/features/rules/interactive-rule-stats.tsxindex d6c6bd8..b6562a1 100644--- a/apps/web/components/features/rules/interactive-rule-stats.tsx+++ b/apps/web/components/features/rules/interactive-rule-stats.tsx@@ -40,6 +40,7 @@ import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badgeimport { DomainExpandedDetails, IPExpandedDetails } from "@/components/features/stats/table/expanded-details";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 { 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";@@ -215,6 +216,15 @@ export function InteractiveRuleStats({// Expanded statesconst [expandedDomain, setExpandedDomain] = useState<string | null>(null);const [expandedIP, setExpandedIP] = useState<string | null>(null);+ const [mobileDomainDetailsOpen, setMobileDomainDetailsOpen] = useState(false);+ const [mobileDomainDetail, setMobileDomainDetail] = useState<DomainStats | null>(null);+ const [mobileIPDetailsOpen, setMobileIPDetailsOpen] = useState(false);+ const [mobileIPDetail, setMobileIPDetail] = useState<IPStats | null>(null);+ const detailDomainKey = mobileDomainDetailsOpen+ ? (mobileDomainDetail?.domain ?? null)+ : expandedDomain;+ const detailIPKey = mobileIPDetailsOpen ? (mobileIPDetail?.ip ?? null) : expandedIP;+ const mobileIPColor = getIPColor(mobileIPDetail?.ip ?? "0.0.0.0");useEffect(() => {const media = window.matchMedia("(min-width: 640px)");@@ -369,34 +379,34 @@ export function InteractiveRuleStats({const expandedDomainProxyQuery = useRuleDomainProxyStats({rule: selectedRule ?? undefined,- domain: expandedDomain ?? undefined,+ domain: detailDomainKey ?? undefined,activeBackendId,range: detailTimeRange,- enabled: !!expandedDomain,+ enabled: !!detailDomainKey,});const expandedDomainIPDetailsQuery = useRuleDomainIPDetails({rule: selectedRule ?? undefined,- domain: expandedDomain ?? undefined,+ domain: detailDomainKey ?? undefined,activeBackendId,range: detailTimeRange,- enabled: !!expandedDomain,+ enabled: !!detailDomainKey,});const expandedIPProxyQuery = useRuleIPProxyStats({rule: selectedRule ?? undefined,- ip: expandedIP ?? undefined,+ ip: detailIPKey ?? undefined,activeBackendId,range: detailTimeRange,- enabled: !!expandedIP,+ enabled: !!detailIPKey,});const expandedIPDomainDetailsQuery = useRuleIPDomainDetails({rule: selectedRule ?? undefined,- ip: expandedIP ?? undefined,+ ip: detailIPKey ?? undefined,activeBackendId,range: detailTimeRange,- enabled: !!expandedIP,+ enabled: !!detailIPKey,});const { data: ruleDomains = [], isLoading: domainsLoading } = useRuleDomains({@@ -455,11 +465,19 @@ export function InteractiveRuleStats({setIpSearch("");setExpandedDomain(null);setExpandedIP(null);+ setMobileDomainDetailsOpen(false);+ setMobileDomainDetail(null);+ setMobileIPDetailsOpen(false);+ setMobileIPDetail(null);}, [selectedRule]);useEffect(() => {setExpandedDomain(null);setExpandedIP(null);+ setMobileDomainDetailsOpen(false);+ setMobileDomainDetail(null);+ setMobileIPDetailsOpen(false);+ setMobileIPDetail(null);}, [activeBackendId]);const handleRuleClick = useCallback((rule: string) => {@@ -468,6 +486,30 @@ export function InteractiveRuleStats({}}, [selectedRule]);+ const openMobileDomainDetails = (domain: DomainStats) => {+ setMobileDomainDetail(domain);+ setMobileDomainDetailsOpen(true);+ };++ const handleMobileDomainDetailsOpenChange = (open: boolean) => {+ setMobileDomainDetailsOpen(open);+ if (!open) {+ setMobileDomainDetail(null);+ }+ };++ const openMobileIPDetails = (ip: IPStats) => {+ setMobileIPDetail(ip);+ setMobileIPDetailsOpen(true);+ };++ const handleMobileIPDetailsOpenChange = (open: boolean) => {+ setMobileIPDetailsOpen(open);+ if (!open) {+ setMobileIPDetail(null);+ }+ };+const selectedRuleData = useMemo(() => {return chartData.find(r => r.rawName === selectedRule);}, [chartData, selectedRule]);@@ -1131,7 +1173,9 @@ export function InteractiveRuleStats({totalFilteredDomainTraffic > 0? (domainTraffic / totalFilteredDomainTraffic) * 100: 0;- const isExpanded = expandedDomain === domain.domain;+ const isDesktopExpanded = expandedDomain === domain.domain;+ const isMobileActive =+ mobileDomainDetailsOpen && mobileDomainDetail?.domain === domain.domain;return (<div key={domain.domain} className="group">@@ -1139,7 +1183,7 @@ export function InteractiveRuleStats({<divclassName={cn("hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer",- isExpanded && "bg-secondary/10"+ isDesktopExpanded && "bg-secondary/10")}style={{ animationDelay: `${index * 50}ms` }}onClick={() => toggleExpandDomain(domain.domain)}@@ -1185,7 +1229,7 @@ export function InteractiveRuleStats({size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium transition-all",- isExpanded+ isDesktopExpanded? "bg-primary/10 text-primary hover:bg-primary/20": "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary")}@@ -1196,7 +1240,7 @@ export function InteractiveRuleStats({><Server className="h-3 w-3" />{domain.ips.length}- {isExpanded ? (+ {isDesktopExpanded ? (<ChevronUp className="h-3 w-3 ml-0.5" />) : (<ChevronDown className="h-3 w-3 ml-0.5" />@@ -1209,9 +1253,9 @@ export function InteractiveRuleStats({<divclassName={cn("sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",- isExpanded && "bg-secondary/10"+ isMobileActive && "bg-secondary/10")}- onClick={() => toggleExpandDomain(domain.domain)}+ onClick={() => openMobileDomainDetails(domain)}>{/* Top: Favicon + Domain + Expand */}<div className="flex items-center gap-2.5 mb-2">@@ -1228,18 +1272,18 @@ export function InteractiveRuleStats({size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium shrink-0",- isExpanded+ isMobileActive? "bg-primary/10 text-primary": "bg-secondary/50 text-muted-foreground")}onClick={(e) => {e.stopPropagation();- toggleExpandDomain(domain.domain);+ openMobileDomainDetails(domain);}}><Server className="h-3 w-3" />{domain.ips.length}- {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}+ {isMobileActive ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}</Button></div>@@ -1261,27 +1305,29 @@ export function InteractiveRuleStats({</div>{/* Expanded Details: Proxy Traffic + Associated IPs */}- {isExpanded && (- <ExpandReveal>- <DomainExpandedDetails- domain={domain}- proxyStats={expandedDomainProxyQuery.data ?? []}- proxyStatsLoading={- expandedDomainProxyQuery.isLoading &&- !expandedDomainProxyQuery.data- }- ipDetails={expandedDomainIPDetailsQuery.data ?? []}- ipDetailsLoading={- expandedDomainIPDetailsQuery.isLoading &&- !expandedDomainIPDetailsQuery.data- }- labels={{- proxyTraffic: domainsT("proxyTraffic"),- associatedIPs: domainsT("associatedIPs"),- conn: domainsT("conn"),- }}- />- </ExpandReveal>+ {isDesktopExpanded && (+ <div className="hidden sm:block">+ <ExpandReveal>+ <DomainExpandedDetails+ domain={domain}+ proxyStats={expandedDomainProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedDomainProxyQuery.isLoading &&+ !expandedDomainProxyQuery.data+ }+ ipDetails={expandedDomainIPDetailsQuery.data ?? []}+ ipDetailsLoading={+ expandedDomainIPDetailsQuery.isLoading &&+ !expandedDomainIPDetailsQuery.data+ }+ labels={{+ proxyTraffic: domainsT("proxyTraffic"),+ associatedIPs: domainsT("associatedIPs"),+ conn: domainsT("conn"),+ }}+ />+ </ExpandReveal>+ </div>)}</div>);@@ -1289,6 +1335,41 @@ export function InteractiveRuleStats({})()}</div>+ <Drawer open={mobileDomainDetailsOpen} onOpenChange={handleMobileDomainDetailsOpenChange}>+ <DrawerContent className="sm:hidden">+ <DrawerHeader className="border-b border-border/60 bg-background/95 px-4 pt-2 pb-2">+ <div className="flex items-center gap-2.5 min-w-0 rounded-lg border border-border/60 bg-muted/25 px-3 py-2">+ <Favicon domain={mobileDomainDetail?.domain || ""} size="sm" className="shrink-0" />+ <DrawerTitle className="truncate text-left text-[15px] font-semibold leading-6">+ {mobileDomainDetail?.domain || domainsT("unknown")}+ </DrawerTitle>+ </div>+ </DrawerHeader>+ <div className="max-h-[76vh] overflow-y-auto pb-[max(env(safe-area-inset-bottom),0px)]">+ {mobileDomainDetail ? (+ <DomainExpandedDetails+ domain={mobileDomainDetail}+ proxyStats={expandedDomainProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedDomainProxyQuery.isLoading &&+ !expandedDomainProxyQuery.data+ }+ ipDetails={expandedDomainIPDetailsQuery.data ?? []}+ ipDetailsLoading={+ expandedDomainIPDetailsQuery.isLoading &&+ !expandedDomainIPDetailsQuery.data+ }+ labels={{+ proxyTraffic: domainsT("proxyTraffic"),+ associatedIPs: domainsT("associatedIPs"),+ conn: domainsT("conn"),+ }}+ />+ ) : null}+ </div>+ </DrawerContent>+ </Drawer>+{/* Pagination */}{filteredDomains.length > 0 && (<div className="p-3 border-t border-border/50 bg-secondary/20">@@ -1487,7 +1568,8 @@ export function InteractiveRuleStats({totalFilteredIPTraffic > 0? (ipTraffic / totalFilteredIPTraffic) * 100: 0;- const isExpanded = expandedIP === ip.ip;+ const isDesktopExpanded = expandedIP === ip.ip;+ const isMobileActive = mobileIPDetailsOpen && mobileIPDetail?.ip === ip.ip;const ipColor = getIPColor(ip.ip);return (@@ -1496,7 +1578,7 @@ export function InteractiveRuleStats({<divclassName={cn("hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer",- isExpanded && "bg-secondary/10"+ isDesktopExpanded && "bg-secondary/10")}style={{ animationDelay: `${index * 50}ms` }}onClick={() => toggleExpandIP(ip.ip)}@@ -1550,7 +1632,7 @@ export function InteractiveRuleStats({size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium transition-all",- isExpanded+ isDesktopExpanded? "bg-primary/10 text-primary hover:bg-primary/20": "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary")}@@ -1561,7 +1643,7 @@ export function InteractiveRuleStats({><Link2 className="h-3 w-3" />{ip.domains.length}- {isExpanded ? (+ {isDesktopExpanded ? (<ChevronUp className="h-3 w-3 ml-0.5" />) : (<ChevronDown className="h-3 w-3 ml-0.5" />@@ -1574,9 +1656,9 @@ export function InteractiveRuleStats({<divclassName={cn("sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",- isExpanded && "bg-secondary/10"+ isMobileActive && "bg-secondary/10")}- onClick={() => toggleExpandIP(ip.ip)}+ onClick={() => openMobileIPDetails(ip)}>{/* Top: IP Icon + IP + Location + Expand */}<div className="flex items-center gap-2.5 mb-2">@@ -1597,18 +1679,18 @@ export function InteractiveRuleStats({size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium shrink-0",- isExpanded+ isMobileActive? "bg-primary/10 text-primary": "bg-secondary/50 text-muted-foreground")}onClick={(e) => {e.stopPropagation();- toggleExpandIP(ip.ip);+ openMobileIPDetails(ip);}}><Link2 className="h-3 w-3" />{ip.domains.length}- {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}+ {isMobileActive ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}</Button></div>@@ -1630,28 +1712,30 @@ export function InteractiveRuleStats({</div>{/* Expanded Details: Proxy Traffic + Associated Domains */}- {isExpanded && (- <ExpandReveal>- <IPExpandedDetails- ip={ip}- proxyStats={expandedIPProxyQuery.data ?? []}- proxyStatsLoading={- expandedIPProxyQuery.isLoading &&- !expandedIPProxyQuery.data- }- domainDetails={expandedIPDomainDetailsQuery.data ?? []}- domainDetailsLoading={- expandedIPDomainDetailsQuery.isLoading &&- !expandedIPDomainDetailsQuery.data- }- associatedDomainsIcon="link"- labels={{- proxyTraffic: ipsT("proxyTraffic"),- associatedDomains: ipsT("associatedDomains"),- conn: ipsT("conn"),- }}- />- </ExpandReveal>+ {isDesktopExpanded && (+ <div className="hidden sm:block">+ <ExpandReveal>+ <IPExpandedDetails+ ip={ip}+ proxyStats={expandedIPProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedIPProxyQuery.isLoading &&+ !expandedIPProxyQuery.data+ }+ domainDetails={expandedIPDomainDetailsQuery.data ?? []}+ domainDetailsLoading={+ expandedIPDomainDetailsQuery.isLoading &&+ !expandedIPDomainDetailsQuery.data+ }+ associatedDomainsIcon="link"+ labels={{+ proxyTraffic: ipsT("proxyTraffic"),+ associatedDomains: ipsT("associatedDomains"),+ conn: ipsT("conn"),+ }}+ />+ </ExpandReveal>+ </div>)}</div>);@@ -1659,6 +1743,50 @@ export function InteractiveRuleStats({})()}</div>+ <Drawer open={mobileIPDetailsOpen} onOpenChange={handleMobileIPDetailsOpenChange}>+ <DrawerContent className="sm:hidden">+ <DrawerHeader className="border-b border-border/60 bg-background/95 px-4 pt-2 pb-2">+ <div className="flex items-center gap-2.5 min-w-0 rounded-lg border border-border/60 bg-muted/25 px-3 py-2">+ <div+ className={cn(+ "w-5 h-5 rounded-md flex items-center justify-center shrink-0",+ mobileIPColor.bg,+ mobileIPColor.text,+ )}+ >+ <Server className="w-3 h-3" />+ </div>+ <DrawerTitle className="truncate text-left font-mono text-[15px] font-semibold leading-6">+ {mobileIPDetail?.ip || ipsT("unknownIP")}+ </DrawerTitle>+ </div>+ </DrawerHeader>+ <div className="max-h-[76vh] overflow-y-auto pb-[max(env(safe-area-inset-bottom),0px)]">+ {mobileIPDetail ? (+ <IPExpandedDetails+ ip={mobileIPDetail}+ proxyStats={expandedIPProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedIPProxyQuery.isLoading &&+ !expandedIPProxyQuery.data+ }+ domainDetails={expandedIPDomainDetailsQuery.data ?? []}+ domainDetailsLoading={+ expandedIPDomainDetailsQuery.isLoading &&+ !expandedIPDomainDetailsQuery.data+ }+ associatedDomainsIcon="link"+ labels={{+ proxyTraffic: ipsT("proxyTraffic"),+ associatedDomains: ipsT("associatedDomains"),+ conn: ipsT("conn"),+ }}+ />+ ) : null}+ </div>+ </DrawerContent>+ </Drawer>+{/* Pagination */}{filteredIPs.length > 0 && (<div className="p-3 border-t border-border/50 bg-secondary/20">diff --git a/apps/web/components/features/stats/table/domain-stats-table.tsx b/apps/web/components/features/stats/table/domain-stats-table.tsxindex 3c36d52..6f9d592 100644--- a/apps/web/components/features/stats/table/domain-stats-table.tsx+++ b/apps/web/components/features/stats/table/domain-stats-table.tsx@@ -37,6 +37,7 @@ import { DomainPreview } from "@/components/features/domains/domain-preview";import { DomainExpandedDetails } from "./expanded-details";import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badge";import { ExpandReveal } from "@/components/ui/expand-reveal";+import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";import { InsightTableSkeleton } from "@/components/ui/insight-skeleton";import {PAGE_SIZE_OPTIONS,@@ -89,10 +90,17 @@ export function DomainStatsTable({const [sortKey, setSortKey] = useState<DomainSortKey>("totalDownload");const [sortOrder, setSortOrder] = useState<SortOrder>("desc");const [expandedDomain, setExpandedDomain] = useState<string | null>(null);+ const [mobileDetailsOpen, setMobileDetailsOpen] = useState(false);+ const [mobileDetailDomain, setMobileDetailDomain] = useState<DomainStats | null>(null);+ const detailDomainKey = mobileDetailsOpen+ ? (mobileDetailDomain?.domain ?? null)+ : expandedDomain;useEffect(() => {// Context switch (backend/device/proxy/rule binding change): collapse.setExpandedDomain(null);+ setMobileDetailsOpen(false);+ setMobileDetailDomain(null);}, [activeBackendId, sourceIP, sourceChain, richExpand]);useEffect(() => {@@ -108,23 +116,23 @@ export function DomainStatsTable({};const expandedDomainProxyQuery = useQuery({- queryKey: getDomainProxyStatsQueryKey(expandedDomain, activeBackendId, detailTimeRange, {+ queryKey: getDomainProxyStatsQueryKey(detailDomainKey, activeBackendId, detailTimeRange, {sourceIP,sourceChain,}),queryFn: () =>api.getDomainProxyStats(- expandedDomain!,+ detailDomainKey!,activeBackendId,detailTimeRange,sourceIP,sourceChain,),- enabled: richExpand && !!activeBackendId && !!expandedDomain,+ enabled: richExpand && !!activeBackendId && !!detailDomainKey,staleTime: DETAIL_QUERY_STALE_MS,placeholderData: (previousData, previousQuery) =>keepPreviousByIdentity(previousData, previousQuery, {- domain: expandedDomain ?? "",+ domain: detailDomainKey ?? "",backendId: activeBackendId ?? null,sourceIP: sourceIP ?? "",sourceChain: sourceChain ?? "",@@ -132,23 +140,23 @@ export function DomainStatsTable({});const expandedDomainIPDetailsQuery = useQuery({- queryKey: getDomainIPDetailsQueryKey(expandedDomain, activeBackendId, detailTimeRange, {+ queryKey: getDomainIPDetailsQueryKey(detailDomainKey, activeBackendId, detailTimeRange, {sourceIP,sourceChain,}),queryFn: () =>api.getDomainIPDetails(- expandedDomain!,+ detailDomainKey!,activeBackendId,detailTimeRange,sourceIP,sourceChain,),- enabled: richExpand && !!activeBackendId && !!expandedDomain,+ enabled: richExpand && !!activeBackendId && !!detailDomainKey,staleTime: DETAIL_QUERY_STALE_MS,placeholderData: (previousData, previousQuery) =>keepPreviousByIdentity(previousData, previousQuery, {- domain: expandedDomain ?? "",+ domain: detailDomainKey ?? "",backendId: activeBackendId ?? null,sourceIP: sourceIP ?? "",sourceChain: sourceChain ?? "",@@ -170,6 +178,18 @@ export function DomainStatsTable({setExpandedDomain(newExpanded);};+ const openMobileDetails = (domain: DomainStats) => {+ setMobileDetailDomain(domain);+ setMobileDetailsOpen(true);+ };++ const handleMobileDetailsOpenChange = (open: boolean) => {+ setMobileDetailsOpen(open);+ if (!open) {+ setMobileDetailDomain(null);+ }+ };+const SortIcon = ({ column }: { column: DomainSortKey }) => {if (sortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;return sortOrder === "asc" ? (@@ -303,14 +323,16 @@ export function DomainStatsTable({<div className="divide-y divide-border/30">{paginatedDomains.map((domain, index) => {- const isExpanded = expandedDomain === domain.domain;+ const isDesktopExpanded = expandedDomain === domain.domain;+ const isMobileActive =+ mobileDetailsOpen && mobileDetailDomain?.domain === domain.domain;return (<div key={domain.domain} className="group"><divclassName={cn("hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer",- isExpanded && "bg-secondary/10",+ isDesktopExpanded && "bg-secondary/10",)}style={{ animationDelay: `${index * 50}ms` }}onClick={() => toggleExpand(domain.domain)}@@ -352,7 +374,7 @@ export function DomainStatsTable({size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium transition-all",- isExpanded+ isDesktopExpanded? "bg-primary/10 text-primary hover:bg-primary/20": "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary",)}@@ -363,7 +385,7 @@ export function DomainStatsTable({><Server className="h-3 w-3" />{domain.ips?.length || 0}- {isExpanded ? (+ {isDesktopExpanded ? (<ChevronUp className="h-3 w-3 ml-0.5" />) : (<ChevronDown className="h-3 w-3 ml-0.5" />@@ -375,9 +397,9 @@ export function DomainStatsTable({<divclassName={cn("sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",- isExpanded && "bg-secondary/10",+ isMobileActive && "bg-secondary/10",)}- onClick={() => toggleExpand(domain.domain)}+ onClick={() => openMobileDetails(domain)}><div className="flex items-center gap-2.5 mb-2"><Favicon domain={domain.domain} size="sm" className="shrink-0" />@@ -393,16 +415,16 @@ export function DomainStatsTable({size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium shrink-0",- isExpanded ? "bg-primary/10 text-primary" : "bg-secondary/50 text-muted-foreground",+ isMobileActive ? "bg-primary/10 text-primary" : "bg-secondary/50 text-muted-foreground",)}onClick={(e) => {e.stopPropagation();- toggleExpand(domain.domain);+ openMobileDetails(domain);}}><Server className="h-3 w-3" />{domain.ips?.length || 0}- {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}+ {isMobileActive ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}</Button></div>@@ -421,35 +443,74 @@ export function DomainStatsTable({</div></div>- {isExpanded && (- <ExpandReveal>- <DomainExpandedDetails- domain={domain}- richExpand={richExpand}- proxyStats={expandedDomainProxyQuery.data ?? []}- proxyStatsLoading={- expandedDomainProxyQuery.isLoading &&- !expandedDomainProxyQuery.data- }- ipDetails={expandedDomainIPDetailsQuery.data ?? []}- ipDetailsLoading={- expandedDomainIPDetailsQuery.isLoading &&- !expandedDomainIPDetailsQuery.data- }- labels={{- proxyTraffic: t("proxyTraffic"),- associatedIPs: t("associatedIPs"),- conn: t("conn"),- }}- showProxyTraffic={showProxyTrafficInExpand}- />- </ExpandReveal>+ {isDesktopExpanded && (+ <div className="hidden sm:block">+ <ExpandReveal>+ <DomainExpandedDetails+ domain={domain}+ richExpand={richExpand}+ proxyStats={expandedDomainProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedDomainProxyQuery.isLoading &&+ !expandedDomainProxyQuery.data+ }+ ipDetails={expandedDomainIPDetailsQuery.data ?? []}+ ipDetailsLoading={+ expandedDomainIPDetailsQuery.isLoading &&+ !expandedDomainIPDetailsQuery.data+ }+ labels={{+ proxyTraffic: t("proxyTraffic"),+ associatedIPs: t("associatedIPs"),+ conn: t("conn"),+ }}+ showProxyTraffic={showProxyTrafficInExpand}+ />+ </ExpandReveal>+ </div>)}</div>);})}</div>+ <Drawer open={mobileDetailsOpen} onOpenChange={handleMobileDetailsOpenChange}>+ <DrawerContent className="sm:hidden">+ <DrawerHeader className="border-b border-border/60 bg-background/95 px-5 pt-2 pb-2.5">+ <div className="flex items-center gap-2.5 min-w-0 rounded-md border border-border/60 bg-muted/25 px-2.5 py-2">+ <Favicon domain={mobileDetailDomain?.domain || ""} size="sm" className="shrink-0" />+ <DrawerTitle className="truncate text-left text-[15px] font-semibold leading-6">+ {mobileDetailDomain?.domain || t("unknown")}+ </DrawerTitle>+ </div>+ </DrawerHeader>+ <div className="max-h-[76vh] overflow-y-auto pb-[max(env(safe-area-inset-bottom),0px)]">+ {mobileDetailDomain ? (+ <DomainExpandedDetails+ domain={mobileDetailDomain}+ richExpand={richExpand}+ proxyStats={expandedDomainProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedDomainProxyQuery.isLoading &&+ !expandedDomainProxyQuery.data+ }+ ipDetails={expandedDomainIPDetailsQuery.data ?? []}+ ipDetailsLoading={+ expandedDomainIPDetailsQuery.isLoading &&+ !expandedDomainIPDetailsQuery.data+ }+ labels={{+ proxyTraffic: t("proxyTraffic"),+ associatedIPs: t("associatedIPs"),+ conn: t("conn"),+ }}+ showProxyTraffic={showProxyTrafficInExpand}+ />+ ) : null}+ </div>+ </DrawerContent>+ </Drawer>+{filteredDomains.length > 0 && (<div className="p-3 border-t border-border/50 bg-secondary/20"><div className="flex flex-col sm:flex-row items-center justify-between gap-3">diff --git a/apps/web/components/features/stats/table/domain-table.tsx b/apps/web/components/features/stats/table/domain-table.tsxindex 354b04c..2509f55 100644--- a/apps/web/components/features/stats/table/domain-table.tsx+++ b/apps/web/components/features/stats/table/domain-table.tsx@@ -12,6 +12,7 @@ import { DomainPreview } from "@/components/features/domains/domain-preview";import { DomainExpandedDetails } from "@/components/features/stats/table/expanded-details";import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badge";import { ExpandReveal } from "@/components/ui/expand-reveal";+import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";import { formatBytes, formatNumber, formatDuration } from "@/lib/utils";import { cn } from "@/lib/utils";import type { DomainStats, StatsSummary } from "@neko-master/shared";@@ -83,6 +84,8 @@ export function DomainsTable({setInternalPageSize(size);}, [onPageSizeChange]);const [expandedDomain, setExpandedDomain] = useState<string | null>(null);+ const [mobileDetailsOpen, setMobileDetailsOpen] = useState(false);+ const [mobileDetailDomain, setMobileDetailDomain] = useState<DomainStats | null>(null);const [wsDomainsPage, setWsDomainsPage] = useState<DomainsPageState | null>(null);const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);const pageOffset = (currentPage - 1) * pageSize;@@ -171,39 +174,44 @@ export function DomainsTable({const data = hasWsDomainsPage ? wsDomainsPage!.data : domainsQuery.data?.data ?? [];const total = hasWsDomainsPage ? wsDomainsPage!.total : domainsQuery.data?.total ?? 0;const loading = !hasWsDomainsPage && domainsQuery.isLoading && !domainsQuery.data;+ const detailDomainKey = mobileDetailsOpen+ ? (mobileDetailDomain?.domain ?? null)+ : expandedDomain;useEffect(() => {// Backend switch means a different data universe, collapse safely.setExpandedDomain(null);+ setMobileDetailsOpen(false);+ setMobileDetailDomain(null);}, [activeBackendId]);const expandedDomainProxyQuery = useQuery({- queryKey: getDomainProxyStatsQueryKey(expandedDomain, activeBackendId, detailTimeRange),- queryFn: () => api.getDomainProxyStats(expandedDomain!, activeBackendId, detailTimeRange),- enabled: !!activeBackendId && !!expandedDomain,+ queryKey: getDomainProxyStatsQueryKey(detailDomainKey, activeBackendId, detailTimeRange),+ queryFn: () => api.getDomainProxyStats(detailDomainKey!, activeBackendId, detailTimeRange),+ enabled: !!activeBackendId && !!detailDomainKey,staleTime: DETAIL_QUERY_STALE_MS,placeholderData: (previousData, previousQuery) => {const prevKey = (previousQuery?.queryKey?.[2] ?? null) as| { domain?: string; backendId?: number | null }| null;if (!prevKey) return undefined;- if (prevKey.domain !== (expandedDomain ?? "")) return undefined;+ if (prevKey.domain !== (detailDomainKey ?? "")) return undefined;if (prevKey.backendId !== (activeBackendId ?? null)) return undefined;return previousData;},});const expandedDomainIPDetailsQuery = useQuery({- queryKey: getDomainIPDetailsQueryKey(expandedDomain, activeBackendId, detailTimeRange),- queryFn: () => api.getDomainIPDetails(expandedDomain!, activeBackendId, detailTimeRange),- enabled: !!activeBackendId && !!expandedDomain,+ queryKey: getDomainIPDetailsQueryKey(detailDomainKey, activeBackendId, detailTimeRange),+ queryFn: () => api.getDomainIPDetails(detailDomainKey!, activeBackendId, detailTimeRange),+ enabled: !!activeBackendId && !!detailDomainKey,staleTime: DETAIL_QUERY_STALE_MS,placeholderData: (previousData, previousQuery) => {const prevKey = (previousQuery?.queryKey?.[2] ?? null) as| { domain?: string; backendId?: number | null }| null;if (!prevKey) return undefined;- if (prevKey.domain !== (expandedDomain ?? "")) return undefined;+ if (prevKey.domain !== (detailDomainKey ?? "")) return undefined;if (prevKey.backendId !== (activeBackendId ?? null)) return undefined;return previousData;},@@ -235,6 +243,18 @@ export function DomainsTable({setExpandedDomain(newExpanded);};+ const openMobileDetails = (domain: DomainStats) => {+ setMobileDetailDomain(domain);+ setMobileDetailsOpen(true);+ };++ const handleMobileDetailsOpenChange = (open: boolean) => {+ setMobileDetailsOpen(open);+ if (!open) {+ setMobileDetailDomain(null);+ }+ };+const SortIcon = ({ column }: { column: SortKey }) => {if (sortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;return sortOrder === "asc" ? (@@ -371,7 +391,9 @@ export function DomainsTable({</div>) : (data.map((domain, index) => {- const isExpanded = expandedDomain === domain.domain;+ const isDesktopExpanded = expandedDomain === domain.domain;+ const isMobileActive =+ mobileDetailsOpen && mobileDetailDomain?.domain === domain.domain;return (<div key={domain.domain} className="group">@@ -379,7 +401,7 @@ export function DomainsTable({<divclassName={cn("hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer min-w-0",- isExpanded && "bg-secondary/10"+ isDesktopExpanded && "bg-secondary/10")}style={{ animationDelay: `${index * 50}ms` }}onClick={() => toggleExpand(domain.domain)}@@ -433,7 +455,7 @@ export function DomainsTable({size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium transition-all",- isExpanded+ isDesktopExpanded? "bg-primary/10 text-primary hover:bg-primary/20": "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary")}@@ -444,7 +466,7 @@ export function DomainsTable({><Server className="h-3 w-3" />{domain.ips.length}- {isExpanded ? (+ {isDesktopExpanded ? (<ChevronUp className="h-3 w-3 ml-0.5" />) : (<ChevronDown className="h-3 w-3 ml-0.5" />@@ -457,9 +479,9 @@ export function DomainsTable({<divclassName={cn("sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",- isExpanded && "bg-secondary/10"+ isMobileActive && "bg-secondary/10")}- onClick={() => toggleExpand(domain.domain)}+ onClick={() => openMobileDetails(domain)}>{/* Row 1: Favicon + Domain (truncate) + IP Count */}<div className="flex items-center gap-2.5 mb-2">@@ -477,18 +499,18 @@ export function DomainsTable({size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium shrink-0",- isExpanded+ isMobileActive? "bg-primary/10 text-primary": "bg-secondary/50 text-muted-foreground")}onClick={(e) => {e.stopPropagation();- toggleExpand(domain.domain);+ openMobileDetails(domain);}}><Server className="h-3 w-3" />{domain.ips.length}- {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}+ {isMobileActive ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}</Button></div>@@ -510,27 +532,29 @@ export function DomainsTable({</div>{/* Expanded Details: Proxy Traffic + IP List */}- {isExpanded && (- <ExpandReveal>- <DomainExpandedDetails- domain={domain}- proxyStats={expandedDomainProxyQuery.data ?? []}- proxyStatsLoading={- expandedDomainProxyQuery.isLoading &&- !expandedDomainProxyQuery.data- }- ipDetails={expandedDomainIPDetailsQuery.data ?? []}- ipDetailsLoading={- expandedDomainIPDetailsQuery.isLoading &&- !expandedDomainIPDetailsQuery.data- }- labels={{- proxyTraffic: t("proxyTraffic"),- associatedIPs: t("associatedIPs"),- conn: t("conn"),- }}- />- </ExpandReveal>+ {isDesktopExpanded && (+ <div className="hidden sm:block">+ <ExpandReveal>+ <DomainExpandedDetails+ domain={domain}+ proxyStats={expandedDomainProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedDomainProxyQuery.isLoading &&+ !expandedDomainProxyQuery.data+ }+ ipDetails={expandedDomainIPDetailsQuery.data ?? []}+ ipDetailsLoading={+ expandedDomainIPDetailsQuery.isLoading &&+ !expandedDomainIPDetailsQuery.data+ }+ labels={{+ proxyTraffic: t("proxyTraffic"),+ associatedIPs: t("associatedIPs"),+ conn: t("conn"),+ }}+ />+ </ExpandReveal>+ </div>)}</div>);@@ -538,6 +562,41 @@ export function DomainsTable({)}</div>+ <Drawer open={mobileDetailsOpen} onOpenChange={handleMobileDetailsOpenChange}>+ <DrawerContent className="sm:hidden">+ <DrawerHeader className="border-b border-border/60 bg-background/95 px-5 pt-2 pb-2.5">+ <div className="flex items-center gap-2.5 min-w-0 rounded-md border border-border/60 bg-muted/25 px-2.5 py-2">+ <Favicon domain={mobileDetailDomain?.domain || ""} size="sm" className="shrink-0" />+ <DrawerTitle className="truncate text-left text-[15px] font-semibold leading-6">+ {mobileDetailDomain?.domain || t("unknown")}+ </DrawerTitle>+ </div>+ </DrawerHeader>+ <div className="max-h-[76vh] overflow-y-auto pb-[max(env(safe-area-inset-bottom),0px)]">+ {mobileDetailDomain ? (+ <DomainExpandedDetails+ domain={mobileDetailDomain}+ proxyStats={expandedDomainProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedDomainProxyQuery.isLoading &&+ !expandedDomainProxyQuery.data+ }+ ipDetails={expandedDomainIPDetailsQuery.data ?? []}+ ipDetailsLoading={+ expandedDomainIPDetailsQuery.isLoading &&+ !expandedDomainIPDetailsQuery.data+ }+ labels={{+ proxyTraffic: t("proxyTraffic"),+ associatedIPs: t("associatedIPs"),+ conn: t("conn"),+ }}+ />+ ) : null}+ </div>+ </DrawerContent>+ </Drawer>+{/* Pagination Footer */}{totalPages > 0 && (<div className="p-3 sm:p-4 border-t border-border/50 bg-secondary/20">diff --git a/apps/web/components/features/stats/table/ip-preview.tsx b/apps/web/components/features/stats/table/ip-preview.tsxnew file mode 100644index 0000000..9c62355--- /dev/null+++ b/apps/web/components/features/stats/table/ip-preview.tsx@@ -0,0 +1,172 @@+"use client";++import { useState, useEffect, useRef, useCallback, type MouseEvent } from "react";+import { Building2, Check, Copy, MapPin, Network, Server } from "lucide-react";+import { CopyToClipboard } from "react-copy-to-clipboard";+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";++interface IPPreviewProps {+ ip?: string | null;+ geoIP?: string[] | null;+ asn?: string | null;+ unknownLabel: string;+ unavailableLabel: string;+ copyLabel: string;+ copiedLabel: string;+ locationLabel: string;+ cityLabel: string;+ asnLabel: string;+ asOrganizationLabel: string;+ className?: string;+ triggerClassName?: string;+}++export function IPPreview({+ ip,+ geoIP,+ asn,+ unknownLabel,+ unavailableLabel,+ copyLabel,+ copiedLabel,+ locationLabel,+ cityLabel,+ asnLabel,+ asOrganizationLabel,+ className,+ triggerClassName,+}: IPPreviewProps) {+ const [copied, setCopied] = useState(false);+ 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 asnValue = asn || unavailableLabel;+ const hasLocation = Boolean(countryCode || countryName);+ const displayLocation = countryName || countryCode || unavailableLabel;++ useEffect(() => {+ return () => {+ if (copiedTimerRef.current) clearTimeout(copiedTimerRef.current);+ };+ }, []);++ const handleTriggerClick = useCallback((event: MouseEvent<HTMLButtonElement>) => {+ event.stopPropagation();+ }, []);++ const handleCopyResult = useCallback((_: string, result: boolean) => {+ if (result) {+ setCopied(true);+ if (copiedTimerRef.current) clearTimeout(copiedTimerRef.current);+ copiedTimerRef.current = setTimeout(() => setCopied(false), 1200);+ } else {+ setCopied(false);+ }+ }, []);++ return (+ <div className={cn("min-w-0", className)} onClick={(event) => event.stopPropagation()}>+ <Popover>+ <PopoverTrigger asChild>+ <button+ type="button"+ className={cn(+ "w-full min-w-0 text-left truncate text-sm rounded-sm outline-none cursor-pointer underline-offset-4 decoration-dotted decoration-transparent hover:underline hover:decoration-muted-foreground/60 hover:text-foreground/95 focus-visible:ring-2 focus-visible:ring-ring/60",+ triggerClassName,+ )}+ onClick={handleTriggerClick}+ >+ {ipText}+ </button>+ </PopoverTrigger>+ <PopoverContent+ align="start"+ side="bottom"+ sideOffset={6}+ collisionPadding={12}+ className="w-[min(94vw,25rem)] rounded-lg border border-border/60 bg-popover/98 p-2.5 shadow-lg ring-1 ring-black/5 dark:bg-slate-950/94 dark:border-white/[0.08] dark:ring-0 dark:shadow-[0_14px_30px_rgba(0,0,0,0.46)]"+ onClick={(event) => event.stopPropagation()}+ >+ <div className="space-y-2">+ <div className="flex items-start gap-2">+ <code className="min-w-0 flex-1 rounded-md border border-border/55 bg-muted/35 px-2 py-1.5 text-[13px] leading-5 break-all dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-slate-100">+ {ipText}+ </code>+ {ip ? (+ <CopyToClipboard text={ip} onCopy={handleCopyResult}>+ <Button+ type="button"+ size="icon"+ variant="ghost"+ title={copied ? copiedLabel : copyLabel}+ aria-label={copied ? copiedLabel : copyLabel}+ className={cn(+ "h-8 w-8 shrink-0 rounded-md border border-border/55 dark:border-white/[0.08] dark:bg-white/[0.02]",+ copied+ ? "text-emerald-600 bg-emerald-500/15 hover:bg-emerald-500/20 dark:text-emerald-400"+ : "text-muted-foreground hover:text-foreground hover:bg-muted/60",+ )}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ >+ {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}+ </Button>+ </CopyToClipboard>+ ) : null}+ </div>++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5">+ <div className="min-h-[70px] rounded-md border border-border/55 bg-card/70 px-2.5 py-2 dark:border-white/[0.08] dark:bg-white/[0.02]">+ <p className="inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ <MapPin className="h-3 w-3" />+ {locationLabel}+ </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" />+ <span className="truncate text-sm font-medium leading-5">{displayLocation}</span>+ </span>+ ) : (+ <span className="mt-1.5 block truncate text-sm leading-5 text-muted-foreground">{unavailableLabel}</span>+ )}+ </div>++ <div className="min-h-[70px] rounded-md border border-border/55 bg-card/70 px-2.5 py-2 dark:border-white/[0.08] dark:bg-white/[0.02]">+ <p className="inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ <Building2 className="h-3 w-3" />+ {cityLabel}+ </p>+ <span title={city} className="mt-1.5 block truncate text-sm font-medium leading-5">{city}</span>+ </div>++ <div className="min-h-[70px] rounded-md border border-border/55 bg-card/70 px-2.5 py-2 dark:border-white/[0.08] dark:bg-white/[0.02]">+ <p className="inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ <Network className="h-3 w-3" />+ {asnLabel}+ </p>+ <span className="mt-1.5 block truncate text-sm font-semibold tabular-nums leading-5">{asnValue}</span>+ </div>++ <div className="min-h-[70px] rounded-md border border-border/55 bg-card/70 px-2.5 py-2 dark:border-white/[0.08] dark:bg-white/[0.02]">+ <p className="inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ <Server className="h-3 w-3" />+ {asOrganizationLabel}+ </p>+ <span title={asOrganization} className="mt-1.5 block truncate text-sm font-medium leading-5">{asOrganization}</span>+ </div>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </div>+ );+}diff --git a/apps/web/components/features/stats/table/ip-stats-table.tsx b/apps/web/components/features/stats/table/ip-stats-table.tsxindex cdb8de7..66eec95 100644--- a/apps/web/components/features/stats/table/ip-stats-table.tsx+++ b/apps/web/components/features/stats/table/ip-stats-table.tsx@@ -38,6 +38,8 @@ import { IPExpandedDetails } from "./expanded-details";import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badge";import { ExpandReveal } from "@/components/ui/expand-reveal";import { InsightTableSkeleton } from "@/components/ui/insight-skeleton";+import { IPPreview } from "./ip-preview";+import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";import {PAGE_SIZE_OPTIONS,getIPGradient,@@ -90,10 +92,15 @@ export function IPStatsTable({const [sortKey, setSortKey] = useState<IPSortKey>("totalDownload");const [sortOrder, setSortOrder] = useState<SortOrder>("desc");const [expandedIP, setExpandedIP] = useState<string | null>(null);+ const [mobileDetailsOpen, setMobileDetailsOpen] = useState(false);+ const [mobileDetailIP, setMobileDetailIP] = useState<IPStats | null>(null);+ const detailIPKey = mobileDetailsOpen ? (mobileDetailIP?.ip ?? null) : expandedIP;useEffect(() => {// Context switch (backend/device/proxy/rule binding change): collapse.setExpandedIP(null);+ setMobileDetailsOpen(false);+ setMobileDetailIP(null);}, [activeBackendId, sourceIP, sourceChain, richExpand]);useEffect(() => {@@ -109,23 +116,23 @@ export function IPStatsTable({};const expandedIPProxyQuery = useQuery({- queryKey: getIPProxyStatsQueryKey(expandedIP, activeBackendId, detailTimeRange, {+ queryKey: getIPProxyStatsQueryKey(detailIPKey, activeBackendId, detailTimeRange, {sourceIP,sourceChain,}),queryFn: () =>api.getIPProxyStats(- expandedIP!,+ detailIPKey!,activeBackendId,detailTimeRange,sourceIP,sourceChain,),- enabled: richExpand && !!activeBackendId && !!expandedIP,+ enabled: richExpand && !!activeBackendId && !!detailIPKey,staleTime: DETAIL_QUERY_STALE_MS,placeholderData: (previousData, previousQuery) =>keepPreviousByIdentity(previousData, previousQuery, {- ip: expandedIP ?? "",+ ip: detailIPKey ?? "",backendId: activeBackendId ?? null,sourceIP: sourceIP ?? "",sourceChain: sourceChain ?? "",@@ -133,24 +140,24 @@ export function IPStatsTable({});const expandedIPDomainDetailsQuery = useQuery({- queryKey: getIPDomainDetailsQueryKey(expandedIP, activeBackendId, detailTimeRange, {+ queryKey: getIPDomainDetailsQueryKey(detailIPKey, activeBackendId, detailTimeRange, {sourceIP,sourceChain,}),queryFn: () =>api.getIPDomainDetails(- expandedIP!,+ detailIPKey!,activeBackendId,detailTimeRange,sourceIP,undefined,sourceChain,),- enabled: richExpand && !!activeBackendId && !!expandedIP,+ enabled: richExpand && !!activeBackendId && !!detailIPKey,staleTime: DETAIL_QUERY_STALE_MS,placeholderData: (previousData, previousQuery) =>keepPreviousByIdentity(previousData, previousQuery, {- ip: expandedIP ?? "",+ ip: detailIPKey ?? "",backendId: activeBackendId ?? null,sourceIP: sourceIP ?? "",sourceChain: sourceChain ?? "",@@ -172,6 +179,18 @@ export function IPStatsTable({setExpandedIP(newExpanded);};+ const openMobileDetails = (ip: IPStats) => {+ setMobileDetailIP(ip);+ setMobileDetailsOpen(true);+ };++ const handleMobileDetailsOpenChange = (open: boolean) => {+ setMobileDetailsOpen(open);+ if (!open) {+ setMobileDetailIP(null);+ }+ };+const SortIcon = ({ column }: { column: IPSortKey }) => {if (sortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;return sortOrder === "asc" ? (@@ -310,14 +329,15 @@ export function IPStatsTable({<div className="divide-y divide-border/30">{paginatedIPs.map((ip) => {- const isExpanded = expandedIP === ip.ip;+ const isDesktopExpanded = expandedIP === ip.ip;+ const isMobileActive = mobileDetailsOpen && mobileDetailIP?.ip === ip.ip;return (<div key={ip.ip} className="group"><divclassName={cn("hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer",- isExpanded && "bg-secondary/10",+ isDesktopExpanded && "bg-secondary/10",)}onClick={() => toggleExpand(ip.ip)}>@@ -325,7 +345,21 @@ export function IPStatsTable({<div className={`w-5 h-5 rounded-md bg-gradient-to-br ${getIPGradient(ip.ip)} flex items-center justify-center shrink-0`}><Server className="w-3 h-3 text-white" /></div>- <code className="font-mono text-sm truncate">{ip.ip}</code>+ <IPPreview+ ip={ip.ip}+ geoIP={ip.geoIP}+ asn={ip.asn}+ unknownLabel={t("unknownIP")}+ unavailableLabel={t("unknown")}+ copyLabel={t("copyIP")}+ copiedLabel={t("copied")}+ locationLabel={t("location")}+ cityLabel={t("city")}+ asnLabel={t("asn")}+ asOrganizationLabel={t("asOrganization")}+ className="flex-1"+ triggerClassName="font-mono"+ /></div>{showProxyColumn && (@@ -365,7 +399,7 @@ export function IPStatsTable({size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium transition-all",- isExpanded+ isDesktopExpanded? "bg-primary/10 text-primary hover:bg-primary/20": "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary",)}@@ -376,7 +410,7 @@ export function IPStatsTable({><Globe className="h-3 w-3" />{ip.domains?.length || 0}- {isExpanded ? (+ {isDesktopExpanded ? (<ChevronUp className="h-3 w-3 ml-0.5" />) : (<ChevronDown className="h-3 w-3 ml-0.5" />@@ -388,30 +422,44 @@ export function IPStatsTable({<divclassName={cn("sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",- isExpanded && "bg-secondary/10",+ isMobileActive && "bg-secondary/10",)}- onClick={() => toggleExpand(ip.ip)}+ onClick={() => openMobileDetails(ip)}><div className="flex items-center gap-2.5 mb-2"><div className={`w-5 h-5 rounded-md bg-gradient-to-br ${getIPGradient(ip.ip)} flex items-center justify-center shrink-0`}><Server className="w-2.5 h-2.5 text-white" /></div>- <code className="font-mono text-sm flex-1 truncate">{ip.ip}</code>+ <IPPreview+ ip={ip.ip}+ geoIP={ip.geoIP}+ asn={ip.asn}+ unknownLabel={t("unknownIP")}+ unavailableLabel={t("unknown")}+ copyLabel={t("copyIP")}+ copiedLabel={t("copied")}+ locationLabel={t("location")}+ cityLabel={t("city")}+ asnLabel={t("asn")}+ asOrganizationLabel={t("asOrganization")}+ className="flex-1"+ triggerClassName="font-mono"+ /><Buttonvariant="ghost"size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium shrink-0",- isExpanded ? "bg-primary/10 text-primary" : "bg-secondary/50 text-muted-foreground",+ isMobileActive ? "bg-primary/10 text-primary" : "bg-secondary/50 text-muted-foreground",)}onClick={(e) => {e.stopPropagation();- toggleExpand(ip.ip);+ openMobileDetails(ip);}}><Globe className="h-3 w-3" />{ip.domains?.length || 0}- {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}+ {isMobileActive ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}</Button></div>@@ -436,36 +484,75 @@ export function IPStatsTable({</div></div>- {isExpanded && (- <ExpandReveal>- <IPExpandedDetails- ip={ip}- richExpand={richExpand}- proxyStats={expandedIPProxyQuery.data ?? []}- proxyStatsLoading={- expandedIPProxyQuery.isLoading &&- !expandedIPProxyQuery.data- }- domainDetails={expandedIPDomainDetailsQuery.data ?? []}- domainDetailsLoading={- expandedIPDomainDetailsQuery.isLoading &&- !expandedIPDomainDetailsQuery.data- }- associatedDomainsIcon="link"- labels={{- proxyTraffic: t("proxyTraffic"),- associatedDomains: t("associatedDomains"),- conn: t("conn"),- }}- showProxyTraffic={showProxyTrafficInExpand}- />- </ExpandReveal>+ {isDesktopExpanded && (+ <div className="hidden sm:block">+ <ExpandReveal>+ <IPExpandedDetails+ ip={ip}+ richExpand={richExpand}+ proxyStats={expandedIPProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedIPProxyQuery.isLoading &&+ !expandedIPProxyQuery.data+ }+ domainDetails={expandedIPDomainDetailsQuery.data ?? []}+ domainDetailsLoading={+ expandedIPDomainDetailsQuery.isLoading &&+ !expandedIPDomainDetailsQuery.data+ }+ associatedDomainsIcon="link"+ labels={{+ proxyTraffic: t("proxyTraffic"),+ associatedDomains: t("associatedDomains"),+ conn: t("conn"),+ }}+ showProxyTraffic={showProxyTrafficInExpand}+ />+ </ExpandReveal>+ </div>)}</div>);})}</div>+ <Drawer open={mobileDetailsOpen} onOpenChange={handleMobileDetailsOpenChange}>+ <DrawerContent className="sm:hidden">+ <DrawerHeader className="border-b border-border/60 bg-background/95 px-5 pt-2 pb-2.5">+ <div className="min-w-0 rounded-md border border-border/60 bg-muted/25 px-2.5 py-2">+ <DrawerTitle className="truncate text-left font-mono text-[15px] font-semibold leading-6">+ {mobileDetailIP?.ip || t("unknownIP")}+ </DrawerTitle>+ </div>+ </DrawerHeader>+ <div className="max-h-[76vh] overflow-y-auto pb-[max(env(safe-area-inset-bottom),0px)]">+ {mobileDetailIP ? (+ <IPExpandedDetails+ ip={mobileDetailIP}+ richExpand={richExpand}+ proxyStats={expandedIPProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedIPProxyQuery.isLoading &&+ !expandedIPProxyQuery.data+ }+ domainDetails={expandedIPDomainDetailsQuery.data ?? []}+ domainDetailsLoading={+ expandedIPDomainDetailsQuery.isLoading &&+ !expandedIPDomainDetailsQuery.data+ }+ associatedDomainsIcon="link"+ labels={{+ proxyTraffic: t("proxyTraffic"),+ associatedDomains: t("associatedDomains"),+ conn: t("conn"),+ }}+ showProxyTraffic={showProxyTrafficInExpand}+ />+ ) : null}+ </div>+ </DrawerContent>+ </Drawer>+{filteredIPs.length > 0 && (<div className="p-3 border-t border-border/50 bg-secondary/20"><div className="flex flex-col sm:flex-row items-center justify-between gap-3">diff --git a/apps/web/components/features/stats/table/ip-table.tsx b/apps/web/components/features/stats/table/ip-table.tsxindex 2ed00ac..da30e36 100644--- a/apps/web/components/features/stats/table/ip-table.tsx+++ b/apps/web/components/features/stats/table/ip-table.tsx@@ -25,7 +25,9 @@ import { formatBytes, formatNumber } from "@/lib/utils";import { cn } from "@/lib/utils";import { IPExpandedDetails } from "@/components/features/stats/table/expanded-details";import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badge";+import { IPPreview } from "@/components/features/stats/table/ip-preview";import { ExpandReveal } from "@/components/ui/expand-reveal";+import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";import type { IPStats, StatsSummary } from "@neko-master/shared";import { api, type TimeRange } from "@/lib/api";import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";@@ -121,6 +123,8 @@ export function IPsTable({setInternalPageSize(size);}, [onPageSizeChange]);const [expandedIP, setExpandedIP] = useState<string | null>(null);+ const [mobileDetailsOpen, setMobileDetailsOpen] = useState(false);+ const [mobileDetailIP, setMobileDetailIP] = useState<IPStats | null>(null);const [wsIPsPage, setWsIPsPage] = useState<IPsPageState | null>(null);const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);const pageOffset = (currentPage - 1) * pageSize;@@ -211,39 +215,42 @@ export function IPsTable({const data = hasWsIPsPage ? wsIPsPage!.data : ipsQuery.data?.data ?? [];const total = hasWsIPsPage ? wsIPsPage!.total : ipsQuery.data?.total ?? 0;const loading = !hasWsIPsPage && ipsQuery.isLoading && !ipsQuery.data;+ const detailIPKey = mobileDetailsOpen ? (mobileDetailIP?.ip ?? null) : expandedIP;useEffect(() => {// Backend switch means a different data universe, collapse safely.setExpandedIP(null);+ setMobileDetailsOpen(false);+ setMobileDetailIP(null);}, [activeBackendId]);const expandedIPProxyQuery = useQuery({- queryKey: getIPProxyStatsQueryKey(expandedIP, activeBackendId, detailTimeRange),- queryFn: () => api.getIPProxyStats(expandedIP!, activeBackendId, detailTimeRange),- enabled: !!activeBackendId && !!expandedIP,+ queryKey: getIPProxyStatsQueryKey(detailIPKey, activeBackendId, detailTimeRange),+ queryFn: () => api.getIPProxyStats(detailIPKey!, activeBackendId, detailTimeRange),+ enabled: !!activeBackendId && !!detailIPKey,staleTime: DETAIL_QUERY_STALE_MS,placeholderData: (previousData, previousQuery) => {const prevKey = (previousQuery?.queryKey?.[2] ?? null) as| { ip?: string; backendId?: number | null }| null;if (!prevKey) return undefined;- if (prevKey.ip !== (expandedIP ?? "")) return undefined;+ if (prevKey.ip !== (detailIPKey ?? "")) return undefined;if (prevKey.backendId !== (activeBackendId ?? null)) return undefined;return previousData;},});const expandedIPDomainDetailsQuery = useQuery({- queryKey: getIPDomainDetailsQueryKey(expandedIP, activeBackendId, detailTimeRange),- queryFn: () => api.getIPDomainDetails(expandedIP!, activeBackendId, detailTimeRange),- enabled: !!activeBackendId && !!expandedIP,+ queryKey: getIPDomainDetailsQueryKey(detailIPKey, activeBackendId, detailTimeRange),+ queryFn: () => api.getIPDomainDetails(detailIPKey!, activeBackendId, detailTimeRange),+ enabled: !!activeBackendId && !!detailIPKey,staleTime: DETAIL_QUERY_STALE_MS,placeholderData: (previousData, previousQuery) => {const prevKey = (previousQuery?.queryKey?.[2] ?? null) as| { ip?: string; backendId?: number | null }| null;if (!prevKey) return undefined;- if (prevKey.ip !== (expandedIP ?? "")) return undefined;+ if (prevKey.ip !== (detailIPKey ?? "")) return undefined;if (prevKey.backendId !== (activeBackendId ?? null)) return undefined;return previousData;},@@ -275,6 +282,18 @@ export function IPsTable({setExpandedIP(newExpanded);};+ const openMobileDetails = (ip: IPStats) => {+ setMobileDetailIP(ip);+ setMobileDetailsOpen(true);+ };++ const handleMobileDetailsOpenChange = (open: boolean) => {+ setMobileDetailsOpen(open);+ if (!open) {+ setMobileDetailIP(null);+ }+ };+const SortIcon = ({ column }: { column: SortKey }) => {if (sortKey !== column)return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;@@ -407,7 +426,8 @@ export function IPsTable({) : (data.map((ip, index) => {const ipColor = getIPColor(ip.ip);- const isExpanded = expandedIP === ip.ip;+ const isDesktopExpanded = expandedIP === ip.ip;+ const isMobileActive = mobileDetailsOpen && mobileDetailIP?.ip === ip.ip;return (<div key={ip.ip} className="group">@@ -415,7 +435,7 @@ export function IPsTable({<divclassName={cn("hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer min-w-0",- isExpanded && "bg-secondary/10",+ isDesktopExpanded && "bg-secondary/10",)}style={{ animationDelay: `${index * 50}ms` }}onClick={() => toggleExpand(ip.ip)}>@@ -425,11 +445,21 @@ export function IPsTable({className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}><Server className="w-3 h-3" /></div>- <div className="min-w-0">- <code className="text-sm font-medium truncate block">- {ip.ip}- </code>- </div>+ <IPPreview+ ip={ip.ip}+ geoIP={ip.geoIP}+ asn={ip.asn}+ unknownLabel={t("unknownIP")}+ unavailableLabel={t("unknown")}+ copyLabel={t("copyIP")}+ copiedLabel={t("copied")}+ locationLabel={t("location")}+ cityLabel={t("city")}+ asnLabel={t("asn")}+ asOrganizationLabel={t("asOrganization")}+ className="flex-1"+ triggerClassName="font-mono font-medium"+ /></div>{/* Proxy */}@@ -479,7 +509,7 @@ export function IPsTable({size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium transition-all",- isExpanded+ isDesktopExpanded? "bg-primary/10 text-primary hover:bg-primary/20": "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary",)}@@ -489,7 +519,7 @@ export function IPsTable({}}><Link2 className="h-3 w-3" />{ip.domains.length}- {isExpanded ? (+ {isDesktopExpanded ? (<ChevronUp className="h-3 w-3 ml-0.5" />) : (<ChevronDown className="h-3 w-3 ml-0.5" />@@ -502,9 +532,9 @@ export function IPsTable({<divclassName={cn("sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",- isExpanded && "bg-secondary/10",+ isMobileActive && "bg-secondary/10",)}- onClick={() => toggleExpand(ip.ip)}>+ onClick={() => openMobileDetails(ip)}>{/* Row 1: IP Icon + IP (truncate) + Domain Count */}<div className="flex items-center gap-2.5 mb-2"><div@@ -512,26 +542,37 @@ export function IPsTable({<Server className="w-3 h-3" /></div><div className="flex-1 min-w-0">- <code className="text-sm font-medium truncate block">- {ip.ip}- </code>+ <IPPreview+ ip={ip.ip}+ geoIP={ip.geoIP}+ asn={ip.asn}+ unknownLabel={t("unknownIP")}+ unavailableLabel={t("unknown")}+ copyLabel={t("copyIP")}+ copiedLabel={t("copied")}+ locationLabel={t("location")}+ cityLabel={t("city")}+ asnLabel={t("asn")}+ asOrganizationLabel={t("asOrganization")}+ triggerClassName="font-mono font-medium"+ /></div><Buttonvariant="ghost"size="sm"className={cn("h-7 px-2 gap-1 text-xs font-medium shrink-0",- isExpanded+ isMobileActive? "bg-primary/10 text-primary": "bg-secondary/50 text-muted-foreground",)}onClick={(e) => {e.stopPropagation();- toggleExpand(ip.ip);+ openMobileDetails(ip);}}><Link2 className="h-3 w-3" />{ip.domains.length}- {isExpanded ? (+ {isMobileActive ? (<ChevronUp className="h-3 w-3" />) : (<ChevronDown className="h-3 w-3" />@@ -569,28 +610,30 @@ export function IPsTable({</div>{/* Expanded Details: Proxy Traffic + Domains List */}- {isExpanded && (- <ExpandReveal>- <IPExpandedDetails- ip={ip}- proxyStats={expandedIPProxyQuery.data ?? []}- proxyStatsLoading={- expandedIPProxyQuery.isLoading &&- !expandedIPProxyQuery.data- }- domainDetails={expandedIPDomainDetailsQuery.data ?? []}- domainDetailsLoading={- expandedIPDomainDetailsQuery.isLoading &&- !expandedIPDomainDetailsQuery.data- }- associatedDomainsIcon="link"- labels={{- proxyTraffic: t("proxyTraffic"),- associatedDomains: t("associatedDomains"),- conn: t("conn"),- }}- />- </ExpandReveal>+ {isDesktopExpanded && (+ <div className="hidden sm:block">+ <ExpandReveal>+ <IPExpandedDetails+ ip={ip}+ proxyStats={expandedIPProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedIPProxyQuery.isLoading &&+ !expandedIPProxyQuery.data+ }+ domainDetails={expandedIPDomainDetailsQuery.data ?? []}+ domainDetailsLoading={+ expandedIPDomainDetailsQuery.isLoading &&+ !expandedIPDomainDetailsQuery.data+ }+ associatedDomainsIcon="link"+ labels={{+ proxyTraffic: t("proxyTraffic"),+ associatedDomains: t("associatedDomains"),+ conn: t("conn"),+ }}+ />+ </ExpandReveal>+ </div>)}</div>);@@ -598,6 +641,39 @@ export function IPsTable({)}</div>+ <Drawer open={mobileDetailsOpen} onOpenChange={handleMobileDetailsOpenChange}>+ <DrawerContent className="sm:hidden">+ <DrawerHeader className="border-b border-border/60 px-4 py-2">+ <DrawerTitle className="truncate text-left text-sm font-semibold">+ {mobileDetailIP?.ip || t("unknownIP")}+ </DrawerTitle>+ </DrawerHeader>+ <div className="max-h-[76vh] overflow-y-auto pb-[max(env(safe-area-inset-bottom),0px)]">+ {mobileDetailIP ? (+ <IPExpandedDetails+ ip={mobileDetailIP}+ proxyStats={expandedIPProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedIPProxyQuery.isLoading &&+ !expandedIPProxyQuery.data+ }+ domainDetails={expandedIPDomainDetailsQuery.data ?? []}+ domainDetailsLoading={+ expandedIPDomainDetailsQuery.isLoading &&+ !expandedIPDomainDetailsQuery.data+ }+ associatedDomainsIcon="link"+ labels={{+ proxyTraffic: t("proxyTraffic"),+ associatedDomains: t("associatedDomains"),+ conn: t("conn"),+ }}+ />+ ) : null}+ </div>+ </DrawerContent>+ </Drawer>+{/* Pagination Footer */}{totalPages > 0 && (<div className="p-3 sm:p-4 border-t border-border/50 bg-secondary/20">diff --git a/apps/web/components/ui/drawer.tsx b/apps/web/components/ui/drawer.tsxnew file mode 100644index 0000000..8aa6923--- /dev/null+++ b/apps/web/components/ui/drawer.tsx@@ -0,0 +1,135 @@+"use client"++import * as React from "react"+import { Drawer as DrawerPrimitive } from "vaul"++import { cn } from "@/lib/utils"++function Drawer({+ ...props+}: React.ComponentProps<typeof DrawerPrimitive.Root>) {+ return <DrawerPrimitive.Root data-slot="drawer" {...props} />+}++function DrawerTrigger({+ ...props+}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {+ return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />+}++function DrawerPortal({+ ...props+}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {+ return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />+}++function DrawerClose({+ ...props+}: React.ComponentProps<typeof DrawerPrimitive.Close>) {+ return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />+}++function DrawerOverlay({+ className,+ ...props+}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {+ return (+ <DrawerPrimitive.Overlay+ data-slot="drawer-overlay"+ className={cn(+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",+ className+ )}+ {...props}+ />+ )+}++function DrawerContent({+ className,+ children,+ ...props+}: React.ComponentProps<typeof DrawerPrimitive.Content>) {+ return (+ <DrawerPortal data-slot="drawer-portal">+ <DrawerOverlay />+ <DrawerPrimitive.Content+ data-slot="drawer-content"+ className={cn(+ "group/drawer-content bg-background fixed z-50 flex h-auto flex-col",+ "data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",+ "data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",+ "data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",+ "data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",+ className+ )}+ {...props}+ >+ <div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />+ {children}+ </DrawerPrimitive.Content>+ </DrawerPortal>+ )+}++function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="drawer-header"+ className={cn(+ "flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",+ className+ )}+ {...props}+ />+ )+}++function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="drawer-footer"+ className={cn("mt-auto flex flex-col gap-2 p-4", className)}+ {...props}+ />+ )+}++function DrawerTitle({+ className,+ ...props+}: React.ComponentProps<typeof DrawerPrimitive.Title>) {+ return (+ <DrawerPrimitive.Title+ data-slot="drawer-title"+ className={cn("text-foreground font-semibold", className)}+ {...props}+ />+ )+}++function DrawerDescription({+ className,+ ...props+}: React.ComponentProps<typeof DrawerPrimitive.Description>) {+ return (+ <DrawerPrimitive.Description+ data-slot="drawer-description"+ className={cn("text-muted-foreground text-sm", className)}+ {...props}+ />+ )+}++export {+ Drawer,+ DrawerPortal,+ DrawerOverlay,+ DrawerTrigger,+ DrawerClose,+ DrawerContent,+ DrawerHeader,+ DrawerFooter,+ DrawerTitle,+ DrawerDescription,+}diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.tsindex fd83fd5..20bfd96 100644--- a/apps/web/lib/api.ts+++ b/apps/web/lib/api.ts@@ -171,6 +171,16 @@ export interface GatewayRulesResponse {_availablePolicies?: string[];}+export type GeoLookupProvider = "online" | "local";++export interface GeoLookupConfig {+ provider: GeoLookupProvider;+ mmdbDir: string;+ onlineApiUrl: string;+ localMmdbReady: boolean;+ missingMmdbFiles: string[];+}+const DEFAULT_DB_STATS = {size: 0,totalConnectionsCount: 0,@@ -182,6 +192,14 @@ const DEFAULT_RETENTION_CONFIG = {autoCleanup: true,} as const;+const DEFAULT_GEO_LOOKUP_CONFIG: GeoLookupConfig = {+ provider: "online",+ mmdbDir: "geoip",+ onlineApiUrl: "https://api.ipinfo.es/ipinfo",+ localMmdbReady: false,+ missingMmdbFiles: [],+};+function buildUrl(base: string, params: Record<string, string | number | undefined>): string {// Use simple URL construction for client-side relative URLsconst searchParams = new URLSearchParams();@@ -554,6 +572,22 @@ export const api = {updateRetentionConfig: (config: { connectionLogsDays: number; hourlyStatsDays: number; autoCleanup?: boolean }) =>fetchJson<{ message: string }>(`${API_BASE}/db/retention`, 'PUT', config),+ getGeoLookupConfig: async () => {+ try {+ return await fetchJson<GeoLookupConfig>(`${API_BASE}/db/geoip`);+ } catch (error) {+ if (isApiStatus(error, 404)) {+ return { ...DEFAULT_GEO_LOOKUP_CONFIG };+ }+ throw error;+ }+ },++ updateGeoLookupConfig: (+ config: { provider?: GeoLookupProvider; onlineApiUrl?: string },+ ) =>+ fetchJson<{ message: string; config: GeoLookupConfig }>(`${API_BASE}/db/geoip`, 'PUT', config),+// Auth managementgetAuthState: () =>fetchJson<{ enabled: boolean; hasToken: boolean }>(`${API_BASE}/auth/state`),diff --git a/apps/web/messages/en.json b/apps/web/messages/en.jsonindex 8f9af46..d20a890 100644--- a/apps/web/messages/en.json+++ b/apps/web/messages/en.json@@ -185,10 +185,18 @@"noResults": "No IPs found","noData": "No IP data available","noDataHint": "Traffic data will appear here after collection starts.",+ "unknownIP": "Unknown IP",+ "unknown": "Unknown","ip": "IP Address","ipAddress": "IP Address","ipList": "IP Addresses",+ "fullIP": "Full IP",+ "copyIP": "Copy",+ "copied": "Copied","location": "Location",+ "city": "City",+ "asn": "ASN",+ "asOrganization": "Organization","domains": "Domains","domainCount": "Domains","proxy": "Proxy",@@ -406,6 +414,14 @@"faviconGoogle": "Google Favicon","faviconIm": "favicon.im (Recommended for China)","faviconOff": "Off (Use default icons)",+ "geoLookupProvider": "IP Lookup Source",+ "geoLookupProviderDescription": "Switch between online API and local MMDB lookup. Local mode avoids external network dependency and improves privacy.",+ "geoLookupOnline": "Online API (Default)",+ "geoLookupLocal": "Local MMDB",+ "geoLookupFixedPathHint": "Local mode automatically reads MMDB files (requires GeoLite2-City.mmdb and GeoLite2-ASN.mmdb, Country optional).",+ "geoLookupLocalUnavailable": "Local MMDB is currently unavailable. Missing required files: {files}",+ "geoLookupUpdated": "IP lookup configuration saved",+ "geoLookupUpdateFailed": "Failed to save IP lookup configuration","dataRetention": "Data Storage Time","dataRetentionDescription": "Control how long detailed connection records are kept. Domain and IP statistics are always preserved. Longer storage uses more disk space but allows troubleshooting older issues.","retentionPresetMinimal": "Minimal",diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.jsonindex daf29fb..50fb222 100644--- a/apps/web/messages/zh.json+++ b/apps/web/messages/zh.json@@ -184,10 +184,18 @@"noResults": "未找到 IP","noData": "暂无 IP 数据","noDataHint": "开始采集后,这里会显示 IP 流量数据。",+ "unknownIP": "未知 IP",+ "unknown": "未知","ip": "IP 地址","ipAddress": "IP 地址","ipList": "IP 地址",+ "fullIP": "完整 IP",+ "copyIP": "复制",+ "copied": "已复制","location": "位置",+ "city": "城市",+ "asn": "ASN",+ "asOrganization": "运营组织","domains": "域名","domainCount": "域名数","proxy": "代理节点",@@ -405,6 +413,14 @@"faviconGoogle": "Google Favicon","faviconIm": "favicon.im (国内推荐)","faviconOff": "关闭(使用默认图标)",+ "geoLookupProvider": "IP 查询来源",+ "geoLookupProviderDescription": "可在在线接口与本地 MMDB 查询间切换。本地模式不依赖外部网络并且更有利于隐私保护。",+ "geoLookupOnline": "在线接口(默认)",+ "geoLookupLocal": "本地 MMDB",+ "geoLookupFixedPathHint": "本地模式会自动读取 MMDB 文件(需包含 GeoLite2-City.mmdb 和 GeoLite2-ASN.mmdb,Country 可选)。",+ "geoLookupLocalUnavailable": "本地 MMDB 当前不可用,缺少必需文件:{files}",+ "geoLookupUpdated": "IP 查询配置已保存",+ "geoLookupUpdateFailed": "IP 查询配置保存失败","dataRetention": "数据存储时间","dataRetentionDescription": "控制详细连接记录的保存时长。域名和IP的统计数据将永久保留。存储时间越长占用磁盘空间越多,但可用于排查更早的问题。","retentionPresetMinimal": "极简",diff --git a/apps/web/package.json b/apps/web/package.jsonindex 2b62d09..61af3b1 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -13,9 +13,15 @@"@ducanh2912/next-pwa": "^10.2.9","@neko-master/shared": "workspace:*","@radix-ui/react-alert-dialog": "^1.1.15",+ "@radix-ui/react-dropdown-menu": "^2.1.16","@radix-ui/react-popover": "^1.1.15","@radix-ui/react-radio-group": "^1.3.8","@radix-ui/react-scroll-area": "^1.2.10",+ "@radix-ui/react-select": "^2.2.6",+ "@radix-ui/react-separator": "^1.1.8",+ "@radix-ui/react-slot": "^1.2.4",+ "@radix-ui/react-switch": "^1.2.6",+ "@radix-ui/react-tabs": "^1.1.13","@tanstack/react-query": "^5.90.20","@xyflow/react": "^12.10.0","class-variance-authority": "^0.7.1",@@ -36,20 +42,15 @@"react-simple-maps": "^3.0.0","recharts": "^2.15.4","sonner": "^2.0.7",- "@radix-ui/react-dropdown-menu": "^2.1.16",- "@radix-ui/react-select": "^2.2.6",- "@radix-ui/react-separator": "^1.1.8",- "@radix-ui/react-slot": "^1.2.4",- "@radix-ui/react-switch": "^1.2.6",- "@radix-ui/react-tabs": "^1.1.13",- "tailwind-merge": "^2.6.1"+ "tailwind-merge": "^2.6.1",+ "vaul": "^1.1.2"},"devDependencies": {"@tailwindcss/postcss": "^4.1.0",- "@types/react-copy-to-clipboard": "^5.0.7","@tanstack/react-query-devtools": "^5.91.3","@types/node": "^22","@types/react": "^19",+ "@types/react-copy-to-clipboard": "^5.0.7","@types/react-dom": "^19","eslint": "^9","eslint-config-next": "^16.0.0",diff --git a/docker-compose.yml b/docker-compose.ymlindex 9b03a85..b9aec4a 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -11,6 +11,7 @@ services:- "${WS_EXTERNAL_PORT:-3002}:3002" # WebSocketvolumes:- ./data:/app/data+ - ./geoip:/app/data/geoip:roenvironment:- NODE_ENV=production- WEB_PORT=3000@@ -21,6 +22,9 @@ services:- API_EXTERNAL_PORT=${API_EXTERNAL_PORT:-3001}- WS_EXTERNAL_PORT=${WS_EXTERNAL_PORT:-3002}- DB_PATH=/app/data/stats.db+ - COOKIE_SECRET=${COOKIE_SECRET:-}+ - GEOIP_LOOKUP_PROVIDER=${GEOIP_LOOKUP_PROVIDER:-}+ - GEOIP_ONLINE_API_URL=${GEOIP_ONLINE_API_URL:-}networks:- neko-master-network# 健康检查diff --git a/package.json b/package.jsonindex 78b60e6..053b823 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "neko-master",- "version": "1.2.8",+ "version": "1.2.9","description": "Modern traffic analytics for edge gateways","private": true,"workspaces": [diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 32cfda4..bfe21f4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -35,6 +35,9 @@ importers:fastify:specifier: ^5.7.4version: 5.7.4+ maxmind:+ specifier: ^5.0.5+ version: 5.0.5ws:specifier: ^8.19.0version: 8.19.0@@ -168,6 +171,9 @@ importers:tailwind-merge:specifier: ^2.6.1version: 2.6.1+ vaul:+ specifier: ^1.1.2+ version: 1.1.2(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])devDependencies:'@tailwindcss/postcss':specifier: ^4.1.0@@ -4085,6 +4091,10 @@ packages:resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-1lcH2kMjbBpCFhuHaMU32vz8CuOsKttRcWMQyXvtlklopCzN7NNHSVR/h9RYa8JPuFTGmkn2vYARm+7cIGuqDw==}+ engines: {node: '>=12', npm: '>=6'}+resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==}@@ -4125,6 +4135,10 @@ packages:resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}+ resolution: {integrity: sha512-7e87vk0DdWT647wjcfEtWeMtjm+zVGqNohN/aeIymbUfjHQ2T4Sx5kM+1irVDBSloNC3CkGKxswdMoo8yhqTDg==}+ engines: {node: '>=10', npm: '>=6'}+resolution: {integrity: sha512-XRPebVypsl0UM+7v0Hr8o9UAj0S2djsQWRdHBd5iVouVpMrQqAI0C/rDAT3QaYnXnHuC5hMcwDHCboNeyYjPoQ==}@@ -4818,6 +4832,10 @@ packages:resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}+ resolution: {integrity: sha512-w/Te7uMUVeH0CR8vZIjr+XiN41V+30lkDdK+NRIDCUYKKuL9VcmaUEmaPISuwGhLlrTGh5yu18lENtR9axSxYw==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}@@ -5028,6 +5046,12 @@ packages:resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}+ resolution: {integrity: sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA==}+ peerDependencies:+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc+resolution: {integrity: sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==}@@ -8583,8 +8607,8 @@ snapshots:'@next/eslint-plugin-next': 16.1.6eslint: 9.39.2([email protected])eslint-import-resolver-node: 0.3.9- eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))+ eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))eslint-plugin-react-hooks: 7.0.1([email protected]([email protected]))@@ -8606,7 +8630,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])):dependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.3@@ -8617,22 +8641,22 @@ snapshots:tinyglobby: 0.2.15unrs-resolver: 1.11.1optionalDependencies:- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.39.2([email protected])eslint-import-resolver-node: 0.3.9- eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])):dependencies:'@rtsao/scc': 1.1.0array-includes: 3.1.9@@ -8643,7 +8667,7 @@ snapshots:doctrine: 2.1.0eslint: 9.39.2([email protected])eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))hasown: 2.0.2is-core-module: 2.16.1is-glob: 4.0.3@@ -9392,6 +9416,11 @@ snapshots:+ dependencies:+ mmdb-lib: 3.0.2+ tiny-lru: 11.4.7+@@ -9425,6 +9454,8 @@ snapshots:+ [email protected]: {}+dependencies:motion-utils: 12.29.2@@ -10277,6 +10308,8 @@ snapshots:+ [email protected]: {}+@@ -10509,6 +10542,15 @@ snapshots:+ [email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected]):+ dependencies:+ '@radix-ui/react-dialog': 1.1.15(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ react: 19.2.4+ react-dom: 19.2.4([email protected])+ transitivePeerDependencies:+ - '@types/react'+ - '@types/react-dom'+dependencies:'@types/d3-array': 3.2.2