Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

refactor: rebrand to Neko Master and cleanup legacy references

luolei5273f4f6027e
diff --git a/.env.example b/.env.example
index 71982db..e8a3fab 100644
--- a/.env.example
+++ b/.env.example
@@ -1,5 +1,5 @@
# =============================================================================
-# Clash Master 环境配置文件
+# Neko Master 环境配置文件
# =============================================================================
# 使用方法:
# 1. 复制本文件为 .env: cp .env.example .env
diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml
index ea8ec06..c850491 100644
--- a/.github/workflows/docker-build.yml
+++ b/.github/workflows/docker-build.yml
@@ -9,7 +9,8 @@ on:
workflow_dispatch:
env:
- DOCKERHUB_IMAGE: foru17/clash-master
+ DOCKERHUB_IMAGE_OLD: foru17/clash-master
+ DOCKERHUB_IMAGE_NEW: foru17/neko-master
GHCR_IMAGE: ghcr.io/${{ github.repository }}
jobs:
@@ -67,7 +68,8 @@ jobs:
uses: docker/metadata-action@v5
with:
images: |
- ${{ env.DOCKERHUB_IMAGE }}
+ ${{ env.DOCKERHUB_IMAGE_OLD }}
+ ${{ env.DOCKERHUB_IMAGE_NEW }}
${{ env.GHCR_IMAGE }}
tags: |
type=raw,value=latest,enable=${{ github.ref_name == 'main' }}
@@ -98,6 +100,6 @@ jobs:
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- repository: foru17/clash-master
+ repository: foru17/neko-master
readme-filepath: ./README.md
- short-description: "Modern traffic analysis dashboard for Clash"
+ short-description: "Modern Network Traffic Analytics"
diff --git a/.gitignore b/.gitignore
index 8c67043..0d3fa12 100644
--- a/.gitignore
+++ b/.gitignore
@@ -61,3 +61,4 @@ next-env.d.ts
# AI dev logs
.specstory/
.claude/
+.refactoring_docs/
diff --git a/Dockerfile b/Dockerfile
index 2f77d7f..38edf18 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -24,17 +24,17 @@ RUN pnpm install --frozen-lockfile
COPY . .
# Build shared package first
-RUN pnpm --filter @clashmaster/shared build
+RUN pnpm --filter @neko-master/shared build
# Build collector
-RUN pnpm --filter @clashmaster/collector build
+RUN pnpm --filter @neko-master/collector build
# Build web with production env for PWA
ENV NODE_ENV=production
-RUN pnpm --filter @clashmaster/web build
+RUN pnpm --filter @neko-master/web build
# Create a minimal, deployable bundle for collector (production deps only)
-RUN pnpm --filter @clashmaster/collector deploy --prod /app/apps/collector-deploy && \
+RUN pnpm --filter @neko-master/collector deploy --prod /app/apps/collector-deploy && \
mkdir -p /app/apps/collector-deploy/dist && \
cp -r /app/apps/collector/dist/* /app/apps/collector-deploy/dist/
diff --git a/MULTI_BACKEND_ARCH.md b/MULTI_BACKEND_ARCH.md
deleted file mode 100644
index d1b9019..0000000
--- a/MULTI_BACKEND_ARCH.md
+++ /dev/null
@@ -1,159 +0,0 @@
-# 多后端架构设计
-
-本文档描述 Clash Master 的多后端架构设计,支持同时监控多个 OpenClash 实例。
-
-## 核心概念
-
-### 1. 数据隔离 (Data Isolation)
-
-每个后端的数据存储在独立的分区中,通过 `backend_id` 字段区分。
-
-**受影响的表:**
-
-- `domain_stats` - 域名统计
-- `ip_stats` - IP 统计
-- `proxy_stats` - 代理统计
-- `rule_stats` - 规则统计
-- `rule_proxy_map` - 规则-代理映射
-- `country_stats` - 国家统计
-- `hourly_stats` - 小时统计
-- `connection_logs` - 连接日志
-
-**主键设计:** 所有统计表使用复合主键 `(backend_id, entity_id)`,例如 `(backend_id, domain)`。
-
-### 2. 后端状态 (Backend States)
-
-每个后端有两个独立的状态标志:
-
-| 字段 | 含义 | 说明 |
-| ----------- | -------- | --------------------------------------------- |
-| `is_active` | 显示状态 | 当前在 UI 中显示哪个后端的数据(唯一) |
-| `listening` | 收集状态 | 是否正在从该后端收集数据(多个可同时为 true) |
-| `enabled` | 启用状态 | 后端是否可用(被禁用的后端不参与任何操作) |
-
-**使用场景:**
-
-- 用户可以在 UI 中查看后端 A 的数据
-- 同时后端 B 和 C 在后台继续收集数据
-- 随时切换到后端 B 或 C 查看它们的数据
-
-### 3. 持续收集 (Continuous Collection)
-
-收集器维护一个连接池:
-
-```typescript
-(Map < backendId, OpenClashCollector > collectors);
-```
-
-- 每个 `listening=true` 且 `enabled=true` 的后端都有一个独立的 WebSocket 连接
-- 连接状态独立管理,一个后端断开不影响其他后端
-- 每 5 秒检查一次后端配置变化,动态启动/停止收集器
-
-## API 设计
-
-### 获取统计数据
-
-所有统计 API 支持可选的 `backendId` 参数:
-
-```
-GET /api/stats/summary?backendId=1
-GET /api/stats/domains?backendId=1&limit=50
-GET /api/stats/trend?backendId=1&minutes=30
-```
-
-如果不提供 `backendId`,则使用当前 `is_active` 的后端。
-
-### 后端管理 API
-
-```
-# 获取所有后端
-GET /api/backends
-
-# 获取当前活跃后端(用于显示)
-GET /api/backends/active
-
-# 获取正在收集数据的后端列表
-GET /api/backends/listening
-
-# 设置显示的后端(切换 UI 显示)
-POST /api/backends/:id/activate
-
-# 设置收集状态(开始/停止收集)
-POST /api/backends/:id/listening
-Body: { "listening": true/false }
-
-# 清空指定后端的所有数据
-POST /api/backends/:id/clear-data
-```
-
-## 前端设计
-
-### 后端选择器
-
-顶部导航栏显示当前显示的后端名称,点击可切换:
-
-```
-[概览] [后端A ▼] [收集指示器] [语言] [主题] [刷新]
-```
-
-下拉菜单显示:
-
-- 所有后端列表,标注当前显示的后端
-- 正在收集数据的后端显示绿色指示器
-- "管理后端" 选项打开配置对话框
-
-### 收集状态指示器
-
-显示当前正在收集数据的后端:
-
-```
-[● 后端A] [● 后端B] [● 后端C] [+2]
-```
-
-### 设置对话框
-
-每个后端卡片显示:
-
-- 名称和连接信息
-- **显示按钮** - 切换 `is_active` 状态
-- **收集开关** - 切换 `listening` 状态
-- 编辑和删除按钮
-
-## 数据库迁移
-
-从单后端迁移到多后端架构时:
-
-1. 创建默认后端配置
-2. 将所有现有数据关联到默认后端(`backend_id=1`)
-3. 添加 `listening` 列到 `backend_configs` 表
-4. 更新所有表的主键为复合主键
-
-迁移代码在 `db.ts` 的 `migrateIfNeeded()` 方法中自动执行。
-
-## 使用场景示例
-
-### 场景 1:主备切换
-
-- 后端 A(主):listening=true, is_active=true
-- 后端 B(备):listening=true, is_active=false
-- 当 A 故障时,点击 B 的显示按钮切换到备用后端
-
-### 场景 2:多节点监控
-
-- 家中路由器:listening=true, is_active=true
-- VPS 服务器:listening=true, is_active=false
-- 办公室路由器:listening=true, is_active=false
-- 同时监控所有节点,在 UI 中切换查看
-
-### 场景 3:数据对比
-
-- 在节点 A 收集一段时间数据
-- 切换到节点 B 查看差异
-- 所有数据都保留,可以随时回顾
-
-## 性能考虑
-
-1. **索引优化**:所有查询都包含 `backend_id` 过滤,已创建相应索引
-2. **连接管理**:每个后端独立 WebSocket 连接,避免相互影响
-3. **数据清理**:支持按后端清理数据,不影响其他后端
-4. **内存使用**:连接池按需创建,无数据后端不占用连接资源
diff --git a/README.en.md b/README.en.md
index f190aa0..ff37293 100644
--- a/README.en.md
+++ b/README.en.md
@@ -1,19 +1,19 @@
<p align="center">
- <img src="./assets/icon-clash-master.png" width="200" alt="Clash Master Logo" style="margin-bottom: 16px;">
+ <img src="./assets/icon-neko-master.png" width="200" alt="Neko Master Logo" style="margin-bottom: 16px;">
<br>
- <b style="font-size: 32px;">Clash Master</b>
+ <b style="font-size: 32px;">Neko Master</b>
</p>
<p align="center">
- <b>Modern network visualization dashboard</b><br>
+ <b>Modern Network Traffic Analytics</b><br>
<span>Real-time Monitoring · Traffic Audit · Multi-Gateway Management</span>
</p>
<p align="center">
- <a href="https://github.com/foru17/clash-master/stargazers"><img src="https://img.shields.io/github/stars/foru17/clash-master?style=flat-square&color=yellow" alt="Stars"></a>
- <a href="https://hub.docker.com/r/foru17/clash-master"><img src="https://img.shields.io/docker/pulls/foru17/clash-master?style=flat-square&color=blue&logo=docker" alt="Docker Pulls"></a>
- <a href="https://hub.docker.com/r/foru17/clash-master"><img src="https://img.shields.io/docker/v/foru17/clash-master?style=flat-square&label=Docker&color=2496ED" alt="Docker Version"></a>
- <a href="https://github.com/foru17/clash-master/blob/main/LICENSE"><img src="https://img.shields.io/github/license/foru17/clash-master?style=flat-square&color=green" alt="License"></a>
+ <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://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" alt="Node.js">
</p>
@@ -31,9 +31,9 @@
>
> This project is open-source under the MIT License. The developers assume no responsibility for any consequences resulting from the use of this software.
-![Clash Master Overview](./assets/clash-master-overview.png)
-![Clash Master Rules](./assets/clash-master-rules.png)
-![Clash Master Regions](./assets/clash-master-regions.png)
+![Neko Master Overview](./assets/neko-master-overview.png)
+![Neko Master Rules](./assets/neko-master-rules.png)
+![Neko Master Regions](./assets/neko-master-regions.png)
## 📋 Table of Contents
@@ -70,9 +70,9 @@
```yaml
services:
- clash-master:
- image: foru17/clash-master:latest
- container_name: clash-master
+ neko-master:
+ image: foru17/neko-master:latest
+ container_name: neko-master
restart: unless-stopped
ports:
- "3000:3000" # Web UI
@@ -90,9 +90,9 @@ services:
```yaml
services:
- clash-master:
- image: foru17/clash-master:latest
- container_name: clash-master
+ neko-master:
+ image: foru17/neko-master:latest
+ container_name: neko-master
restart: unless-stopped
ports:
- "3000:3000" # Web UI
@@ -117,20 +117,20 @@ Open <http://localhost:3000> to get started.
```bash
# Minimal (only 3000)
docker run -d \
- --name clash-master \
+ --name neko-master \
-p 3000:3000 \
-v $(pwd)/data:/app/data \
--restart unless-stopped \
- foru17/clash-master:latest
+ foru17/neko-master:latest
# Real-time WS (with reverse proxy)
docker run -d \
- --name clash-master \
+ --name neko-master \
-p 3000:3000 \
-p 3002:3002 \
-v $(pwd)/data:/app/data \
--restart unless-stopped \
- foru17/clash-master:latest
+ foru17/neko-master:latest
```
Open <http://localhost:3000> to get started.
@@ -147,10 +147,10 @@ Automatically detects port conflicts and configures everything:
```bash
# Using curl
-curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash
# Or using wget
-wget -qO- https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+wget -qO- https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash
```
The script will automatically:
@@ -164,8 +164,8 @@ The script will automatically:
```bash
# 1. Clone the repository
-git clone https://github.com/foru17/clash-master.git
-cd clash-master
+git clone https://github.com/foru17/neko-master.git
+cd neko-master
# 2. Install dependencies
pnpm install
@@ -178,7 +178,7 @@ Open <http://localhost:3000> to configure.
## 📖 First Use
-![First Use](./assets/clash-master-setup.png)
+![First Use](./assets/neko-master-setup.png)
1. Open <http://localhost:3000>
2. The **Gateway Configuration** dialog will appear on first visit
@@ -228,7 +228,7 @@ ports:
### Solution 3: Use One-Click Script
```bash
-curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash
```
The script will automatically detect and suggest available ports.
@@ -276,7 +276,7 @@ server {
server_name clash.example.com;
location / {
- proxy_pass http://<clash-master-host>:3000;
+ 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;
@@ -285,7 +285,7 @@ server {
}
location ^~ /_cm_ws {
- proxy_pass http://<clash-master-host>:3002;
+ proxy_pass http://<neko-master-host>:3002;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
@@ -409,10 +409,10 @@ The difference is real-time experience: without WS, updates are polling-based (a
```bash
# View all logs
-docker logs -f clash-master
+docker logs -f neko-master
# View last 100 lines
-docker logs --tail 100 clash-master
+docker logs --tail 100 neko-master
```
### Q: How to backup data?
@@ -434,7 +434,7 @@ cp -r ./data ./data-backup-$(date +%Y%m%d)
## 📁 Project Structure
```
-clash-master/
+neko-master/
├── docker-compose.yml # Docker Compose config
├── Dockerfile # Docker image build
├── setup.sh # One-click setup script
@@ -462,9 +462,9 @@ clash-master/
Contributions are welcome!
-- 🐛 [Submit Bug](https://github.com/foru17/clash-master/issues/new)
-- 💡 [Request Feature](https://github.com/foru17/clash-master/issues/new)
-- 🔧 [Contribute Code](https://github.com/foru17/clash-master/pulls)
+- 🐛 [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
@@ -474,7 +474,7 @@ Contributions are welcome!
## ⭐ Star History
-[![Star History Chart](https://api.star-history.com/svg?repos=foru17/clash-master&type=date&legend=top-left)](https://www.star-history.com/#foru17/clash-master&type=date&legend=top-left)
+[![Star History Chart](https://api.star-history.com/svg?repos=foru17/neko-master&type=date&legend=top-left)](https://www.star-history.com/#foru17/neko-master&type=date&legend=top-left)
---
diff --git a/README.md b/README.md
index 0632c66..7e8e94f 100644
--- a/README.md
+++ b/README.md
@@ -1,19 +1,19 @@
<p align="center">
- <img src="./assets/icon-clash-master.png" width="200" alt="Clash Master Logo" style="margin-bottom: 16px;">
+ <img src="./assets/icon-neko-master.png" width="200" alt="Neko Master Logo" style="margin-bottom: 16px;">
<br>
- <b style="font-size: 32px;">Clash Master</b>
+ <b style="font-size: 32px;">Neko Master</b>
</p>
<p align="center">
- <b>优雅且现代化的网络可视化分析面板</b><br>
+ <b>优雅且现代化的网络可视化分析工具</b><br>
<span>实时监控 · 流量审计 · 多网关管理</span>
</p>
<p align="center">
- <a href="https://github.com/foru17/clash-master/stargazers"><img src="https://img.shields.io/github/stars/foru17/clash-master?style=flat-square&color=yellow" alt="Stars"></a>
- <a href="https://hub.docker.com/r/foru17/clash-master"><img src="https://img.shields.io/docker/pulls/foru17/clash-master?style=flat-square&color=blue&logo=docker" alt="Docker Pulls"></a>
- <a href="https://hub.docker.com/r/foru17/clash-master"><img src="https://img.shields.io/docker/v/foru17/clash-master?style=flat-square&label=Docker&color=2496ED" alt="Docker Version"></a>
- <a href="https://github.com/foru17/clash-master/blob/main/LICENSE"><img src="https://img.shields.io/github/license/foru17/clash-master?style=flat-square&color=green" alt="License"></a>
+ <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://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" alt="Node.js">
</p>
@@ -31,9 +31,9 @@
>
> 本项目遵循 MIT 协议开源,不对因使用本软件产生的任何后果承担责任。请在合规范围内使用。
-![Clash Master Overview](./assets/clash-master-overview.png)
-![Clash Master Rules](./assets/clash-master-rules.png)
-![Clash Master Regions](./assets/clash-master-regions.png)
+![Neko Master Overview](./assets/neko-master-overview.png)
+![Neko Master Rules](./assets/neko-master-rules.png)
+![Neko Master Regions](./assets/neko-master-regions.png)
## 📋 目录
@@ -55,9 +55,9 @@
```yaml
services:
- clash-master:
- image: foru17/clash-master:latest
- container_name: clash-master
+ neko-master:
+ image: foru17/neko-master:latest
+ container_name: neko-master
restart: unless-stopped
ports:
- "3000:3000" # Web UI
@@ -75,9 +75,9 @@ services:
```yaml
services:
- clash-master:
- image: foru17/clash-master:latest
- container_name: clash-master
+ neko-master:
+ image: foru17/neko-master:latest
+ container_name: neko-master
restart: unless-stopped
ports:
- "3000:3000" # Web UI
@@ -102,20 +102,20 @@ docker compose up -d
```bash
# 最简(仅 3000)
docker run -d \
- --name clash-master \
+ --name neko-master \
-p 3000:3000 \
-v $(pwd)/data:/app/data \
--restart unless-stopped \
- foru17/clash-master:latest
+ foru17/neko-master:latest
# 实时 WS(配合反代)
docker run -d \
- --name clash-master \
+ --name neko-master \
-p 3000:3000 \
-p 3002:3002 \
-v $(pwd)/data:/app/data \
--restart unless-stopped \
- foru17/clash-master:latest
+ foru17/neko-master:latest
```
> 默认前端 API 走同域 `/api`,通常不需要额外暴露 3001。
@@ -132,10 +132,10 @@ docker run -d \
```bash
# 使用 curl
-curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash
# 或使用 wget
-wget -qO- https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+wget -qO- https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash
```
脚本会自动:
@@ -149,8 +149,8 @@ wget -qO- https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh |
```bash
# 1. 克隆仓库
-git clone https://github.com/foru17/clash-master.git
-cd clash-master
+git clone https://github.com/foru17/neko-master.git
+cd neko-master
# 2. 安装依赖
pnpm install
@@ -163,7 +163,7 @@ pnpm dev
## 📖 首次使用
-![首次使用](./assets/clash-master-setup.png)
+![首次使用](./assets/neko-master-setup.png)
1. 打开 <http://localhost:3000>
2. 首次访问会弹出**网关配置**对话框
@@ -213,7 +213,7 @@ ports:
### 方案 3:使用一键脚本
```bash
-curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh | bash
+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash
```
脚本会自动检测并提供可用的端口。
@@ -260,7 +260,7 @@ server {
server_name clash.example.com;
location / {
- proxy_pass http://<clash-master-host>:3000;
+ 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;
@@ -269,7 +269,7 @@ server {
}
location ^~ /_cm_ws {
- proxy_pass http://<clash-master-host>:3002;
+ proxy_pass http://<neko-master-host>:3002;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
@@ -394,10 +394,10 @@ docker compose up -d
```bash
# 查看所有日志
-docker logs -f clash-master
+docker logs -f neko-master
# 只看最后 100 行
-docker logs --tail 100 clash-master
+docker logs --tail 100 neko-master
```
### Q: 如何备份数据?
@@ -419,7 +419,7 @@ cp -r ./data ./data-backup-$(date +%Y%m%d)
## 📁 项目结构
```
-clash-master/
+neko-master/
├── docker-compose.yml # Docker Compose 配置
├── Dockerfile # Docker 镜像构建
├── setup.sh # 一键配置脚本
@@ -448,7 +448,7 @@ MIT License © 2024 [foru17](https://github.com/foru17)
## Star History
-[![Star History Chart](https://api.star-history.com/svg?repos=foru17/clash-master&type=date&legend=top-left)](https://www.star-history.com/#foru17/clash-master&type=date&legend=top-left)
+[![Star History Chart](https://api.star-history.com/svg?repos=foru17/neko-master&type=date&legend=top-left)](https://www.star-history.com/#foru17/neko-master&type=date&legend=top-left)
---
diff --git a/apps/collector/.env.example b/apps/collector/.env.example
index 7319ede..3a1502e 100644
--- a/apps/collector/.env.example
+++ b/apps/collector/.env.example
@@ -1,4 +1,4 @@
-# Clash Master Collector 配置(可选)
+# Neko Master Collector 配置(可选)
# 默认端口即可满足大部分需求
# API 服务端口(默认 3001)
@@ -10,5 +10,5 @@
# SQLite 数据库路径(默认当前目录)
# DB_PATH=./stats.db
-# ⚠️ 注意:OpenClash 后端配置通过 Web 界面动态添加
-# 无需在此文件配置 CLASH_URL 或 CLASH_TOKEN
+# ⚠️ 注意:Gateway 后端配置通过 Web 界面动态添加
+# 无需在此文件配置 GATEWAY_URL 或 GATEWAY_TOKEN
diff --git a/apps/collector/package.json b/apps/collector/package.json
index 20e1eb6..5c17b04 100644
--- a/apps/collector/package.json
+++ b/apps/collector/package.json
@@ -1,5 +1,5 @@
{
- "name": "@clashmaster/collector",
+ "name": "@neko-master/collector",
"version": "1.0.0",
"type": "module",
"scripts": {
@@ -8,7 +8,7 @@
"start": "node dist/index.js"
},
"dependencies": {
- "@clashmaster/shared": "workspace:*",
+ "@neko-master/shared": "workspace:*",
"@fastify/cors": "^9.0.1",
"better-sqlite3": "^11.8.0",
"dotenv": "^16.6.0",
diff --git a/apps/collector/src/api.ts b/apps/collector/src/api.ts
index 33bc95c..f80b70c 100644
--- a/apps/collector/src/api.ts
+++ b/apps/collector/src/api.ts
@@ -1,1354 +1,10 @@
-import Fastify from 'fastify';
-import cors from '@fastify/cors';
-import type { StatsDatabase } from './db.js';
-import { realtimeStore } from './realtime.js';
-
-export class APIServer {
- private app: ReturnType<typeof Fastify> | null = null;
- private db: StatsDatabase;
- private port: number;
-
- constructor(port: number, db: StatsDatabase) {
- this.port = port;
- this.db = db;
- }
-
- async start() {
- const app = Fastify({ logger: false });
- this.app = app;
-
- await app.register(cors, {
- origin: true,
- credentials: true
- });
-
- // Helper to get backend ID from query or use active backend
- const getBackendId = (request: any): number | null => {
- const { backendId } = request.query as { backendId?: string };
- if (backendId) {
- const id = parseInt(backendId);
- return isNaN(id) ? null : id;
- }
- // If no backendId specified, use the active backend
- const activeBackend = this.db.getActiveBackend();
- return activeBackend?.id ?? null;
- };
-
- const getTimeRange = (
- request: any,
- reply: any,
- ): { start?: string; end?: string; active: boolean } | null => {
- const { start, end } = request.query as { start?: string; end?: string };
- if (!start && !end) {
- return { active: false };
- }
- if (!start || !end) {
- reply.status(400).send({ error: 'Both start and end must be provided together' });
- return null;
- }
-
- const startDate = new Date(start);
- const endDate = new Date(end);
- if (Number.isNaN(startDate.getTime()) || Number.isNaN(endDate.getTime())) {
- reply.status(400).send({ error: 'Invalid time range format, expected ISO datetime' });
- return null;
- }
- if (startDate > endDate) {
- reply.status(400).send({ error: 'start must be less than or equal to end' });
- return null;
- }
-
- return {
- start: startDate.toISOString(),
- end: endDate.toISOString(),
- active: true,
- };
- };
-
- const parseLimit = (
- raw: string | undefined,
- fallback: number,
- max: number,
- ): number => {
- if (raw === undefined || raw === null || raw === '') {
- return fallback;
- }
- const parsed = parseInt(raw, 10);
- if (Number.isNaN(parsed) || parsed <= 0) {
- return fallback;
- }
- return Math.min(parsed, max);
- };
-
- const shouldIncludeRealtime = (
- timeRange: { start?: string; end?: string; active: boolean },
- ): boolean => {
- if (!timeRange.active) {
- return true;
- }
- if (!timeRange.end) {
- return false;
- }
-
- const endMs = new Date(timeRange.end).getTime();
- if (Number.isNaN(endMs)) {
- return false;
- }
-
- // For "latest window" queries (end close to now), keep merging in-memory deltas
- // so dashboard updates stay near real-time between DB flushes.
- const toleranceMs = parseInt(
- process.env.REALTIME_RANGE_END_TOLERANCE_MS || '120000',
- 10,
- );
- const windowMs = Number.isFinite(toleranceMs)
- ? Math.max(10_000, toleranceMs)
- : 120_000;
- return endMs >= Date.now() - windowMs;
- };
-
- // Health check
- app.get('/health', async () => ({ status: 'ok' }));
-
- // Get summary statistics for a specific backend
- app.get('/api/stats/summary', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const backend = this.db.getBackend(backendId);
- if (!backend) {
- return reply.status(404).send({ error: 'Backend not found' });
- }
-
- const includeRealtime = shouldIncludeRealtime(timeRange);
- const summary = this.db.getSummary(
- backendId,
- timeRange.start,
- timeRange.end,
- );
- const summaryWithRealtime = includeRealtime
- ? realtimeStore.applySummaryDelta(backendId, summary)
- : summary;
-
- const dbTopDomains = this.db.getTopDomains(
- backendId,
- 10,
- timeRange.start,
- timeRange.end,
- );
- const topDomains = includeRealtime
- ? realtimeStore.mergeTopDomains(backendId, dbTopDomains, 10)
- : dbTopDomains;
-
- const dbTopIPs = this.db.getTopIPs(
- backendId,
- 10,
- timeRange.start,
- timeRange.end,
- );
- const topIPs = includeRealtime
- ? realtimeStore.mergeTopIPs(backendId, dbTopIPs, 10)
- : dbTopIPs;
-
- const dbProxyStats = this.db.getProxyStats(
- backendId,
- timeRange.start,
- timeRange.end,
- );
- const proxyStats = includeRealtime
- ? realtimeStore.mergeProxyStats(backendId, dbProxyStats)
- : dbProxyStats;
-
- const dbRuleStats = this.db.getRuleStats(
- backendId,
- timeRange.start,
- timeRange.end,
- );
- const ruleStats = includeRealtime
- ? realtimeStore.mergeRuleStats(backendId, dbRuleStats)
- : dbRuleStats;
- const hourlyStats = this.db.getHourlyStats(
- backendId,
- 24,
- timeRange.start,
- timeRange.end,
- );
- const todayTraffic = this.db.getTrafficInRange(
- backendId,
- timeRange.start,
- timeRange.end,
- );
- const todayDelta = includeRealtime
- ? realtimeStore.getTodayDelta(backendId)
- : { upload: 0, download: 0 };
-
- return {
- backend: {
- id: backend.id,
- name: backend.name,
- isActive: backend.is_active,
- listening: backend.listening,
- },
- totalConnections: summaryWithRealtime.totalConnections,
- totalUpload: summaryWithRealtime.totalUpload,
- totalDownload: summaryWithRealtime.totalDownload,
- totalDomains: summary.uniqueDomains,
- totalIPs: summary.uniqueIPs,
- totalRules: ruleStats.length,
- totalProxies: proxyStats.length,
- todayUpload: todayTraffic.upload + todayDelta.upload,
- todayDownload: todayTraffic.download + todayDelta.download,
- topDomains,
- topIPs,
- proxyStats,
- ruleStats,
- hourlyStats
- };
- });
-
- // Get global summary across all backends
- app.get('/api/stats/global', async () => {
- return this.db.getGlobalSummary();
- });
-
- // Get domain statistics for a specific backend (paginated)
- app.get('/api/stats/domains', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { offset, limit, sortBy, sortOrder, search } = request.query as {
- offset?: string;
- limit?: string;
- sortBy?: string;
- sortOrder?: string;
- search?: string;
- };
- const parsedOffset = offset ? parseInt(offset) || 0 : 0;
- const parsedLimit = limit ? parseInt(limit) || 50 : 50;
- const stats = this.db.getDomainStatsPaginated(backendId, {
- offset: parsedOffset,
- limit: parsedLimit,
- sortBy,
- sortOrder,
- search,
- start: timeRange.start,
- end: timeRange.end,
- });
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeDomainStatsPaginated(backendId, stats, {
- offset: parsedOffset,
- limit: parsedLimit,
- sortBy,
- sortOrder,
- search,
- });
- }
- return stats;
- });
-
- // Get IP statistics for a specific backend (paginated)
- app.get('/api/stats/ips', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { offset, limit, sortBy, sortOrder, search } = request.query as {
- offset?: string;
- limit?: string;
- sortBy?: string;
- sortOrder?: string;
- search?: string;
- };
- const parsedOffset = offset ? parseInt(offset) || 0 : 0;
- const parsedLimit = limit ? parseInt(limit) || 50 : 50;
- const stats = this.db.getIPStatsPaginated(backendId, {
- offset: parsedOffset,
- limit: parsedLimit,
- sortBy,
- sortOrder,
- search,
- start: timeRange.start,
- end: timeRange.end,
- });
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeIPStatsPaginated(backendId, stats, {
- offset: parsedOffset,
- limit: parsedLimit,
- sortBy,
- sortOrder,
- search,
- });
- }
- return stats;
- });
-
- // Get per-proxy traffic breakdown for a specific domain
- app.get('/api/stats/domains/proxy-stats', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { domain, sourceIP, sourceChain } = request.query as {
- domain?: string;
- sourceIP?: string;
- sourceChain?: string;
- };
- if (!domain) {
- return reply.status(400).send({ error: 'Domain parameter is required' });
- }
-
- return this.db.getDomainProxyStats(
- backendId,
- domain,
- timeRange.start,
- timeRange.end,
- sourceIP,
- sourceChain,
- );
- });
-
- // Get IP details for a specific domain (includes geoIP and traffic)
- app.get('/api/stats/domains/ip-details', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { domain, sourceIP, sourceChain } = request.query as {
- domain?: string;
- sourceIP?: string;
- sourceChain?: string;
- };
- if (!domain) {
- return reply.status(400).send({ error: 'Domain parameter is required' });
- }
-
- return this.db.getDomainIPDetails(
- backendId,
- domain,
- timeRange.start,
- timeRange.end,
- 100,
- sourceIP,
- sourceChain,
- );
- });
-
- // Get per-proxy traffic breakdown for a specific IP
- app.get('/api/stats/ips/proxy-stats', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { ip, sourceIP, sourceChain } = request.query as {
- ip?: string;
- sourceIP?: string;
- sourceChain?: string;
- };
- if (!ip) {
- return reply.status(400).send({ error: 'IP parameter is required' });
- }
-
- return this.db.getIPProxyStats(
- backendId,
- ip,
- timeRange.start,
- timeRange.end,
- sourceIP,
- sourceChain,
- );
- });
-
- // Get domain details for a specific IP (includes traffic and proxy chains)
- app.get('/api/stats/ips/domain-details', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { ip, sourceIP, sourceChain, limit } = request.query as {
- ip?: string;
- sourceIP?: string;
- sourceChain?: string;
- limit?: string;
- };
- if (!ip) {
- return reply.status(400).send({ error: 'IP parameter is required' });
- }
-
- const effectiveLimit = parseLimit(limit, 100, 2000);
- return this.db.getIPDomainDetails(
- backendId,
- ip,
- timeRange.start,
- timeRange.end,
- effectiveLimit,
- sourceIP,
- sourceChain,
- );
- });
-
- // Get domains for a specific proxy/chain
- app.get('/api/stats/proxies/domains', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { chain, limit } = request.query as { chain?: string; limit?: string };
- if (!chain) {
- return reply.status(400).send({ error: 'Chain parameter is required' });
- }
- const effectiveLimit = parseLimit(limit, 5000, 20000);
-
- const stats = this.db.getProxyDomains(
- backendId,
- chain,
- effectiveLimit,
- timeRange.start,
- timeRange.end,
- );
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeProxyDomains(backendId, chain, stats, effectiveLimit);
- }
- return stats;
- });
-
- // Get IPs for a specific proxy/chain
- app.get('/api/stats/proxies/ips', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { chain, limit } = request.query as { chain?: string; limit?: string };
- if (!chain) {
- return reply.status(400).send({ error: 'Chain parameter is required' });
- }
- const effectiveLimit = parseLimit(limit, 5000, 20000);
-
- const stats = this.db.getProxyIPs(
- backendId,
- chain,
- effectiveLimit,
- timeRange.start,
- timeRange.end,
- );
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeProxyIPs(backendId, chain, stats, effectiveLimit);
- }
- return stats;
- });
-
- // Get proxy/chain statistics for a specific backend
- app.get('/api/stats/proxies', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const stats = this.db.getProxyStats(backendId, timeRange.start, timeRange.end);
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeProxyStats(backendId, stats);
- }
- return stats;
- });
-
- // Get rule statistics for a specific backend
- app.get('/api/stats/rules', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const stats = this.db.getRuleStats(backendId, timeRange.start, timeRange.end);
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeRuleStats(backendId, stats);
- }
- return stats;
- });
-
- // Get domains for a specific rule
- app.get('/api/stats/rules/domains', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { rule, limit } = request.query as { rule?: string; limit?: string };
- if (!rule) {
- return reply.status(400).send({ error: 'Rule parameter is required' });
- }
- const effectiveLimit = parseLimit(limit, 5000, 20000);
-
- const stats = this.db.getRuleDomains(
- backendId,
- rule,
- effectiveLimit,
- timeRange.start,
- timeRange.end,
- );
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeRuleDomains(backendId, rule, stats, effectiveLimit);
- }
- return stats;
- });
-
- // Get IPs for a specific rule
- app.get('/api/stats/rules/ips', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { rule, limit } = request.query as { rule?: string; limit?: string };
- if (!rule) {
- return reply.status(400).send({ error: 'Rule parameter is required' });
- }
- const effectiveLimit = parseLimit(limit, 5000, 20000);
-
- const stats = this.db.getRuleIPs(
- backendId,
- rule,
- effectiveLimit,
- timeRange.start,
- timeRange.end,
- );
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeRuleIPs(backendId, rule, stats, effectiveLimit);
- }
- return stats;
- });
-
- // Get per-proxy traffic breakdown for a specific domain under a specific rule
- app.get('/api/stats/rules/domains/proxy-stats', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { rule, domain } = request.query as { rule?: string; domain?: string };
- if (!rule || !domain) {
- return reply.status(400).send({ error: 'Rule and domain parameters are required' });
- }
-
- return this.db.getRuleDomainProxyStats(
- backendId,
- rule,
- domain,
- timeRange.start,
- timeRange.end,
- );
- });
-
- // Get IP details for a specific domain under a specific rule
- app.get('/api/stats/rules/domains/ip-details', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { rule, domain, limit } = request.query as {
- rule?: string;
- domain?: string;
- limit?: string;
- };
- if (!rule || !domain) {
- return reply.status(400).send({ error: 'Rule and domain parameters are required' });
- }
- const effectiveLimit = parseLimit(limit, 100, 2000);
-
- return this.db.getRuleDomainIPDetails(
- backendId,
- rule,
- domain,
- timeRange.start,
- timeRange.end,
- effectiveLimit,
- );
- });
-
- // Get per-proxy traffic breakdown for a specific IP under a specific rule
- app.get('/api/stats/rules/ips/proxy-stats', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { rule, ip } = request.query as { rule?: string; ip?: string };
- if (!rule || !ip) {
- return reply.status(400).send({ error: 'Rule and IP parameters are required' });
- }
-
- return this.db.getRuleIPProxyStats(
- backendId,
- rule,
- ip,
- timeRange.start,
- timeRange.end,
- );
- });
-
- // Get domain details for a specific IP under a specific rule
- app.get('/api/stats/rules/ips/domain-details', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { rule, ip, limit } = request.query as {
- rule?: string;
- ip?: string;
- limit?: string;
- };
- if (!rule || !ip) {
- return reply.status(400).send({ error: 'Rule and IP parameters are required' });
- }
- const effectiveLimit = parseLimit(limit, 100, 2000);
-
- return this.db.getRuleIPDomainDetails(
- backendId,
- rule,
- ip,
- timeRange.start,
- timeRange.end,
- effectiveLimit,
- );
- });
-
- // Get rule chain flow for a specific rule
- app.get('/api/stats/rules/chain-flow', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { rule } = request.query as { rule?: string };
- if (!rule) {
- return reply.status(400).send({ error: 'Rule parameter is required' });
- }
-
- return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end);
- });
-
- // Get all rule chain flows merged into unified DAG
- app.get('/api/stats/rules/chain-flow-all', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end);
- });
-
- // Get rule to proxy mapping for a specific backend
- app.get('/api/stats/rule-proxy-map', async (request, reply) => {
- const backendId = getBackendId(request);
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- return this.db.getRuleProxyMap(backendId);
- });
-
- // Get country traffic statistics for a specific backend
- app.get('/api/stats/countries', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { limit } = request.query as { limit?: string };
- const stats = this.db.getCountryStats(
- backendId,
- parseInt(limit || '50', 10),
- timeRange.start,
- timeRange.end,
- );
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeCountryStats(backendId, stats);
- }
- return stats;
- });
-
- // Get device statistics for a specific backend
- app.get('/api/stats/devices', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
- if (timeRange === null) {
- return;
- }
- const { limit } = request.query as { limit?: string };
- const effectiveLimit = parseLimit(limit, 50, 2000);
- const stats = this.db.getDevices(
- backendId,
- effectiveLimit,
- timeRange.start,
- timeRange.end,
- );
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeDeviceStats(backendId, stats, effectiveLimit);
- }
- return stats;
- });
-
- app.get('/api/stats/devices/domains', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
- if (timeRange === null) {
- return;
- }
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
- const { sourceIP, limit } = request.query as { sourceIP: string; limit?: string };
- if (!sourceIP) return [];
- const effectiveLimit = parseLimit(limit, 5000, 20000);
- const stats = this.db.getDeviceDomains(
- backendId,
- sourceIP,
- effectiveLimit,
- timeRange.start,
- timeRange.end,
- );
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeDeviceDomains(backendId, sourceIP, stats, effectiveLimit);
- }
- return stats;
- });
-
- app.get('/api/stats/devices/ips', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
- if (timeRange === null) {
- return;
- }
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
- const { sourceIP, limit } = request.query as { sourceIP: string; limit?: string };
- if (!sourceIP) return [];
- const effectiveLimit = parseLimit(limit, 5000, 20000);
- const stats = this.db.getDeviceIPs(
- backendId,
- sourceIP,
- effectiveLimit,
- timeRange.start,
- timeRange.end,
- );
- if (shouldIncludeRealtime(timeRange)) {
- return realtimeStore.mergeDeviceIPs(backendId, sourceIP, stats, effectiveLimit);
- }
- return stats;
- });
-
- // Get hourly statistics for a specific backend
- app.get('/api/stats/hourly', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { hours = 24 } = request.query as { hours?: string };
- return this.db.getHourlyStats(
- backendId,
- parseInt(hours as string) || 24,
- timeRange.start,
- timeRange.end,
- );
- });
-
- // Get traffic trend for a specific backend (for time range selection)
- app.get('/api/stats/trend', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { minutes = 30 } = request.query as { minutes?: string };
- const windowMinutes = parseInt(minutes as string) || 30;
- const base = this.db.getTrafficTrend(
- backendId,
- windowMinutes,
- timeRange.start,
- timeRange.end,
- );
- if (!shouldIncludeRealtime(timeRange)) {
- return base;
- }
- return realtimeStore.mergeTrend(backendId, base, windowMinutes, 1);
- });
-
- // Get traffic trend aggregated by time buckets for chart display
- app.get('/api/stats/trend/aggregated', async (request, reply) => {
- const backendId = getBackendId(request);
- const timeRange = getTimeRange(request, reply);
-
- if (timeRange === null) {
- return;
- }
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { minutes = 30, bucketMinutes = 1 } = request.query as { minutes?: string; bucketMinutes?: string };
- const windowMinutes = parseInt(minutes as string) || 30;
- const bucket = parseInt(bucketMinutes as string) || 1;
- const base = this.db.getTrafficTrendAggregated(
- backendId,
- windowMinutes,
- bucket,
- timeRange.start,
- timeRange.end,
- );
- if (!shouldIncludeRealtime(timeRange)) {
- return base;
- }
- return realtimeStore.mergeTrend(backendId, base, windowMinutes, bucket);
- });
-
- // Get recent connections for a specific backend
- app.get('/api/stats/connections', async (request, reply) => {
- const backendId = getBackendId(request);
-
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
-
- const { limit = 100 } = request.query as { limit?: string };
- return this.db.getRecentConnections(backendId, parseInt(limit as string) || 100);
- });
-
- // Backend management APIs
- // Get all backends
- app.get('/api/backends', async () => {
- const backends = this.db.getAllBackends();
- // Don't return tokens for security
- return backends.map(({ token, ...rest }) => ({ ...rest, hasToken: !!token }));
- });
-
- // Get active backend
- app.get('/api/backends/active', async () => {
- const backend = this.db.getActiveBackend();
- if (!backend) {
- return { error: 'No active backend configured' };
- }
- // Don't return token for security
- const { token, ...rest } = backend;
- return { ...rest, hasToken: !!token };
- });
-
- // Get listening backends (all backends currently collecting data)
- app.get('/api/backends/listening', async () => {
- const backends = this.db.getListeningBackends();
- return backends.map(({ token, ...rest }) => ({ ...rest, hasToken: !!token }));
- });
-
- // Create new backend
- app.post('/api/backends', async (request, reply) => {
- const { name, url, token } = request.body as { name: string; url: string; token?: string };
-
- if (!name || !url) {
- return reply.status(400).send({ error: 'Name and URL are required' });
- }
-
- try {
- // Check if this is the first backend
- const existingBackends = this.db.getAllBackends();
- const isFirstBackend = existingBackends.length === 0;
-
- const id = this.db.createBackend({ name, url, token });
-
- // If this is the first backend, automatically set it as active
- if (isFirstBackend) {
- this.db.setActiveBackend(id);
- console.log(`[API] First backend created, automatically set as active: ${name} (ID: ${id})`);
- }
-
- return { id, isActive: isFirstBackend, message: 'Backend created successfully' };
- } catch (error: any) {
- if (error.message?.includes('UNIQUE constraint failed')) {
- return reply.status(409).send({ error: 'Backend name already exists' });
- }
- throw error;
- }
- });
-
- // Update backend
- app.put('/api/backends/:id', async (request, reply) => {
- const { id } = request.params as { id: string };
- const { name, url, token, enabled, listening } = request.body as {
- name?: string;
- url?: string;
- token?: string;
- enabled?: boolean;
- listening?: boolean;
- };
-
- const backendId = parseInt(id);
- const backend = this.db.getBackend(backendId);
-
- if (!backend) {
- return reply.status(404).send({ error: 'Backend not found' });
- }
-
- this.db.updateBackend(backendId, { name, url, token, enabled, listening });
- return { message: 'Backend updated successfully' };
- });
-
- // Delete backend
- app.delete('/api/backends/:id', async (request, reply) => {
- const { id } = request.params as { id: string };
- const backendId = parseInt(id);
-
- const backend = this.db.getBackend(backendId);
- if (!backend) {
- return reply.status(404).send({ error: 'Backend not found' });
- }
-
- this.db.deleteBackend(backendId);
- return { message: 'Backend deleted successfully' };
- });
-
- // Set active backend (for display in UI)
- app.post('/api/backends/:id/activate', async (request, reply) => {
- const { id } = request.params as { id: string };
- const backendId = parseInt(id);
-
- const backend = this.db.getBackend(backendId);
- if (!backend) {
- return reply.status(404).send({ error: 'Backend not found' });
- }
-
- this.db.setActiveBackend(backendId);
- return { message: 'Backend activated successfully' };
- });
-
- // Set listening state for a backend (controls data collection)
- app.post('/api/backends/:id/listening', async (request, reply) => {
- const { id } = request.params as { id: string };
- const { listening } = request.body as { listening: boolean };
-
- const backendId = parseInt(id);
- const backend = this.db.getBackend(backendId);
-
- if (!backend) {
- return reply.status(404).send({ error: 'Backend not found' });
- }
-
- this.db.setBackendListening(backendId, listening);
- return { message: `Backend ${listening ? 'started' : 'stopped'} listening` };
- });
-
- // Test existing backend connection (uses stored token)
- app.post('/api/backends/:id/test', async (request, reply) => {
- const { id } = request.params as { id: string };
- const backend = this.db.getBackend(parseInt(id));
- if (!backend) {
- return reply.status(404).send({ error: 'Backend not found' });
- }
-
- try {
- const wsUrl = backend.url.replace('http://', 'ws://').replace('https://', 'wss://');
- const fullUrl = wsUrl.includes('/connections') ? wsUrl : `${wsUrl}/connections`;
-
- const headers: Record<string, string> = {};
- if (backend.token) {
- headers['Authorization'] = `Bearer ${backend.token}`;
- }
-
- const WebSocket = (await import('ws')).default;
-
- return new Promise((resolve) => {
- const ws = new WebSocket(fullUrl, { headers, timeout: 5000 });
-
- ws.on('open', () => {
- ws.close();
- resolve({ success: true, message: 'Connection successful' });
- });
-
- ws.on('error', (error: any) => {
- resolve({ success: false, message: error.message || 'Connection failed' });
- });
-
- ws.on('close', (code: number) => {
- if (code !== 1000 && code !== 1005) {
- resolve({ success: false, message: `Connection closed with code ${code}` });
- }
- });
-
- setTimeout(() => {
- ws.terminate();
- resolve({ success: false, message: 'Connection timeout' });
- }, 5000);
- });
- } catch (error: any) {
- return { success: false, message: error.message || 'Connection failed' };
- }
- });
-
- // Test backend connection
- app.post('/api/backends/test', async (request) => {
- const { url, token } = request.body as { url: string; token?: string };
-
- try {
- const wsUrl = url.replace('http://', 'ws://').replace('https://', 'wss://');
- const fullUrl = wsUrl.includes('/connections') ? wsUrl : `${wsUrl}/connections`;
-
- const headers: Record<string, string> = {};
- if (token) {
- headers['Authorization'] = `Bearer ${token}`;
- }
-
- // Try to establish WebSocket connection
- const WebSocket = (await import('ws')).default;
-
- return new Promise((resolve) => {
- const ws = new WebSocket(fullUrl, { headers, timeout: 5000 });
-
- ws.on('open', () => {
- ws.close();
- resolve({ success: true, message: 'Connection successful' });
- });
-
- ws.on('error', (error: any) => {
- resolve({ success: false, message: error.message || 'Connection failed' });
- });
-
- ws.on('close', (code: number) => {
- if (code !== 1000 && code !== 1005) {
- resolve({ success: false, message: `Connection closed with code ${code}` });
- }
- });
-
- // Timeout after 5 seconds
- setTimeout(() => {
- ws.terminate();
- resolve({ success: false, message: 'Connection timeout' });
- }, 5000);
- });
- } catch (error: any) {
- return { success: false, message: error.message || 'Connection failed' };
- }
- });
-
- // Clear all data for a specific backend
- app.post('/api/backends/:id/clear-data', async (request, reply) => {
- const { id } = request.params as { id: string };
- const backendId = parseInt(id);
-
- const backend = this.db.getBackend(backendId);
- if (!backend) {
- return reply.status(404).send({ error: 'Backend not found' });
- }
-
- this.db.deleteBackendData(backendId);
- return { message: 'Backend data cleared successfully' };
- });
-
- // Clash API proxy endpoints
- // Get providers/proxies from Clash backend
- app.get('/api/clash/providers/proxies', async (request, reply) => {
- const backendId = getBackendId(request);
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
- const backend = this.db.getBackend(backendId);
- if (!backend) {
- return reply.status(404).send({ error: 'Backend not found' });
- }
-
- // Derive Clash REST base URL from the stored WebSocket URL
- const clashBaseUrl = backend.url
- .replace('ws://', 'http://').replace('wss://', 'https://')
- .replace(/\/connections\/?$/, '');
-
- const headers: Record<string, string> = { 'Content-Type': 'application/json' };
- if (backend.token) {
- headers['Authorization'] = `Bearer ${backend.token}`;
- }
-
- try {
- const res = await fetch(`${clashBaseUrl}/providers/proxies`, { headers });
- if (!res.ok) {
- return reply.status(res.status).send({ error: `Clash API error: ${res.status}` });
- }
- return res.json();
- } catch (err: any) {
- return reply.status(502).send({ error: err.message || 'Failed to reach Clash API' });
- }
- });
-
- // Get rules from Clash backend
- app.get('/api/clash/rules', async (request, reply) => {
- const backendId = getBackendId(request);
- if (backendId === null) {
- return reply.status(404).send({ error: 'No backend specified or active' });
- }
- const backend = this.db.getBackend(backendId);
- if (!backend) {
- return reply.status(404).send({ error: 'Backend not found' });
- }
-
- const clashBaseUrl = backend.url
- .replace('ws://', 'http://').replace('wss://', 'https://')
- .replace(/\/connections\/?$/, '');
-
- const headers: Record<string, string> = { 'Content-Type': 'application/json' };
- if (backend.token) {
- headers['Authorization'] = `Bearer ${backend.token}`;
- }
-
- try {
- const res = await fetch(`${clashBaseUrl}/rules`, { headers });
- if (!res.ok) {
- return reply.status(res.status).send({ error: `Clash API error: ${res.status}` });
- }
- return res.json();
- } catch (err: any) {
- return reply.status(502).send({ error: err.message || 'Failed to reach Clash API' });
- }
- });
-
- // Database management APIs
- // Get database stats
- app.get('/api/db/stats', async () => {
- return {
- size: this.db.getDatabaseSize(),
- totalConnectionsCount: this.db.getTotalConnectionLogsCount(),
- };
- });
-
- // Clear old logs (for all backends or specific backend)
- // days=0 means clear all logs
- app.post('/api/db/cleanup', async (request) => {
- const { days, backendId } = request.body as { days: number; backendId?: number };
-
- if (typeof days !== 'number' || days < 0) {
- return { error: 'Valid days parameter required' };
- }
-
- const result = this.db.cleanupOldData(backendId || null, days);
-
- // Also clear realtime cache when clearing all data
- if (days === 0) {
- if (backendId) {
- // Clear specific backend's cache
- realtimeStore.clearBackend(backendId);
- } else {
- // Clear all backends' cache
- const backends = this.db.getAllBackends();
- for (const backend of backends) {
- realtimeStore.clearBackend(backend.id);
- }
- }
-
- return {
- message: `Cleaned all data: ${result.deletedConnections} connections, ${result.deletedDomains} domains, ${result.deletedProxies} proxies`,
- deleted: result.deletedConnections,
- domains: result.deletedDomains,
- ips: result.deletedIPs,
- proxies: result.deletedProxies,
- rules: result.deletedRules
- };
- }
-
- return {
- message: `Cleaned ${result.deletedConnections} old connection logs`,
- deleted: result.deletedConnections
- };
- });
-
- // Vacuum database
- app.post('/api/db/vacuum', async () => {
- this.db.vacuum();
- return { message: 'Database vacuumed successfully' };
- });
-
- // Get retention configuration
- app.get('/api/db/retention', async () => {
- return this.db.getRetentionConfig();
- });
-
- // Update retention configuration
- app.put('/api/db/retention', async (request, reply) => {
- const { connectionLogsDays, hourlyStatsDays, autoCleanup } = request.body as {
- connectionLogsDays?: number;
- hourlyStatsDays?: number;
- autoCleanup?: boolean;
- };
-
- // Validate input
- if (connectionLogsDays !== undefined && (connectionLogsDays < 1 || connectionLogsDays > 90)) {
- return reply.status(400).send({ error: 'connectionLogsDays must be between 1 and 90' });
- }
- if (hourlyStatsDays !== undefined && (hourlyStatsDays < 7 || hourlyStatsDays > 365)) {
- return reply.status(400).send({ error: 'hourlyStatsDays must be between 7 and 365' });
- }
-
- const newConfig = this.db.updateRetentionConfig({
- connectionLogsDays,
- hourlyStatsDays,
- autoCleanup,
- });
-
- return { message: 'Retention configuration updated', config: newConfig };
- });
-
- await app.listen({ port: this.port, host: '0.0.0.0' });
- console.log(`[API] Server running at http://localhost:${this.port}`);
-
- return app;
- }
-
- stop() {
- if (this.app) {
- this.app.close();
- console.log('[API] Server stopped');
- }
- }
-}
+/**
+ * Legacy compatibility entry.
+ *
+ * The API implementation was migrated to `app.ts`.
+ * Keep this file as a thin re-export to avoid duplicate route definitions
+ * and to preserve old import paths.
+ */
+
+export { createApp, APIServer } from './app.js';
+export { default } from './app.js';
diff --git a/apps/collector/src/app.ts b/apps/collector/src/app.ts
new file mode 100644
index 0000000..b507dc1
--- /dev/null
+++ b/apps/collector/src/app.ts
@@ -0,0 +1,250 @@
+/**
+ * Main Fastify Application
+ *
+ * This file registers all controllers and services for the API.
+ */
+
+import Fastify from 'fastify';
+import cors from '@fastify/cors';
+import type { StatsDatabase } from './db.js';
+import type { RealtimeStore } from './realtime.js';
+
+// Import modules
+import { BackendService, backendController } from './modules/backend/index.js';
+import { StatsService, statsController } from './modules/stats/index.js';
+
+// Extend Fastify instance to include services
+declare module 'fastify' {
+ interface FastifyInstance {
+ backendService: BackendService;
+ statsService: StatsService;
+ }
+}
+
+export interface AppOptions {
+ port: number;
+ db: StatsDatabase;
+ realtimeStore: RealtimeStore;
+ logger?: boolean;
+}
+
+export async function createApp(options: AppOptions) {
+ const { port, db, realtimeStore, logger = false } = options;
+
+ // Create Fastify instance
+ const app = Fastify({ logger });
+
+ // Register CORS
+ await app.register(cors, {
+ origin: true,
+ credentials: true,
+ });
+
+ // Create services
+ const backendService = new BackendService(db, realtimeStore);
+ const statsService = new StatsService(db, realtimeStore);
+
+ // Decorate Fastify instance with services
+ app.decorate('backendService', backendService);
+ app.decorate('statsService', statsService);
+
+ const getBackendIdFromQuery = (query: Record<string, unknown>): number | null => {
+ const backendId = typeof query.backendId === 'string' ? query.backendId : undefined;
+ return statsService.resolveBackendId(backendId);
+ };
+
+ const getGatewayBaseUrl = (url: string): string => {
+ return url
+ .replace(/^ws:\/\//, 'http://')
+ .replace(/^wss:\/\//, 'https://')
+ .replace(/\/connections\/?$/, '');
+ };
+
+ // Health check endpoint (not part of any module)
+ app.get('/health', async () => ({ status: 'ok' }));
+
+ // Compatibility routes: DB management
+ app.get('/api/db/stats', async () => {
+ return {
+ size: db.getDatabaseSize(),
+ totalConnectionsCount: db.getTotalConnectionLogsCount(),
+ };
+ });
+
+ app.post('/api/db/cleanup', async (request, reply) => {
+ const body = request.body as { days?: number; backendId?: number };
+ const days = body?.days;
+ const backendId = typeof body?.backendId === 'number' ? body.backendId : undefined;
+
+ if (typeof days !== 'number' || days < 0) {
+ return reply.status(400).send({ error: 'Valid days parameter required' });
+ }
+
+ const result = db.cleanupOldData(backendId ?? null, days);
+
+ if (days === 0) {
+ if (backendId) {
+ realtimeStore.clearBackend(backendId);
+ } else {
+ const backends = db.getAllBackends();
+ for (const backend of backends) {
+ realtimeStore.clearBackend(backend.id);
+ }
+ }
+
+ return {
+ message: `Cleaned all data: ${result.deletedConnections} connections, ${result.deletedDomains} domains, ${result.deletedProxies} proxies`,
+ deleted: result.deletedConnections,
+ domains: result.deletedDomains,
+ ips: result.deletedIPs,
+ proxies: result.deletedProxies,
+ rules: result.deletedRules,
+ };
+ }
+
+ return {
+ message: `Cleaned ${result.deletedConnections} old connection logs`,
+ deleted: result.deletedConnections,
+ };
+ });
+
+ app.post('/api/db/vacuum', async () => {
+ db.vacuum();
+ return { message: 'Database vacuumed successfully' };
+ });
+
+ app.get('/api/db/retention', async () => {
+ return db.getRetentionConfig();
+ });
+
+ app.put('/api/db/retention', async (request, reply) => {
+ const body = request.body as {
+ connectionLogsDays?: number;
+ hourlyStatsDays?: number;
+ autoCleanup?: boolean;
+ };
+
+ if (
+ body.connectionLogsDays !== undefined &&
+ (body.connectionLogsDays < 1 || body.connectionLogsDays > 90)
+ ) {
+ return reply.status(400).send({ error: 'connectionLogsDays must be between 1 and 90' });
+ }
+
+ if (
+ body.hourlyStatsDays !== undefined &&
+ (body.hourlyStatsDays < 7 || body.hourlyStatsDays > 365)
+ ) {
+ return reply.status(400).send({ error: 'hourlyStatsDays must be between 7 and 365' });
+ }
+
+ const config = db.updateRetentionConfig({
+ connectionLogsDays: body.connectionLogsDays,
+ hourlyStatsDays: body.hourlyStatsDays,
+ autoCleanup: body.autoCleanup,
+ });
+
+ return { message: 'Retention configuration updated', config };
+ });
+
+ // Compatibility routes: Gateway APIs
+ app.get('/api/gateway/providers/proxies', async (request, reply) => {
+ const backendId = getBackendIdFromQuery(request.query as Record<string, unknown>);
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const backend = db.getBackend(backendId);
+ if (!backend) {
+ return reply.status(404).send({ error: 'Backend not found' });
+ }
+
+ const gatewayBaseUrl = getGatewayBaseUrl(backend.url);
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
+ if (backend.token) {
+ headers.Authorization = `Bearer ${backend.token}`;
+ }
+
+ try {
+ const res = await fetch(`${gatewayBaseUrl}/providers/proxies`, { headers });
+ if (!res.ok) {
+ return reply.status(res.status).send({ error: `Gateway API error: ${res.status}` });
+ }
+ return res.json();
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : 'Failed to reach Gateway API';
+ return reply.status(502).send({ error: message });
+ }
+ });
+
+ app.get('/api/gateway/rules', async (request, reply) => {
+ const backendId = getBackendIdFromQuery(request.query as Record<string, unknown>);
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const backend = db.getBackend(backendId);
+ if (!backend) {
+ return reply.status(404).send({ error: 'Backend not found' });
+ }
+
+ const gatewayBaseUrl = getGatewayBaseUrl(backend.url);
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
+ if (backend.token) {
+ headers.Authorization = `Bearer ${backend.token}`;
+ }
+
+ try {
+ const res = await fetch(`${gatewayBaseUrl}/rules`, { headers });
+ if (!res.ok) {
+ return reply.status(res.status).send({ error: `Gateway API error: ${res.status}` });
+ }
+ return res.json();
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : 'Failed to reach Gateway API';
+ return reply.status(502).send({ error: message });
+ }
+ });
+
+ // Register controllers
+ await app.register(backendController, { prefix: '/api/backends' });
+ await app.register(statsController, { prefix: '/api/stats' });
+
+ // Start server
+ await app.listen({ port, host: '0.0.0.0' });
+ console.log(`[API] Server running at http://localhost:${port}`);
+
+ return app;
+}
+
+export class APIServer {
+ private app: ReturnType<typeof Fastify> | null = null;
+ private db: StatsDatabase;
+ private realtimeStore: RealtimeStore;
+ private port: number;
+
+ constructor(port: number, db: StatsDatabase, realtimeStore: RealtimeStore) {
+ this.port = port;
+ this.db = db;
+ this.realtimeStore = realtimeStore;
+ }
+
+ async start() {
+ this.app = await createApp({
+ port: this.port,
+ db: this.db,
+ realtimeStore: this.realtimeStore,
+ logger: false,
+ });
+ return this.app;
+ }
+
+ stop() {
+ if (this.app) {
+ this.app.close();
+ console.log('[API] Server stopped');
+ }
+ }
+}
+
+export default createApp;
diff --git a/apps/collector/src/collector.ts b/apps/collector/src/collector.ts
index 2d18e83..bb99a24 100644
--- a/apps/collector/src/collector.ts
+++ b/apps/collector/src/collector.ts
@@ -1,5 +1,5 @@
import WebSocket from "ws";
-import type { ConnectionsData } from "@clashmaster/shared";
+import type { ConnectionsData } from "@neko-master/shared";
import { StatsDatabase } from "./db.js";
import { GeoIPService } from "./geo-service.js";
import { realtimeStore } from "./realtime.js";
@@ -42,7 +42,7 @@ function toMinuteKey(timestampMs?: number): string {
return `${date.slice(0, 16)}:00`;
}
-export class OpenClashCollector {
+export class GatewayCollector {
private ws: WebSocket | null = null;
private url: string;
private token?: string;
@@ -339,7 +339,7 @@ export function createCollector(
flushBatch();
}, FLUSH_INTERVAL_MS);
- const collector = new OpenClashCollector(id, {
+ const collector = new GatewayCollector(id, {
url,
token,
onData: (data) => {
diff --git a/apps/collector/src/data-retention.ts b/apps/collector/src/data-retention.ts
index 9d5d694..0308ff7 100644
--- a/apps/collector/src/data-retention.ts
+++ b/apps/collector/src/data-retention.ts
@@ -1,5 +1,5 @@
/**
- * Data Retention Policy for Clash Master
+ * Data Retention Policy for Neko Master
*
* Tiered storage strategy:
* - Raw data (connection_logs): 7 days for detailed analysis
diff --git a/apps/collector/src/database/connection.ts b/apps/collector/src/database/connection.ts
new file mode 100644
index 0000000..83b8b0a
--- /dev/null
+++ b/apps/collector/src/database/connection.ts
@@ -0,0 +1,42 @@
+import Database from 'better-sqlite3';
+import path from 'path';
+
+export interface DatabaseConfig {
+ dbPath: string;
+ enableWAL?: boolean;
+ cacheSize?: number; // in KB, negative for pages
+ busyTimeout?: number; // in milliseconds
+}
+
+const DEFAULT_CONFIG: Partial<DatabaseConfig> = {
+ enableWAL: true,
+ cacheSize: -16000, // 16MB page cache
+ busyTimeout: 5000,
+};
+
+export function createDatabase(config: DatabaseConfig): Database.Database {
+ const finalConfig = { ...DEFAULT_CONFIG, ...config };
+ const resolvedPath = path.resolve(finalConfig.dbPath);
+
+ const db = new Database(resolvedPath);
+
+ // Enable WAL mode for better concurrency
+ if (finalConfig.enableWAL) {
+ db.pragma('journal_mode = WAL');
+ db.pragma('synchronous = NORMAL');
+ db.pragma('wal_autocheckpoint = 1000');
+ }
+
+ // Performance settings
+ db.pragma('temp_store = MEMORY');
+ db.pragma(`cache_size = ${finalConfig.cacheSize}`);
+ db.pragma(`busy_timeout = ${finalConfig.busyTimeout}`);
+
+ return db;
+}
+
+export function closeDatabase(db: Database.Database): void {
+ if (db) {
+ db.close();
+ }
+}
diff --git a/apps/collector/src/database/index.ts b/apps/collector/src/database/index.ts
new file mode 100644
index 0000000..6996e51
--- /dev/null
+++ b/apps/collector/src/database/index.ts
@@ -0,0 +1,22 @@
+/**
+ * Database Module
+ *
+ * This module provides database schema definitions and repository classes
+ * for performing database operations in a modular and type-safe way.
+ */
+
+// Schema definitions
+export {
+ SCHEMA,
+ INDEXES,
+ DEFAULT_APP_CONFIG,
+ getAllSchemaStatements,
+} from './schema.js';
+
+// Repositories
+export {
+ BaseRepository,
+ DomainRepository,
+ BackendRepository,
+ type BackendConfig,
+} from './repositories/index.js';
diff --git a/apps/collector/src/database/repositories/backend.repository.ts b/apps/collector/src/database/repositories/backend.repository.ts
new file mode 100644
index 0000000..e298250
--- /dev/null
+++ b/apps/collector/src/database/repositories/backend.repository.ts
@@ -0,0 +1,285 @@
+/**
+ * Backend Repository
+ *
+ * Handles all backend configuration and management operations including:
+ * - Backend CRUD operations
+ * - Backend activation and listening state
+ * - Backend data management
+ */
+import type Database from 'better-sqlite3';
+
+export interface BackendConfig {
+ id: number;
+ name: string;
+ url: string;
+ token: string;
+ enabled: boolean;
+ is_active: boolean;
+ listening: boolean;
+ created_at: string;
+ updated_at: string;
+}
+
+export class BackendRepository {
+ private db: Database.Database;
+
+ constructor(db: Database.Database) {
+ this.db = db;
+ }
+
+ /**
+ * Create a new backend configuration
+ */
+ createBackend(backend: { name: string; url: string; token?: string }): number {
+ const stmt = this.db.prepare(`
+ INSERT INTO backend_configs (name, url, token, enabled, is_active, listening)
+ VALUES (?, ?, ?, 1, 0, 1)
+ `);
+ const result = stmt.run(backend.name, backend.url, backend.token || '');
+ return Number(result.lastInsertRowid);
+ }
+
+ /**
+ * Get all backend configurations
+ */
+ getAllBackends(): BackendConfig[] {
+ const stmt = this.db.prepare(`
+ SELECT id, name, url, token, enabled, is_active, listening, created_at, updated_at
+ FROM backend_configs
+ ORDER BY created_at ASC
+ `);
+ return stmt.all() as BackendConfig[];
+ }
+
+ /**
+ * Get a backend by ID
+ */
+ getBackend(id: number): BackendConfig | undefined {
+ const stmt = this.db.prepare(`
+ SELECT id, name, url, token, enabled, is_active, listening, created_at, updated_at
+ FROM backend_configs
+ WHERE id = ?
+ `);
+ return stmt.get(id) as BackendConfig | undefined;
+ }
+
+ /**
+ * Get the currently active backend
+ */
+ getActiveBackend(): BackendConfig | undefined {
+ const stmt = this.db.prepare(`
+ SELECT id, name, url, token, enabled, is_active, listening, created_at, updated_at
+ FROM backend_configs
+ WHERE is_active = 1
+ LIMIT 1
+ `);
+ return stmt.get() as BackendConfig | undefined;
+ }
+
+ /**
+ * Get all backends that should be listening (collecting data)
+ */
+ getListeningBackends(): BackendConfig[] {
+ const stmt = this.db.prepare(`
+ SELECT id, name, url, token, enabled, is_active, listening, created_at, updated_at
+ FROM backend_configs
+ WHERE listening = 1 AND enabled = 1
+ `);
+ return stmt.all() as BackendConfig[];
+ }
+
+ /**
+ * Update a backend configuration
+ */
+ updateBackend(id: number, updates: Partial<Omit<BackendConfig, 'id' | 'created_at'>>): void {
+ const sets: string[] = [];
+ const values: (string | number | boolean)[] = [];
+
+ if (updates.name !== undefined) {
+ sets.push('name = ?');
+ values.push(updates.name);
+ }
+ if (updates.url !== undefined) {
+ sets.push('url = ?');
+ values.push(updates.url);
+ }
+ if (updates.token !== undefined) {
+ sets.push('token = ?');
+ values.push(updates.token);
+ }
+ if (updates.enabled !== undefined) {
+ sets.push('enabled = ?');
+ values.push(updates.enabled ? 1 : 0);
+ }
+ if (updates.listening !== undefined) {
+ sets.push('listening = ?');
+ values.push(updates.listening ? 1 : 0);
+ }
+ if (updates.is_active !== undefined) {
+ sets.push('is_active = ?');
+ values.push(updates.is_active ? 1 : 0);
+ }
+
+ if (sets.length === 0) return;
+
+ sets.push('updated_at = CURRENT_TIMESTAMP');
+ values.push(id);
+
+ const stmt = this.db.prepare(`
+ UPDATE backend_configs
+ SET ${sets.join(', ')}
+ WHERE id = ?
+ `);
+ stmt.run(...values);
+ }
+
+ /**
+ * Set a backend as active (for display) - unsets all others
+ */
+ setActiveBackend(id: number): void {
+ this.db.exec('BEGIN TRANSACTION');
+ try {
+ // Unset all backends as active
+ this.db.prepare(`UPDATE backend_configs SET is_active = 0`).run();
+ // Set the specified backend as active
+ this.db.prepare(`UPDATE backend_configs SET is_active = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?`).run(id);
+ this.db.exec('COMMIT');
+ } catch (error) {
+ this.db.exec('ROLLBACK');
+ throw error;
+ }
+ }
+
+ /**
+ * Set listening state for a backend (controls data collection)
+ */
+ setBackendListening(id: number, listening: boolean): void {
+ const stmt = this.db.prepare(`
+ UPDATE backend_configs
+ SET listening = ?, updated_at = CURRENT_TIMESTAMP
+ WHERE id = ?
+ `);
+ stmt.run(listening ? 1 : 0, id);
+ }
+
+ /**
+ * Delete a backend and all its associated data
+ */
+ deleteBackend(id: number): void {
+ // Due to ON DELETE CASCADE, all associated stats will be deleted automatically
+ const stmt = this.db.prepare(`DELETE FROM backend_configs WHERE id = ?`);
+ stmt.run(id);
+ }
+
+ /**
+ * Delete all data for a specific backend
+ */
+ deleteBackendData(id: number): void {
+ this.db.exec('BEGIN TRANSACTION');
+ try {
+ this.db.prepare(`DELETE FROM domain_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM ip_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM proxy_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM rule_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM rule_proxy_map WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM rule_chain_traffic WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM rule_domain_traffic WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM rule_ip_traffic WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM country_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM hourly_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM connection_logs WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM minute_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM minute_dim_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM minute_country_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM domain_proxy_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM ip_proxy_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM device_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM device_domain_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM device_ip_stats WHERE backend_id = ?`).run(id);
+ this.db.exec('COMMIT');
+ } catch (error) {
+ this.db.exec('ROLLBACK');
+ throw error;
+ }
+ }
+
+ /**
+ * Get total stats across all backends
+ */
+ getGlobalSummary(): {
+ totalConnections: number;
+ totalUpload: number;
+ totalDownload: number;
+ uniqueDomains: number;
+ uniqueIPs: number;
+ backendCount: number
+ } {
+ // Calculate totals from ip_stats to include traffic with unknown domains
+ const trafficStmt = this.db.prepare(`
+ SELECT
+ COALESCE(SUM(total_connections), 0) as connections,
+ COALESCE(SUM(total_upload), 0) as upload,
+ COALESCE(SUM(total_download), 0) as download
+ FROM ip_stats
+ `);
+ const { connections, upload, download } = trafficStmt.get() as {
+ connections: number;
+ upload: number;
+ download: number;
+ };
+
+ const domainsStmt = this.db.prepare(`
+ SELECT COUNT(DISTINCT domain) as count FROM domain_stats
+ `);
+ const uniqueDomains = (domainsStmt.get() as { count: number }).count;
+
+ const ipsStmt = this.db.prepare(`
+ SELECT COUNT(DISTINCT ip) as count FROM ip_stats
+ `);
+ const uniqueIPs = (ipsStmt.get() as { count: number }).count;
+
+ const backendStmt = this.db.prepare(`
+ SELECT COUNT(*) as count FROM backend_configs
+ `);
+ const backendCount = (backendStmt.get() as { count: number }).count;
+
+ return {
+ totalConnections: connections,
+ totalUpload: upload,
+ totalDownload: download,
+ uniqueDomains,
+ uniqueIPs,
+ backendCount
+ };
+ }
+
+ /**
+ * Check if a backend exists
+ */
+ backendExists(id: number): boolean {
+ const stmt = this.db.prepare(`
+ SELECT 1 FROM backend_configs WHERE id = ?
+ `);
+ return stmt.get(id) !== undefined;
+ }
+
+ /**
+ * Get backend count
+ */
+ getBackendCount(): number {
+ const stmt = this.db.prepare(`
+ SELECT COUNT(*) as count FROM backend_configs
+ `);
+ return (stmt.get() as { count: number }).count;
+ }
+
+ /**
+ * Get first backend (for migrations)
+ */
+ getFirstBackend(): { id: number } | undefined {
+ const stmt = this.db.prepare(`
+ SELECT id FROM backend_configs LIMIT 1
+ `);
+ return stmt.get() as { id: number } | undefined;
+ }
+}
diff --git a/apps/collector/src/database/repositories/base.repository.ts b/apps/collector/src/database/repositories/base.repository.ts
new file mode 100644
index 0000000..e402c40
--- /dev/null
+++ b/apps/collector/src/database/repositories/base.repository.ts
@@ -0,0 +1,183 @@
+/**
+ * Base Repository Class
+ *
+ * Provides common database operations and utilities for all repositories.
+ * All specific repositories should extend this class.
+ */
+import type Database from 'better-sqlite3';
+
+export abstract class BaseRepository {
+ protected db: Database.Database;
+
+ constructor(db: Database.Database) {
+ this.db = db;
+ }
+
+ /**
+ * Convert a Date to minute key format (YYYY-MM-DDTHH:MM:00)
+ */
+ protected toMinuteKey(date: Date): string {
+ return `${date.toISOString().slice(0, 16)}:00`;
+ }
+
+ /**
+ * Convert a Date to hour key format (YYYY-MM-DDTHH:00:00)
+ */
+ protected toHourKey(date: Date): string {
+ return `${date.toISOString().slice(0, 13)}:00:00`;
+ }
+
+ /**
+ * Parse minute range from start and end ISO strings
+ */
+ protected parseMinuteRange(
+ start?: string,
+ end?: string,
+ ): { startMinute: string; endMinute: string } | null {
+ if (!start || !end) {
+ return null;
+ }
+
+ const startDate = new Date(start);
+ const endDate = new Date(end);
+ if (
+ Number.isNaN(startDate.getTime()) ||
+ Number.isNaN(endDate.getTime()) ||
+ startDate > endDate
+ ) {
+ return null;
+ }
+
+ return {
+ startMinute: this.toMinuteKey(startDate),
+ endMinute: this.toMinuteKey(endDate),
+ };
+ }
+
+ /**
+ * Execute a transaction with automatic rollback on error
+ */
+ protected withTransaction<T>(fn: () => T): T {
+ const transaction = this.db.transaction(fn);
+ return transaction();
+ }
+
+ /**
+ * Split chain string into parts
+ */
+ protected splitChainParts(chain: string): string[] {
+ return chain
+ .split(">")
+ .map((part) => part.trim())
+ .filter(Boolean);
+ }
+
+ /**
+ * Normalize flow label for comparison
+ */
+ protected normalizeFlowLabel(label: string): string {
+ return label
+ .normalize("NFKC")
+ .replace(/^[^\p{L}\p{N}]+/gu, "")
+ .replace(/\s+/g, " ")
+ .trim()
+ .toLowerCase();
+ }
+
+ /**
+ * Find rule index in chain parts
+ */
+ protected findRuleIndexInChain(chainParts: string[], rule: string): number {
+ const exactIndex = chainParts.findIndex((part) => part === rule);
+ if (exactIndex !== -1) {
+ return exactIndex;
+ }
+
+ const normalizedRule = this.normalizeFlowLabel(rule);
+ if (!normalizedRule) {
+ return -1;
+ }
+
+ return chainParts.findIndex(
+ (part) => this.normalizeFlowLabel(part) === normalizedRule,
+ );
+ }
+
+ /**
+ * Get the first hop from a chain
+ */
+ protected getChainFirstHop(chain: string): string {
+ const parts = this.splitChainParts(chain);
+ return parts[0] || chain;
+ }
+
+ /**
+ * Build a normalized rule flow path in "rule -> ... -> proxy" order
+ */
+ protected buildRuleFlowPath(rule: string, chain: string): string[] {
+ const chainParts = this.splitChainParts(chain);
+ if (chainParts.length === 0) {
+ return [];
+ }
+
+ const ruleIndex = this.findRuleIndexInChain(chainParts, rule);
+ if (ruleIndex !== -1) {
+ // Full chain stored as proxy > ... > rule, reverse to rule > ... > proxy.
+ return chainParts.slice(0, ruleIndex + 1).reverse();
+ }
+
+ // Fallback for mismatched labels or minute_dim rows:
+ // normalize direction to rule/group -> ... -> proxy.
+ const reversed = [...chainParts].reverse();
+ const normalizedRule = this.normalizeFlowLabel(rule);
+ const normalizedHead = this.normalizeFlowLabel(reversed[0] || "");
+ if (normalizedRule && normalizedRule === normalizedHead) {
+ return reversed;
+ }
+
+ return [rule, ...reversed];
+ }
+
+ /**
+ * Get unique non-empty values from an array
+ */
+ protected uniqueNonEmpty(values: string[]): string[] {
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const raw of values) {
+ const v = (raw || "").trim();
+ if (!v || seen.has(v)) continue;
+ seen.add(v);
+ out.push(v);
+ }
+ return out;
+ }
+
+ /**
+ * Allocate a total value by weights
+ */
+ protected allocateByWeights(total: number, weights: number[]): number[] {
+ if (weights.length === 0) return [];
+ const sum = weights.reduce((acc, w) => acc + w, 0);
+ if (sum <= 0) {
+ const base = Math.floor(total / weights.length);
+ const result = new Array(weights.length).fill(base);
+ let remainder = total - base * weights.length;
+ for (let i = 0; i < result.length && remainder > 0; i++, remainder--) {
+ result[i] += 1;
+ }
+ return result;
+ }
+
+ const raw = weights.map(w => (total * w) / sum);
+ const floored = raw.map(v => Math.floor(v));
+ let remainder = total - floored.reduce((acc, v) => acc + v, 0);
+ const order = raw
+ .map((v, i) => ({ i, frac: v - Math.floor(v) }))
+ .sort((a, b) => b.frac - a.frac);
+ for (let k = 0; k < order.length && remainder > 0; k++, remainder--) {
+ floored[order[k].i] += 1;
+ }
+ return floored;
+ }
+}
diff --git a/apps/collector/src/database/repositories/domain.repository.ts b/apps/collector/src/database/repositories/domain.repository.ts
new file mode 100644
index 0000000..ccc838f
--- /dev/null
+++ b/apps/collector/src/database/repositories/domain.repository.ts
@@ -0,0 +1,724 @@
+/**
+ * Domain Repository
+ *
+ * Handles all domain-related database operations including:
+ * - Domain statistics queries
+ * - Domain-IP relationship queries
+ * - Domain pagination and search
+ * - Domain proxy statistics
+ */
+import type Database from 'better-sqlite3';
+import type { DomainStats, IPStats } from '@neko-master/shared';
+import { BaseRepository } from './base.repository.js';
+
+export class DomainRepository extends BaseRepository {
+ constructor(db: Database.Database) {
+ super(db);
+ }
+
+ /**
+ * Get a specific domain by name
+ */
+ getDomainByName(backendId: number, domain: string): DomainStats | null {
+ const stmt = this.db.prepare(`
+ SELECT domain, total_upload as totalUpload, total_download as totalDownload,
+ total_connections as totalConnections, last_seen as lastSeen, ips, rules, chains
+ FROM domain_stats
+ WHERE backend_id = ? AND domain = ?
+ `);
+ const row = stmt.get(backendId, domain) as {
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string;
+ rules: string | null;
+ chains: string | null;
+ } | undefined;
+
+ if (!row) return null;
+
+ return {
+ ...row,
+ ips: row.ips ? row.ips.split(',') : [],
+ rules: row.rules ? row.rules.split(',') : [],
+ chains: row.chains ? row.chains.split(',') : [],
+ } as DomainStats;
+ }
+
+ /**
+ * Get all domain stats for a specific backend
+ */
+ getDomainStats(backendId: number, limit = 100, start?: string, end?: string): DomainStats[] {
+ const range = this.parseMinuteRange(start, end);
+ if (range) {
+ const stmt = this.db.prepare(`
+ SELECT
+ domain,
+ SUM(upload) as totalUpload,
+ SUM(download) as totalDownload,
+ SUM(connections) as totalConnections,
+ MAX(minute) as lastSeen,
+ GROUP_CONCAT(DISTINCT ip) as ips,
+ GROUP_CONCAT(DISTINCT rule) as rules,
+ GROUP_CONCAT(DISTINCT chain) as chains
+ FROM minute_dim_stats
+ WHERE backend_id = ? AND minute >= ? AND minute <= ? AND domain != ''
+ GROUP BY domain
+ ORDER BY (SUM(upload) + SUM(download)) DESC
+ LIMIT ?
+ `);
+ const rows = stmt.all(
+ backendId,
+ range.startMinute,
+ range.endMinute,
+ limit,
+ ) as Array<{
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string | null;
+ rules: string | null;
+ chains: string | null;
+ }>;
+
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
+ }
+
+ const stmt = this.db.prepare(`
+ SELECT domain, total_upload as totalUpload, total_download as totalDownload,
+ total_connections as totalConnections, last_seen as lastSeen, ips, rules, chains
+ FROM domain_stats
+ WHERE backend_id = ?
+ ORDER BY (total_upload + total_download) DESC
+ LIMIT ?
+ `);
+ const rows = stmt.all(backendId, limit) as Array<{
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string | null;
+ rules: string | null;
+ chains: string | null;
+ }>;
+
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ ips: row.ips ? row.ips.split(',') : [],
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
+ }
+
+ /**
+ * Get top domains for a specific backend
+ */
+ getTopDomains(backendId: number, limit = 10, start?: string, end?: string): DomainStats[] {
+ return this.getDomainStats(backendId, limit, start, end);
+ }
+
+ /**
+ * Get domain stats with server-side pagination, sorting and search
+ */
+ getDomainStatsPaginated(backendId: number, opts: {
+ offset?: number;
+ limit?: number;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+ start?: string;
+ end?: string;
+ } = {}): { data: DomainStats[]; total: number } {
+ const offset = opts.offset ?? 0;
+ const limit = Math.min(opts.limit ?? 50, 200);
+ const sortOrder = opts.sortOrder === 'asc' ? 'ASC' : 'DESC';
+ const search = opts.search?.trim() || '';
+ const range = this.parseMinuteRange(opts.start, opts.end);
+
+ const sortColumnMap: Record<string, string> = {
+ domain: 'domain',
+ totalDownload: 'total_download',
+ totalUpload: 'total_upload',
+ totalTraffic: '(total_upload + total_download)',
+ totalConnections: 'total_connections',
+ lastSeen: 'last_seen',
+ };
+ const sortColumn = sortColumnMap[opts.sortBy || 'totalDownload'] || 'total_download';
+
+ if (range) {
+ const rangeSortColumnMap: Record<string, string> = {
+ domain: 'domain',
+ totalDownload: 'totalDownload',
+ totalUpload: 'totalUpload',
+ totalTraffic: '(totalUpload + totalDownload)',
+ totalConnections: 'totalConnections',
+ lastSeen: 'lastSeen',
+ };
+ const rangeSortColumn =
+ rangeSortColumnMap[opts.sortBy || 'totalDownload'] || 'totalDownload';
+
+ const whereSearch = search ? 'AND domain LIKE ?' : '';
+ const baseParams: any[] = [backendId, range.startMinute, range.endMinute];
+ const searchParams: any[] = search ? [`%${search}%`] : [];
+
+ const countStmt = this.db.prepare(`
+ SELECT COUNT(*) as total
+ FROM (
+ SELECT domain
+ FROM minute_dim_stats
+ WHERE backend_id = ? AND minute >= ? AND minute <= ? AND domain != '' ${whereSearch}
+ GROUP BY domain
+ )
+ `);
+ const { total } = countStmt.get(
+ ...baseParams,
+ ...searchParams,
+ ) as { total: number };
+
+ const dataStmt = this.db.prepare(`
+ SELECT
+ domain,
+ SUM(upload) as totalUpload,
+ SUM(download) as totalDownload,
+ SUM(connections) as totalConnections,
+ MAX(minute) as lastSeen,
+ GROUP_CONCAT(DISTINCT ip) as ips,
+ GROUP_CONCAT(DISTINCT rule) as rules,
+ GROUP_CONCAT(DISTINCT chain) as chains
+ FROM minute_dim_stats
+ WHERE backend_id = ? AND minute >= ? AND minute <= ? AND domain != '' ${whereSearch}
+ GROUP BY domain
+ ORDER BY ${rangeSortColumn} ${sortOrder}
+ LIMIT ? OFFSET ?
+ `);
+ const rows = dataStmt.all(
+ ...baseParams,
+ ...searchParams,
+ limit,
+ offset,
+ ) as Array<{
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string | null;
+ rules: string | null;
+ chains: string | null;
+ }>;
+
+ const data = rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
+
+ return { data, total };
+ }
+
+ const whereClause = search
+ ? 'WHERE backend_id = ? AND domain LIKE ?'
+ : 'WHERE backend_id = ?';
+ const params: any[] = search
+ ? [backendId, `%${search}%`]
+ : [backendId];
+
+ const countStmt = this.db.prepare(
+ `SELECT COUNT(*) as total FROM domain_stats ${whereClause}`
+ );
+ const { total } = countStmt.get(...params) as { total: number };
+
+ const dataStmt = this.db.prepare(`
+ SELECT domain, total_upload as totalUpload, total_download as totalDownload,
+ total_connections as totalConnections, last_seen as lastSeen, ips, rules, chains
+ FROM domain_stats
+ ${whereClause}
+ ORDER BY ${sortColumn} ${sortOrder}
+ LIMIT ? OFFSET ?
+ `);
+ const rows = dataStmt.all(...params, limit, offset) as Array<{
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string | null;
+ rules: string | null;
+ chains: string | null;
+ }>;
+
+ const data = rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ ips: row.ips ? row.ips.split(',') : [],
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
+
+ return { data, total };
+ }
+
+ /**
+ * Get IP details for a specific domain
+ */
+ getDomainIPDetails(
+ backendId: number,
+ domain: string,
+ start?: string,
+ end?: string,
+ limit = 100,
+ sourceIP?: string,
+ sourceChain?: string,
+ ): IPStats[] {
+ const range = this.parseMinuteRange(start, end);
+ if (range || sourceIP || sourceChain) {
+ const conditions = ["m.backend_id = ?", "m.domain = ?", "m.ip != ''"];
+ const params: Array<string | number> = [backendId, domain];
+ if (range) {
+ conditions.push("m.minute >= ?", "m.minute <= ?");
+ params.push(range.startMinute, range.endMinute);
+ }
+ if (sourceIP) {
+ conditions.push("m.source_ip = ?");
+ params.push(sourceIP);
+ }
+ if (sourceChain) {
+ conditions.push("(m.chain = ? OR m.chain LIKE ?)");
+ params.push(sourceChain, `${sourceChain} > %`);
+ }
+
+ const stmt = this.db.prepare(`
+ SELECT
+ m.ip,
+ GROUP_CONCAT(DISTINCT CASE WHEN m.domain != '' THEN m.domain END) as domains,
+ SUM(m.upload) as totalUpload,
+ SUM(m.download) as totalDownload,
+ SUM(m.connections) as totalConnections,
+ MAX(m.minute) as lastSeen,
+ COALESCE(i.asn, g.asn) as asn,
+ CASE
+ WHEN g.country IS NOT NULL THEN
+ json_array(
+ g.country,
+ COALESCE(g.country_name, g.country),
+ COALESCE(g.city, ''),
+ COALESCE(g.as_name, '')
+ )
+ WHEN i.geoip IS NOT NULL THEN
+ json(i.geoip)
+ ELSE
+ NULL
+ END as geoIP,
+ GROUP_CONCAT(DISTINCT m.chain) as chains,
+ GROUP_CONCAT(DISTINCT m.rule) as rules
+ FROM minute_dim_stats m
+ LEFT JOIN ip_stats i ON m.backend_id = i.backend_id AND m.ip = i.ip
+ LEFT JOIN geoip_cache g ON m.ip = g.ip
+ WHERE ${conditions.join(" AND ")}
+ GROUP BY m.ip
+ ORDER BY (SUM(m.upload) + SUM(m.download)) DESC
+ LIMIT ?
+ `);
+ const rows = stmt.all(...params, limit) as Array<{
+ ip: string;
+ domains: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ asn: string | null;
+ geoIP: string | null;
+ chains: string | null;
+ rules: string | null;
+ }>;
+
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
+ geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
+ asn: row.asn || undefined,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as IPStats[];
+ }
+
+ const domainData = this.getDomainByName(backendId, domain);
+ if (!domainData || !domainData.ips || domainData.ips.length === 0) {
+ return [];
+ }
+ return this.getIPStatsByIPs(backendId, domainData.ips.slice(0, limit));
+ }
+
+ /**
+ * Get per-proxy traffic breakdown for a specific domain
+ */
+ getDomainProxyStats(
+ backendId: number,
+ domain: string,
+ start?: string,
+ end?: string,
+ sourceIP?: string,
+ sourceChain?: string,
+ ): Array<{ chain: string; totalUpload: number; totalDownload: number; totalConnections: number }> {
+ const range = this.parseMinuteRange(start, end);
+ if (range || sourceIP || sourceChain) {
+ const conditions = ["backend_id = ?", "domain = ?"];
+ const params: Array<string | number> = [backendId, domain];
+ if (range) {
+ conditions.push("minute >= ?", "minute <= ?");
+ params.push(range.startMinute, range.endMinute);
+ }
+ if (sourceIP) {
+ conditions.push("source_ip = ?");
+ params.push(sourceIP);
+ }
+ if (sourceChain) {
+ conditions.push("(chain = ? OR chain LIKE ?)");
+ params.push(sourceChain, `${sourceChain} > %`);
+ }
+
+ const stmt = this.db.prepare(`
+ SELECT
+ chain,
+ SUM(upload) as totalUpload,
+ SUM(download) as totalDownload,
+ SUM(connections) as totalConnections
+ FROM minute_dim_stats
+ WHERE ${conditions.join(" AND ")}
+ GROUP BY chain
+ ORDER BY (SUM(upload) + SUM(download)) DESC
+ `);
+ return stmt.all(...params) as Array<{ chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>;
+ }
+
+ const stmt = this.db.prepare(`
+ SELECT chain,
+ total_upload as totalUpload,
+ total_download as totalDownload,
+ total_connections as totalConnections
+ FROM domain_proxy_stats
+ WHERE backend_id = ? AND domain = ?
+ ORDER BY (total_upload + total_download) DESC
+ `);
+ return stmt.all(backendId, domain) as Array<{ chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>;
+ }
+
+ /**
+ * Get domains for a specific proxy/node
+ */
+ getProxyDomains(
+ backendId: number,
+ chain: string,
+ limit = 50,
+ start?: string,
+ end?: string,
+ ): DomainStats[] {
+ const range = this.parseMinuteRange(start, end);
+ if (range) {
+ const stmt = this.db.prepare(`
+ SELECT
+ domain,
+ SUM(upload) as totalUpload,
+ SUM(download) as totalDownload,
+ SUM(connections) as totalConnections,
+ MAX(minute) as lastSeen,
+ GROUP_CONCAT(DISTINCT ip) as ips
+ FROM minute_dim_stats
+ WHERE backend_id = ? AND minute >= ? AND minute <= ? AND (chain = ? OR chain LIKE ?) AND domain != ''
+ GROUP BY domain
+ ORDER BY (SUM(upload) + SUM(download)) DESC
+ LIMIT ?
+ `);
+ const rows = stmt.all(
+ backendId,
+ range.startMinute,
+ range.endMinute,
+ chain,
+ `${chain} > %`,
+ limit,
+ ) as Array<{
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string | null;
+ }>;
+
+ return rows.map(row => ({
+ ...row,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ rules: [],
+ chains: [chain],
+ })) as DomainStats[];
+ }
+
+ const stmt = this.db.prepare(`
+ SELECT
+ dps.domain,
+ dps.total_upload as totalUpload,
+ dps.total_download as totalDownload,
+ dps.total_connections as totalConnections,
+ dps.last_seen as lastSeen,
+ ds.ips
+ FROM domain_proxy_stats dps
+ LEFT JOIN domain_stats ds ON dps.backend_id = ds.backend_id AND dps.domain = ds.domain
+ WHERE dps.backend_id = ? AND (dps.chain = ? OR dps.chain LIKE ?)
+ ORDER BY (dps.total_upload + dps.total_download) DESC
+ LIMIT ?
+ `);
+ const rows = stmt.all(backendId, chain, `${chain} > %`, limit) as Array<{
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string | null;
+ }>;
+
+ return rows.map(row => ({
+ ...row,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ rules: [],
+ chains: [chain],
+ })) as DomainStats[];
+ }
+
+ /**
+ * Get domains for a specific rule
+ */
+ getRuleDomains(
+ backendId: number,
+ rule: string,
+ limit = 50,
+ start?: string,
+ end?: string,
+ ): DomainStats[] {
+ const range = this.parseMinuteRange(start, end);
+ if (range) {
+ const stmt = this.db.prepare(`
+ SELECT
+ domain,
+ SUM(upload) as totalUpload,
+ SUM(download) as totalDownload,
+ SUM(connections) as totalConnections,
+ MAX(minute) as lastSeen,
+ GROUP_CONCAT(DISTINCT ip) as ips,
+ GROUP_CONCAT(DISTINCT chain) as chains
+ FROM minute_dim_stats
+ WHERE backend_id = ? AND minute >= ? AND minute <= ? AND rule = ? AND domain != ''
+ GROUP BY domain
+ ORDER BY (SUM(upload) + SUM(download)) DESC
+ LIMIT ?
+ `);
+ const rows = stmt.all(
+ backendId,
+ range.startMinute,
+ range.endMinute,
+ rule,
+ limit,
+ ) as Array<{
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string | null;
+ chains: string | null;
+ }>;
+
+ return rows.map(row => {
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ domain: row.domain,
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ chains: this.expandShortChainsForRules(backendId, chains, [rule]),
+ rules: [rule],
+ };
+ }) as DomainStats[];
+ }
+
+ // Query rule_domain_traffic for accurate all-time per-rule domain traffic
+ const stmt = this.db.prepare(`
+ SELECT
+ rdt.domain,
+ rdt.total_upload as totalUpload,
+ rdt.total_download as totalDownload,
+ rdt.total_connections as totalConnections,
+ rdt.last_seen as lastSeen,
+ ds.ips,
+ ds.chains
+ FROM rule_domain_traffic rdt
+ LEFT JOIN domain_stats ds ON rdt.backend_id = ds.backend_id AND rdt.domain = ds.domain
+ WHERE rdt.backend_id = ? AND rdt.rule = ?
+ ORDER BY (rdt.total_upload + rdt.total_download) DESC
+ LIMIT ?
+ `);
+
+ const rows = stmt.all(backendId, rule, limit) as Array<{
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: string | null;
+ chains: string | null;
+ }>;
+
+ return rows.map(row => ({
+ domain: row.domain,
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ chains: this.expandShortChainsForRules(
+ backendId,
+ row.chains ? row.chains.split(',').filter(Boolean) : [],
+ [rule],
+ ),
+ rules: [rule],
+ })) as DomainStats[];
+ }
+
+ /**
+ * Helper: Get IP stats by IPs (used for domain IP details)
+ */
+ private getIPStatsByIPs(backendId: number, ips: string[]): IPStats[] {
+ const filteredIps = ips.filter(ip => ip && ip.trim() !== '');
+ if (filteredIps.length === 0) return [];
+
+ const placeholders = filteredIps.map(() => '?').join(',');
+ const stmt = this.db.prepare(`
+ SELECT
+ i.ip,
+ i.domains,
+ i.total_upload as totalUpload,
+ i.total_download as totalDownload,
+ i.total_connections as totalConnections,
+ i.last_seen as lastSeen,
+ COALESCE(i.asn, g.asn) as asn,
+ CASE
+ WHEN g.country IS NOT NULL THEN
+ json_array(
+ g.country,
+ COALESCE(g.country_name, g.country),
+ COALESCE(g.city, ''),
+ COALESCE(g.as_name, '')
+ )
+ WHEN i.geoip IS NOT NULL THEN
+ json(i.geoip)
+ ELSE
+ NULL
+ END as geoIP,
+ i.chains
+ FROM ip_stats i
+ LEFT JOIN geoip_cache g ON i.ip = g.ip
+ WHERE i.backend_id = ? AND i.ip IN (${placeholders})
+ ORDER BY (i.total_upload + i.total_download) DESC
+ `);
+ const rows = stmt.all(backendId, ...filteredIps) as Array<{
+ ip: string;
+ domains: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ asn: string | null;
+ geoIP: string | null;
+ chains: string | null;
+ }>;
+
+ return rows.map(row => ({
+ ...row,
+ domains: row.domains ? row.domains.split(',') : [],
+ geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
+ asn: row.asn || undefined,
+ chains: row.chains ? row.chains.split(',') : [],
+ })) as IPStats[];
+ }
+
+ /**
+ * Expand short chains for rules using rule_chain_traffic
+ */
+ private expandShortChainsForRules(
+ backendId: number,
+ chains: string[],
+ rules: string[],
+ ): string[] {
+ const normalizedChains = this.uniqueNonEmpty(chains);
+ if (normalizedChains.length === 0) return [];
+
+ const shortChains = normalizedChains.filter((c) => !c.includes(">"));
+ if (shortChains.length === 0) return normalizedChains;
+
+ const normalizedRules = this.uniqueNonEmpty(rules);
+ const whereParts: string[] = [];
+ const params: Array<string | number> = [backendId];
+
+ if (normalizedRules.length > 0) {
+ const rulePlaceholders = normalizedRules.map(() => "?").join(", ");
+ whereParts.push(`rule IN (${rulePlaceholders})`);
+ params.push(...normalizedRules);
+ }
+
+ const chainMatchers: string[] = [];
+ for (const chain of shortChains) {
+ chainMatchers.push("(chain = ? OR chain LIKE ?)");
+ params.push(chain, `${chain} > %`);
+ }
+ whereParts.push(`(${chainMatchers.join(" OR ")})`);
+
+ const whereClause = whereParts.length > 0 ? `AND ${whereParts.join(" AND ")}` : "";
+ const stmt = this.db.prepare(`
+ SELECT DISTINCT chain
+ FROM rule_chain_traffic
+ WHERE backend_id = ? ${whereClause}
+ LIMIT 500
+ `);
+
+ const rows = stmt.all(...params) as Array<{ chain: string }>;
+ const expanded = this.uniqueNonEmpty(rows.map((r) => r.chain));
+
+ if (expanded.length === 0) {
+ return normalizedChains;
+ }
+
+ // Prefer expanded full chains, but keep already-full values from input too.
+ const fullInputChains = normalizedChains.filter((c) => c.includes(">"));
+ return this.uniqueNonEmpty([...expanded, ...fullInputChains]);
+ }
+}
diff --git a/apps/collector/src/database/repositories/index.ts b/apps/collector/src/database/repositories/index.ts
new file mode 100644
index 0000000..e04c6ae
--- /dev/null
+++ b/apps/collector/src/database/repositories/index.ts
@@ -0,0 +1,10 @@
+/**
+ * Database Repositories
+ *
+ * This module exports all repository classes for database operations.
+ * Use these repositories to perform specific domain operations.
+ */
+
+export { BaseRepository } from './base.repository.js';
+export { DomainRepository } from './domain.repository.js';
+export { BackendRepository, type BackendConfig } from './backend.repository.js';
diff --git a/apps/collector/src/database/schema.ts b/apps/collector/src/database/schema.ts
new file mode 100644
index 0000000..3c0c30d
--- /dev/null
+++ b/apps/collector/src/database/schema.ts
@@ -0,0 +1,432 @@
+/**
+ * Database Schema Definition
+ *
+ * This file contains all CREATE TABLE statements for the SQLite database.
+ * Used for initializing the database schema in a modular way.
+ */
+
+export const SCHEMA = {
+ // Domain statistics - aggregated by domain per backend
+ DOMAIN_STATS: `
+ CREATE TABLE IF NOT EXISTS domain_stats (
+ backend_id INTEGER NOT NULL,
+ domain TEXT NOT NULL,
+ ips TEXT,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ rules TEXT,
+ chains TEXT,
+ PRIMARY KEY (backend_id, domain),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // IP statistics per backend
+ IP_STATS: `
+ CREATE TABLE IF NOT EXISTS ip_stats (
+ backend_id INTEGER NOT NULL,
+ ip TEXT NOT NULL,
+ domains TEXT,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ asn TEXT,
+ geoip TEXT,
+ chains TEXT,
+ rules TEXT,
+ PRIMARY KEY (backend_id, ip),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Proxy/Chain statistics per backend
+ PROXY_STATS: `
+ CREATE TABLE IF NOT EXISTS proxy_stats (
+ backend_id INTEGER NOT NULL,
+ chain TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, chain),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Rule statistics per backend
+ RULE_STATS: `
+ CREATE TABLE IF NOT EXISTS rule_stats (
+ backend_id INTEGER NOT NULL,
+ rule TEXT NOT NULL,
+ final_proxy TEXT,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, rule),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Rule to proxy mapping per backend
+ RULE_PROXY_MAP: `
+ CREATE TABLE IF NOT EXISTS rule_proxy_map (
+ backend_id INTEGER NOT NULL,
+ rule TEXT,
+ proxy TEXT,
+ PRIMARY KEY (backend_id, rule, proxy),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // ASN cache
+ ASN_CACHE: `
+ CREATE TABLE IF NOT EXISTS asn_cache (
+ ip TEXT PRIMARY KEY,
+ asn TEXT,
+ org TEXT,
+ queried_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ `,
+
+ // GeoIP cache
+ GEOIP_CACHE: `
+ CREATE TABLE IF NOT EXISTS geoip_cache (
+ ip TEXT PRIMARY KEY,
+ country TEXT,
+ country_name TEXT,
+ city TEXT,
+ asn TEXT,
+ as_name TEXT,
+ as_domain TEXT,
+ continent TEXT,
+ continent_name TEXT,
+ queried_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ `,
+
+ // Country traffic statistics per backend
+ COUNTRY_STATS: `
+ CREATE TABLE IF NOT EXISTS country_stats (
+ backend_id INTEGER NOT NULL,
+ country TEXT NOT NULL,
+ country_name TEXT,
+ continent TEXT,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, country),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Device statistics per backend
+ DEVICE_STATS: `
+ CREATE TABLE IF NOT EXISTS device_stats (
+ backend_id INTEGER NOT NULL,
+ source_ip TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, source_ip),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Device×domain traffic aggregation
+ DEVICE_DOMAIN_STATS: `
+ CREATE TABLE IF NOT EXISTS device_domain_stats (
+ backend_id INTEGER NOT NULL,
+ source_ip TEXT NOT NULL,
+ domain TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, source_ip, domain),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Device×IP traffic aggregation
+ DEVICE_IP_STATS: `
+ CREATE TABLE IF NOT EXISTS device_ip_stats (
+ backend_id INTEGER NOT NULL,
+ source_ip TEXT NOT NULL,
+ ip TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, source_ip, ip),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Hourly aggregation per backend
+ HOURLY_STATS: `
+ CREATE TABLE IF NOT EXISTS hourly_stats (
+ backend_id INTEGER NOT NULL,
+ hour TEXT NOT NULL,
+ upload INTEGER DEFAULT 0,
+ download INTEGER DEFAULT 0,
+ connections INTEGER DEFAULT 0,
+ PRIMARY KEY (backend_id, hour),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Connection log per backend
+ CONNECTION_LOGS: `
+ CREATE TABLE IF NOT EXISTS connection_logs (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ backend_id INTEGER NOT NULL,
+ domain TEXT,
+ ip TEXT,
+ chain TEXT,
+ upload INTEGER DEFAULT 0,
+ download INTEGER DEFAULT 0,
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Minute-level traffic aggregation
+ MINUTE_STATS: `
+ CREATE TABLE IF NOT EXISTS minute_stats (
+ backend_id INTEGER NOT NULL,
+ minute TEXT NOT NULL,
+ upload INTEGER DEFAULT 0,
+ download INTEGER DEFAULT 0,
+ connections INTEGER DEFAULT 0,
+ PRIMARY KEY (backend_id, minute),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Minute-level fact table for accurate range queries
+ MINUTE_DIM_STATS: `
+ CREATE TABLE IF NOT EXISTS minute_dim_stats (
+ backend_id INTEGER NOT NULL,
+ minute TEXT NOT NULL,
+ domain TEXT NOT NULL DEFAULT '',
+ ip TEXT NOT NULL DEFAULT '',
+ source_ip TEXT NOT NULL DEFAULT '',
+ chain TEXT NOT NULL,
+ rule TEXT NOT NULL,
+ upload INTEGER DEFAULT 0,
+ download INTEGER DEFAULT 0,
+ connections INTEGER DEFAULT 0,
+ PRIMARY KEY (backend_id, minute, domain, ip, source_ip, chain, rule),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Minute-level country facts for range-based country queries
+ MINUTE_COUNTRY_STATS: `
+ CREATE TABLE IF NOT EXISTS minute_country_stats (
+ backend_id INTEGER NOT NULL,
+ minute TEXT NOT NULL,
+ country TEXT NOT NULL,
+ country_name TEXT,
+ continent TEXT,
+ upload INTEGER DEFAULT 0,
+ download INTEGER DEFAULT 0,
+ connections INTEGER DEFAULT 0,
+ PRIMARY KEY (backend_id, minute, country),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Domain×proxy traffic aggregation
+ DOMAIN_PROXY_STATS: `
+ CREATE TABLE IF NOT EXISTS domain_proxy_stats (
+ backend_id INTEGER NOT NULL,
+ domain TEXT NOT NULL,
+ chain TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, domain, chain),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // IP×proxy traffic aggregation
+ IP_PROXY_STATS: `
+ CREATE TABLE IF NOT EXISTS ip_proxy_stats (
+ backend_id INTEGER NOT NULL,
+ ip TEXT NOT NULL,
+ chain TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ domains TEXT,
+ PRIMARY KEY (backend_id, ip, chain),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Rule-specific cross-reference tables
+ RULE_CHAIN_TRAFFIC: `
+ CREATE TABLE IF NOT EXISTS rule_chain_traffic (
+ backend_id INTEGER NOT NULL,
+ rule TEXT NOT NULL,
+ chain TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, rule, chain),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ RULE_DOMAIN_TRAFFIC: `
+ CREATE TABLE IF NOT EXISTS rule_domain_traffic (
+ backend_id INTEGER NOT NULL,
+ rule TEXT NOT NULL,
+ domain TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, rule, domain),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ RULE_IP_TRAFFIC: `
+ CREATE TABLE IF NOT EXISTS rule_ip_traffic (
+ backend_id INTEGER NOT NULL,
+ rule TEXT NOT NULL,
+ ip TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, rule, ip),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
+
+ // Backend configurations
+ BACKEND_CONFIGS: `
+ CREATE TABLE IF NOT EXISTS backend_configs (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ url TEXT NOT NULL,
+ token TEXT DEFAULT '',
+ enabled BOOLEAN DEFAULT 1,
+ is_active BOOLEAN DEFAULT 0,
+ listening BOOLEAN DEFAULT 1,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ `,
+
+ // App configuration
+ APP_CONFIG: `
+ CREATE TABLE IF NOT EXISTS app_config (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ `,
+} as const;
+
+// Index definitions
+export const INDEXES = [
+ // Device stats indexes
+ `CREATE INDEX IF NOT EXISTS idx_device_domain_source_ip ON device_domain_stats(backend_id, source_ip);`,
+ `CREATE INDEX IF NOT EXISTS idx_device_ip_source_ip ON device_ip_stats(backend_id, source_ip);`,
+
+ // Domain proxy stats index
+ `CREATE INDEX IF NOT EXISTS idx_domain_proxy_chain ON domain_proxy_stats(backend_id, chain);`,
+
+ // IP proxy stats index
+ `CREATE INDEX IF NOT EXISTS idx_ip_proxy_chain ON ip_proxy_stats(backend_id, chain);`,
+
+ // Rule traffic indexes
+ `CREATE INDEX IF NOT EXISTS idx_rule_chain_traffic ON rule_chain_traffic(backend_id, rule);`,
+ `CREATE INDEX IF NOT EXISTS idx_rule_domain_traffic ON rule_domain_traffic(backend_id, rule);`,
+ `CREATE INDEX IF NOT EXISTS idx_rule_ip_traffic ON rule_ip_traffic(backend_id, rule);`,
+
+ // Stats indexes
+ `CREATE INDEX IF NOT EXISTS idx_domain_stats_backend ON domain_stats(backend_id);`,
+ `CREATE INDEX IF NOT EXISTS idx_domain_stats_traffic ON domain_stats(total_download + total_upload);`,
+ `CREATE INDEX IF NOT EXISTS idx_ip_stats_backend ON ip_stats(backend_id);`,
+ `CREATE INDEX IF NOT EXISTS idx_ip_stats_traffic ON ip_stats(total_download + total_upload);`,
+ `CREATE INDEX IF NOT EXISTS idx_proxy_stats_backend ON proxy_stats(backend_id);`,
+ `CREATE INDEX IF NOT EXISTS idx_proxy_stats_traffic ON proxy_stats(total_download + total_upload);`,
+ `CREATE INDEX IF NOT EXISTS idx_rule_stats_backend ON rule_stats(backend_id);`,
+ `CREATE INDEX IF NOT EXISTS idx_rule_stats_traffic ON rule_stats(total_download + total_upload);`,
+ `CREATE INDEX IF NOT EXISTS idx_rule_proxy_map ON rule_proxy_map(backend_id, rule, proxy);`,
+ `CREATE INDEX IF NOT EXISTS idx_country_stats_backend ON country_stats(backend_id);`,
+ `CREATE INDEX IF NOT EXISTS idx_hourly_stats_backend ON hourly_stats(backend_id);`,
+
+ // Minute stats indexes
+ `CREATE INDEX IF NOT EXISTS idx_minute_stats_backend_minute ON minute_stats(backend_id, minute);`,
+ `CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute ON minute_dim_stats(backend_id, minute);`,
+ `CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute_domain ON minute_dim_stats(backend_id, minute, domain);`,
+ `CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute_ip ON minute_dim_stats(backend_id, minute, ip);`,
+ `CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute_chain ON minute_dim_stats(backend_id, minute, chain);`,
+ `CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute_rule ON minute_dim_stats(backend_id, minute, rule);`,
+ `CREATE INDEX IF NOT EXISTS idx_minute_dim_backend_minute_source ON minute_dim_stats(backend_id, minute, source_ip);`,
+ `CREATE INDEX IF NOT EXISTS idx_minute_country_backend_minute ON minute_country_stats(backend_id, minute);`,
+
+ // Connection logs indexes
+ `CREATE INDEX IF NOT EXISTS idx_connection_logs_backend ON connection_logs(backend_id);`,
+ `CREATE INDEX IF NOT EXISTS idx_connection_logs_timestamp ON connection_logs(timestamp);`,
+ `CREATE INDEX IF NOT EXISTS idx_connection_logs_domain ON connection_logs(domain);`,
+ `CREATE INDEX IF NOT EXISTS idx_connection_logs_chain ON connection_logs(chain);`,
+
+ // Backend configs unique index
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_backend_configs_name ON backend_configs(name);`,
+] as const;
+
+// Default app config values
+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');
+`;
+
+// Get all schema creation statements in order
+export function getAllSchemaStatements(): string[] {
+ return [
+ SCHEMA.DOMAIN_STATS,
+ SCHEMA.IP_STATS,
+ SCHEMA.PROXY_STATS,
+ SCHEMA.RULE_STATS,
+ SCHEMA.RULE_PROXY_MAP,
+ SCHEMA.ASN_CACHE,
+ SCHEMA.GEOIP_CACHE,
+ SCHEMA.COUNTRY_STATS,
+ SCHEMA.DEVICE_STATS,
+ SCHEMA.DEVICE_DOMAIN_STATS,
+ SCHEMA.DEVICE_IP_STATS,
+ SCHEMA.HOURLY_STATS,
+ SCHEMA.CONNECTION_LOGS,
+ SCHEMA.MINUTE_STATS,
+ SCHEMA.MINUTE_DIM_STATS,
+ SCHEMA.MINUTE_COUNTRY_STATS,
+ SCHEMA.DOMAIN_PROXY_STATS,
+ SCHEMA.IP_PROXY_STATS,
+ SCHEMA.RULE_CHAIN_TRAFFIC,
+ SCHEMA.RULE_DOMAIN_TRAFFIC,
+ SCHEMA.RULE_IP_TRAFFIC,
+ SCHEMA.BACKEND_CONFIGS,
+ SCHEMA.APP_CONFIG,
+ ...INDEXES,
+ DEFAULT_APP_CONFIG,
+ ];
+}
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index 8f6ad3e..6ba6233 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -1,7 +1,7 @@
import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
-import type { Connection, DomainStats, IPStats, HourlyStats, DailyStats, ProxyStats, RuleStats, ProxyTrafficStats, DeviceStats } from '@clashmaster/shared';
+import type { Connection, DomainStats, IPStats, HourlyStats, DailyStats, ProxyStats, RuleStats, ProxyTrafficStats, DeviceStats } from '@neko-master/shared';
// Retention config stored in database (doesn't include cleanupInterval)
interface DatabaseRetentionConfig {
connectionLogsDays: number;
@@ -396,7 +396,7 @@ export class StatsDatabase {
this.db.exec(`CREATE INDEX IF NOT EXISTS idx_connection_logs_domain ON connection_logs(domain);`);
this.db.exec(`CREATE INDEX IF NOT EXISTS idx_connection_logs_chain ON connection_logs(chain);`);
- // Backend configurations - stores OpenClash backend connections
+ // Backend configurations - stores Gateway backend connections
this.db.exec(`
CREATE TABLE IF NOT EXISTS backend_configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -1074,7 +1074,7 @@ export class StatsDatabase {
for (const update of updates) {
if (update.upload === 0 && update.download === 0) continue;
- // Use the last element of chains as the rule name (friendly name from Clash config)
+ // Use the last element of chains as the rule name (friendly name from Gateway config)
// e.g., "漏网之鱼", "微软服务", "TikTok"
const ruleName = update.chains.length > 1 ? update.chains[update.chains.length - 1] :
update.rulePayload ? `${update.rule}(${update.rulePayload})` : update.rule;
diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.ts
index f885b73..e254fe0 100644
--- a/apps/collector/src/index.ts
+++ b/apps/collector/src/index.ts
@@ -2,12 +2,13 @@ import { config } from 'dotenv';
config();
import { StatsDatabase, BackendConfig } from './db.js';
-import { createCollector, OpenClashCollector } from './collector.js';
+import { createCollector, GatewayCollector } from './collector.js';
import { StatsWebSocketServer } from './websocket.js';
+import { realtimeStore } from './realtime.js';
let wsServer: StatsWebSocketServer;
-import { APIServer } from './api.js';
+import { APIServer } from './app.js';
import { GeoIPService } from './geo-service.js';
import path from 'path';
@@ -15,8 +16,8 @@ const COLLECTOR_WS_PORT = parseInt(process.env.COLLECTOR_WS_PORT || '3002');
const API_PORT = parseInt(process.env.API_PORT || '3001');
const DB_PATH = process.env.DB_PATH || path.join(process.cwd(), 'stats.db');
-// Map of backend connections: backendId -> OpenClashCollector
-const collectors = new Map<number, OpenClashCollector>();
+// Map of backend connections: backendId -> GatewayCollector
+const collectors = new Map<number, GatewayCollector>();
let db: StatsDatabase;
let apiServer: APIServer;
@@ -42,7 +43,7 @@ async function main() {
// Initialize API server
console.log('[Main] Starting API server on port', API_PORT);
- apiServer = new APIServer(API_PORT, db);
+ apiServer = new APIServer(API_PORT, db, realtimeStore);
apiServer.start();
// Start backend management loop
diff --git a/apps/collector/src/modules/backend/backend.controller.ts b/apps/collector/src/modules/backend/backend.controller.ts
new file mode 100644
index 0000000..cc47003
--- /dev/null
+++ b/apps/collector/src/modules/backend/backend.controller.ts
@@ -0,0 +1,157 @@
+/**
+ * Backend Controller - Fastify routes for /api/backends
+ */
+
+import type { FastifyInstance, FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify';
+import type { BackendService } from './backend.service.js';
+import type {
+ CreateBackendInput,
+ UpdateBackendInput,
+ TestConnectionInput,
+} from './backend.types.js';
+
+// Extend Fastify instance to include backendService
+declare module 'fastify' {
+ interface FastifyInstance {
+ backendService: BackendService;
+ }
+}
+
+interface BackendParams {
+ id: string;
+}
+
+interface ListeningBody {
+ listening: boolean;
+}
+
+const backendController: FastifyPluginAsync = async (fastify: FastifyInstance): Promise<void> => {
+ const service = fastify.backendService;
+
+ // Get all backends
+ fastify.get('/', async () => {
+ return service.getAllBackends();
+ });
+
+ // Get active backend
+ fastify.get('/active', async () => {
+ return service.getActiveBackend();
+ });
+
+ // Get listening backends
+ fastify.get('/listening', async () => {
+ return service.getListeningBackends();
+ });
+
+ // Create new backend
+ fastify.post<{ Body: CreateBackendInput }>('/', async (request, reply) => {
+ const { name, url, token } = request.body;
+
+ if (!name || !url) {
+ return reply.status(400).send({ error: 'Name and URL are required' });
+ }
+
+ try {
+ const result = service.createBackend({ name, url, token });
+ return result;
+ } catch (error: any) {
+ if (error.message?.includes('UNIQUE constraint failed')) {
+ return reply.status(409).send({ error: 'Backend name already exists' });
+ }
+ throw error;
+ }
+ });
+
+ // Update backend
+ fastify.put<{ Params: BackendParams; Body: UpdateBackendInput }>('/:id', async (request, reply) => {
+ const { id } = request.params;
+ const backendId = parseInt(id);
+
+ const backend = service.getBackend(backendId);
+ if (!backend) {
+ return reply.status(404).send({ error: 'Backend not found' });
+ }
+
+ const result = service.updateBackend(backendId, request.body);
+ return result;
+ });
+
+ // Delete backend
+ fastify.delete<{ Params: BackendParams }>('/:id', async (request, reply) => {
+ const { id } = request.params;
+ const backendId = parseInt(id);
+
+ const backend = service.getBackend(backendId);
+ if (!backend) {
+ return reply.status(404).send({ error: 'Backend not found' });
+ }
+
+ const result = service.deleteBackend(backendId);
+ return result;
+ });
+
+ // Set active backend
+ fastify.post<{ Params: BackendParams }>('/:id/activate', async (request, reply) => {
+ const { id } = request.params;
+ const backendId = parseInt(id);
+
+ const backend = service.getBackend(backendId);
+ if (!backend) {
+ return reply.status(404).send({ error: 'Backend not found' });
+ }
+
+ const result = service.setActiveBackend(backendId);
+ return result;
+ });
+
+ // Set listening state for a backend
+ fastify.post<{ Params: BackendParams; Body: ListeningBody }>('/:id/listening', async (request, reply) => {
+ const { id } = request.params;
+ const { listening } = request.body;
+ const backendId = parseInt(id);
+
+ const backend = service.getBackend(backendId);
+ if (!backend) {
+ return reply.status(404).send({ error: 'Backend not found' });
+ }
+
+ const result = service.setBackendListening(backendId, listening);
+ return result;
+ });
+
+ // Test existing backend connection (uses stored token)
+ fastify.post<{ Params: BackendParams }>('/:id/test', async (request, reply) => {
+ const { id } = request.params;
+ const backendId = parseInt(id);
+
+ const backend = service.getBackend(backendId);
+ if (!backend) {
+ return reply.status(404).send({ error: 'Backend not found' });
+ }
+
+ const result = await service.testExistingBackendConnection(backendId);
+ return result;
+ });
+
+ // Test backend connection
+ fastify.post<{ Body: TestConnectionInput }>('/test', async (request) => {
+ const result = await service.testConnection(request.body);
+ return result;
+ });
+
+ // Clear all data for a specific backend
+ fastify.post<{ Params: BackendParams }>('/:id/clear-data', async (request, reply) => {
+ const { id } = request.params;
+ const backendId = parseInt(id);
+
+ const backend = service.getBackend(backendId);
+ if (!backend) {
+ return reply.status(404).send({ error: 'Backend not found' });
+ }
+
+ const result = service.clearBackendData(backendId);
+ return result;
+ });
+};
+
+export default backendController;
diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.ts
new file mode 100644
index 0000000..60ea8d8
--- /dev/null
+++ b/apps/collector/src/modules/backend/backend.service.ts
@@ -0,0 +1,198 @@
+/**
+ * Backend Service - Business logic for backend management
+ */
+
+import type { StatsDatabase } from '../../db.js';
+import type { RealtimeStore } from '../../realtime.js';
+import type {
+ BackendConfig,
+ CreateBackendInput,
+ UpdateBackendInput,
+ BackendResponse,
+ TestConnectionInput,
+ TestConnectionResult,
+ CreateBackendResult,
+} from './backend.types.js';
+
+export class BackendService {
+ constructor(
+ private db: StatsDatabase,
+ private realtimeStore: RealtimeStore,
+ ) {}
+
+ /**
+ * Get all backends (with token hidden)
+ */
+ getAllBackends(): BackendResponse[] {
+ const backends = this.db.getAllBackends();
+ return backends.map(({ token, ...rest }) => ({
+ ...rest,
+ hasToken: !!token,
+ }));
+ }
+
+ /**
+ * Get active backend
+ */
+ getActiveBackend(): BackendResponse | { error: string } {
+ const backend = this.db.getActiveBackend();
+ if (!backend) {
+ return { error: 'No active backend configured' };
+ }
+ const { token, ...rest } = backend;
+ return { ...rest, hasToken: !!token };
+ }
+
+ /**
+ * Get listening backends
+ */
+ getListeningBackends(): BackendResponse[] {
+ const backends = this.db.getListeningBackends();
+ return backends.map(({ token, ...rest }) => ({
+ ...rest,
+ hasToken: !!token,
+ }));
+ }
+
+ /**
+ * Get a single backend by ID
+ */
+ getBackend(id: number): BackendConfig | undefined {
+ return this.db.getBackend(id);
+ }
+
+ /**
+ * Create a new backend
+ */
+ createBackend(input: CreateBackendInput): CreateBackendResult {
+ const { name, url, token } = input;
+
+ // Check if this is the first backend
+ const existingBackends = this.db.getAllBackends();
+ const isFirstBackend = existingBackends.length === 0;
+
+ const id = this.db.createBackend({ name, url, token });
+
+ // If this is the first backend, automatically set it as active
+ if (isFirstBackend) {
+ this.db.setActiveBackend(id);
+ console.log(`[API] First backend created, automatically set as active: ${name} (ID: ${id})`);
+ }
+
+ return { id, isActive: isFirstBackend, message: 'Backend created successfully' };
+ }
+
+ /**
+ * Update a backend
+ */
+ updateBackend(id: number, input: UpdateBackendInput): { message: string } {
+ this.db.updateBackend(id, input);
+ return { message: 'Backend updated successfully' };
+ }
+
+ /**
+ * Delete a backend
+ */
+ deleteBackend(id: number): { message: string } {
+ this.db.deleteBackend(id);
+ return { message: 'Backend deleted successfully' };
+ }
+
+ /**
+ * Set active backend
+ */
+ setActiveBackend(id: number): { message: string } {
+ this.db.setActiveBackend(id);
+ return { message: 'Backend activated successfully' };
+ }
+
+ /**
+ * Set listening state for a backend
+ */
+ setBackendListening(id: number, listening: boolean): { message: string } {
+ this.db.setBackendListening(id, listening);
+ return { message: `Backend ${listening ? 'started' : 'stopped'} listening` };
+ }
+
+ /**
+ * Clear all data for a specific backend
+ */
+ clearBackendData(id: number): { message: string } {
+ this.db.deleteBackendData(id);
+ // Also clear realtime cache
+ this.realtimeStore.clearBackend(id);
+ return { message: 'Backend data cleared successfully' };
+ }
+
+ /**
+ * Test connection to a backend (uses stored token)
+ */
+ async testExistingBackendConnection(id: number): Promise<TestConnectionResult> {
+ const backend = this.db.getBackend(id);
+ if (!backend) {
+ throw new Error('Backend not found');
+ }
+
+ return this.testConnection({
+ url: backend.url,
+ token: backend.token,
+ });
+ }
+
+ /**
+ * Test connection to a backend
+ */
+ async testConnection(input: TestConnectionInput): Promise<TestConnectionResult> {
+ const { url, token } = input;
+
+ try {
+ const wsUrl = url.replace('http://', 'ws://').replace('https://', 'wss://');
+ const fullUrl = wsUrl.includes('/connections') ? wsUrl : `${wsUrl}/connections`;
+
+ const headers: Record<string, string> = {};
+ if (token) {
+ headers['Authorization'] = `Bearer ${token}`;
+ }
+
+ // Try to establish WebSocket connection
+ const WebSocket = (await import('ws')).default;
+
+ return new Promise((resolve) => {
+ const ws = new WebSocket(fullUrl, { headers, timeout: 5000 });
+ let settled = false;
+ const timeout = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ ws.terminate();
+ resolve({ success: false, message: 'Connection timeout' });
+ }, 5000);
+
+ const finish = (result: TestConnectionResult): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ resolve(result);
+ };
+
+ ws.on('open', () => {
+ ws.close();
+ finish({ success: true, message: 'Connection successful' });
+ });
+
+ ws.on('error', (error: unknown) => {
+ const message = error instanceof Error ? error.message : 'Connection failed';
+ finish({ success: false, message });
+ });
+
+ ws.on('close', (code: number) => {
+ if (code !== 1000 && code !== 1005) {
+ finish({ success: false, message: `Connection closed with code ${code}` });
+ }
+ });
+ });
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : 'Connection failed';
+ return { success: false, message };
+ }
+ }
+}
diff --git a/apps/collector/src/modules/backend/backend.types.ts b/apps/collector/src/modules/backend/backend.types.ts
new file mode 100644
index 0000000..2d7ac78
--- /dev/null
+++ b/apps/collector/src/modules/backend/backend.types.ts
@@ -0,0 +1,72 @@
+/**
+ * Backend module type definitions
+ */
+
+export interface BackendConfig {
+ id: number;
+ name: string;
+ url: string;
+ token: string;
+ enabled: boolean;
+ is_active: boolean;
+ listening: boolean;
+ created_at: string;
+ updated_at: string;
+}
+
+// Re-export from db.ts for compatibility
+export type { BackendConfig as BackendConfigFromDb } from '../../db.js';
+
+export interface CreateBackendInput {
+ name: string;
+ url: string;
+ token?: string;
+}
+
+export interface UpdateBackendInput {
+ name?: string;
+ url?: string;
+ token?: string;
+ enabled?: boolean;
+ listening?: boolean;
+}
+
+export interface BackendResponse {
+ id: number;
+ name: string;
+ url: string;
+ enabled: boolean;
+ is_active: boolean;
+ listening: boolean;
+ created_at: string;
+ updated_at: string;
+ hasToken: boolean;
+}
+
+export interface TestConnectionInput {
+ url: string;
+ token?: string;
+}
+
+export interface TestConnectionResult {
+ success: boolean;
+ message: string;
+}
+
+export interface BackendActivationResult {
+ message: string;
+}
+
+export interface BackendListeningResult {
+ message: string;
+}
+
+export interface ClearDataResult {
+ message: string;
+}
+
+export interface CreateBackendResult {
+ id: number;
+ isActive: boolean;
+ message: string;
+}
diff --git a/apps/collector/src/modules/backend/index.ts b/apps/collector/src/modules/backend/index.ts
new file mode 100644
index 0000000..ecc1783
--- /dev/null
+++ b/apps/collector/src/modules/backend/index.ts
@@ -0,0 +1,7 @@
+/**
+ * Backend Module
+ */
+
+export { BackendService } from './backend.service.js';
+export { default as backendController } from './backend.controller.js';
+export type * from './backend.types.js';
diff --git a/apps/collector/src/modules/realtime/index.ts b/apps/collector/src/modules/realtime/index.ts
new file mode 100644
index 0000000..1081468
--- /dev/null
+++ b/apps/collector/src/modules/realtime/index.ts
@@ -0,0 +1,3 @@
+export * from './realtime.types.js';
+export * from './realtime.store.js';
+export * from './realtime.merger.js';
diff --git a/apps/collector/src/modules/realtime/realtime.merger.ts b/apps/collector/src/modules/realtime/realtime.merger.ts
new file mode 100644
index 0000000..29e5a9b
--- /dev/null
+++ b/apps/collector/src/modules/realtime/realtime.merger.ts
@@ -0,0 +1,897 @@
+
+import {
+ DomainStats,
+ IPStats,
+ ProxyStats,
+ CountryStats,
+ DeviceStats,
+ RuleStats,
+ TrafficTrendPoint,
+} from '@neko-master/shared';
+import { RealtimeStore } from './realtime.store.js';
+import { MinuteBucket, SummaryDelta } from './realtime.types.js';
+
+// --- Helper Functions ---
+
+function matchesChainPrefix(fullChain: string, chain: string): boolean {
+ return fullChain === chain || fullChain.startsWith(`${chain} > `);
+}
+
+function toMinuteKey(tsMs: number): string {
+ const iso = new Date(tsMs).toISOString();
+ return `${iso.slice(0, 16)}:00`;
+}
+
+function bucketMinuteKey(minuteKey: string, bucketMinutes: number): string {
+ if (bucketMinutes <= 1) return minuteKey;
+ const minute = parseInt(minuteKey.slice(14, 16), 10);
+ const bucketMinute = Math.floor(minute / bucketMinutes) * bucketMinutes;
+ return `${minuteKey.slice(0, 14)}${String(bucketMinute).padStart(2, '0')}:00`;
+}
+
+function normalizeSortOrder(order?: string): 'asc' | 'desc' {
+ return order?.toLowerCase() === 'asc' ? 'asc' : 'desc';
+}
+
+function compareString(a: string, b: string, order: 'asc' | 'desc'): number {
+ const delta = a.localeCompare(b);
+ return order === 'asc' ? delta : -delta;
+}
+
+function compareNumber(a: number, b: number, order: 'asc' | 'desc'): number {
+ const delta = a - b;
+ return order === 'asc' ? delta : -delta;
+}
+
+function compareTimestamp(a: string, b: string, order: 'asc' | 'desc'): number {
+ const aMs = Date.parse(a || '');
+ const bMs = Date.parse(b || '');
+ const safeA = Number.isFinite(aMs) ? aMs : 0;
+ const safeB = Number.isFinite(bMs) ? bMs : 0;
+ return compareNumber(safeA, safeB, order);
+}
+
+function matchesDomainSearch(domain: string, search: string): boolean {
+ if (!search) return true;
+ return domain.toLowerCase().includes(search);
+}
+
+function matchesIPSearch(ip: string, domains: Iterable<string>, search: string): boolean {
+ if (!search) return true;
+ if (ip.toLowerCase().includes(search)) return true;
+ for (const domain of domains) {
+ if (domain.toLowerCase().includes(search)) return true;
+ }
+ return false;
+}
+
+function sortDomains(data: DomainStats[], sortBy: string, sortOrder: 'asc' | 'desc'): DomainStats[] {
+ return data.sort((a, b) => {
+ switch (sortBy) {
+ case 'domain':
+ return compareString(a.domain, b.domain, sortOrder);
+ case 'totalTraffic':
+ return compareNumber(
+ a.totalDownload + a.totalUpload,
+ b.totalDownload + b.totalUpload,
+ sortOrder,
+ );
+ case 'totalUpload':
+ return compareNumber(a.totalUpload, b.totalUpload, sortOrder);
+ case 'totalConnections':
+ return compareNumber(a.totalConnections, b.totalConnections, sortOrder);
+ case 'lastSeen':
+ return compareTimestamp(a.lastSeen, b.lastSeen, sortOrder);
+ case 'totalDownload':
+ default:
+ return compareNumber(a.totalDownload, b.totalDownload, sortOrder);
+ }
+ });
+}
+
+function sortIPs(data: IPStats[], sortBy: string, sortOrder: 'asc' | 'desc'): IPStats[] {
+ return data.sort((a, b) => {
+ switch (sortBy) {
+ case 'ip':
+ return compareString(a.ip, b.ip, sortOrder);
+ case 'totalTraffic':
+ return compareNumber(
+ a.totalDownload + a.totalUpload,
+ b.totalDownload + b.totalUpload,
+ sortOrder,
+ );
+ case 'totalUpload':
+ return compareNumber(a.totalUpload, b.totalUpload, sortOrder);
+ case 'totalConnections':
+ return compareNumber(a.totalConnections, b.totalConnections, sortOrder);
+ case 'lastSeen':
+ return compareTimestamp(a.lastSeen, b.lastSeen, sortOrder);
+ case 'totalDownload':
+ default:
+ return compareNumber(a.totalDownload, b.totalDownload, sortOrder);
+ }
+ });
+}
+
+export type DomainPageOptions = {
+ offset?: number;
+ limit?: number;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+};
+
+export type IPPageOptions = {
+ offset?: number;
+ limit?: number;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+};
+
+// --- RealtimeMerger Class ---
+
+export class RealtimeMerger {
+ constructor(private store: RealtimeStore) {}
+
+ applySummaryDelta<T extends { totalUpload: number; totalDownload: number; totalConnections: number }>(
+ backendId: number,
+ base: T,
+ ): T {
+ const delta = this.store.getSummaryDelta(backendId);
+ if (delta.upload === 0 && delta.download === 0 && delta.connections === 0) {
+ return base;
+ }
+
+ return {
+ ...base,
+ totalUpload: base.totalUpload + delta.upload,
+ totalDownload: base.totalDownload + delta.download,
+ totalConnections: base.totalConnections + delta.connections,
+ };
+ }
+
+ mergeTrend(
+ backendId: number,
+ basePoints: TrafficTrendPoint[],
+ minutes: number,
+ bucketMinutes = 1,
+ nowMs = Date.now(),
+ ): TrafficTrendPoint[] {
+ const minuteMap = this.store.minuteByBackend.get(backendId);
+ if (!minuteMap || minuteMap.size === 0) return basePoints;
+
+ const cutoffKey = toMinuteKey(nowMs - minutes * 60 * 1000);
+ const deltaMap = new Map<string, { upload: number; download: number }>();
+
+ for (const [minuteKey, bucket] of minuteMap) {
+ if (minuteKey < cutoffKey) continue;
+ const bucketKey = bucketMinuteKey(minuteKey, bucketMinutes);
+ const existing = deltaMap.get(bucketKey);
+ if (existing) {
+ existing.upload += bucket.upload;
+ existing.download += bucket.download;
+ } else {
+ deltaMap.set(bucketKey, { upload: bucket.upload, download: bucket.download });
+ }
+ }
+
+ if (deltaMap.size === 0) return basePoints;
+
+ const merged = new Map<string, { upload: number; download: number }>();
+ for (const point of basePoints) {
+ merged.set(point.time, { upload: point.upload, download: point.download });
+ }
+
+ for (const [time, delta] of deltaMap) {
+ const existing = merged.get(time);
+ if (existing) {
+ existing.upload += delta.upload;
+ existing.download += delta.download;
+ } else {
+ merged.set(time, { upload: delta.upload, download: delta.download });
+ }
+ }
+
+ return Array.from(merged.entries())
+ .map(([time, data]) => ({ time, upload: data.upload, download: data.download }))
+ .sort((a, b) => a.time.localeCompare(b.time));
+ }
+
+ mergeTopDomains(backendId: number, base: DomainStats[], limit: number): DomainStats[] {
+ const domainMap = this.store.domainByBackend.get(backendId);
+ if (!domainMap || domainMap.size === 0) return base;
+
+ const merged = new Map<string, DomainStats>();
+ for (const item of base) {
+ merged.set(item.domain, { ...item });
+ }
+
+ for (const [domain, delta] of domainMap) {
+ const existing = merged.get(domain);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ if (delta.ips.size > 0) {
+ const ips = new Set(existing.ips || []);
+ for (const ip of delta.ips) ips.add(ip);
+ existing.ips = Array.from(ips);
+ }
+ if (delta.rules.size > 0) {
+ const rules = new Set(existing.rules || []);
+ for (const rule of delta.rules) rules.add(rule);
+ existing.rules = Array.from(rules);
+ }
+ if (delta.chains.size > 0) {
+ const chains = new Set(existing.chains || []);
+ for (const chain of delta.chains) chains.add(chain);
+ existing.chains = Array.from(chains);
+ }
+ } else {
+ merged.set(domain, {
+ domain,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ ips: Array.from(delta.ips),
+ rules: Array.from(delta.rules),
+ chains: Array.from(delta.chains),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeTopIPs(backendId: number, base: IPStats[], limit: number): IPStats[] {
+ const ipMap = this.store.ipByBackend.get(backendId);
+ if (!ipMap || ipMap.size === 0) return base;
+
+ const merged = new Map<string, IPStats>();
+ for (const item of base) {
+ merged.set(item.ip, { ...item });
+ }
+
+ for (const [ip, delta] of ipMap) {
+ const existing = merged.get(ip);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ if (delta.domains.size > 0) {
+ const domains = new Set(existing.domains || []);
+ for (const domain of delta.domains) domains.add(domain);
+ existing.domains = Array.from(domains);
+ }
+ if (delta.chains.size > 0) {
+ const chains = new Set(existing.chains || []);
+ for (const chain of delta.chains) chains.add(chain);
+ existing.chains = Array.from(chains);
+ }
+ } else {
+ merged.set(ip, {
+ ip,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ domains: Array.from(delta.domains),
+ chains: Array.from(delta.chains),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeDomainStatsPaginated(
+ backendId: number,
+ base: { data: DomainStats[]; total: number },
+ opts: DomainPageOptions = {},
+ ): { data: DomainStats[]; total: number } {
+ const domainMap = this.store.domainByBackend.get(backendId);
+ if (!domainMap || domainMap.size === 0) return base;
+
+ const offset = Math.max(0, opts.offset ?? 0);
+ const limit = Math.max(1, (opts.limit ?? base.data.length) || 50);
+ const sortBy = opts.sortBy || 'totalDownload';
+ const sortOrder = normalizeSortOrder(opts.sortOrder);
+ const search = (opts.search || '').trim().toLowerCase();
+
+ const merged = new Map<string, DomainStats>();
+ for (const item of base.data) {
+ if (!matchesDomainSearch(item.domain, search)) continue;
+ merged.set(item.domain, { ...item });
+ }
+
+ let addedCount = 0;
+ for (const [domain, delta] of domainMap) {
+ if (!matchesDomainSearch(domain, search)) continue;
+
+ const existing = merged.get(domain);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const ips = new Set(existing.ips || []);
+ for (const ip of delta.ips) ips.add(ip);
+ existing.ips = Array.from(ips);
+ const rules = new Set(existing.rules || []);
+ for (const rule of delta.rules) rules.add(rule);
+ existing.rules = Array.from(rules);
+ const chains = new Set(existing.chains || []);
+ for (const chain of delta.chains) chains.add(chain);
+ existing.chains = Array.from(chains);
+ continue;
+ }
+
+ // For non-first pages, avoid injecting unknown new rows that can shift boundaries.
+ if (offset > 0) continue;
+ merged.set(domain, {
+ domain,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ ips: Array.from(delta.ips),
+ rules: Array.from(delta.rules),
+ chains: Array.from(delta.chains),
+ });
+ addedCount += 1;
+ }
+
+ const sorted = sortDomains(Array.from(merged.values()), sortBy, sortOrder);
+ return {
+ data: sorted.slice(0, limit),
+ total: base.total + addedCount,
+ };
+ }
+
+ mergeIPStatsPaginated(
+ backendId: number,
+ base: { data: IPStats[]; total: number },
+ opts: IPPageOptions = {},
+ ): { data: IPStats[]; total: number } {
+ const ipMap = this.store.ipByBackend.get(backendId);
+ if (!ipMap || ipMap.size === 0) return base;
+
+ const offset = Math.max(0, opts.offset ?? 0);
+ const limit = Math.max(1, (opts.limit ?? base.data.length) || 50);
+ const sortBy = opts.sortBy || 'totalDownload';
+ const sortOrder = normalizeSortOrder(opts.sortOrder);
+ const search = (opts.search || '').trim().toLowerCase();
+
+ const merged = new Map<string, IPStats>();
+ for (const item of base.data) {
+ if (!matchesIPSearch(item.ip, item.domains || [], search)) continue;
+ merged.set(item.ip, { ...item });
+ }
+
+ let addedCount = 0;
+ for (const [ip, delta] of ipMap) {
+ if (!matchesIPSearch(ip, delta.domains, search)) continue;
+
+ const existing = merged.get(ip);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const domains = new Set(existing.domains || []);
+ for (const domain of delta.domains) domains.add(domain);
+ existing.domains = Array.from(domains);
+ const chains = new Set(existing.chains || []);
+ for (const chain of delta.chains) chains.add(chain);
+ existing.chains = Array.from(chains);
+ continue;
+ }
+
+ if (offset > 0) continue;
+ merged.set(ip, {
+ ip,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ domains: Array.from(delta.domains),
+ chains: Array.from(delta.chains),
+ });
+ addedCount += 1;
+ }
+
+ const sorted = sortIPs(Array.from(merged.values()), sortBy, sortOrder);
+ return {
+ data: sorted.slice(0, limit),
+ total: base.total + addedCount,
+ };
+ }
+
+ mergeProxyDomains(
+ backendId: number,
+ chain: string,
+ base: DomainStats[],
+ limit = 5000,
+ ): DomainStats[] {
+ const domainMap = this.store.domainByBackend.get(backendId);
+ if (!domainMap || domainMap.size === 0) return base;
+
+ const merged = new Map<string, DomainStats>();
+ for (const item of base) {
+ merged.set(item.domain, { ...item });
+ }
+
+ for (const [domain, delta] of domainMap) {
+ const matched = Array.from(delta.chains).some((full) => matchesChainPrefix(full, chain));
+ if (!matched) continue;
+
+ const existing = merged.get(domain);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const ips = new Set(existing.ips || []);
+ for (const ip of delta.ips) ips.add(ip);
+ existing.ips = Array.from(ips);
+ const rules = new Set(existing.rules || []);
+ for (const rule of delta.rules) rules.add(rule);
+ existing.rules = Array.from(rules);
+ const chains = new Set(existing.chains || []);
+ for (const full of delta.chains) {
+ if (matchesChainPrefix(full, chain)) chains.add(full);
+ }
+ existing.chains = Array.from(chains);
+ } else {
+ merged.set(domain, {
+ domain,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ ips: Array.from(delta.ips),
+ rules: Array.from(delta.rules),
+ chains: Array.from(delta.chains).filter((full) => matchesChainPrefix(full, chain)),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeProxyIPs(
+ backendId: number,
+ chain: string,
+ base: IPStats[],
+ limit = 5000,
+ ): IPStats[] {
+ const ipMap = this.store.ipByBackend.get(backendId);
+ if (!ipMap || ipMap.size === 0) return base;
+
+ const merged = new Map<string, IPStats>();
+ for (const item of base) {
+ merged.set(item.ip, { ...item });
+ }
+
+ for (const [ip, delta] of ipMap) {
+ const matched = Array.from(delta.chains).some((full) => matchesChainPrefix(full, chain));
+ if (!matched) continue;
+
+ const existing = merged.get(ip);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const domains = new Set(existing.domains || []);
+ for (const domain of delta.domains) domains.add(domain);
+ existing.domains = Array.from(domains);
+ const chains = new Set(existing.chains || []);
+ for (const full of delta.chains) {
+ if (matchesChainPrefix(full, chain)) chains.add(full);
+ }
+ existing.chains = Array.from(chains);
+ } else {
+ merged.set(ip, {
+ ip,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ domains: Array.from(delta.domains),
+ chains: Array.from(delta.chains).filter((full) => matchesChainPrefix(full, chain)),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeProxyStats(backendId: number, base: ProxyStats[]): ProxyStats[] {
+ const proxyMap = this.store.proxyByBackend.get(backendId);
+ if (!proxyMap || proxyMap.size === 0) return base;
+
+ const merged = new Map<string, ProxyStats>();
+ for (const item of base) {
+ merged.set(item.chain, { ...item });
+ }
+
+ for (const [chain, delta] of proxyMap) {
+ const existing = merged.get(chain);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ } else {
+ merged.set(chain, {
+ chain,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ });
+ }
+ }
+
+ return Array.from(merged.values()).sort(
+ (a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload),
+ );
+ }
+
+ mergeDeviceStats(backendId: number, base: DeviceStats[], limit = 50): DeviceStats[] {
+ const deviceMap = this.store.deviceByBackend.get(backendId);
+ if (!deviceMap || deviceMap.size === 0) {
+ return base;
+ }
+
+ const merged = new Map<string, DeviceStats>();
+ for (const item of base) {
+ merged.set(item.sourceIP, { ...item });
+ }
+
+ for (const [sourceIP, delta] of deviceMap) {
+ const existing = merged.get(sourceIP);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ } else {
+ merged.set(sourceIP, {
+ sourceIP,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeDeviceDomains(
+ backendId: number,
+ sourceIP: string,
+ base: DomainStats[],
+ limit = 5000,
+ ): DomainStats[] {
+ const sourceDomainMap = this.store.deviceDomainByBackend.get(backendId);
+ const domainMap = sourceDomainMap?.get(sourceIP);
+ if (!domainMap || domainMap.size === 0) {
+ return base;
+ }
+
+ const merged = new Map<string, DomainStats>();
+ for (const item of base) {
+ merged.set(item.domain, { ...item });
+ }
+
+ for (const [domain, delta] of domainMap) {
+ const existing = merged.get(domain);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ if (delta.ips.size > 0) {
+ const ips = new Set(existing.ips || []);
+ for (const ip of delta.ips) ips.add(ip);
+ existing.ips = Array.from(ips);
+ }
+ if (delta.rules.size > 0) {
+ const rules = new Set(existing.rules || []);
+ for (const rule of delta.rules) rules.add(rule);
+ existing.rules = Array.from(rules);
+ }
+ if (delta.chains.size > 0) {
+ const chains = new Set(existing.chains || []);
+ for (const chain of delta.chains) chains.add(chain);
+ existing.chains = Array.from(chains);
+ }
+ } else {
+ merged.set(domain, {
+ domain,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ ips: Array.from(delta.ips),
+ rules: Array.from(delta.rules),
+ chains: Array.from(delta.chains),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeDeviceIPs(
+ backendId: number,
+ sourceIP: string,
+ base: IPStats[],
+ limit = 5000,
+ ): IPStats[] {
+ const sourceIPMap = this.store.deviceIPByBackend.get(backendId);
+ const ipMap = sourceIPMap?.get(sourceIP);
+ if (!ipMap || ipMap.size === 0) {
+ return base;
+ }
+
+ const merged = new Map<string, IPStats>();
+ for (const item of base) {
+ merged.set(item.ip, { ...item });
+ }
+
+ for (const [ip, delta] of ipMap) {
+ const existing = merged.get(ip);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ if (delta.domains.size > 0) {
+ const domains = new Set(existing.domains || []);
+ for (const domain of delta.domains) domains.add(domain);
+ existing.domains = Array.from(domains);
+ }
+ if (delta.chains.size > 0) {
+ const chains = new Set(existing.chains || []);
+ for (const chain of delta.chains) chains.add(chain);
+ existing.chains = Array.from(chains);
+ }
+ } else {
+ merged.set(ip, {
+ ip,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ domains: Array.from(delta.domains),
+ chains: Array.from(delta.chains),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeRuleStats(backendId: number, base: RuleStats[]): RuleStats[] {
+ const ruleMap = this.store.ruleByBackend.get(backendId);
+ if (!ruleMap || ruleMap.size === 0) return base;
+
+ const merged = new Map<string, RuleStats>();
+ for (const item of base) {
+ merged.set(item.rule, { ...item });
+ }
+
+ for (const [rule, delta] of ruleMap) {
+ const existing = merged.get(rule);
+ if (existing) {
+ existing.finalProxy = delta.finalProxy || existing.finalProxy;
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ } else {
+ merged.set(rule, {
+ rule,
+ finalProxy: delta.finalProxy,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ });
+ }
+ }
+
+ return Array.from(merged.values()).sort(
+ (a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload),
+ );
+ }
+
+ mergeRuleDomains(
+ backendId: number,
+ rule: string,
+ base: DomainStats[],
+ limit = 5000,
+ ): DomainStats[] {
+ const domainMap = this.store.domainByBackend.get(backendId);
+ if (!domainMap || domainMap.size === 0) return base;
+
+ const merged = new Map<string, DomainStats>();
+ for (const item of base) {
+ merged.set(item.domain, { ...item });
+ }
+
+ for (const [domain, delta] of domainMap) {
+ if (!delta.rules.has(rule)) continue;
+
+ const existing = merged.get(domain);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const ips = new Set(existing.ips || []);
+ for (const ip of delta.ips) ips.add(ip);
+ existing.ips = Array.from(ips);
+ const rules = new Set(existing.rules || []);
+ for (const r of delta.rules) rules.add(r);
+ existing.rules = Array.from(rules);
+ const chains = new Set(existing.chains || []);
+ for (const full of delta.chains) chains.add(full);
+ existing.chains = Array.from(chains);
+ } else {
+ merged.set(domain, {
+ domain,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ ips: Array.from(delta.ips),
+ rules: Array.from(delta.rules),
+ chains: Array.from(delta.chains),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeRuleIPs(
+ backendId: number,
+ rule: string,
+ base: IPStats[],
+ limit = 5000,
+ ): IPStats[] {
+ const ipMap = this.store.ipByBackend.get(backendId);
+ if (!ipMap || ipMap.size === 0) return base;
+
+ const merged = new Map<string, IPStats>();
+ for (const item of base) {
+ merged.set(item.ip, { ...item });
+ }
+
+ for (const [ip, delta] of ipMap) {
+ if (!delta.rules.has(rule)) continue;
+
+ const existing = merged.get(ip);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (delta.lastSeen > existing.lastSeen) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ const domains = new Set(existing.domains || []);
+ for (const domain of delta.domains) domains.add(domain);
+ existing.domains = Array.from(domains);
+ const chains = new Set(existing.chains || []);
+ for (const full of delta.chains) chains.add(full);
+ existing.chains = Array.from(chains);
+ } else {
+ merged.set(ip, {
+ ip,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ domains: Array.from(delta.domains),
+ chains: Array.from(delta.chains),
+ });
+ }
+ }
+
+ return Array.from(merged.values())
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, limit);
+ }
+
+ mergeCountryStats(backendId: number, base: CountryStats[]): CountryStats[] {
+ const countryMap = this.store.countryByBackend.get(backendId);
+ if (!countryMap || countryMap.size === 0) return base;
+
+ const merged = new Map<string, CountryStats>();
+ for (const item of base) {
+ merged.set(item.country, { ...item });
+ }
+
+ for (const [country, delta] of countryMap) {
+ const existing = merged.get(country);
+ if (existing) {
+ existing.totalUpload += delta.totalUpload;
+ existing.totalDownload += delta.totalDownload;
+ existing.totalConnections += delta.totalConnections;
+ if (!existing.countryName && delta.countryName) {
+ existing.countryName = delta.countryName;
+ }
+ if (!existing.continent && delta.continent) {
+ existing.continent = delta.continent;
+ }
+ if (delta.lastSeen && (!existing.lastSeen || delta.lastSeen > existing.lastSeen)) {
+ existing.lastSeen = delta.lastSeen;
+ }
+ } else {
+ merged.set(country, {
+ country,
+ countryName: delta.countryName,
+ continent: delta.continent,
+ totalUpload: delta.totalUpload,
+ totalDownload: delta.totalDownload,
+ totalConnections: delta.totalConnections,
+ lastSeen: delta.lastSeen,
+ });
+ }
+ }
+
+ return Array.from(merged.values()).sort(
+ (a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload),
+ );
+ }
+}
diff --git a/apps/collector/src/modules/realtime/realtime.store.ts b/apps/collector/src/modules/realtime/realtime.store.ts
new file mode 100644
index 0000000..e2967b7
--- /dev/null
+++ b/apps/collector/src/modules/realtime/realtime.store.ts
@@ -0,0 +1,353 @@
+import {
+ SummaryDelta,
+ MinuteBucket,
+ DomainDelta,
+ IPDelta,
+ ProxyDelta,
+ DeviceDelta,
+ RuleDelta,
+ CountryDelta,
+ TrafficMeta,
+} from './realtime.types.js';
+
+export class RealtimeStore {
+ // Expose these as public readonly or via getters if needed by the merger,
+ // but for now we'll make them public to allow the merger to access them easily.
+ // In a stricter design, we might use getters.
+ public summaryByBackend = new Map<number, SummaryDelta>();
+ public minuteByBackend = new Map<number, Map<string, MinuteBucket>>();
+ public domainByBackend = new Map<number, Map<string, DomainDelta>>();
+ public ipByBackend = new Map<number, Map<string, IPDelta>>();
+ public proxyByBackend = new Map<number, Map<string, ProxyDelta>>();
+ public deviceByBackend = new Map<number, Map<string, DeviceDelta>>();
+ public deviceDomainByBackend = new Map<number, Map<string, Map<string, DomainDelta>>>();
+ public deviceIPByBackend = new Map<number, Map<string, Map<string, IPDelta>>>();
+ public ruleByBackend = new Map<number, Map<string, RuleDelta>>();
+ public countryByBackend = new Map<number, Map<string, CountryDelta>>();
+
+ private maxMinutes: number;
+
+ constructor(maxMinutes = parseInt(process.env.REALTIME_MAX_MINUTES || '180', 10)) {
+ this.maxMinutes = Number.isFinite(maxMinutes) ? Math.max(30, maxMinutes) : 180;
+ }
+
+ /**
+ * Helper to generate minute key "YYYY-MM-DDTHH:mm:00"
+ */
+ private toMinuteKey(tsMs: number): string {
+ const iso = new Date(tsMs).toISOString();
+ return `${iso.slice(0, 16)}:00`;
+ }
+
+ private pruneOldBuckets(minuteMap: Map<string, MinuteBucket>, nowMs: number) {
+ // Simple pruning strategy: remove keys older than maxMinutes
+ // This is less efficient than a rolling buffer but easier to implement with Map
+ const cutoff = new Date(nowMs - this.maxMinutes * 60 * 1000).toISOString().slice(0, 16) + ':00';
+ for (const key of minuteMap.keys()) {
+ if (key < cutoff) {
+ minuteMap.delete(key);
+ }
+ }
+ }
+
+ recordTraffic(
+ backendId: number,
+ meta: TrafficMeta,
+ connections = 1,
+ timestamp = Date.now()
+ ): void {
+ if (meta.upload <= 0 && meta.download <= 0) return;
+
+ // 1. Summary
+ const summary = this.summaryByBackend.get(backendId) || {
+ upload: 0,
+ download: 0,
+ connections: 0,
+ lastUpdated: 0,
+ };
+ summary.upload += meta.upload;
+ summary.download += meta.download;
+ summary.connections += connections;
+ summary.lastUpdated = timestamp;
+ this.summaryByBackend.set(backendId, summary);
+
+ // 2. Minute Bucket
+ const minuteKey = this.toMinuteKey(timestamp);
+ let minuteMap = this.minuteByBackend.get(backendId);
+ if (!minuteMap) {
+ minuteMap = new Map();
+ this.minuteByBackend.set(backendId, minuteMap);
+ }
+ const bucket = minuteMap.get(minuteKey) || { upload: 0, download: 0, lastUpdated: 0 };
+ bucket.upload += meta.upload;
+ bucket.download += meta.download;
+ bucket.lastUpdated = timestamp;
+ minuteMap.set(minuteKey, bucket);
+
+ this.pruneOldBuckets(minuteMap, timestamp);
+
+ const ruleName =
+ meta.chains.length > 1
+ ? meta.chains[meta.chains.length - 1]
+ : meta.rulePayload
+ ? `${meta.rule}(${meta.rulePayload})`
+ : meta.rule;
+ const fullChain = meta.chains.join(' > ');
+ const lastSeen = new Date(timestamp).toISOString();
+
+ // 3. Domain
+ if (meta.domain) {
+ let domainMap = this.domainByBackend.get(backendId);
+ if (!domainMap) {
+ domainMap = new Map();
+ this.domainByBackend.set(backendId, domainMap);
+ }
+
+ const domainDelta = domainMap.get(meta.domain) || {
+ domain: meta.domain,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ ips: new Set<string>(),
+ rules: new Set<string>(),
+ chains: new Set<string>(),
+ };
+
+ domainDelta.totalUpload += meta.upload;
+ domainDelta.totalDownload += meta.download;
+ domainDelta.totalConnections += connections;
+ domainDelta.lastSeen = lastSeen;
+ if (meta.ip) domainDelta.ips.add(meta.ip);
+ if (ruleName) domainDelta.rules.add(ruleName);
+ if (fullChain) domainDelta.chains.add(fullChain);
+ domainMap.set(meta.domain, domainDelta);
+ }
+
+ // 4. IP
+ if (meta.ip) {
+ let ipMap = this.ipByBackend.get(backendId);
+ if (!ipMap) {
+ ipMap = new Map();
+ this.ipByBackend.set(backendId, ipMap);
+ }
+
+ const ipDelta = ipMap.get(meta.ip) || {
+ ip: meta.ip,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ domains: new Set<string>(),
+ chains: new Set<string>(),
+ rules: new Set<string>(),
+ };
+
+ ipDelta.totalUpload += meta.upload;
+ ipDelta.totalDownload += meta.download;
+ ipDelta.totalConnections += connections;
+ ipDelta.lastSeen = lastSeen;
+ const ipDomain = meta.domain || 'unknown';
+ if (ipDomain) ipDelta.domains.add(ipDomain);
+ if (fullChain) ipDelta.chains.add(fullChain);
+ if (ruleName) ipDelta.rules.add(ruleName);
+ ipMap.set(meta.ip, ipDelta);
+ }
+
+ // 5. Proxy
+ const proxyChain = meta.chains[0] || 'DIRECT';
+ let proxyMap = this.proxyByBackend.get(backendId);
+ if (!proxyMap) {
+ proxyMap = new Map();
+ this.proxyByBackend.set(backendId, proxyMap);
+ }
+
+ const proxyDelta = proxyMap.get(proxyChain) || {
+ chain: proxyChain,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ };
+
+ proxyDelta.totalUpload += meta.upload;
+ proxyDelta.totalDownload += meta.download;
+ proxyDelta.totalConnections += connections;
+ proxyDelta.lastSeen = lastSeen;
+ proxyMap.set(proxyChain, proxyDelta);
+
+ // 6. Device (Source IP)
+ const sourceIP = (meta.sourceIP || '').trim();
+ if (sourceIP) {
+ let deviceMap = this.deviceByBackend.get(backendId);
+ if (!deviceMap) {
+ deviceMap = new Map();
+ this.deviceByBackend.set(backendId, deviceMap);
+ }
+
+ const deviceDelta = deviceMap.get(sourceIP) || {
+ sourceIP,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ };
+ deviceDelta.totalUpload += meta.upload;
+ deviceDelta.totalDownload += meta.download;
+ deviceDelta.totalConnections += connections;
+ deviceDelta.lastSeen = lastSeen;
+ deviceMap.set(sourceIP, deviceDelta);
+
+ // Device -> Domain
+ if (meta.domain) {
+ let sourceDomainMap = this.deviceDomainByBackend.get(backendId);
+ if (!sourceDomainMap) {
+ sourceDomainMap = new Map();
+ this.deviceDomainByBackend.set(backendId, sourceDomainMap);
+ }
+ let domainMap = sourceDomainMap.get(sourceIP);
+ if (!domainMap) {
+ domainMap = new Map();
+ sourceDomainMap.set(sourceIP, domainMap);
+ }
+
+ const domainDelta = domainMap.get(meta.domain) || {
+ domain: meta.domain,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ ips: new Set<string>(),
+ rules: new Set<string>(),
+ chains: new Set<string>(),
+ };
+ domainDelta.totalUpload += meta.upload;
+ domainDelta.totalDownload += meta.download;
+ domainDelta.totalConnections += connections;
+ domainDelta.lastSeen = lastSeen;
+ if (meta.ip) domainDelta.ips.add(meta.ip);
+ if (ruleName) domainDelta.rules.add(ruleName);
+ if (fullChain) domainDelta.chains.add(fullChain);
+ domainMap.set(meta.domain, domainDelta);
+ }
+
+ // Device -> IP
+ if (meta.ip) {
+ let sourceIPMap = this.deviceIPByBackend.get(backendId);
+ if (!sourceIPMap) {
+ sourceIPMap = new Map();
+ this.deviceIPByBackend.set(backendId, sourceIPMap);
+ }
+ let ipMap = sourceIPMap.get(sourceIP);
+ if (!ipMap) {
+ ipMap = new Map();
+ sourceIPMap.set(sourceIP, ipMap);
+ }
+
+ const ipDelta = ipMap.get(meta.ip) || {
+ ip: meta.ip,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ domains: new Set<string>(),
+ chains: new Set<string>(),
+ rules: new Set<string>(),
+ };
+ ipDelta.totalUpload += meta.upload;
+ ipDelta.totalDownload += meta.download;
+ ipDelta.totalConnections += connections;
+ ipDelta.lastSeen = lastSeen;
+ if (meta.domain) ipDelta.domains.add(meta.domain);
+ if (fullChain) ipDelta.chains.add(fullChain);
+ if (ruleName) ipDelta.rules.add(ruleName);
+ ipMap.set(meta.ip, ipDelta);
+ }
+ }
+
+ // 7. Rule
+ let ruleMap = this.ruleByBackend.get(backendId);
+ if (!ruleMap) {
+ ruleMap = new Map();
+ this.ruleByBackend.set(backendId, ruleMap);
+ }
+
+ const finalProxy = proxyChain || 'DIRECT';
+ const ruleDelta = ruleMap.get(ruleName) || {
+ rule: ruleName,
+ finalProxy,
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ };
+ ruleDelta.finalProxy = finalProxy;
+ ruleDelta.totalUpload += meta.upload;
+ ruleDelta.totalDownload += meta.download;
+ ruleDelta.totalConnections += connections;
+ ruleDelta.lastSeen = lastSeen;
+ ruleMap.set(ruleName, ruleDelta);
+ }
+
+ recordCountryTraffic(
+ backendId: number,
+ geo: { country: string; country_name: string; continent: string },
+ upload: number,
+ download: number,
+ connections = 1,
+ timestamp = Date.now(),
+ ): void {
+ if (upload <= 0 && download <= 0) return;
+
+ const lastSeen = new Date(timestamp).toISOString();
+ let countryMap = this.countryByBackend.get(backendId);
+ if (!countryMap) {
+ countryMap = new Map();
+ this.countryByBackend.set(backendId, countryMap);
+ }
+
+ const key = geo.country || 'Unknown';
+ const countryDelta = countryMap.get(key) || {
+ country: key,
+ countryName: geo.country_name || geo.country || 'Unknown',
+ continent: geo.continent || 'Unknown',
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ lastSeen,
+ };
+
+ countryDelta.totalUpload += upload;
+ countryDelta.totalDownload += download;
+ countryDelta.totalConnections += connections;
+ countryDelta.lastSeen = lastSeen;
+ countryMap.set(key, countryDelta);
+ }
+
+ getSummaryDelta(backendId: number): SummaryDelta {
+ return this.summaryByBackend.get(backendId) || {
+ upload: 0,
+ download: 0,
+ connections: 0,
+ lastUpdated: 0,
+ };
+ }
+
+ getTodayDelta(backendId: number, nowMs = Date.now()): { upload: number; download: number } {
+ const minuteMap = this.minuteByBackend.get(backendId);
+ if (!minuteMap || minuteMap.size === 0) return { upload: 0, download: 0 };
+
+ const todayPrefix = new Date(nowMs).toISOString().slice(0, 10);
+ let upload = 0;
+ let download = 0;
+
+ for (const [minuteKey, bucket] of minuteMap) {
+ if (minuteKey.startsWith(todayPrefix)) {
+ upload += bucket.upload;
+ download += bucket.download;
+ }
+ }
+
+ return { upload, download };
+ }
+}
diff --git a/apps/collector/src/modules/realtime/realtime.types.ts b/apps/collector/src/modules/realtime/realtime.types.ts
new file mode 100644
index 0000000..e9825d3
--- /dev/null
+++ b/apps/collector/src/modules/realtime/realtime.types.ts
@@ -0,0 +1,81 @@
+
+export type SummaryDelta = {
+ upload: number;
+ download: number;
+ connections: number;
+ lastUpdated: number;
+};
+
+export type MinuteBucket = {
+ upload: number;
+ download: number;
+ lastUpdated: number;
+};
+
+export type ProxyDelta = {
+ chain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+};
+
+export type DeviceDelta = {
+ sourceIP: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+};
+
+export type RuleDelta = {
+ rule: string;
+ finalProxy: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+};
+
+export type CountryDelta = {
+ country: string;
+ countryName: string;
+ continent: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+};
+
+export type DomainDelta = {
+ domain: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ ips: Set<string>;
+ rules: Set<string>;
+ chains: Set<string>;
+};
+
+export type IPDelta = {
+ ip: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ domains: Set<string>;
+ chains: Set<string>;
+ rules: Set<string>;
+};
+
+export type TrafficMeta = {
+ domain: string;
+ ip: string;
+ sourceIP?: string;
+ chains: string[];
+ rule: string;
+ rulePayload: string;
+ upload: number;
+ download: number;
+};
diff --git a/apps/collector/src/modules/stats/index.ts b/apps/collector/src/modules/stats/index.ts
new file mode 100644
index 0000000..cd322c4
--- /dev/null
+++ b/apps/collector/src/modules/stats/index.ts
@@ -0,0 +1,7 @@
+/**
+ * Stats Module
+ */
+
+export { StatsService } from './stats.service.js';
+export { default as statsController } from './stats.controller.js';
+export type * from './stats.types.js';
diff --git a/apps/collector/src/modules/stats/stats.controller.ts b/apps/collector/src/modules/stats/stats.controller.ts
new file mode 100644
index 0000000..47812f2
--- /dev/null
+++ b/apps/collector/src/modules/stats/stats.controller.ts
@@ -0,0 +1,649 @@
+/**
+ * Stats Controller - Fastify routes for /api/stats
+ */
+
+import type { FastifyInstance, FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify';
+import type { StatsService } from './stats.service.js';
+import type { TimeRange } from './stats.types.js';
+
+// Extend Fastify instance to include statsService
+declare module 'fastify' {
+ interface FastifyInstance {
+ statsService: StatsService;
+ }
+}
+
+function parseOffset(raw: string | undefined): number {
+ if (!raw) return 0;
+ const parsed = Number.parseInt(raw, 10);
+ if (Number.isNaN(parsed) || parsed < 0) return 0;
+ return parsed;
+}
+
+// Helper function to get backend ID from request
+function getBackendId(request: FastifyRequest, service: StatsService): number | null {
+ const query = request.query as Record<string, string | undefined>;
+ return service.resolveBackendId(query.backendId);
+}
+
+// Helper function to parse time range
+function getTimeRange(request: FastifyRequest, reply: FastifyReply): TimeRange | null {
+ const query = request.query as Record<string, string | undefined>;
+ const { start, end } = query;
+
+ if (!start && !end) {
+ return { active: false };
+ }
+ if (!start || !end) {
+ reply.status(400).send({ error: 'Both start and end must be provided together' });
+ return null;
+ }
+
+ const startDate = new Date(start);
+ const endDate = new Date(end);
+ if (Number.isNaN(startDate.getTime()) || Number.isNaN(endDate.getTime())) {
+ reply.status(400).send({ error: 'Invalid time range format, expected ISO datetime' });
+ return null;
+ }
+ if (startDate > endDate) {
+ reply.status(400).send({ error: 'start must be less than or equal to end' });
+ return null;
+ }
+
+ return {
+ start: startDate.toISOString(),
+ end: endDate.toISOString(),
+ active: true,
+ };
+}
+
+const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Promise<void> => {
+ const service = fastify.statsService;
+
+ // Get summary statistics for a specific backend
+ fastify.get('/summary', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ try {
+ const result = service.getSummary(backendId, timeRange);
+ return result;
+ } catch (error: unknown) {
+ if (error instanceof Error && error.message === 'Backend not found') {
+ return reply.status(404).send({ error: 'Backend not found' });
+ }
+ throw error;
+ }
+ });
+
+ // Get global summary across all backends
+ fastify.get('/global', async () => {
+ return service.getGlobalSummary();
+ });
+
+ // Get domain statistics for a specific backend (paginated)
+ fastify.get('/domains', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { offset, limit, sortBy, sortOrder, search } = query;
+ const parsedOffset = parseOffset(offset);
+ const parsedLimit = service.parseLimit(limit, 50, 200);
+
+ return service.getDomainStatsPaginated(backendId, timeRange, {
+ offset: parsedOffset,
+ limit: parsedLimit,
+ sortBy,
+ sortOrder,
+ search,
+ });
+ });
+
+ // Get IP statistics for a specific backend (paginated)
+ fastify.get('/ips', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { offset, limit, sortBy, sortOrder, search } = query;
+ const parsedOffset = parseOffset(offset);
+ const parsedLimit = service.parseLimit(limit, 50, 200);
+
+ return service.getIPStatsPaginated(backendId, timeRange, {
+ offset: parsedOffset,
+ limit: parsedLimit,
+ sortBy,
+ sortOrder,
+ search,
+ });
+ });
+
+ // Get per-proxy traffic breakdown for a specific domain
+ fastify.get('/domains/proxy-stats', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { domain, sourceIP, sourceChain } = query;
+ if (!domain) {
+ return reply.status(400).send({ error: 'Domain parameter is required' });
+ }
+
+ return service.getDomainProxyStats(backendId, domain, timeRange, sourceIP, sourceChain);
+ });
+
+ // Get IP details for a specific domain
+ fastify.get('/domains/ip-details', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { domain, sourceIP, sourceChain, limit } = query;
+ if (!domain) {
+ return reply.status(400).send({ error: 'Domain parameter is required' });
+ }
+
+ const effectiveLimit = service.parseLimit(limit, 100, 2000);
+ return service.getDomainIPDetails(backendId, domain, timeRange, effectiveLimit, sourceIP, sourceChain);
+ });
+
+ // Get per-proxy traffic breakdown for a specific IP
+ fastify.get('/ips/proxy-stats', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { ip, sourceIP, sourceChain } = query;
+ if (!ip) {
+ return reply.status(400).send({ error: 'IP parameter is required' });
+ }
+
+ return service.getIPProxyStats(backendId, ip, timeRange, sourceIP, sourceChain);
+ });
+
+ // Get domain details for a specific IP
+ fastify.get('/ips/domain-details', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { ip, sourceIP, sourceChain, limit } = query;
+ if (!ip) {
+ return reply.status(400).send({ error: 'IP parameter is required' });
+ }
+
+ const effectiveLimit = service.parseLimit(limit, 100, 2000);
+ return service.getIPDomainDetails(backendId, ip, timeRange, effectiveLimit, sourceIP, sourceChain);
+ });
+
+ // Get domains for a specific proxy/chain
+ fastify.get('/proxies/domains', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { chain, limit } = query;
+ if (!chain) {
+ return reply.status(400).send({ error: 'Chain parameter is required' });
+ }
+ const effectiveLimit = service.parseLimit(limit, 5000, 20000);
+
+ return service.getProxyDomains(backendId, chain, timeRange, effectiveLimit);
+ });
+
+ // Get IPs for a specific proxy/chain
+ fastify.get('/proxies/ips', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { chain, limit } = query;
+ if (!chain) {
+ return reply.status(400).send({ error: 'Chain parameter is required' });
+ }
+ const effectiveLimit = service.parseLimit(limit, 5000, 20000);
+
+ return service.getProxyIPs(backendId, chain, timeRange, effectiveLimit);
+ });
+
+ // Get proxy/chain statistics for a specific backend
+ fastify.get('/proxies', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ return service.getProxyStats(backendId, timeRange);
+ });
+
+ // Get rule statistics for a specific backend
+ fastify.get('/rules', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ return service.getRuleStats(backendId, timeRange);
+ });
+
+ // Get domains for a specific rule
+ fastify.get('/rules/domains', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { rule, limit } = query;
+ if (!rule) {
+ return reply.status(400).send({ error: 'Rule parameter is required' });
+ }
+ const effectiveLimit = service.parseLimit(limit, 5000, 20000);
+
+ return service.getRuleDomains(backendId, rule, timeRange, effectiveLimit);
+ });
+
+ // Get IPs for a specific rule
+ fastify.get('/rules/ips', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { rule, limit } = query;
+ if (!rule) {
+ return reply.status(400).send({ error: 'Rule parameter is required' });
+ }
+ const effectiveLimit = service.parseLimit(limit, 5000, 20000);
+
+ return service.getRuleIPs(backendId, rule, timeRange, effectiveLimit);
+ });
+
+ // Get per-proxy traffic breakdown for a specific domain under a specific rule
+ fastify.get('/rules/domains/proxy-stats', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { rule, domain } = query;
+ if (!rule || !domain) {
+ return reply.status(400).send({ error: 'Rule and domain parameters are required' });
+ }
+
+ return service.getRuleDomainProxyStats(backendId, rule, domain, timeRange);
+ });
+
+ // Get IP details for a specific domain under a specific rule
+ fastify.get('/rules/domains/ip-details', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { rule, domain, limit } = query;
+ if (!rule || !domain) {
+ return reply.status(400).send({ error: 'Rule and domain parameters are required' });
+ }
+ const effectiveLimit = service.parseLimit(limit, 100, 2000);
+
+ return service.getRuleDomainIPDetails(backendId, rule, domain, timeRange, effectiveLimit);
+ });
+
+ // Get per-proxy traffic breakdown for a specific IP under a specific rule
+ fastify.get('/rules/ips/proxy-stats', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { rule, ip } = query;
+ if (!rule || !ip) {
+ return reply.status(400).send({ error: 'Rule and IP parameters are required' });
+ }
+
+ return service.getRuleIPProxyStats(backendId, rule, ip, timeRange);
+ });
+
+ // Get domain details for a specific IP under a specific rule
+ fastify.get('/rules/ips/domain-details', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { rule, ip, limit } = query;
+ if (!rule || !ip) {
+ return reply.status(400).send({ error: 'Rule and IP parameters are required' });
+ }
+ const effectiveLimit = service.parseLimit(limit, 100, 2000);
+
+ return service.getRuleIPDomainDetails(backendId, rule, ip, timeRange, effectiveLimit);
+ });
+
+ // Get rule chain flow for a specific rule
+ fastify.get('/rules/chain-flow', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { rule } = query;
+ if (!rule) {
+ return reply.status(400).send({ error: 'Rule parameter is required' });
+ }
+
+ return service.getRuleChainFlow(backendId, rule, timeRange);
+ });
+
+ // Get all rule chain flows merged into unified DAG
+ fastify.get('/rules/chain-flow-all', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ return service.getAllRuleChainFlows(backendId, timeRange);
+ });
+
+ // Get rule to proxy mapping for a specific backend
+ fastify.get('/rule-proxy-map', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ return service.getRuleProxyMap(backendId);
+ });
+
+ // Get country traffic statistics for a specific backend
+ fastify.get('/countries', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { limit } = query;
+ const limitNum = service.parseLimit(limit, 50, 2000);
+
+ return service.getCountryStats(backendId, timeRange, limitNum);
+ });
+
+ // Get device statistics for a specific backend
+ fastify.get('/devices', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+ if (timeRange === null) {
+ return;
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { limit } = query;
+ const effectiveLimit = service.parseLimit(limit, 50, 2000);
+
+ return service.getDeviceStats(backendId, timeRange, effectiveLimit);
+ });
+
+ // Get domains for a specific device
+ fastify.get('/devices/domains', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { sourceIP, limit } = query;
+ const effectiveLimit = service.parseLimit(limit, 5000, 20000);
+
+ return service.getDeviceDomains(backendId, sourceIP || '', timeRange, effectiveLimit);
+ });
+
+ // Get IPs for a specific device
+ fastify.get('/devices/ips', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { sourceIP, limit } = query;
+ const effectiveLimit = service.parseLimit(limit, 5000, 20000);
+
+ return service.getDeviceIPs(backendId, sourceIP || '', timeRange, effectiveLimit);
+ });
+
+ // Get hourly statistics for a specific backend
+ fastify.get('/hourly', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { hours = '24' } = query;
+ const hoursNum = service.parseLimit(hours, 24, 24 * 30);
+ return service.getHourlyStats(backendId, timeRange, hoursNum);
+ });
+
+ // Get traffic trend for a specific backend
+ fastify.get('/trend', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { minutes = '30' } = query;
+ const windowMinutes = service.parseLimit(minutes, 30, 60 * 24 * 7);
+ return service.getTrafficTrend(backendId, timeRange, windowMinutes);
+ });
+
+ // Get traffic trend aggregated by time buckets for chart display
+ fastify.get('/trend/aggregated', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { minutes = '30', bucketMinutes = '1' } = query;
+ const windowMinutes = service.parseLimit(minutes, 30, 60 * 24 * 7);
+ const bucket = service.parseLimit(bucketMinutes, 1, 60);
+ return service.getTrafficTrendAggregated(backendId, timeRange, windowMinutes, bucket);
+ });
+
+ // Get recent connections for a specific backend
+ fastify.get('/connections', async (request, reply) => {
+ const backendId = getBackendId(request, service);
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const query = request.query as Record<string, string | undefined>;
+ const { limit = '100' } = query;
+ const limitNum = service.parseLimit(limit, 100, 2000);
+ return service.getRecentConnections(backendId, limitNum);
+ });
+};
+
+export default statsController;
diff --git a/apps/collector/src/modules/stats/stats.service.ts b/apps/collector/src/modules/stats/stats.service.ts
new file mode 100644
index 0000000..eaff15e
--- /dev/null
+++ b/apps/collector/src/modules/stats/stats.service.ts
@@ -0,0 +1,472 @@
+/**
+ * Stats Service - Business logic for statistics
+ */
+
+import type { StatsDatabase } from '../../db.js';
+import type { RealtimeStore } from '../../realtime.js';
+import type {
+ SummaryResponse,
+ GlobalSummary,
+ PaginatedDomainStats,
+ PaginatedIPStats,
+ TrafficTrendPoint,
+ TimeRange,
+ CountryStats,
+ DomainStats,
+ IPStats,
+ ProxyStats,
+ RuleStats,
+ HourlyStats,
+ DeviceStats,
+} from './stats.types.js';
+
+interface PaginatedStatsOptions {
+ offset?: number;
+ limit?: number;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+ start?: string;
+ end?: string;
+}
+
+export class StatsService {
+ constructor(
+ private db: StatsDatabase,
+ private realtimeStore: RealtimeStore,
+ ) {}
+
+ /**
+ * Resolve backend ID from query param or active backend fallback
+ */
+ resolveBackendId(rawBackendId?: string): number | null {
+ if (rawBackendId) {
+ const id = Number.parseInt(rawBackendId, 10);
+ return Number.isNaN(id) ? null : id;
+ }
+ return this.db.getActiveBackend()?.id ?? null;
+ }
+
+ /**
+ * Parse limit parameter with fallback and max
+ */
+ parseLimit(raw: string | undefined, fallback: number, max: number): number {
+ if (raw === undefined || raw === null || raw === '') {
+ return fallback;
+ }
+ const parsed = parseInt(raw, 10);
+ if (Number.isNaN(parsed) || parsed <= 0) {
+ return fallback;
+ }
+ return Math.min(parsed, max);
+ }
+
+ /**
+ * Check if realtime data should be included
+ */
+ shouldIncludeRealtime(timeRange: TimeRange): boolean {
+ if (!timeRange.active) {
+ return true;
+ }
+ if (!timeRange.end) {
+ return false;
+ }
+
+ const endMs = new Date(timeRange.end).getTime();
+ if (Number.isNaN(endMs)) {
+ return false;
+ }
+
+ // For "latest window" queries (end close to now), keep merging in-memory deltas
+ // so dashboard updates stay near real-time between DB flushes.
+ const toleranceMs = parseInt(
+ process.env.REALTIME_RANGE_END_TOLERANCE_MS || '120000',
+ 10,
+ );
+ const windowMs = Number.isFinite(toleranceMs)
+ ? Math.max(10_000, toleranceMs)
+ : 120_000;
+ return endMs >= Date.now() - windowMs;
+ }
+
+ /**
+ * Get summary statistics for a specific backend
+ */
+ getSummary(backendId: number, timeRange: TimeRange): SummaryResponse {
+ const includeRealtime = this.shouldIncludeRealtime(timeRange);
+
+ const backend = this.db.getBackend(backendId);
+ if (!backend) {
+ throw new Error('Backend not found');
+ }
+
+ const summary = this.db.getSummary(backendId, timeRange.start, timeRange.end);
+ const summaryWithRealtime = includeRealtime
+ ? this.realtimeStore.applySummaryDelta(backendId, summary)
+ : summary;
+
+ const dbTopDomains = this.db.getTopDomains(backendId, 10, timeRange.start, timeRange.end);
+ const topDomains = includeRealtime
+ ? this.realtimeStore.mergeTopDomains(backendId, dbTopDomains, 10)
+ : dbTopDomains;
+
+ const dbTopIPs = this.db.getTopIPs(backendId, 10, timeRange.start, timeRange.end);
+ const topIPs = includeRealtime
+ ? this.realtimeStore.mergeTopIPs(backendId, dbTopIPs, 10)
+ : dbTopIPs;
+
+ const dbProxyStats = this.db.getProxyStats(backendId, timeRange.start, timeRange.end);
+ const proxyStats = includeRealtime
+ ? this.realtimeStore.mergeProxyStats(backendId, dbProxyStats)
+ : dbProxyStats;
+
+ const dbRuleStats = this.db.getRuleStats(backendId, timeRange.start, timeRange.end);
+ const ruleStats = includeRealtime
+ ? this.realtimeStore.mergeRuleStats(backendId, dbRuleStats)
+ : dbRuleStats;
+
+ const hourlyStats = this.db.getHourlyStats(backendId, 24, timeRange.start, timeRange.end);
+ const todayTraffic = this.db.getTrafficInRange(backendId, timeRange.start, timeRange.end);
+ const todayDelta = includeRealtime
+ ? this.realtimeStore.getTodayDelta(backendId)
+ : { upload: 0, download: 0 };
+
+ return {
+ backend: {
+ id: backend.id,
+ name: backend.name,
+ isActive: backend.is_active,
+ listening: backend.listening,
+ },
+ totalConnections: summaryWithRealtime.totalConnections,
+ totalUpload: summaryWithRealtime.totalUpload,
+ totalDownload: summaryWithRealtime.totalDownload,
+ totalDomains: summary.uniqueDomains,
+ totalIPs: summary.uniqueIPs,
+ totalRules: ruleStats.length,
+ totalProxies: proxyStats.length,
+ todayUpload: todayTraffic.upload + todayDelta.upload,
+ todayDownload: todayTraffic.download + todayDelta.download,
+ topDomains,
+ topIPs,
+ proxyStats,
+ ruleStats,
+ hourlyStats,
+ };
+ }
+
+ /**
+ * Get global summary across all backends
+ */
+ getGlobalSummary(): GlobalSummary {
+ return this.db.getGlobalSummary();
+ }
+
+ /**
+ * Get domain statistics for a specific backend (paginated)
+ */
+ getDomainStatsPaginated(backendId: number, timeRange: TimeRange, options: PaginatedStatsOptions): PaginatedDomainStats {
+ const stats = this.db.getDomainStatsPaginated(backendId, {
+ offset: options.offset,
+ limit: options.limit,
+ sortBy: options.sortBy,
+ sortOrder: options.sortOrder,
+ search: options.search,
+ start: timeRange.start,
+ end: timeRange.end,
+ });
+
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeDomainStatsPaginated(backendId, stats, {
+ offset: options.offset,
+ limit: options.limit,
+ sortBy: options.sortBy,
+ sortOrder: options.sortOrder,
+ search: options.search,
+ });
+ }
+ return stats;
+ }
+
+ /**
+ * Get IP statistics for a specific backend (paginated)
+ */
+ getIPStatsPaginated(backendId: number, timeRange: TimeRange, options: PaginatedStatsOptions): PaginatedIPStats {
+ const stats = this.db.getIPStatsPaginated(backendId, {
+ offset: options.offset,
+ limit: options.limit,
+ sortBy: options.sortBy,
+ sortOrder: options.sortOrder,
+ search: options.search,
+ start: timeRange.start,
+ end: timeRange.end,
+ });
+
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeIPStatsPaginated(backendId, stats, {
+ offset: options.offset,
+ limit: options.limit,
+ sortBy: options.sortBy,
+ sortOrder: options.sortOrder,
+ search: options.search,
+ });
+ }
+ return stats;
+ }
+
+ /**
+ * Get per-proxy traffic breakdown for a specific domain
+ */
+ getDomainProxyStats(
+ backendId: number,
+ domain: string,
+ timeRange: TimeRange,
+ sourceIP?: string,
+ sourceChain?: string,
+ ): any[] {
+ return this.db.getDomainProxyStats(backendId, domain, timeRange.start, timeRange.end, sourceIP, sourceChain);
+ }
+
+ /**
+ * Get IP details for a specific domain
+ */
+ getDomainIPDetails(
+ backendId: number,
+ domain: string,
+ timeRange: TimeRange,
+ limit: number,
+ sourceIP?: string,
+ sourceChain?: string,
+ ): IPStats[] {
+ return this.db.getDomainIPDetails(backendId, domain, timeRange.start, timeRange.end, limit, sourceIP, sourceChain);
+ }
+
+ /**
+ * Get per-proxy traffic breakdown for a specific IP
+ */
+ getIPProxyStats(
+ backendId: number,
+ ip: string,
+ timeRange: TimeRange,
+ sourceIP?: string,
+ sourceChain?: string,
+ ): any[] {
+ return this.db.getIPProxyStats(backendId, ip, timeRange.start, timeRange.end, sourceIP, sourceChain);
+ }
+
+ /**
+ * Get domain details for a specific IP
+ */
+ getIPDomainDetails(
+ backendId: number,
+ ip: string,
+ timeRange: TimeRange,
+ limit: number,
+ sourceIP?: string,
+ sourceChain?: string,
+ ): DomainStats[] {
+ return this.db.getIPDomainDetails(backendId, ip, timeRange.start, timeRange.end, limit, sourceIP, sourceChain);
+ }
+
+ /**
+ * Get domains for a specific proxy/chain
+ */
+ getProxyDomains(backendId: number, chain: string, timeRange: TimeRange, limit: number): DomainStats[] {
+ const stats = this.db.getProxyDomains(backendId, chain, limit, timeRange.start, timeRange.end);
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeProxyDomains(backendId, chain, stats, limit);
+ }
+ return stats;
+ }
+
+ /**
+ * Get IPs for a specific proxy/chain
+ */
+ getProxyIPs(backendId: number, chain: string, timeRange: TimeRange, limit: number): IPStats[] {
+ const stats = this.db.getProxyIPs(backendId, chain, limit, timeRange.start, timeRange.end);
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeProxyIPs(backendId, chain, stats, limit);
+ }
+ return stats;
+ }
+
+ /**
+ * Get proxy/chain statistics for a specific backend
+ */
+ getProxyStats(backendId: number, timeRange: TimeRange): ProxyStats[] {
+ const stats = this.db.getProxyStats(backendId, timeRange.start, timeRange.end);
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeProxyStats(backendId, stats);
+ }
+ return stats;
+ }
+
+ /**
+ * Get rule statistics for a specific backend
+ */
+ getRuleStats(backendId: number, timeRange: TimeRange): RuleStats[] {
+ const stats = this.db.getRuleStats(backendId, timeRange.start, timeRange.end);
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeRuleStats(backendId, stats);
+ }
+ return stats;
+ }
+
+ /**
+ * Get domains for a specific rule
+ */
+ getRuleDomains(backendId: number, rule: string, timeRange: TimeRange, limit: number): DomainStats[] {
+ const stats = this.db.getRuleDomains(backendId, rule, limit, timeRange.start, timeRange.end);
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeRuleDomains(backendId, rule, stats, limit);
+ }
+ return stats;
+ }
+
+ /**
+ * Get IPs for a specific rule
+ */
+ getRuleIPs(backendId: number, rule: string, timeRange: TimeRange, limit: number): IPStats[] {
+ const stats = this.db.getRuleIPs(backendId, rule, limit, timeRange.start, timeRange.end);
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeRuleIPs(backendId, rule, stats, limit);
+ }
+ return stats;
+ }
+
+ /**
+ * Get per-proxy traffic breakdown for a specific domain under a specific rule
+ */
+ getRuleDomainProxyStats(backendId: number, rule: string, domain: string, timeRange: TimeRange): any[] {
+ return this.db.getRuleDomainProxyStats(backendId, rule, domain, timeRange.start, timeRange.end);
+ }
+
+ /**
+ * Get IP details for a specific domain under a specific rule
+ */
+ getRuleDomainIPDetails(backendId: number, rule: string, domain: string, timeRange: TimeRange, limit: number): IPStats[] {
+ return this.db.getRuleDomainIPDetails(backendId, rule, domain, timeRange.start, timeRange.end, limit);
+ }
+
+ /**
+ * Get per-proxy traffic breakdown for a specific IP under a specific rule
+ */
+ getRuleIPProxyStats(backendId: number, rule: string, ip: string, timeRange: TimeRange): any[] {
+ return this.db.getRuleIPProxyStats(backendId, rule, ip, timeRange.start, timeRange.end);
+ }
+
+ /**
+ * Get domain details for a specific IP under a specific rule
+ */
+ getRuleIPDomainDetails(backendId: number, rule: string, ip: string, timeRange: TimeRange, limit: number): DomainStats[] {
+ return this.db.getRuleIPDomainDetails(backendId, rule, ip, timeRange.start, timeRange.end, limit);
+ }
+
+ /**
+ * Get rule chain flow for a specific rule
+ */
+ getRuleChainFlow(backendId: number, rule: string, timeRange: TimeRange): any {
+ return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end);
+ }
+
+ /**
+ * Get all rule chain flows merged into unified DAG
+ */
+ getAllRuleChainFlows(backendId: number, timeRange: TimeRange): any {
+ return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end);
+ }
+
+ /**
+ * Get rule to proxy mapping for a specific backend
+ */
+ getRuleProxyMap(backendId: number): any {
+ return this.db.getRuleProxyMap(backendId);
+ }
+
+ /**
+ * Get country traffic statistics for a specific backend
+ */
+ getCountryStats(backendId: number, timeRange: TimeRange, limit: number): CountryStats[] {
+ const stats = this.db.getCountryStats(backendId, limit, timeRange.start, timeRange.end);
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeCountryStats(backendId, stats);
+ }
+ return stats;
+ }
+
+ /**
+ * Get device statistics for a specific backend
+ */
+ getDeviceStats(backendId: number, timeRange: TimeRange, limit: number): DeviceStats[] {
+ const stats = this.db.getDevices(backendId, limit, timeRange.start, timeRange.end);
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeDeviceStats(backendId, stats, limit);
+ }
+ return stats;
+ }
+
+ /**
+ * Get domains for a specific device
+ */
+ getDeviceDomains(backendId: number, sourceIP: string, timeRange: TimeRange, limit: number): DomainStats[] {
+ if (!sourceIP) return [];
+ const stats = this.db.getDeviceDomains(backendId, sourceIP, limit, timeRange.start, timeRange.end);
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeDeviceDomains(backendId, sourceIP, stats, limit);
+ }
+ return stats;
+ }
+
+ /**
+ * Get IPs for a specific device
+ */
+ getDeviceIPs(backendId: number, sourceIP: string, timeRange: TimeRange, limit: number): IPStats[] {
+ if (!sourceIP) return [];
+ const stats = this.db.getDeviceIPs(backendId, sourceIP, limit, timeRange.start, timeRange.end);
+ if (this.shouldIncludeRealtime(timeRange)) {
+ return this.realtimeStore.mergeDeviceIPs(backendId, sourceIP, stats, limit);
+ }
+ return stats;
+ }
+
+ /**
+ * Get hourly statistics for a specific backend
+ */
+ getHourlyStats(backendId: number, timeRange: TimeRange, hours: number): HourlyStats[] {
+ return this.db.getHourlyStats(backendId, hours, timeRange.start, timeRange.end);
+ }
+
+ /**
+ * Get traffic trend for a specific backend
+ */
+ getTrafficTrend(backendId: number, timeRange: TimeRange, minutes: number): TrafficTrendPoint[] {
+ const base = this.db.getTrafficTrend(backendId, minutes, timeRange.start, timeRange.end);
+ if (!this.shouldIncludeRealtime(timeRange)) {
+ return base;
+ }
+ return this.realtimeStore.mergeTrend(backendId, base, minutes, 1);
+ }
+
+ /**
+ * Get traffic trend aggregated by time buckets for chart display
+ */
+ getTrafficTrendAggregated(
+ backendId: number,
+ timeRange: TimeRange,
+ minutes: number,
+ bucketMinutes: number,
+ ): TrafficTrendPoint[] {
+ const base = this.db.getTrafficTrendAggregated(backendId, minutes, bucketMinutes, timeRange.start, timeRange.end);
+ if (!this.shouldIncludeRealtime(timeRange)) {
+ return base;
+ }
+ return this.realtimeStore.mergeTrend(backendId, base, minutes, bucketMinutes);
+ }
+
+ /**
+ * Get recent connections for a specific backend
+ */
+ getRecentConnections(backendId: number, limit: number): any[] {
+ return this.db.getRecentConnections(backendId, limit);
+ }
+}
diff --git a/apps/collector/src/modules/stats/stats.types.ts b/apps/collector/src/modules/stats/stats.types.ts
new file mode 100644
index 0000000..723a2cc
--- /dev/null
+++ b/apps/collector/src/modules/stats/stats.types.ts
@@ -0,0 +1,135 @@
+/**
+ * Stats module type definitions
+ */
+
+import type { DomainStats, IPStats, ProxyStats, RuleStats, HourlyStats, DeviceStats } from '@neko-master/shared';
+
+export interface TimeRangeQuery {
+ start?: string;
+ end?: string;
+}
+
+export interface BackendIdQuery {
+ backendId?: string;
+}
+
+export interface PaginationQuery {
+ offset?: string;
+ limit?: string;
+ sortBy?: string;
+ sortOrder?: string;
+ search?: string;
+}
+
+export interface DomainQuery extends TimeRangeQuery {
+ domain?: string;
+ sourceIP?: string;
+ sourceChain?: string;
+}
+
+export interface IPQuery extends TimeRangeQuery {
+ ip?: string;
+ sourceIP?: string;
+ sourceChain?: string;
+}
+
+export interface ChainQuery extends TimeRangeQuery {
+ chain?: string;
+ limit?: string;
+}
+
+export interface RuleQuery extends TimeRangeQuery {
+ rule?: string;
+ limit?: string;
+}
+
+export interface RuleDomainQuery extends TimeRangeQuery {
+ rule?: string;
+ domain?: string;
+ limit?: string;
+}
+
+export interface RuleIPQuery extends TimeRangeQuery {
+ rule?: string;
+ ip?: string;
+ limit?: string;
+}
+
+export interface DeviceQuery extends TimeRangeQuery {
+ sourceIP: string;
+ limit?: string;
+}
+
+export interface TrendQuery extends TimeRangeQuery {
+ minutes?: string;
+ bucketMinutes?: string;
+}
+
+export interface ConnectionsQuery {
+ limit?: string;
+}
+
+export interface SummaryResponse {
+ backend: {
+ id: number;
+ name: string;
+ isActive: boolean;
+ listening: boolean;
+ };
+ totalConnections: number;
+ totalUpload: number;
+ totalDownload: number;
+ totalDomains: number;
+ totalIPs: number;
+ totalRules: number;
+ totalProxies: number;
+ todayUpload: number;
+ todayDownload: number;
+ topDomains: DomainStats[];
+ topIPs: IPStats[];
+ proxyStats: ProxyStats[];
+ ruleStats: RuleStats[];
+ hourlyStats: HourlyStats[];
+}
+
+export interface GlobalSummary {
+ totalConnections: number;
+ totalUpload: number;
+ totalDownload: number;
+ uniqueDomains: number;
+ uniqueIPs: number;
+ backendCount: number;
+}
+
+export interface PaginatedDomainStats {
+ data: DomainStats[];
+ total: number;
+}
+
+export interface PaginatedIPStats {
+ data: IPStats[];
+ total: number;
+}
+
+export interface TrafficTrendPoint {
+ time: string;
+ upload: number;
+ download: number;
+}
+
+export interface TimeRange {
+ start?: string;
+ end?: string;
+ active: boolean;
+}
+
+export interface CountryStats {
+ country: string;
+ countryName: string;
+ continent: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+}
+
+export type { DomainStats, IPStats, ProxyStats, RuleStats, HourlyStats, DeviceStats };
diff --git a/apps/collector/src/modules/websocket/message.parser.ts b/apps/collector/src/modules/websocket/message.parser.ts
new file mode 100644
index 0000000..9b453b4
--- /dev/null
+++ b/apps/collector/src/modules/websocket/message.parser.ts
@@ -0,0 +1,300 @@
+
+import {
+ ClientRange,
+ ClientTrend,
+ ClientDeviceDetail,
+ ClientProxyDetail,
+ ClientRuleDetail,
+ ClientDomainsPage,
+ ClientIPsPage,
+} from './websocket.types.js';
+
+export class MessageParser {
+ parseRange(start?: string, end?: string): ClientRange | null {
+ if (start === undefined && end === undefined) {
+ return {};
+ }
+
+ if (!start || !end) {
+ return null;
+ }
+
+ const startDate = new Date(start);
+ const endDate = new Date(end);
+ if (Number.isNaN(startDate.getTime()) || Number.isNaN(endDate.getTime())) {
+ return null;
+ }
+ if (startDate > endDate) {
+ return null;
+ }
+
+ return {
+ start: startDate.toISOString(),
+ end: endDate.toISOString(),
+ };
+ }
+
+ parseMinPushIntervalMs(value: number, fallback: number): number {
+ if (!Number.isFinite(value)) return fallback;
+ // Keep range conservative to avoid client misuse.
+ return Math.max(0, Math.min(60_000, Math.floor(value)));
+ }
+
+ shouldIncludeRealtime(range: ClientRange): boolean {
+ if (!range.start && !range.end) {
+ return true;
+ }
+ if (!range.end) {
+ return false;
+ }
+
+ const endMs = new Date(range.end).getTime();
+ if (Number.isNaN(endMs)) {
+ return false;
+ }
+
+ const toleranceMs = parseInt(process.env.REALTIME_RANGE_END_TOLERANCE_MS || '120000', 10);
+ const windowMs = Number.isFinite(toleranceMs) ? Math.max(10_000, toleranceMs) : 120_000;
+ return endMs >= Date.now() - windowMs;
+ }
+
+ parsePositiveInt(value: number | undefined): number | null {
+ if (value === undefined) return null;
+ const parsed = Number.parseInt(String(value), 10);
+ if (!Number.isFinite(parsed) || parsed <= 0) return null;
+ return parsed;
+ }
+
+ parseNonNegativeInt(value: number | undefined): number | null {
+ if (value === undefined) return null;
+ const parsed = Number.parseInt(String(value), 10);
+ if (!Number.isFinite(parsed) || parsed < 0) return null;
+ return parsed;
+ }
+
+ resolveMinutesFromRange(range: ClientRange): number | null {
+ if (!range.start || !range.end) return null;
+ const startMs = new Date(range.start).getTime();
+ const endMs = new Date(range.end).getTime();
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs < startMs) {
+ return null;
+ }
+ return Math.max(1, Math.ceil((endMs - startMs) / 60000));
+ }
+
+ parseTrend(
+ includeTrend: boolean | undefined,
+ trendMinutes: number | undefined,
+ trendBucketMinutes: number | undefined,
+ range: ClientRange,
+ ): ClientTrend | undefined {
+ if (includeTrend === false) return null;
+ if (
+ includeTrend !== true &&
+ trendMinutes === undefined &&
+ trendBucketMinutes === undefined
+ ) {
+ return undefined;
+ }
+
+ const parsedMinutes = this.parsePositiveInt(trendMinutes);
+ const parsedBucket = this.parsePositiveInt(trendBucketMinutes);
+ if (trendMinutes !== undefined && parsedMinutes === null) return undefined;
+ if (trendBucketMinutes !== undefined && parsedBucket === null) return undefined;
+
+ const fallbackMinutes = this.resolveMinutesFromRange(range) ?? 30;
+ const minutes = Math.min(parsedMinutes ?? fallbackMinutes, 30 * 24 * 60);
+ const bucketMinutes = Math.min(parsedBucket ?? 1, 24 * 60);
+
+ return {
+ minutes,
+ bucketMinutes,
+ };
+ }
+
+ parseDeviceDetail(
+ includeDeviceDetails: boolean | undefined,
+ deviceSourceIP: string | undefined,
+ deviceDetailLimit: number | undefined,
+ ): ClientDeviceDetail | undefined {
+ if (includeDeviceDetails === false) return null;
+ if (
+ includeDeviceDetails !== true &&
+ deviceSourceIP === undefined &&
+ deviceDetailLimit === undefined
+ ) {
+ return undefined;
+ }
+
+ const sourceIP = (deviceSourceIP || '').trim();
+ if (!sourceIP) return undefined;
+
+ const parsedLimit = this.parsePositiveInt(deviceDetailLimit);
+ if (deviceDetailLimit !== undefined && parsedLimit === null) {
+ return undefined;
+ }
+
+ return {
+ sourceIP,
+ limit: Math.min(parsedLimit ?? 5000, 20000),
+ };
+ }
+
+ parseProxyDetail(
+ includeProxyDetails: boolean | undefined,
+ proxyChain: string | undefined,
+ proxyDetailLimit: number | undefined,
+ ): ClientProxyDetail | undefined {
+ if (includeProxyDetails === false) return null;
+ if (
+ includeProxyDetails !== true &&
+ proxyChain === undefined &&
+ proxyDetailLimit === undefined
+ ) {
+ return undefined;
+ }
+
+ const chain = (proxyChain || '').trim();
+ if (!chain) return undefined;
+
+ const parsedLimit = this.parsePositiveInt(proxyDetailLimit);
+ if (proxyDetailLimit !== undefined && parsedLimit === null) {
+ return undefined;
+ }
+
+ return {
+ chain,
+ limit: Math.min(parsedLimit ?? 5000, 20000),
+ };
+ }
+
+ parseRuleDetail(
+ includeRuleDetails: boolean | undefined,
+ ruleName: string | undefined,
+ ruleDetailLimit: number | undefined,
+ ): ClientRuleDetail | undefined {
+ if (includeRuleDetails === false) return null;
+ if (
+ includeRuleDetails !== true &&
+ ruleName === undefined &&
+ ruleDetailLimit === undefined
+ ) {
+ return undefined;
+ }
+
+ const rule = (ruleName || '').trim();
+ if (!rule) return undefined;
+
+ const parsedLimit = this.parsePositiveInt(ruleDetailLimit);
+ if (ruleDetailLimit !== undefined && parsedLimit === null) {
+ return undefined;
+ }
+
+ return {
+ rule,
+ limit: Math.min(parsedLimit ?? 5000, 20000),
+ };
+ }
+
+ normalizePageSortOrder(sortOrder?: string): 'asc' | 'desc' {
+ return sortOrder?.toLowerCase() === 'asc' ? 'asc' : 'desc';
+ }
+
+ normalizeDomainSortBy(sortBy?: string): string {
+ const value = (sortBy || '').trim();
+ switch (value) {
+ case 'domain':
+ case 'totalUpload':
+ case 'totalTraffic':
+ case 'totalConnections':
+ case 'lastSeen':
+ case 'totalDownload':
+ return value;
+ default:
+ return 'totalDownload';
+ }
+ }
+
+ normalizeIPSortBy(sortBy?: string): string {
+ const value = (sortBy || '').trim();
+ switch (value) {
+ case 'ip':
+ case 'totalUpload':
+ case 'totalTraffic':
+ case 'totalConnections':
+ case 'lastSeen':
+ case 'totalDownload':
+ return value;
+ default:
+ return 'totalDownload';
+ }
+ }
+
+ parseDomainsPage(
+ includeDomainsPage: boolean | undefined,
+ offset: number | undefined,
+ limit: number | undefined,
+ sortBy: string | undefined,
+ sortOrder: string | undefined,
+ search: string | undefined,
+ ): ClientDomainsPage | undefined {
+ if (includeDomainsPage === false) return null;
+ if (
+ includeDomainsPage !== true &&
+ offset === undefined &&
+ limit === undefined &&
+ sortBy === undefined &&
+ sortOrder === undefined &&
+ search === undefined
+ ) {
+ return undefined;
+ }
+
+ const parsedOffset = this.parseNonNegativeInt(offset);
+ const parsedLimit = this.parsePositiveInt(limit);
+ if (offset !== undefined && parsedOffset === null) return undefined;
+ if (limit !== undefined && parsedLimit === null) return undefined;
+
+ return {
+ offset: parsedOffset ?? 0,
+ limit: Math.min(parsedLimit ?? 50, 200),
+ sortBy: this.normalizeDomainSortBy(sortBy),
+ sortOrder: this.normalizePageSortOrder(sortOrder),
+ search: (search || '').trim() || undefined,
+ };
+ }
+
+ parseIPsPage(
+ includeIPsPage: boolean | undefined,
+ offset: number | undefined,
+ limit: number | undefined,
+ sortBy: string | undefined,
+ sortOrder: string | undefined,
+ search: string | undefined,
+ ): ClientIPsPage | undefined {
+ if (includeIPsPage === false) return null;
+ if (
+ includeIPsPage !== true &&
+ offset === undefined &&
+ limit === undefined &&
+ sortBy === undefined &&
+ sortOrder === undefined &&
+ search === undefined
+ ) {
+ return undefined;
+ }
+
+ const parsedOffset = this.parseNonNegativeInt(offset);
+ const parsedLimit = this.parsePositiveInt(limit);
+ if (offset !== undefined && parsedOffset === null) return undefined;
+ if (limit !== undefined && parsedLimit === null) return undefined;
+
+ return {
+ offset: parsedOffset ?? 0,
+ limit: Math.min(parsedLimit ?? 50, 200),
+ sortBy: this.normalizeIPSortBy(sortBy),
+ sortOrder: this.normalizePageSortOrder(sortOrder),
+ search: (search || '').trim() || undefined,
+ };
+ }
+}
diff --git a/apps/collector/src/modules/websocket/websocket.types.ts b/apps/collector/src/modules/websocket/websocket.types.ts
new file mode 100644
index 0000000..cf3fe2f
--- /dev/null
+++ b/apps/collector/src/modules/websocket/websocket.types.ts
@@ -0,0 +1,112 @@
+
+import { WebSocket } from 'ws';
+import { StatsSummary } from '@neko-master/shared';
+
+// --- Client Request / Message Types ---
+
+export interface WebSocketMessage {
+ type: 'stats' | 'ping' | 'pong' | 'subscribe';
+ backendId?: number;
+ start?: string;
+ end?: string;
+ minPushIntervalMs?: number;
+
+ // Trend
+ includeTrend?: boolean;
+ trendMinutes?: number;
+ trendBucketMinutes?: number;
+
+ // Device Detail (Source IP)
+ includeDeviceDetails?: boolean;
+ deviceSourceIP?: string;
+ deviceDetailLimit?: number;
+
+ // Proxy Detail
+ includeProxyDetails?: boolean;
+ proxyChain?: string;
+ proxyDetailLimit?: number;
+
+ // Rule Detail
+ includeRuleDetails?: boolean;
+ ruleName?: string;
+ ruleDetailLimit?: number;
+ includeRuleChainFlow?: boolean;
+
+ // Pagination: Domains
+ includeDomainsPage?: boolean;
+ domainsPageOffset?: number;
+ domainsPageLimit?: number;
+ domainsPageSortBy?: string;
+ domainsPageSortOrder?: string;
+ domainsPageSearch?: string;
+
+ // Pagination: IPs
+ includeIPsPage?: boolean;
+ ipsPageOffset?: number;
+ ipsPageLimit?: number;
+ ipsPageSortBy?: string;
+ ipsPageSortOrder?: string;
+ ipsPageSearch?: string;
+
+ // Response Data (server to client)
+ data?: StatsSummary;
+ timestamp?: string;
+}
+
+// --- Internal Client State Types ---
+
+export type ClientRange = {
+ start?: string;
+ end?: string;
+};
+
+export type ClientTrend = {
+ minutes: number;
+ bucketMinutes: number;
+} | null;
+
+export type ClientDeviceDetail = {
+ sourceIP: string;
+ limit: number;
+} | null;
+
+export type ClientProxyDetail = {
+ chain: string;
+ limit: number;
+} | null;
+
+export type ClientRuleDetail = {
+ rule: string;
+ limit: number;
+} | null;
+
+export type ClientDomainsPage = {
+ offset: number;
+ limit: number;
+ sortBy?: string;
+ sortOrder?: 'asc' | 'desc';
+ search?: string;
+} | null;
+
+export type ClientIPsPage = {
+ offset: number;
+ limit: number;
+ sortBy?: string;
+ sortOrder?: 'asc' | 'desc';
+ search?: string;
+} | null;
+
+export interface ClientInfo {
+ ws: WebSocket;
+ backendId: number | null; // null means use active backend
+ range: ClientRange;
+ minPushIntervalMs: number;
+ lastSentAt: number;
+ trend: ClientTrend;
+ deviceDetail: ClientDeviceDetail;
+ proxyDetail: ClientProxyDetail;
+ ruleDetail: ClientRuleDetail;
+ includeRuleChainFlow: boolean;
+ domainsPage: ClientDomainsPage;
+ ipsPage: ClientIPsPage;
+}
diff --git a/apps/collector/src/realtime.ts b/apps/collector/src/realtime.ts
index e6320da..2bd36e0 100644
--- a/apps/collector/src/realtime.ts
+++ b/apps/collector/src/realtime.ts
@@ -7,7 +7,7 @@ import type {
RuleStats,
StatsSummary,
TrafficTrendPoint,
-} from '@clashmaster/shared';
+} from '@neko-master/shared';
type SummaryDelta = {
upload: number;
diff --git a/apps/collector/src/websocket.ts b/apps/collector/src/websocket.ts
index c40dbb3..dff1c6c 100644
--- a/apps/collector/src/websocket.ts
+++ b/apps/collector/src/websocket.ts
@@ -1,5 +1,5 @@
import { WebSocketServer as WSServer, WebSocket } from 'ws';
-import type { StatsSummary } from '@clashmaster/shared';
+import type { StatsSummary } from '@neko-master/shared';
import type { StatsDatabase } from './db.js';
import { realtimeStore } from './realtime.js';
diff --git a/apps/web/app/[locale]/dashboard/components/content/index.tsx b/apps/web/app/[locale]/dashboard/components/content/index.tsx
new file mode 100644
index 0000000..3b47663
--- /dev/null
+++ b/apps/web/app/[locale]/dashboard/components/content/index.tsx
@@ -0,0 +1,392 @@
+"use client";
+
+import { useState, memo } from "react";
+import { useTranslations } from "next-intl";
+import {
+ keepPreviousData,
+ useQuery,
+} from "@tanstack/react-query";
+import { Activity, BarChart3, Link2 } from "lucide-react";
+import { StatsCards, TopDomainsChart } from "@/components/features/stats";
+import { OverviewTab } from "@/components/overview";
+import { InteractiveProxyStats } from "@/components/features/proxies";
+import { InteractiveDeviceStats } from "@/components/features/devices";
+import { InteractiveRuleStats } from "@/components/features/rules";
+import { WorldTrafficMap, CountryTrafficList } from "@/components/features/countries";
+import { DomainsTable, IPsTable } from "@/components/features/stats/table";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { InsightThreePanelSkeleton } from "@/components/ui/insight-skeleton";
+import { api, type TimeRange } from "@/lib/api";
+import { getDevicesQueryKey } from "@/lib/stats-query-keys";
+import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
+import { cn } from "@/lib/utils";
+import type { BackendStatus, TabId, TimePreset } from "@/lib/types/dashboard";
+import type {
+ StatsSummary,
+ CountryStats,
+ DeviceStats,
+ ProxyStats,
+} from "@neko-master/shared";
+import type { PageSize } from "@/lib/stats-utils";
+
+interface ContentProps {
+ activeTab: TabId;
+ data: StatsSummary | null;
+ countryData: CountryStats[];
+ error: string | null;
+ timeRange: TimeRange;
+ timePreset: TimePreset;
+ autoRefresh: boolean;
+ activeBackendId?: number;
+ backendStatus: BackendStatus;
+ onNavigate?: (tab: string) => void;
+}
+
+// Overview Content Component
+const OverviewContent = memo(function OverviewContent({
+ data,
+ countryData,
+ error,
+ timeRange,
+ timePreset,
+ autoRefresh,
+ activeBackendId,
+ onNavigate,
+ backendStatus,
+}: {
+ data: StatsSummary | null;
+ countryData: CountryStats[];
+ error: string | null;
+ timeRange: TimeRange;
+ timePreset: TimePreset;
+ autoRefresh: boolean;
+ activeBackendId?: number;
+ onNavigate?: (tab: string) => void;
+ backendStatus: BackendStatus;
+}) {
+ return (
+ <div className="space-y-6">
+ <StatsCards data={data} error={error} backendStatus={backendStatus} />
+ <OverviewTab
+ domains={data?.topDomains || []}
+ proxies={data?.proxyStats || []}
+ countries={countryData}
+ timeRange={timeRange}
+ timePreset={timePreset}
+ autoRefresh={autoRefresh}
+ activeBackendId={activeBackendId}
+ onNavigate={onNavigate}
+ backendStatus={backendStatus}
+ />
+ </div>
+ );
+});
+
+// Domains Content Component
+const DomainsContent = memo(function DomainsContent({
+ activeBackendId,
+ timeRange,
+ autoRefresh,
+}: {
+ activeBackendId?: number;
+ timeRange: TimeRange;
+ autoRefresh: boolean;
+}) {
+ const t = useTranslations("domains");
+ const [sharedPageSize, setSharedPageSize] = useState<PageSize>(10);
+
+ return (
+ <div className="space-y-6">
+ <TopDomainsChart
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ />
+ <Tabs defaultValue="domains" className="w-full">
+ <TabsList className="glass">
+ <TabsTrigger value="domains">{t("domainList")}</TabsTrigger>
+ <TabsTrigger value="ips">{t("ipList")}</TabsTrigger>
+ </TabsList>
+ <TabsContent value="domains" className="overflow-hidden">
+ <DomainsTable
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ autoRefresh={autoRefresh}
+ pageSize={sharedPageSize}
+ onPageSizeChange={setSharedPageSize}
+ />
+ </TabsContent>
+ <TabsContent value="ips" className="overflow-hidden">
+ <IPsTable
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ autoRefresh={autoRefresh}
+ pageSize={sharedPageSize}
+ onPageSizeChange={setSharedPageSize}
+ />
+ </TabsContent>
+ </Tabs>
+ </div>
+ );
+});
+
+// Countries Content Component
+const CountriesContent = memo(function CountriesContent({
+ countryData,
+}: {
+ countryData: CountryStats[];
+}) {
+ const t = useTranslations("countries");
+ const [sortBy, setSortBy] = useState<"traffic" | "connections">("traffic");
+
+ return (
+ <div className="space-y-6">
+ <WorldTrafficMap data={countryData} />
+ <Card>
+ <CardHeader className="pb-3">
+ <div className="flex items-center justify-between gap-3">
+ <CardTitle className="text-lg font-semibold">
+ {t("details")}
+ </CardTitle>
+ <div className="flex items-center gap-0.5 bg-muted/50 rounded-lg p-0.5">
+ <Button
+ variant="ghost"
+ size="icon"
+ className={cn(
+ "h-7 w-7 rounded-md transition-all",
+ sortBy === "traffic"
+ ? "bg-background shadow-sm text-primary"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ onClick={() => setSortBy("traffic")}
+ title={t("sortByTraffic")}
+ aria-label={t("sortByTraffic")}
+ >
+ <BarChart3 className="w-4 h-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className={cn(
+ "h-7 w-7 rounded-md transition-all",
+ sortBy === "connections"
+ ? "bg-background shadow-sm text-primary"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ onClick={() => setSortBy("connections")}
+ title={t("sortByConnections")}
+ aria-label={t("sortByConnections")}
+ >
+ <Link2 className="w-4 h-4" />
+ </Button>
+ </div>
+ </div>
+ </CardHeader>
+ <CardContent>
+ <CountryTrafficList data={countryData} sortBy={sortBy} />
+ </CardContent>
+ </Card>
+ </div>
+ );
+});
+
+// Proxies Content Component
+const ProxiesContent = memo(function ProxiesContent({
+ data,
+ activeBackendId,
+ timeRange,
+ backendStatus,
+ autoRefresh,
+}: {
+ data?: ProxyStats[];
+ activeBackendId?: number;
+ timeRange: TimeRange;
+ backendStatus: BackendStatus;
+ autoRefresh: boolean;
+}) {
+ return (
+ <div className="space-y-6">
+ <InteractiveProxyStats
+ data={data}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
+ />
+ </div>
+ );
+});
+
+// Rules Content Component
+const RulesContent = memo(function RulesContent({
+ activeBackendId,
+ timeRange,
+ backendStatus,
+ autoRefresh,
+}: {
+ activeBackendId?: number;
+ timeRange: TimeRange;
+ backendStatus: BackendStatus;
+ autoRefresh: boolean;
+}) {
+ return (
+ <div className="space-y-6">
+ <InteractiveRuleStats
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
+ />
+ </div>
+ );
+});
+
+// Devices Content Component
+const DevicesContent = memo(function DevicesContent({
+ data,
+ activeBackendId,
+ timeRange,
+ backendStatus,
+ autoRefresh,
+}: {
+ data?: DeviceStats[];
+ activeBackendId?: number;
+ timeRange: TimeRange;
+ backendStatus: BackendStatus;
+ autoRefresh: boolean;
+}) {
+ const stableTimeRange = useStableTimeRange(timeRange);
+
+ const devicesQuery = useQuery({
+ queryKey: getDevicesQueryKey(activeBackendId, 50, stableTimeRange),
+ queryFn: () => api.getDevices(activeBackendId, 50, stableTimeRange),
+ enabled: !data && !!activeBackendId,
+ placeholderData: keepPreviousData,
+ });
+
+ const deviceStats: DeviceStats[] = data ?? devicesQuery.data ?? [];
+ const loading = !data && devicesQuery.isLoading && !devicesQuery.data;
+
+ if (loading) {
+ return (
+ <Card>
+ <CardContent className="p-5 sm:p-6">
+ <InsightThreePanelSkeleton />
+ </CardContent>
+ </Card>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <InteractiveDeviceStats
+ data={deviceStats}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
+ />
+ </div>
+ );
+});
+
+// Network Content Component
+const NetworkContent = memo(function NetworkContent() {
+ const t = useTranslations("network");
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const _typeCheck: TabId = "overview"; // Ensure TabId type is imported
+ return (
+ <div className="space-y-6">
+ <div className="p-12 text-center text-muted-foreground border rounded-xl">
+ <Activity className="w-12 h-12 mx-auto mb-4 opacity-50" />
+ <p>{t("comingSoon")}</p>
+ </div>
+ </div>
+ );
+});
+
+export function Content({
+ activeTab,
+ data,
+ countryData,
+ error,
+ timeRange,
+ timePreset,
+ autoRefresh,
+ activeBackendId,
+ backendStatus,
+ onNavigate,
+}: ContentProps) {
+ switch (activeTab) {
+ case "overview":
+ return (
+ <OverviewContent
+ data={data}
+ countryData={countryData}
+ error={error}
+ timeRange={timeRange}
+ timePreset={timePreset}
+ autoRefresh={autoRefresh}
+ activeBackendId={activeBackendId}
+ onNavigate={onNavigate}
+ backendStatus={backendStatus}
+ />
+ );
+ case "domains":
+ return (
+ <DomainsContent
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ autoRefresh={autoRefresh}
+ />
+ );
+ case "countries":
+ return <CountriesContent countryData={countryData} />;
+ case "proxies":
+ return (
+ <ProxiesContent
+ data={data?.proxyStats}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
+ />
+ );
+ case "rules":
+ return (
+ <RulesContent
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
+ />
+ );
+ case "devices":
+ return (
+ <DevicesContent
+ data={data?.deviceStats}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ backendStatus={backendStatus}
+ autoRefresh={autoRefresh}
+ />
+ );
+ case "network":
+ return <NetworkContent />;
+ default:
+ return (
+ <OverviewContent
+ data={data}
+ countryData={countryData}
+ error={error}
+ timeRange={timeRange}
+ timePreset={timePreset}
+ autoRefresh={autoRefresh}
+ activeBackendId={activeBackendId}
+ onNavigate={onNavigate}
+ backendStatus={backendStatus}
+ />
+ );
+ }
+}
diff --git a/apps/web/app/[locale]/dashboard/components/header/index.tsx b/apps/web/app/[locale]/dashboard/components/header/index.tsx
new file mode 100644
index 0000000..7c8d1e4
--- /dev/null
+++ b/apps/web/app/[locale]/dashboard/components/header/index.tsx
@@ -0,0 +1,460 @@
+"use client";
+
+import {
+ Server,
+ Radio,
+ RefreshCw,
+ ChevronDown,
+ AlertTriangle,
+ Settings,
+ Globe,
+ Moon,
+ Sun,
+ Monitor,
+ MoreVertical,
+ Info,
+} from "lucide-react";
+import Image from "next/image";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Switch } from "@/components/ui/switch";
+import { TimeRangePicker, LanguageSwitcher, ThemeToggle } from "@/components/common";
+import { cn } from "@/lib/utils";
+import type { TimeRange } from "@/lib/api";
+import type { BackendStatus, TimePreset } from "@/lib/types/dashboard";
+
+interface Backend {
+ id: number;
+ name: string;
+ is_active: boolean;
+ listening: boolean;
+}
+
+interface HeaderProps {
+ // Backend data
+ backends: Backend[];
+ activeBackend: Backend | null;
+ listeningBackends: Backend[];
+ backendStatus: BackendStatus;
+ backendStatusHint: string | null;
+
+ // Time range
+ timeRange: TimeRange;
+ onTimeRangeChange: (range: TimeRange, preset: TimePreset) => void;
+
+ // Auto refresh
+ autoRefresh: boolean;
+ autoRefreshTick: number;
+ onAutoRefreshToggle: () => void;
+
+ // Actions
+ onSwitchBackend: (backendId: number) => void;
+ onOpenBackendDialog: () => void;
+ onRefresh: () => void;
+ onOpenAboutDialog: () => void;
+
+ // Theme
+ theme: string | undefined;
+ onThemeChange: (theme: string) => void;
+
+ // Locale/Router
+ locale: string;
+ pathname: string;
+ onNavigate: (path: string) => void;
+
+ // Loading states
+ isLoading: boolean;
+
+ // Translations
+ backendT: (key: string) => string;
+ dashboardT: (key: string) => string;
+}
+
+export function Header({
+ backends,
+ activeBackend,
+ listeningBackends,
+ backendStatus,
+ backendStatusHint,
+ timeRange,
+ onTimeRangeChange,
+ autoRefresh,
+ autoRefreshTick,
+ onAutoRefreshToggle,
+ onSwitchBackend,
+ onOpenBackendDialog,
+ onRefresh,
+ onOpenAboutDialog,
+ theme,
+ onThemeChange,
+ locale,
+ pathname,
+ onNavigate,
+ isLoading,
+ backendT,
+ dashboardT,
+}: HeaderProps) {
+ return (
+ <header className="sticky top-0 z-40 border-b border-border/40 bg-background/80 backdrop-blur-md">
+ <div className="flex items-center justify-between h-14 px-4 lg:px-6">
+ <div className="flex items-center gap-3">
+ {/* Mobile: Logo */}
+ <div className="flex items-center gap-2">
+ <div className="lg:hidden w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center overflow-hidden">
+ <Image
+ src="/logo.png"
+ alt="Neko Master"
+ width={32}
+ height={32}
+ className="w-full h-full object-cover"
+ />
+ </div>
+ </div>
+
+ {/* Backend Selector */}
+ {backends.length > 0 && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="gap-1 px-2 sm:px-3"
+ >
+ <Server className="w-4 h-4" />
+ <span className="max-w-[80px] sm:max-w-[120px] truncate">
+ {activeBackend?.name || backendT("selectBackend")}
+ </span>
+ <ChevronDown className="w-3 h-3" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-56">
+ <DropdownMenuLabel>{backendT("backendsTab")}</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ {backends.map((backend) => (
+ <DropdownMenuItem
+ key={backend.id}
+ onClick={() => onSwitchBackend(backend.id)}
+ className="flex items-center justify-between"
+ >
+ <span
+ className={cn(
+ "truncate",
+ backend.is_active && "font-medium"
+ )}
+ >
+ {backend.name}
+ </span>
+ <div className="flex items-center gap-1">
+ {!!backend.is_active && (
+ <Badge
+ variant="default"
+ className="text-[10px] h-5"
+ >
+ {backendT("displaying")}
+ </Badge>
+ )}
+ {!!backend.listening && !backend.is_active && (
+ <Badge
+ variant="secondary"
+ className="text-[10px] h-5 gap-1"
+ >
+ <Radio className="w-2 h-2" />
+ {backendT("collecting")}
+ </Badge>
+ )}
+ </div>
+ </DropdownMenuItem>
+ ))}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={onOpenBackendDialog}>
+ <Settings className="w-4 h-4 mr-2" />
+ {backendT("manageBackends")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+
+ {/* Listening Indicators */}
+ {listeningBackends.length > 0 && (
+ <div className="hidden md:flex items-center gap-1">
+ {listeningBackends.slice(0, 3).map((backend) => (
+ <Badge
+ key={backend.id}
+ variant="outline"
+ className="text-[10px] h-5 gap-1 px-1.5 border-green-500/30 text-green-600"
+ >
+ <Radio className="w-2 h-2" />
+ {backend.name}
+ </Badge>
+ ))}
+ {listeningBackends.length > 3 && (
+ <Badge variant="outline" className="text-[10px] h-5 px-1.5">
+ +{listeningBackends.length - 3}
+ </Badge>
+ )}
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center gap-1 sm:gap-2">
+ {/* Desktop: Compact auto-refresh toggle */}
+ <div className="hidden sm:flex items-center mr-1">
+ <TooltipProvider delayDuration={200}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={onAutoRefreshToggle}
+ aria-label={
+ autoRefresh
+ ? dashboardT("autoRefresh")
+ : dashboardT("paused")
+ }
+ className={cn(
+ "h-9 w-9 rounded-full transition-colors",
+ autoRefresh
+ ? "text-emerald-600 hover:bg-emerald-500/10"
+ : "text-muted-foreground hover:bg-muted"
+ )}
+ >
+ <RefreshCw
+ className={cn(
+ "w-4 h-4",
+ autoRefresh && "text-emerald-500"
+ )}
+ style={
+ autoRefresh
+ ? {
+ transform: `rotate(${autoRefreshTick * 360}deg)`,
+ transition: "transform 650ms linear",
+ }
+ : undefined
+ }
+ />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ <p className="font-medium">
+ {autoRefresh
+ ? dashboardT("autoRefresh")
+ : dashboardT("paused")}
+ </p>
+ <p className="opacity-80">
+ {autoRefresh
+ ? dashboardT("clickToPause")
+ : dashboardT("clickToResume")}
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+
+ {/* Desktop: Language & Theme */}
+ <div className="hidden sm:flex items-center gap-1">
+ <TimeRangePicker
+ value={timeRange}
+ onChange={onTimeRangeChange}
+ />
+ <LanguageSwitcher />
+ <ThemeToggle />
+ </div>
+
+ {/* Mobile: Time range picker */}
+ <div className="sm:hidden">
+ <TimeRangePicker
+ value={timeRange}
+ onChange={onTimeRangeChange}
+ className="w-[122px]"
+ />
+ </div>
+
+ {/* Mobile: Backend warning in top actions */}
+ {backendStatus === "unhealthy" && (
+ <div className="sm:hidden">
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ size="icon"
+ variant="ghost"
+ aria-label={dashboardT("backendUnavailable")}
+ className="relative h-9 w-9 text-rose-500 hover:bg-rose-500/10 hover:text-rose-500"
+ >
+ <span className="absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full bg-rose-500 animate-ping [animation-duration:900ms]" />
+ <AlertTriangle className="h-4 w-4" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="end"
+ side="bottom"
+ className="w-[240px] p-3"
+ >
+ <div className="flex items-start gap-2">
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-rose-500" />
+ <div className="min-w-0">
+ <p className="text-sm font-medium text-rose-600 dark:text-rose-400">
+ {dashboardT("backendUnavailable")}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {backendStatusHint ||
+ dashboardT("backendUnavailableHint")}
+ </p>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ </div>
+ )}
+
+ {/* Mobile: More Options Dropdown */}
+ <div className="sm:hidden">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon" className="h-9 w-9">
+ <MoreVertical className="w-5 h-5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-56">
+ {/* Auto Refresh Toggle */}
+ <DropdownMenuLabel className="flex items-center gap-2">
+ <RefreshCw className="w-4 h-4" />
+ {dashboardT("refresh")}
+ </DropdownMenuLabel>
+ <DropdownMenuItem
+ onSelect={(event) => {
+ event.preventDefault();
+ onAutoRefreshToggle();
+ }}
+ >
+ <div className="flex items-center justify-between w-full">
+ <span>
+ {autoRefresh
+ ? dashboardT("autoRefresh")
+ : dashboardT("paused")}
+ </span>
+ <Switch
+ checked={autoRefresh}
+ onCheckedChange={onAutoRefreshToggle}
+ onClick={(event) => event.stopPropagation()}
+ className="data-[state=checked]:bg-emerald-500 ml-2"
+ />
+ </div>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+
+ {/* Theme Selection */}
+ <DropdownMenuLabel className="flex items-center gap-2">
+ {theme === "dark" ? (
+ <Moon className="w-4 h-4" />
+ ) : (
+ <Sun className="w-4 h-4" />
+ )}
+ Theme
+ </DropdownMenuLabel>
+ <DropdownMenuItem
+ onClick={() => onThemeChange("light")}
+ className={theme === "light" ? "bg-muted" : ""}
+ >
+ <Sun className="w-4 h-4 mr-2 text-amber-500" />
+ Light {theme === "light" && "✓"}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => onThemeChange("dark")}
+ className={theme === "dark" ? "bg-muted" : ""}
+ >
+ <Moon className="w-4 h-4 mr-2 text-indigo-500" />
+ Dark {theme === "dark" && "✓"}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => onThemeChange("system")}
+ className={theme === "system" ? "bg-muted" : ""}
+ >
+ <Monitor className="w-4 h-4 mr-2 text-slate-500" />
+ System {theme === "system" && "✓"}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+
+ {/* Language Selection */}
+ <DropdownMenuLabel className="flex items-center gap-2">
+ <Globe className="w-4 h-4" />
+ Language
+ </DropdownMenuLabel>
+ <DropdownMenuItem
+ onClick={() => {
+ const newPathname = pathname.replace(
+ `/${locale}`,
+ "/en"
+ );
+ onNavigate(newPathname);
+ }}
+ className={locale === "en" ? "bg-muted" : ""}
+ >
+ English {locale === "en" && "✓"}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => {
+ const newPathname = pathname.replace(
+ `/${locale}`,
+ "/zh"
+ );
+ onNavigate(newPathname);
+ }}
+ className={locale === "zh" ? "bg-muted" : ""}
+ >
+ 中文 {locale === "zh" && "✓"}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+
+ {/* Settings */}
+ <DropdownMenuItem onClick={onOpenBackendDialog}>
+ <Settings className="w-4 h-4 mr-2" />
+ {backendT("manageBackends")}
+ </DropdownMenuItem>
+
+ {/* About */}
+ <DropdownMenuItem onClick={onOpenAboutDialog}>
+ <Info className="w-4 h-4 mr-2 text-primary" />
+ About
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ {/* Refresh Button - show when auto refresh is off or backend is unhealthy */}
+ {(!autoRefresh || backendStatus === "unhealthy") && (
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={onRefresh}
+ disabled={isLoading}
+ className="h-9 w-9"
+ >
+ <RefreshCw
+ className={cn("w-4 h-4", isLoading && "animate-spin")}
+ />
+ </Button>
+ )}
+ </div>
+ </div>
+ </header>
+ );
+}
diff --git a/apps/web/app/[locale]/dashboard/components/sidebar/index.tsx b/apps/web/app/[locale]/dashboard/components/sidebar/index.tsx
new file mode 100644
index 0000000..d8bb4e2
--- /dev/null
+++ b/apps/web/app/[locale]/dashboard/components/sidebar/index.tsx
@@ -0,0 +1,27 @@
+"use client";
+
+import { Navigation } from "@/components/layout";
+import type { BackendStatus } from "@/lib/types/dashboard";
+
+interface SidebarProps {
+ activeTab: string;
+ onTabChange: (tab: string) => void;
+ onBackendChange: () => Promise<void>;
+ backendStatus: BackendStatus;
+}
+
+export function Sidebar({
+ activeTab,
+ onTabChange,
+ onBackendChange,
+ backendStatus,
+}: SidebarProps) {
+ return (
+ <Navigation
+ activeTab={activeTab}
+ onTabChange={onTabChange}
+ onBackendChange={onBackendChange}
+ backendStatus={backendStatus}
+ />
+ );
+}
diff --git a/apps/web/app/[locale]/dashboard/hooks/use-dashboard.ts b/apps/web/app/[locale]/dashboard/hooks/use-dashboard.ts
new file mode 100644
index 0000000..2234023
--- /dev/null
+++ b/apps/web/app/[locale]/dashboard/hooks/use-dashboard.ts
@@ -0,0 +1,381 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useTranslations } from "next-intl";
+import { useTheme } from "next-themes";
+import {
+ keepPreviousData,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
+import { usePathname, useRouter } from "next/navigation";
+import { api, getPresetTimeRange, type TimeRange } from "@/lib/api";
+import type {
+ BackendStatus,
+ TabId,
+ TimePreset,
+} from "@/lib/types/dashboard";
+import {
+ getCountriesQueryKey,
+ getDevicesQueryKey,
+ getSummaryQueryKey,
+} from "@/lib/stats-query-keys";
+import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
+import { useStatsWebSocket } from "@/lib/websocket";
+import type {
+ StatsSummary,
+ CountryStats,
+} from "@neko-master/shared";
+
+export type { BackendStatus, TabId, TimePreset };
+
+type RollingTimePreset = Exclude<TimePreset, "custom">;
+
+const SUMMARY_WS_MIN_PUSH_MS = 3000;
+
+function isRollingTimePreset(preset: TimePreset): preset is RollingTimePreset {
+ return preset !== "custom";
+}
+
+export interface UseDashboardReturn {
+ // State
+ activeTab: TabId;
+ timeRange: TimeRange;
+ timePreset: TimePreset;
+ autoRefresh: boolean;
+ isManualRefreshing: boolean;
+ showBackendDialog: boolean;
+ showAboutDialog: boolean;
+ isFirstTime: boolean;
+ autoRefreshTick: number;
+
+ // Data
+ data: StatsSummary | null;
+ countryData: CountryStats[];
+ backends: Awaited<ReturnType<typeof api.getBackends>>;
+ activeBackend: Awaited<ReturnType<typeof api.getBackends>>[0] | null;
+ listeningBackends: Awaited<ReturnType<typeof api.getBackends>>;
+ activeBackendId: number | undefined;
+ backendStatus: BackendStatus;
+ backendStatusHint: string | null;
+ queryError: string | null;
+ wsConnected: boolean;
+ wsRealtimeActive: boolean;
+
+ // Actions
+ setActiveTab: (tab: TabId) => void;
+ setAutoRefresh: (value: boolean | ((prev: boolean) => boolean)) => void;
+ setShowBackendDialog: (value: boolean) => void;
+ setShowAboutDialog: (value: boolean) => void;
+ handleTimeRangeChange: (range: TimeRange, preset: TimePreset) => void;
+ handleSwitchBackend: (backendId: number) => Promise<void>;
+ handleBackendChange: () => Promise<void>;
+ refreshNow: (showLoading?: boolean) => Promise<void>;
+
+ // Theme
+ theme: string | undefined;
+ setTheme: (theme: string) => void;
+
+ // Locale/Router
+ locale: string;
+ router: ReturnType<typeof useRouter>;
+ pathname: string;
+
+ // Translations
+ t: ReturnType<typeof useTranslations>;
+ dashboardT: ReturnType<typeof useTranslations>;
+ backendT: ReturnType<typeof useTranslations>;
+}
+
+export function useDashboard(): UseDashboardReturn {
+ const t = useTranslations("nav");
+ const dashboardT = useTranslations("dashboard");
+ const backendT = useTranslations("backend");
+ const router = useRouter();
+ const pathname = usePathname();
+ const { theme, setTheme } = useTheme();
+ const queryClient = useQueryClient();
+
+ // Get locale from pathname (e.g., /en/dashboard -> en)
+ const locale = useMemo(() => {
+ const match = pathname.match(/^\/([^/]+)/);
+ return match ? match[1] : "en";
+ }, [pathname]);
+
+ // UI State
+ const [activeTab, setActiveTab] = useState<TabId>("overview");
+ const [timeRange, setTimeRange] = useState<TimeRange>(getPresetTimeRange("24h"));
+ const [timePreset, setTimePreset] = useState<TimePreset>("24h");
+ const [isManualRefreshing, setIsManualRefreshing] = useState(false);
+ const [autoRefresh, setAutoRefresh] = useState(true);
+ const [autoRefreshTick, setAutoRefreshTick] = useState(0);
+ const [showBackendDialog, setShowBackendDialog] = useState(false);
+ const [isFirstTime, setIsFirstTime] = useState(false);
+ const [showAboutDialog, setShowAboutDialog] = useState(false);
+
+ const stableTimeRange = useStableTimeRange(timeRange);
+ const isWsSummaryTab = activeTab === "overview" || activeTab === "countries";
+
+ // Backends Query
+ const backendsQuery = useQuery({
+ queryKey: ["backends"],
+ queryFn: () => api.getBackends(),
+ refetchInterval: autoRefresh ? 5000 : false,
+ refetchIntervalInBackground: true,
+ });
+
+ const backends = backendsQuery.data ?? [];
+ const activeBackend = useMemo(
+ () => backends.find((backend) => backend.is_active) || backends[0] || null,
+ [backends]
+ );
+ const listeningBackends = useMemo(
+ () => backends.filter((backend) => backend.listening),
+ [backends]
+ );
+ const activeBackendId = activeBackend?.id;
+
+ // WebSocket
+ const wsEnabled = autoRefresh && isWsSummaryTab && !!activeBackendId;
+ const { status: wsStatus, lastMessage: wsSummary } = useStatsWebSocket({
+ backendId: activeBackendId,
+ range: stableTimeRange,
+ minPushIntervalMs: SUMMARY_WS_MIN_PUSH_MS,
+ enabled: wsEnabled,
+ onMessage: useCallback(
+ (stats: StatsSummary) => {
+ if (!activeBackendId) return;
+ setAutoRefreshTick((tick) => tick + 1);
+ queryClient.setQueryData(
+ getSummaryQueryKey(activeBackendId, stableTimeRange),
+ (previous) => ({
+ ...(typeof previous === "object" && previous ? previous : {}),
+ ...stats,
+ })
+ );
+ if (stats.countryStats) {
+ queryClient.setQueryData(
+ getCountriesQueryKey(activeBackendId, 50, stableTimeRange),
+ stats.countryStats
+ );
+ }
+ if (stats.deviceStats) {
+ queryClient.setQueryData(
+ getDevicesQueryKey(activeBackendId, 50, stableTimeRange),
+ stats.deviceStats
+ );
+ }
+ },
+ [activeBackendId, queryClient, stableTimeRange]
+ ),
+ });
+
+ const wsConnected = wsStatus === "connected";
+ const wsRealtimeActive = wsEnabled && wsConnected;
+ const shouldReducePolling = wsRealtimeActive;
+ const hasWsCountries =
+ wsRealtimeActive &&
+ !!wsSummary?.countryStats &&
+ (activeTab === "overview" || activeTab === "countries");
+
+ const needsCountries = activeTab === "overview" || activeTab === "countries";
+
+ // Stats Queries
+ const summaryQuery = useQuery({
+ queryKey: getSummaryQueryKey(activeBackendId, stableTimeRange),
+ queryFn: () => api.getSummary(activeBackendId, stableTimeRange),
+ enabled: !!activeBackendId && !(wsEnabled && wsConnected),
+ placeholderData: keepPreviousData,
+ });
+
+ const countriesQuery = useQuery({
+ queryKey: getCountriesQueryKey(activeBackendId, 50, stableTimeRange),
+ queryFn: () => api.getCountries(activeBackendId, 50, stableTimeRange),
+ enabled: !!activeBackendId && needsCountries && !hasWsCountries,
+ placeholderData: keepPreviousData,
+ });
+
+ const data: StatsSummary | null =
+ (wsEnabled && wsConnected && wsSummary) || summaryQuery.data || null;
+ const countryData: CountryStats[] =
+ (hasWsCountries ? wsSummary?.countryStats : countriesQuery.data) ?? [];
+
+ // Errors
+ const summaryError = useMemo(() => {
+ if (!summaryQuery.error) return null;
+ return summaryQuery.error instanceof Error
+ ? summaryQuery.error.message
+ : "Unknown error";
+ }, [summaryQuery.error]);
+ const effectiveSummaryError = wsEnabled && wsConnected ? null : summaryError;
+
+ const countriesError = useMemo(() => {
+ if (!countriesQuery.error) return null;
+ return countriesQuery.error instanceof Error
+ ? countriesQuery.error.message
+ : "Unknown error";
+ }, [countriesQuery.error]);
+ const effectiveCountriesError = hasWsCountries ? null : countriesError;
+
+ const queryError = effectiveSummaryError ?? effectiveCountriesError;
+
+ // Backend Status
+ const backendStatus: BackendStatus = useMemo(() => {
+ if (!activeBackend) return "unknown";
+ if (effectiveSummaryError) return "unhealthy";
+ if (activeBackend.listening) return "healthy";
+ return "unhealthy";
+ }, [activeBackend, effectiveSummaryError]);
+
+ const backendStatusHint = useMemo(() => {
+ if (effectiveSummaryError) return effectiveSummaryError;
+ if (activeBackend && !activeBackend.listening)
+ return dashboardT("backendUnavailableHint");
+ return null;
+ }, [effectiveSummaryError, activeBackend, dashboardT]);
+
+ // Actions
+ const refreshNow = useCallback(
+ async (showLoading = false) => {
+ if (showLoading) {
+ setIsManualRefreshing(true);
+ }
+ try {
+ if (isRollingTimePreset(timePreset)) {
+ setTimeRange(getPresetTimeRange(timePreset));
+ }
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: ["stats"] }),
+ queryClient.invalidateQueries({ queryKey: ["backends"] }),
+ ]);
+ } finally {
+ if (showLoading) {
+ setIsManualRefreshing(false);
+ }
+ }
+ },
+ [queryClient, timePreset]
+ );
+
+ const handleTimeRangeChange = useCallback(
+ (range: TimeRange, preset: TimePreset) => {
+ setTimePreset(preset);
+ setTimeRange(range);
+ },
+ []
+ );
+
+ const handleSwitchBackend = useCallback(
+ async (backendId: number) => {
+ try {
+ await api.setActiveBackend(backendId);
+ await backendsQuery.refetch();
+ await refreshNow(true);
+ } catch (err) {
+ console.error("Failed to switch backend:", err);
+ }
+ },
+ [backendsQuery.refetch, refreshNow]
+ );
+
+ const handleBackendChange = useCallback(async () => {
+ await backendsQuery.refetch();
+ await refreshNow(true);
+ }, [backendsQuery.refetch, refreshNow]);
+
+ // Effects
+
+ // Open setup dialog automatically when no backend is configured
+ useEffect(() => {
+ if (backendsQuery.isError) return;
+ if (backendsQuery.isLoading || backendsQuery.isFetching) return;
+ if (backends.length === 0) {
+ setIsFirstTime(true);
+ setShowBackendDialog(true);
+ return;
+ }
+ if (isFirstTime) {
+ setIsFirstTime(false);
+ }
+ }, [
+ backends.length,
+ backendsQuery.isError,
+ backendsQuery.isFetching,
+ backendsQuery.isLoading,
+ isFirstTime,
+ ]);
+
+ // Rolling presets: keep the time window moving
+ useEffect(() => {
+ if (!autoRefresh || !isRollingTimePreset(timePreset)) return;
+ const intervalMs =
+ activeTab === "rules" ? 30000 : shouldReducePolling ? 30000 : 5000;
+ const interval = setInterval(() => {
+ setAutoRefreshTick((tick) => tick + 1);
+ setTimeRange(getPresetTimeRange(timePreset));
+ }, intervalMs);
+ return () => clearInterval(interval);
+ }, [activeTab, autoRefresh, shouldReducePolling, timePreset]);
+
+ // Fixed presets: keep HTTP polling only when WS realtime is not active
+ useEffect(() => {
+ if (!autoRefresh || isRollingTimePreset(timePreset) || wsRealtimeActive)
+ return;
+ const intervalMs = 5000;
+ const interval = setInterval(() => {
+ setAutoRefreshTick((tick) => tick + 1);
+ queryClient.invalidateQueries({ queryKey: ["stats"] });
+ }, intervalMs);
+ return () => clearInterval(interval);
+ }, [autoRefresh, queryClient, wsRealtimeActive, timePreset]);
+
+ return {
+ // State
+ activeTab,
+ timeRange,
+ timePreset,
+ autoRefresh,
+ isManualRefreshing,
+ showBackendDialog,
+ showAboutDialog,
+ isFirstTime,
+ autoRefreshTick,
+
+ // Data
+ data,
+ countryData,
+ backends,
+ activeBackend,
+ listeningBackends,
+ activeBackendId,
+ backendStatus,
+ backendStatusHint,
+ queryError,
+ wsConnected,
+ wsRealtimeActive,
+
+ // Actions
+ setActiveTab,
+ setAutoRefresh,
+ setShowBackendDialog,
+ setShowAboutDialog,
+ handleTimeRangeChange,
+ handleSwitchBackend,
+ handleBackendChange,
+ refreshNow,
+
+ // Theme
+ theme,
+ setTheme,
+
+ // Locale/Router
+ locale,
+ router,
+ pathname,
+
+ // Translations
+ t,
+ dashboardT,
+ backendT,
+ };
+}
diff --git a/apps/web/app/[locale]/dashboard/layout.tsx b/apps/web/app/[locale]/dashboard/layout.tsx
new file mode 100644
index 0000000..a7f4b62
--- /dev/null
+++ b/apps/web/app/[locale]/dashboard/layout.tsx
@@ -0,0 +1,9 @@
+import { ReactNode } from "react";
+
+export default function DashboardLayout({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ return children;
+}
diff --git a/apps/web/app/[locale]/dashboard/page.tsx b/apps/web/app/[locale]/dashboard/page.tsx
new file mode 100644
index 0000000..bfd00fc
--- /dev/null
+++ b/apps/web/app/[locale]/dashboard/page.tsx
@@ -0,0 +1,125 @@
+"use client";
+
+import { BackendConfigDialog } from "@/components/features/backend";
+import { AboutDialog } from "@/components/common";
+import { useDashboard, type TabId } from "./hooks/use-dashboard";
+import { Header } from "./components/header";
+import { Sidebar } from "./components/sidebar";
+import { Content } from "./components/content";
+
+export default function DashboardPage() {
+ const {
+ // State
+ activeTab,
+ timeRange,
+ timePreset,
+ autoRefresh,
+ isManualRefreshing,
+ showBackendDialog,
+ showAboutDialog,
+ isFirstTime,
+ autoRefreshTick,
+
+ // Data
+ data,
+ countryData,
+ backends,
+ activeBackend,
+ listeningBackends,
+ activeBackendId,
+ backendStatus,
+ backendStatusHint,
+ queryError,
+
+ // Actions
+ setActiveTab,
+ setAutoRefresh,
+ setShowBackendDialog,
+ setShowAboutDialog,
+ handleTimeRangeChange,
+ handleSwitchBackend,
+ handleBackendChange,
+ refreshNow,
+
+ // Theme
+ theme,
+ setTheme,
+
+ // Locale/Router
+ locale,
+ router,
+ pathname,
+
+ // Translations
+ backendT,
+ dashboardT,
+ } = useDashboard();
+
+ return (
+ <div className="flex min-h-screen bg-background">
+ <Sidebar
+ activeTab={activeTab}
+ onTabChange={(tab) => setActiveTab(tab as TabId)}
+ onBackendChange={handleBackendChange}
+ backendStatus={backendStatus}
+ />
+
+ <main className="flex-1 min-w-0 lg:ml-0">
+ <Header
+ backends={backends}
+ activeBackend={activeBackend}
+ listeningBackends={listeningBackends}
+ backendStatus={backendStatus}
+ backendStatusHint={backendStatusHint}
+ timeRange={timeRange}
+ onTimeRangeChange={handleTimeRangeChange}
+ autoRefresh={autoRefresh}
+ autoRefreshTick={autoRefreshTick}
+ onAutoRefreshToggle={() => setAutoRefresh((prev) => !prev)}
+ onSwitchBackend={handleSwitchBackend}
+ onOpenBackendDialog={() => setShowBackendDialog(true)}
+ onRefresh={() => refreshNow(true)}
+ onOpenAboutDialog={() => setShowAboutDialog(true)}
+ theme={theme}
+ onThemeChange={setTheme}
+ locale={locale}
+ pathname={pathname}
+ onNavigate={(path) => router.push(path)}
+ isLoading={isManualRefreshing}
+ backendT={backendT}
+ dashboardT={dashboardT}
+ />
+
+ <div className="p-4 lg:p-6 pb-24 lg:pb-6 max-w-7xl mx-auto">
+ <Content
+ activeTab={activeTab}
+ data={data}
+ countryData={countryData}
+ error={queryError}
+ timeRange={timeRange}
+ timePreset={timePreset}
+ autoRefresh={autoRefresh}
+ activeBackendId={activeBackendId}
+ backendStatus={backendStatus}
+ onNavigate={(tab) => setActiveTab(tab as TabId)}
+ />
+ </div>
+ </main>
+
+ {/* Backend Configuration Dialog */}
+ <BackendConfigDialog
+ open={showBackendDialog}
+ onOpenChange={setShowBackendDialog}
+ isFirstTime={isFirstTime}
+ onConfigComplete={() => {
+ setShowBackendDialog(false);
+ handleBackendChange();
+ }}
+ onBackendChange={handleBackendChange}
+ />
+
+ {/* About Dialog */}
+ <AboutDialog open={showAboutDialog} onOpenChange={setShowAboutDialog} />
+ </div>
+ );
+}
diff --git a/apps/web/app/[locale]/layout.tsx b/apps/web/app/[locale]/layout.tsx
index ef78ef5..4fc0ccd 100644
--- a/apps/web/app/[locale]/layout.tsx
+++ b/apps/web/app/[locale]/layout.tsx
@@ -7,7 +7,7 @@ import { NextIntlClientProvider } from "next-intl";
import { getMessages } from "next-intl/server";
import { notFound } from "next/navigation";
import { routing } from "@/i18n/routing";
-import { ServiceWorkerRegister } from "@/components/sw-register";
+import { ServiceWorkerRegister } from "@/components/common";
import { Toaster } from "@/components/ui/sonner";
const geistSans = Geist({
@@ -21,19 +21,19 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
- title: "Clash Master",
- description: "Modern and beautiful network traffic analysis dashboard",
+ title: "Neko Master",
+ description: "Modern Network Traffic Analytics",
icons: {
- icon: "/clash-master.png",
- shortcut: "/clash-master.png",
+ icon: "/logo.png",
+ shortcut: "/logo.png",
apple: "/icons/icon-192x192.png",
},
appleWebApp: {
capable: true,
statusBarStyle: "black-translucent",
- title: "Clash Master",
+ title: "Neko Master",
},
- applicationName: "Clash Master",
+ applicationName: "Neko Master",
};
export const viewport: Viewport = {
@@ -71,7 +71,7 @@ export default async function RootLayout({
name="apple-mobile-web-app-status-bar-style"
content="black-translucent"
/>
- <meta name="apple-mobile-web-app-title" content="Clash Master" />
+ <meta name="apple-mobile-web-app-title" content="Neko Master" />
<script src="/runtime-config.js" />
</head>
<body
diff --git a/apps/web/app/[locale]/page.tsx b/apps/web/app/[locale]/page.tsx
index ee337ed..e635937 100644
--- a/apps/web/app/[locale]/page.tsx
+++ b/apps/web/app/[locale]/page.tsx
@@ -1,1043 +1,3 @@
-"use client";
+import DashboardPage from "./dashboard/page";
-import { useEffect, useState, useCallback, memo, useMemo } from "react";
-import { useTranslations, useLocale } from "next-intl";
-import { useTheme } from "next-themes";
-import {
- keepPreviousData,
- useQuery,
- useQueryClient,
-} from "@tanstack/react-query";
-import {
- Globe,
- MapPin,
- Server,
- Route,
- Activity,
- BarChart3,
- Link2,
- RefreshCw,
- Radio,
- ChevronDown,
- Settings,
- AlertTriangle,
- Moon,
- Sun,
- Monitor,
- Info,
- MoreVertical,
-} from "lucide-react";
-import { useRouter, usePathname } from "next/navigation";
-import Image from "next/image";
-import { Navigation } from "@/components/navigation";
-import { StatsCards } from "@/components/stats-cards";
-import { OverviewTab } from "@/components/overview";
-import { TopDomainsChart } from "@/components/top-domains-chart";
-import { ProxyStatsChart } from "@/components/proxy-stats-chart";
-import { InteractiveProxyStats } from "@/components/interactive-proxy-stats";
-import { InteractiveDeviceStats } from "@/components/interactive-device-stats";
-import { InteractiveRuleStats } from "@/components/interactive-rule-stats";
-import { RuleChainChart } from "@/components/rule-chain-chart";
-import { WorldTrafficMap } from "@/components/world-traffic-map";
-import { CountryTrafficList } from "@/components/country-traffic-list";
-import { DomainsTable } from "@/components/domains-table";
-import { IPsTable } from "@/components/ips-table";
-import { BackendConfigDialog } from "@/components/backend-config-dialog";
-import { AboutDialog } from "@/components/about-dialog";
-import { ThemeToggle } from "@/components/theme-toggle";
-import { LanguageSwitcher } from "@/components/language-switcher";
-import { TimeRangePicker } from "@/components/time-range-picker";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { Badge } from "@/components/ui/badge";
-import { InsightThreePanelSkeleton } from "@/components/ui/insight-skeleton";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { Switch } from "@/components/ui/switch";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover";
-import { api, getPresetTimeRange, type TimeRange } from "@/lib/api";
-import {
- getCountriesQueryKey,
- getDevicesQueryKey,
- getSummaryQueryKey,
-} from "@/lib/stats-query-keys";
-import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
-import { useStatsWebSocket } from "@/lib/websocket";
-import { cn } from "@/lib/utils";
-import type {
- StatsSummary,
- CountryStats,
- DeviceStats,
- ProxyStats,
-} from "@clashmaster/shared";
-
-function formatTimeAgo(date: Date, t: any): string {
- const now = new Date();
- const diff = now.getTime() - date.getTime();
- const seconds = Math.floor(diff / 1000);
- if (seconds < 5) return t("justNow");
- if (seconds < 60) return t("secondsAgo", { seconds });
- const minutes = Math.floor(seconds / 60);
- if (minutes < 60) return t("minutesAgo", { minutes });
- const hours = Math.floor(minutes / 60);
- if (hours < 24) return t("hoursAgo", { hours });
- return t("daysAgo", { days: Math.floor(hours / 24) });
-}
-
-const NAV_ITEMS = [
- { id: "overview", label: "overview" },
- { id: "domains", label: "domains" },
- { id: "countries", label: "countries" },
- { id: "devices", label: "devices" },
- { id: "proxies", label: "proxies" },
- { id: "rules", label: "rules" },
-];
-
-type TimePreset =
- | "1m"
- | "5m"
- | "15m"
- | "30m"
- | "24h"
- | "7d"
- | "30d"
- | "today"
- | "custom";
-type RollingTimePreset = Exclude<TimePreset, "custom">;
-type BackendStatus = "healthy" | "unhealthy" | "unknown";
-const SUMMARY_WS_MIN_PUSH_MS = 3000;
-
-function isRollingTimePreset(preset: TimePreset): preset is RollingTimePreset {
- return preset !== "custom";
-}
-
-// Memoized tab content components to prevent unnecessary re-renders
-const OverviewContent = memo(function OverviewContent({
- data,
- countryData,
- error,
- timeRange,
- timePreset,
- autoRefresh,
- activeBackendId,
- onNavigate,
- backendStatus,
-}: {
- data: StatsSummary | null;
- countryData: CountryStats[];
- error: string | null;
- timeRange: TimeRange;
- timePreset: TimePreset;
- autoRefresh: boolean;
- activeBackendId?: number;
- onNavigate?: (tab: string) => void;
- backendStatus: BackendStatus;
-}) {
- return (
- <div className="space-y-6">
- <StatsCards data={data} error={error} backendStatus={backendStatus} />
- <OverviewTab
- domains={data?.topDomains || []}
- proxies={data?.proxyStats || []}
- countries={countryData}
- timeRange={timeRange}
- timePreset={timePreset}
- autoRefresh={autoRefresh}
- activeBackendId={activeBackendId}
- onNavigate={onNavigate}
- backendStatus={backendStatus}
- />
- </div>
- );
-});
-
-const DomainsContent = memo(function DomainsContent({
- activeBackendId,
- timeRange,
- autoRefresh,
-}: {
- activeBackendId?: number;
- timeRange: TimeRange;
- autoRefresh: boolean;
-}) {
- const t = useTranslations("domains");
- const [sharedPageSize, setSharedPageSize] = useState<10 | 20 | 50 | 100>(10);
- return (
- <div className="space-y-6">
- <TopDomainsChart
- activeBackendId={activeBackendId}
- timeRange={timeRange}
- />
- <Tabs defaultValue="domains" className="w-full">
- <TabsList className="glass">
- <TabsTrigger value="domains">{t("domainList")}</TabsTrigger>
- <TabsTrigger value="ips">{t("ipList")}</TabsTrigger>
- </TabsList>
- <TabsContent value="domains" className="overflow-hidden">
- <DomainsTable
- activeBackendId={activeBackendId}
- timeRange={timeRange}
- autoRefresh={autoRefresh}
- pageSize={sharedPageSize}
- onPageSizeChange={setSharedPageSize}
- />
- </TabsContent>
- <TabsContent value="ips" className="overflow-hidden">
- <IPsTable
- activeBackendId={activeBackendId}
- timeRange={timeRange}
- autoRefresh={autoRefresh}
- pageSize={sharedPageSize}
- onPageSizeChange={setSharedPageSize}
- />
- </TabsContent>
- </Tabs>
- </div>
- );
-});
-
-const CountriesContent = memo(function CountriesContent({
- countryData,
-}: {
- countryData: CountryStats[];
-}) {
- const t = useTranslations("countries");
- const [sortBy, setSortBy] = useState<"traffic" | "connections">("traffic");
- return (
- <div className="space-y-6">
- <WorldTrafficMap data={countryData} />
- <Card>
- <CardHeader className="pb-3">
- <div className="flex items-center justify-between gap-3">
- <CardTitle className="text-lg font-semibold">
- {t("details")}
- </CardTitle>
- <div className="flex items-center gap-0.5 bg-muted/50 rounded-lg p-0.5">
- <Button
- variant="ghost"
- size="icon"
- className={cn(
- "h-7 w-7 rounded-md transition-all",
- sortBy === "traffic"
- ? "bg-background shadow-sm text-primary"
- : "text-muted-foreground hover:text-foreground",
- )}
- onClick={() => setSortBy("traffic")}
- title={t("sortByTraffic")}
- aria-label={t("sortByTraffic")}>
- <BarChart3 className="w-4 h-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className={cn(
- "h-7 w-7 rounded-md transition-all",
- sortBy === "connections"
- ? "bg-background shadow-sm text-primary"
- : "text-muted-foreground hover:text-foreground",
- )}
- onClick={() => setSortBy("connections")}
- title={t("sortByConnections")}
- aria-label={t("sortByConnections")}>
- <Link2 className="w-4 h-4" />
- </Button>
- </div>
- </div>
- </CardHeader>
- <CardContent>
- <CountryTrafficList data={countryData} sortBy={sortBy} />
- </CardContent>
- </Card>
- </div>
- );
-});
-
-const ProxiesContent = memo(function ProxiesContent({
- data,
- activeBackendId,
- timeRange,
- backendStatus,
- autoRefresh,
-}: {
- data?: ProxyStats[];
- activeBackendId?: number;
- timeRange: TimeRange;
- backendStatus: BackendStatus;
- autoRefresh: boolean;
-}) {
- return (
- <div className="space-y-6">
- <InteractiveProxyStats
- data={data}
- activeBackendId={activeBackendId}
- timeRange={timeRange}
- backendStatus={backendStatus}
- autoRefresh={autoRefresh}
- />
- </div>
- );
-});
-
-const RulesContent = memo(function RulesContent({
- activeBackendId,
- timeRange,
- backendStatus,
- autoRefresh,
-}: {
- activeBackendId?: number;
- timeRange: TimeRange;
- backendStatus: BackendStatus;
- autoRefresh: boolean;
-}) {
- return (
- <div className="space-y-6">
- <InteractiveRuleStats
- activeBackendId={activeBackendId}
- timeRange={timeRange}
- backendStatus={backendStatus}
- autoRefresh={autoRefresh}
- />
- </div>
- );
-});
-
-const DevicesContent = memo(function DevicesContent({
- data,
- activeBackendId,
- timeRange,
- backendStatus,
- autoRefresh,
-}: {
- data?: DeviceStats[];
- activeBackendId?: number;
- timeRange: TimeRange;
- backendStatus: BackendStatus;
- autoRefresh: boolean;
-}) {
- const stableTimeRange = useStableTimeRange(timeRange);
-
- const devicesQuery = useQuery({
- queryKey: getDevicesQueryKey(activeBackendId, 50, stableTimeRange),
- queryFn: () => api.getDevices(activeBackendId, 50, stableTimeRange),
- enabled: !data && !!activeBackendId,
- placeholderData: keepPreviousData,
- });
-
- const deviceStats: DeviceStats[] = data ?? devicesQuery.data ?? [];
- const loading = !data && devicesQuery.isLoading && !devicesQuery.data;
-
- if (loading) {
- return (
- <Card>
- <CardContent className="p-5 sm:p-6">
- <InsightThreePanelSkeleton />
- </CardContent>
- </Card>
- );
- }
-
- return (
- <div className="space-y-6">
- <InteractiveDeviceStats
- data={deviceStats}
- activeBackendId={activeBackendId}
- timeRange={timeRange}
- backendStatus={backendStatus}
- autoRefresh={autoRefresh}
- />
- </div>
- );
-});
-
-const NetworkContent = memo(function NetworkContent() {
- const t = useTranslations("network");
- return (
- <div className="space-y-6">
- <div className="p-12 text-center text-muted-foreground border rounded-xl">
- <Activity className="w-12 h-12 mx-auto mb-4 opacity-50" />
- <p>{t("comingSoon")}</p>
- </div>
- </div>
- );
-});
-
-export default function DashboardPage() {
- const t = useTranslations("nav");
- const dashboardT = useTranslations("dashboard");
- const backendT = useTranslations("backend");
- const router = useRouter();
- const pathname = usePathname();
- const locale = useLocale();
- const { theme, setTheme } = useTheme();
- const queryClient = useQueryClient();
- const [activeTab, setActiveTab] = useState("overview");
- const [timeRange, setTimeRange] = useState<TimeRange>(
- getPresetTimeRange("24h"),
- );
- const [timePreset, setTimePreset] = useState<TimePreset>("24h");
- const [isManualRefreshing, setIsManualRefreshing] = useState(false);
- const [autoRefresh, setAutoRefresh] = useState(true);
- const [autoRefreshTick, setAutoRefreshTick] = useState(0);
- const [showBackendDialog, setShowBackendDialog] = useState(false);
- const [isFirstTime, setIsFirstTime] = useState(false);
- const [showAboutDialog, setShowAboutDialog] = useState(false);
-
- const stableTimeRange = useStableTimeRange(timeRange);
- const isWsSummaryTab = activeTab === "overview" || activeTab === "countries";
-
- const backendsQuery = useQuery({
- queryKey: ["backends"],
- queryFn: () => api.getBackends(),
- refetchInterval: autoRefresh ? 5000 : false,
- refetchIntervalInBackground: true,
- });
-
- const backends = backendsQuery.data ?? [];
- const activeBackend = useMemo(
- () => backends.find((backend) => backend.is_active) || backends[0] || null,
- [backends],
- );
- const listeningBackends = useMemo(
- () => backends.filter((backend) => backend.listening),
- [backends],
- );
- const activeBackendId = activeBackend?.id;
-
- // Use WebSocket for summary-driven tabs; keep detail-heavy tabs on HTTP.
- const wsEnabled = autoRefresh && isWsSummaryTab && !!activeBackendId;
- const { status: wsStatus, lastMessage: wsSummary } = useStatsWebSocket({
- backendId: activeBackendId,
- range: stableTimeRange,
- minPushIntervalMs: SUMMARY_WS_MIN_PUSH_MS,
- enabled: wsEnabled,
- onMessage: useCallback(
- (stats: StatsSummary) => {
- if (!activeBackendId) return;
- setAutoRefreshTick((tick) => tick + 1);
- queryClient.setQueryData(
- getSummaryQueryKey(activeBackendId, stableTimeRange),
- (previous) => ({
- ...(typeof previous === "object" && previous ? previous : {}),
- ...stats,
- }),
- );
- if (stats.countryStats) {
- queryClient.setQueryData(
- getCountriesQueryKey(activeBackendId, 50, stableTimeRange),
- stats.countryStats,
- );
- }
- if (stats.deviceStats) {
- queryClient.setQueryData(
- getDevicesQueryKey(activeBackendId, 50, stableTimeRange),
- stats.deviceStats,
- );
- }
- },
- [activeBackendId, queryClient, stableTimeRange],
- ),
- });
- const wsConnected = wsStatus === "connected";
- const wsRealtimeActive = wsEnabled && wsConnected;
- const shouldReducePolling = wsRealtimeActive;
- const hasWsCountries =
- wsRealtimeActive &&
- !!wsSummary?.countryStats &&
- (activeTab === "overview" || activeTab === "countries");
-
- const needsCountries = activeTab === "overview" || activeTab === "countries";
-
- const summaryQuery = useQuery({
- queryKey: getSummaryQueryKey(activeBackendId, stableTimeRange),
- queryFn: () => api.getSummary(activeBackendId, stableTimeRange),
- enabled: !!activeBackendId && !(wsEnabled && wsConnected),
- placeholderData: keepPreviousData,
- });
-
- const countriesQuery = useQuery({
- queryKey: getCountriesQueryKey(activeBackendId, 50, stableTimeRange),
- queryFn: () => api.getCountries(activeBackendId, 50, stableTimeRange),
- enabled: !!activeBackendId && needsCountries && !hasWsCountries,
- placeholderData: keepPreviousData,
- });
-
- const data: StatsSummary | null =
- (wsEnabled && wsConnected && wsSummary) || summaryQuery.data || null;
- const countryData: CountryStats[] =
- (hasWsCountries ? wsSummary?.countryStats : countriesQuery.data) ?? [];
- const isLoading = isManualRefreshing;
-
- const summaryError = useMemo(() => {
- if (!summaryQuery.error) return null;
- return summaryQuery.error instanceof Error
- ? summaryQuery.error.message
- : "Unknown error";
- }, [summaryQuery.error]);
- const effectiveSummaryError = wsEnabled && wsConnected ? null : summaryError;
-
- const countriesError = useMemo(() => {
- if (!countriesQuery.error) return null;
- return countriesQuery.error instanceof Error
- ? countriesQuery.error.message
- : "Unknown error";
- }, [countriesQuery.error]);
- const effectiveCountriesError = hasWsCountries ? null : countriesError;
-
- const queryError = effectiveSummaryError ?? effectiveCountriesError;
-
- const backendStatus: BackendStatus = useMemo(() => {
- if (!activeBackend) return "unknown";
- if (effectiveSummaryError) return "unhealthy";
- if (activeBackend.listening) return "healthy";
- return "unhealthy";
- }, [activeBackend, effectiveSummaryError]);
-
- const backendStatusHint = useMemo(() => {
- if (effectiveSummaryError) return effectiveSummaryError;
- if (activeBackend && !activeBackend.listening)
- return dashboardT("backendUnavailableHint");
- return null;
- }, [effectiveSummaryError, activeBackend, dashboardT]);
-
- const refreshNow = useCallback(
- async (showLoading = false) => {
- if (showLoading) {
- setIsManualRefreshing(true);
- }
- try {
- if (isRollingTimePreset(timePreset)) {
- setTimeRange(getPresetTimeRange(timePreset));
- }
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: ["stats"] }),
- queryClient.invalidateQueries({ queryKey: ["backends"] }),
- ]);
- } finally {
- if (showLoading) {
- setIsManualRefreshing(false);
- }
- }
- },
- [queryClient, timePreset],
- );
-
- const handleTimeRangeChange = useCallback(
- (range: TimeRange, preset: TimePreset) => {
- setTimePreset(preset);
- setTimeRange(range);
- },
- [],
- );
-
- // Switch active backend
- const handleSwitchBackend = async (backendId: number) => {
- try {
- await api.setActiveBackend(backendId);
- await backendsQuery.refetch();
- await refreshNow(true);
- } catch (err) {
- console.error("Failed to switch backend:", err);
- }
- };
-
- // Handle backend configuration changes
- const handleBackendChange = useCallback(async () => {
- await backendsQuery.refetch();
- await refreshNow(true);
- }, [backendsQuery.refetch, refreshNow]);
-
- // Open setup dialog automatically when no backend is configured.
- useEffect(() => {
- if (backendsQuery.isError) return;
- if (backendsQuery.isLoading || backendsQuery.isFetching) return;
- if (backends.length === 0) {
- setIsFirstTime(true);
- setShowBackendDialog(true);
- return;
- }
- if (isFirstTime) {
- setIsFirstTime(false);
- }
- }, [
- backends.length,
- backendsQuery.isError,
- backendsQuery.isFetching,
- backendsQuery.isLoading,
- isFirstTime,
- ]);
-
- // Rolling presets: keep the time window moving.
- // Only reduce to 30s on lightweight WS tabs (overview/countries).
- useEffect(() => {
- if (!autoRefresh || !isRollingTimePreset(timePreset)) return;
- const intervalMs =
- activeTab === "rules" ? 30000 : shouldReducePolling ? 30000 : 5000;
- const interval = setInterval(() => {
- setAutoRefreshTick((tick) => tick + 1);
- setTimeRange(getPresetTimeRange(timePreset));
- }, intervalMs);
- return () => clearInterval(interval);
- }, [activeTab, autoRefresh, shouldReducePolling, timePreset]);
-
- // Fixed presets: keep HTTP polling only when WS realtime is not active.
- useEffect(() => {
- if (!autoRefresh || isRollingTimePreset(timePreset) || wsRealtimeActive)
- return;
- const intervalMs = 5000;
- const interval = setInterval(() => {
- setAutoRefreshTick((tick) => tick + 1);
- queryClient.invalidateQueries({ queryKey: ["stats"] });
- }, intervalMs);
- return () => clearInterval(interval);
- }, [autoRefresh, queryClient, wsRealtimeActive, timePreset]);
-
- const renderContent = () => {
- switch (activeTab) {
- case "overview":
- return (
- <OverviewContent
- data={data}
- countryData={countryData}
- error={queryError}
- timeRange={timeRange}
- timePreset={timePreset}
- autoRefresh={autoRefresh}
- activeBackendId={activeBackendId}
- onNavigate={setActiveTab}
- backendStatus={backendStatus}
- />
- );
- case "domains":
- return (
- <DomainsContent
- activeBackendId={activeBackendId}
- timeRange={timeRange}
- autoRefresh={autoRefresh}
- />
- );
- case "countries":
- return <CountriesContent countryData={countryData} />;
- case "proxies":
- return (
- <ProxiesContent
- data={data?.proxyStats}
- activeBackendId={activeBackendId}
- timeRange={timeRange}
- backendStatus={backendStatus}
- autoRefresh={autoRefresh}
- />
- );
- case "rules":
- return (
- <RulesContent
- activeBackendId={activeBackendId}
- timeRange={timeRange}
- backendStatus={backendStatus}
- autoRefresh={autoRefresh}
- />
- );
- case "devices":
- return (
- <DevicesContent
- data={data?.deviceStats}
- activeBackendId={activeBackendId}
- timeRange={timeRange}
- backendStatus={backendStatus}
- autoRefresh={autoRefresh}
- />
- );
- case "network":
- return <NetworkContent />;
- default:
- return (
- <OverviewContent
- data={data}
- countryData={countryData}
- error={queryError}
- timeRange={timeRange}
- timePreset={timePreset}
- autoRefresh={autoRefresh}
- activeBackendId={activeBackendId}
- onNavigate={setActiveTab}
- backendStatus={backendStatus}
- />
- );
- }
- };
-
- return (
- <div className="flex min-h-screen bg-background">
- <Navigation
- activeTab={activeTab}
- onTabChange={setActiveTab}
- onBackendChange={handleBackendChange}
- backendStatus={backendStatus}
- />
-
- <main className="flex-1 min-w-0 lg:ml-0">
- <header className="sticky top-0 z-40 border-b border-border/40 bg-background/80 backdrop-blur-md">
- <div className="flex items-center justify-between h-14 px-4 lg:px-6">
- <div className="flex items-center gap-3">
- {/* Mobile: Logo */}
- <div className="flex items-center gap-2">
- <div className="lg:hidden w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center overflow-hidden">
- <Image
- src="/clash-master.png"
- alt="Clash Master"
- width={32}
- height={32}
- className="w-full h-full object-cover"
- />
- </div>
- </div>
-
- {/* Backend Selector */}
- {backends.length > 0 && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="sm"
- className="gap-1 px-2 sm:px-3">
- <Server className="w-4 h-4" />
- <span className="max-w-[80px] sm:max-w-[120px] truncate">
- {activeBackend?.name || backendT("selectBackend")}
- </span>
- <ChevronDown className="w-3 h-3" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="w-56">
- <DropdownMenuLabel>
- {backendT("backendsTab")}
- </DropdownMenuLabel>
- <DropdownMenuSeparator />
- {backends.map((backend) => (
- <DropdownMenuItem
- key={backend.id}
- onClick={() => handleSwitchBackend(backend.id)}
- className="flex items-center justify-between">
- <span
- className={cn(
- "truncate",
- backend.is_active && "font-medium",
- )}>
- {backend.name}
- </span>
- <div className="flex items-center gap-1">
- {!!backend.is_active && (
- <Badge
- variant="default"
- className="text-[10px] h-5">
- {backendT("displaying")}
- </Badge>
- )}
- {!!backend.listening && !backend.is_active && (
- <Badge
- variant="secondary"
- className="text-[10px] h-5 gap-1">
- <Radio className="w-2 h-2" />
- {backendT("collecting")}
- </Badge>
- )}
- </div>
- </DropdownMenuItem>
- ))}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={() => setShowBackendDialog(true)}>
- <Settings className="w-4 h-4 mr-2" />
- {backendT("manageBackends")}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
-
- {/* Listening Indicators */}
- {listeningBackends.length > 0 && (
- <div className="hidden md:flex items-center gap-1">
- {listeningBackends.slice(0, 3).map((backend) => (
- <Badge
- key={backend.id}
- variant="outline"
- className="text-[10px] h-5 gap-1 px-1.5 border-green-500/30 text-green-600">
- <Radio className="w-2 h-2" />
- {backend.name}
- </Badge>
- ))}
- {listeningBackends.length > 3 && (
- <Badge variant="outline" className="text-[10px] h-5 px-1.5">
- +{listeningBackends.length - 3}
- </Badge>
- )}
- </div>
- )}
- </div>
-
- <div className="flex items-center gap-1 sm:gap-2">
- {/* Desktop: Compact auto-refresh toggle */}
- <div className="hidden sm:flex items-center mr-1">
- <TooltipProvider delayDuration={200}>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => setAutoRefresh((prev) => !prev)}
- aria-label={
- autoRefresh
- ? dashboardT("autoRefresh")
- : dashboardT("paused")
- }
- className={cn(
- "h-9 w-9 rounded-full transition-colors",
- autoRefresh
- ? "text-emerald-600 hover:bg-emerald-500/10"
- : "text-muted-foreground hover:bg-muted",
- )}>
- <RefreshCw
- className={cn(
- "w-4 h-4",
- autoRefresh && "text-emerald-500",
- )}
- style={
- autoRefresh
- ? {
- transform: `rotate(${autoRefreshTick * 360}deg)`,
- transition: "transform 650ms linear",
- }
- : undefined
- }
- />
- </Button>
- </TooltipTrigger>
- <TooltipContent side="bottom">
- <p className="font-medium">
- {autoRefresh
- ? dashboardT("autoRefresh")
- : dashboardT("paused")}
- </p>
- <p className="opacity-80">
- {autoRefresh
- ? dashboardT("clickToPause")
- : dashboardT("clickToResume")}
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
-
- {/* Desktop: Language & Theme */}
- <div className="hidden sm:flex items-center gap-1">
- <TimeRangePicker
- value={timeRange}
- onChange={handleTimeRangeChange}
- />
- <LanguageSwitcher />
- <ThemeToggle />
- </div>
-
- {/* Mobile: Time range picker */}
- <div className="sm:hidden">
- <TimeRangePicker
- value={timeRange}
- onChange={handleTimeRangeChange}
- className="w-[122px]"
- />
- </div>
-
- {/* Mobile: Backend warning in top actions */}
- {backendStatus === "unhealthy" && (
- <div className="sm:hidden">
- <Popover>
- <PopoverTrigger asChild>
- <Button
- size="icon"
- variant="ghost"
- aria-label={dashboardT("backendUnavailable")}
- className="relative h-9 w-9 text-rose-500 hover:bg-rose-500/10 hover:text-rose-500">
- <span className="absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full bg-rose-500 animate-ping [animation-duration:900ms]" />
- <AlertTriangle className="h-4 w-4" />
- </Button>
- </PopoverTrigger>
- <PopoverContent
- align="end"
- side="bottom"
- className="w-[240px] p-3">
- <div className="flex items-start gap-2">
- <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-rose-500" />
- <div className="min-w-0">
- <p className="text-sm font-medium text-rose-600 dark:text-rose-400">
- {dashboardT("backendUnavailable")}
- </p>
- <p className="text-xs text-muted-foreground">
- {backendStatusHint ||
- dashboardT("backendUnavailableHint")}
- </p>
- </div>
- </div>
- </PopoverContent>
- </Popover>
- </div>
- )}
-
- {/* Mobile: More Options Dropdown */}
- <div className="sm:hidden">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="icon" className="h-9 w-9">
- <MoreVertical className="w-5 h-5" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-56">
- {/* Auto Refresh Toggle -->
- <DropdownMenuLabel className="flex items-center gap-2">
- <RefreshCw className="w-4 h-4" />
- {dashboardT("refresh")}
- </DropdownMenuLabel>
- <DropdownMenuItem
- onSelect={(event) => {
- event.preventDefault();
- setAutoRefresh((prev) => !prev);
- }}>
- <div className="flex items-center justify-between w-full">
- <span>{autoRefresh ? dashboardT("autoRefresh") : dashboardT("paused")}</span>
- <Switch
- checked={autoRefresh}
- onCheckedChange={setAutoRefresh}
- onClick={(event) => event.stopPropagation()}
- className="data-[state=checked]:bg-emerald-500 ml-2"
- />
- </div>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
-
- {/* Theme Selection */}
- <DropdownMenuLabel className="flex items-center gap-2">
- {theme === "dark" ? (
- <Moon className="w-4 h-4" />
- ) : (
- <Sun className="w-4 h-4" />
- )}
- Theme
- </DropdownMenuLabel>
- <DropdownMenuItem
- onClick={() => setTheme("light")}
- className={theme === "light" ? "bg-muted" : ""}>
- <Sun className="w-4 h-4 mr-2 text-amber-500" />
- Light {theme === "light" && "✓"}
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => setTheme("dark")}
- className={theme === "dark" ? "bg-muted" : ""}>
- <Moon className="w-4 h-4 mr-2 text-indigo-500" />
- Dark {theme === "dark" && "✓"}
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => setTheme("system")}
- className={theme === "system" ? "bg-muted" : ""}>
- <Monitor className="w-4 h-4 mr-2 text-slate-500" />
- System {theme === "system" && "✓"}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
-
- {/* Language Selection */}
- <DropdownMenuLabel className="flex items-center gap-2">
- <Globe className="w-4 h-4" />
- Language
- </DropdownMenuLabel>
- <DropdownMenuItem
- onClick={() => {
- const newPathname = pathname.replace(
- `/${locale}`,
- "/en",
- );
- router.push(newPathname);
- }}
- className={locale === "en" ? "bg-muted" : ""}>
- English {locale === "en" && "✓"}
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => {
- const newPathname = pathname.replace(
- `/${locale}`,
- "/zh",
- );
- router.push(newPathname);
- }}
- className={locale === "zh" ? "bg-muted" : ""}>
- 中文 {locale === "zh" && "✓"}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
-
- {/* Settings */}
- <DropdownMenuItem
- onClick={() => setShowBackendDialog(true)}>
- <Settings className="w-4 h-4 mr-2" />
- {backendT("manageBackends")}
- </DropdownMenuItem>
-
- {/* About */}
- <DropdownMenuItem onClick={() => setShowAboutDialog(true)}>
- <Info className="w-4 h-4 mr-2 text-primary" />
- About
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
-
- {/* Refresh Button - show when auto refresh is off or backend is unhealthy */}
- {(!autoRefresh || backendStatus === "unhealthy") && (
- <Button
- variant="outline"
- size="icon"
- onClick={() => refreshNow(true)}
- disabled={isLoading}
- className="h-9 w-9">
- <RefreshCw
- className={cn("w-4 h-4", isLoading && "animate-spin")}
- />
- </Button>
- )}
- </div>
- </div>
- </header>
-
- <div className="p-4 lg:p-6 pb-24 lg:pb-6 max-w-7xl mx-auto">
- {renderContent()}
- </div>
- </main>
-
- {/* Backend Configuration Dialog */}
- <BackendConfigDialog
- open={showBackendDialog}
- onOpenChange={setShowBackendDialog}
- isFirstTime={isFirstTime}
- onConfigComplete={() => {
- setIsFirstTime(false);
- handleBackendChange();
- }}
- onBackendChange={handleBackendChange}
- />
-
- {/* About Dialog */}
- <AboutDialog open={showAboutDialog} onOpenChange={setShowAboutDialog} />
- </div>
- );
-}
+export default DashboardPage;
diff --git a/apps/web/app/manifest.ts b/apps/web/app/manifest.ts
index 29b1ad0..a127d61 100644
--- a/apps/web/app/manifest.ts
+++ b/apps/web/app/manifest.ts
@@ -2,9 +2,9 @@ import type { MetadataRoute } from "next";
export default function manifest(): MetadataRoute.Manifest {
return {
- name: "Clash Master",
- short_name: "Clash Master",
- description: "Modern network traffic analysis dashboard",
+ name: "Neko Master",
+ short_name: "Neko Master",
+ description: "Modern Network Traffic Analytics",
start_url: "/",
scope: "/",
display: "standalone",
diff --git a/apps/web/components/about-dialog.tsx b/apps/web/components/common/about-dialog.tsx
similarity index 97%
rename from apps/web/components/about-dialog.tsx
rename to apps/web/components/common/about-dialog.tsx
index 940e354..d07fa32 100644
--- a/apps/web/components/about-dialog.tsx
+++ b/apps/web/components/common/about-dialog.tsx
@@ -13,7 +13,7 @@ interface AboutDialogProps {
}
const APP_VERSION = process.env.NEXT_PUBLIC_APP_VERSION || "0.0.0";
-const GITHUB_URL = "https://github.com/foru17/clash-master";
+const GITHUB_URL = "https://github.com/foru17/neko-master";
export function AboutDialog({ open, onOpenChange }: AboutDialogProps) {
const aboutT = useTranslations("about");
@@ -49,15 +49,15 @@ export function AboutDialog({ open, onOpenChange }: AboutDialogProps) {
<div className="flex items-center gap-4 mb-4">
<div className="w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center overflow-hidden shrink-0">
<Image
- src="/clash-master.png"
- alt="Clash Master"
+ src="/logo.png"
+ alt="Neko Master"
width={64}
height={64}
className="w-full h-full object-cover"
/>
</div>
<div>
- <h3 className="text-xl font-bold">Clash Master</h3>
+ <h3 className="text-xl font-bold">Neko Master</h3>
<p className="text-sm text-muted-foreground mt-1">
{aboutT("description")}
</p>
diff --git a/apps/web/components/favicon.tsx b/apps/web/components/common/favicon.tsx
similarity index 100%
rename from apps/web/components/favicon.tsx
rename to apps/web/components/common/favicon.tsx
diff --git a/apps/web/components/header.tsx b/apps/web/components/common/header.tsx
similarity index 100%
rename from apps/web/components/header.tsx
rename to apps/web/components/common/header.tsx
diff --git a/apps/web/components/common/index.ts b/apps/web/components/common/index.ts
new file mode 100644
index 0000000..48d4ec1
--- /dev/null
+++ b/apps/web/components/common/index.ts
@@ -0,0 +1,10 @@
+export { AboutDialog } from "./about-dialog";
+export { Favicon } from "./favicon";
+export { Header } from "./header";
+export { LanguageSwitcher } from "./language-switcher";
+export { PWARegister } from "./pwa-register";
+export { ServiceWorkerRegister } from "./sw-register";
+export { ThemeToggle } from "./theme-toggle";
+export { TimeRangePicker } from "./time-range-picker";
+export { TopListItem } from "./top-list-item";
+export { OverviewCard } from "./overview-card";
diff --git a/apps/web/components/language-switcher.tsx b/apps/web/components/common/language-switcher.tsx
similarity index 100%
rename from apps/web/components/language-switcher.tsx
rename to apps/web/components/common/language-switcher.tsx
diff --git a/apps/web/components/overview-card.tsx b/apps/web/components/common/overview-card.tsx
similarity index 100%
rename from apps/web/components/overview-card.tsx
rename to apps/web/components/common/overview-card.tsx
diff --git a/apps/web/components/pwa-register.tsx b/apps/web/components/common/pwa-register.tsx
similarity index 100%
rename from apps/web/components/pwa-register.tsx
rename to apps/web/components/common/pwa-register.tsx
diff --git a/apps/web/components/sw-register.tsx b/apps/web/components/common/sw-register.tsx
similarity index 100%
rename from apps/web/components/sw-register.tsx
rename to apps/web/components/common/sw-register.tsx
diff --git a/apps/web/components/theme-toggle.tsx b/apps/web/components/common/theme-toggle.tsx
similarity index 100%
rename from apps/web/components/theme-toggle.tsx
rename to apps/web/components/common/theme-toggle.tsx
diff --git a/apps/web/components/time-range-picker.tsx b/apps/web/components/common/time-range-picker.tsx
similarity index 100%
rename from apps/web/components/time-range-picker.tsx
rename to apps/web/components/common/time-range-picker.tsx
diff --git a/apps/web/components/top-list-item.tsx b/apps/web/components/common/top-list-item.tsx
similarity index 100%
rename from apps/web/components/top-list-item.tsx
rename to apps/web/components/common/top-list-item.tsx
diff --git a/apps/web/components/backend-config-dialog.tsx b/apps/web/components/features/backend/backend-config-dialog.tsx
similarity index 99%
rename from apps/web/components/backend-config-dialog.tsx
rename to apps/web/components/features/backend/backend-config-dialog.tsx
index fb1e9ff..144ecd6 100644
--- a/apps/web/components/backend-config-dialog.tsx
+++ b/apps/web/components/features/backend/backend-config-dialog.tsx
@@ -38,7 +38,7 @@ import {
import { cn, formatBytes, formatNumber } from "@/lib/utils";
import { api } from "@/lib/api";
import { toast } from "sonner";
-import { BackendVerifyAnimation } from "./backend-verify-animation";
+import { BackendVerifyAnimation } from "@/components/features/backend/backend-verify-animation";
import { useSettings, FaviconProvider, getFaviconUrl } from "@/lib/settings";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
diff --git a/apps/web/components/backend-verify-animation.tsx b/apps/web/components/features/backend/backend-verify-animation.tsx
similarity index 100%
rename from apps/web/components/backend-verify-animation.tsx
rename to apps/web/components/features/backend/backend-verify-animation.tsx
diff --git a/apps/web/components/features/backend/index.ts b/apps/web/components/features/backend/index.ts
new file mode 100644
index 0000000..519b987
--- /dev/null
+++ b/apps/web/components/features/backend/index.ts
@@ -0,0 +1,2 @@
+export { BackendConfigDialog } from "./backend-config-dialog";
+export { BackendVerifyAnimation } from "./backend-verify-animation";
diff --git a/apps/web/components/country-flag.tsx b/apps/web/components/features/countries/country-flag.tsx
similarity index 100%
rename from apps/web/components/country-flag.tsx
rename to apps/web/components/features/countries/country-flag.tsx
diff --git a/apps/web/components/country-top-list.tsx b/apps/web/components/features/countries/country-top-list.tsx
similarity index 91%
rename from apps/web/components/country-top-list.tsx
rename to apps/web/components/features/countries/country-top-list.tsx
index 9130519..3071f72 100644
--- a/apps/web/components/country-top-list.tsx
+++ b/apps/web/components/features/countries/country-top-list.tsx
@@ -3,11 +3,11 @@
import { useMemo } from "react";
import { MapPin } from "lucide-react";
import { useTranslations } from "next-intl";
-import { CountryFlag } from "@/components/country-flag";
-import { OverviewCard } from "./overview-card";
-import { TopListItem } from "./top-list-item";
+import { CountryFlag } from "./country-flag";
+import { OverviewCard } from "@/components/common";
+import { TopListItem } from "@/components/common";
import { Button } from "@/components/ui/button";
-import type { CountryStats } from "@clashmaster/shared";
+import type { CountryStats } from "@neko-master/shared";
interface CountryTopListProps {
data: CountryStats[];
diff --git a/apps/web/components/country-traffic-chart.tsx b/apps/web/components/features/countries/country-traffic-chart.tsx
similarity index 98%
rename from apps/web/components/country-traffic-chart.tsx
rename to apps/web/components/features/countries/country-traffic-chart.tsx
index 5345857..5542c3a 100644
--- a/apps/web/components/country-traffic-chart.tsx
+++ b/apps/web/components/features/countries/country-traffic-chart.tsx
@@ -5,9 +5,9 @@ import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from "recharts";
import { Globe, Link2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { CountryFlag } from "@/components/country-flag";
+import { CountryFlag } from "./country-flag";
import { formatBytes, formatNumber } from "@/lib/utils";
-import type { CountryStats } from "@clashmaster/shared";
+import type { CountryStats } from "@neko-master/shared";
interface CountryTrafficChartProps {
data: CountryStats[];
diff --git a/apps/web/components/country-traffic-list.tsx b/apps/web/components/features/countries/country-traffic-list.tsx
similarity index 97%
rename from apps/web/components/country-traffic-list.tsx
rename to apps/web/components/features/countries/country-traffic-list.tsx
index 06f081e..9a9b6f6 100644
--- a/apps/web/components/country-traffic-list.tsx
+++ b/apps/web/components/features/countries/country-traffic-list.tsx
@@ -2,9 +2,9 @@
import { useMemo } from "react";
import { Link2 } from "lucide-react";
-import { CountryFlag } from "@/components/country-flag";
+import { CountryFlag } from "./country-flag";
import { formatBytes, formatNumber } from "@/lib/utils";
-import type { CountryStats } from "@clashmaster/shared";
+import type { CountryStats } from "@neko-master/shared";
interface CountryTrafficListProps {
data: CountryStats[];
diff --git a/apps/web/components/features/countries/index.ts b/apps/web/components/features/countries/index.ts
new file mode 100644
index 0000000..362c754
--- /dev/null
+++ b/apps/web/components/features/countries/index.ts
@@ -0,0 +1,5 @@
+export { CountryFlag, extractCountryCodeFromText, stripLeadingFlagEmoji } from "./country-flag";
+export { CountryTopList } from "./country-top-list";
+export { CountryTrafficChart } from "./country-traffic-chart";
+export { CountryTrafficList } from "./country-traffic-list";
+export { WorldTrafficMap } from "./world-traffic-map";
diff --git a/apps/web/components/world-traffic-map.tsx b/apps/web/components/features/countries/world-traffic-map.tsx
similarity index 99%
rename from apps/web/components/world-traffic-map.tsx
rename to apps/web/components/features/countries/world-traffic-map.tsx
index 9500ee2..51f9a5c 100644
--- a/apps/web/components/world-traffic-map.tsx
+++ b/apps/web/components/features/countries/world-traffic-map.tsx
@@ -12,7 +12,7 @@ import { Globe, Info } from "lucide-react";
import { useTranslations } from "next-intl";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { formatBytes, formatNumber } from "@/lib/utils";
-import type { CountryStats } from "@clashmaster/shared";
+import type { CountryStats } from "@neko-master/shared";
interface WorldTrafficMapProps {
data: CountryStats[];
diff --git a/apps/web/components/features/devices/index.ts b/apps/web/components/features/devices/index.ts
new file mode 100644
index 0000000..9cd8cfc
--- /dev/null
+++ b/apps/web/components/features/devices/index.ts
@@ -0,0 +1 @@
+export { InteractiveDeviceStats } from "./interactive-device-stats";
diff --git a/apps/web/components/interactive-device-stats.tsx b/apps/web/components/features/devices/interactive-device-stats.tsx
similarity index 99%
rename from apps/web/components/interactive-device-stats.tsx
rename to apps/web/components/features/devices/interactive-device-stats.tsx
index 45bbc04..235211d 100644
--- a/apps/web/components/interactive-device-stats.tsx
+++ b/apps/web/components/features/devices/interactive-device-stats.tsx
@@ -18,11 +18,11 @@ import {
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { keepPreviousByIdentity } from "@/lib/query-placeholder";
import { useStatsWebSocket } from "@/lib/websocket";
-import { Favicon } from "@/components/favicon";
-import { DomainStatsTable, IPStatsTable } from "@/components/stats-tables";
+import { Favicon } from "@/components/common";
+import { DomainStatsTable, IPStatsTable } from "@/components/features/stats/table";
import { InsightChartSkeleton } from "@/components/ui/insight-skeleton";
import { COLORS, type PageSize } from "@/lib/stats-utils";
-import type { DeviceStats, DomainStats, IPStats, StatsSummary } from "@clashmaster/shared";
+import type { DeviceStats, DomainStats, IPStats, StatsSummary } from "@neko-master/shared";
interface InteractiveDeviceStatsProps {
data: DeviceStats[];
diff --git a/apps/web/components/domain-preview.tsx b/apps/web/components/features/domains/domain-preview.tsx
similarity index 100%
rename from apps/web/components/domain-preview.tsx
rename to apps/web/components/features/domains/domain-preview.tsx
diff --git a/apps/web/components/domain-top-grid.tsx b/apps/web/components/features/domains/domain-top-grid.tsx
similarity index 99%
rename from apps/web/components/domain-top-grid.tsx
rename to apps/web/components/features/domains/domain-top-grid.tsx
index cddc63a..bc673ea 100644
--- a/apps/web/components/domain-top-grid.tsx
+++ b/apps/web/components/features/domains/domain-top-grid.tsx
@@ -7,7 +7,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { formatBytes, formatNumber } from "@/lib/utils";
import { useSettings, getFaviconUrl } from "@/lib/settings";
-import type { DomainStats } from "@clashmaster/shared";
+import type { DomainStats } from "@neko-master/shared";
interface DomainTopGridProps {
data: DomainStats[];
diff --git a/apps/web/components/domain-top-list.tsx b/apps/web/components/features/domains/domain-top-list.tsx
similarity index 96%
rename from apps/web/components/domain-top-list.tsx
rename to apps/web/components/features/domains/domain-top-list.tsx
index 980d562..5b3d836 100644
--- a/apps/web/components/domain-top-list.tsx
+++ b/apps/web/components/features/domains/domain-top-list.tsx
@@ -3,12 +3,12 @@
import { useMemo, useState } from "react";
import { Globe, Link2, ArrowUpDown } from "lucide-react";
import { useTranslations } from "next-intl";
-import { OverviewCard } from "./overview-card";
-import { TopListItem } from "./top-list-item";
+import { OverviewCard } from "@/components/common";
+import { TopListItem } from "@/components/common";
import { Button } from "@/components/ui/button";
import { formatBytes, formatNumber } from "@/lib/utils";
import { useSettings, getFaviconUrl } from "@/lib/settings";
-import type { DomainStats } from "@clashmaster/shared";
+import type { DomainStats } from "@neko-master/shared";
interface DomainTopListProps {
data: DomainStats[];
diff --git a/apps/web/components/features/domains/index.ts b/apps/web/components/features/domains/index.ts
new file mode 100644
index 0000000..b510775
--- /dev/null
+++ b/apps/web/components/features/domains/index.ts
@@ -0,0 +1,3 @@
+export { DomainPreview } from "./domain-preview";
+export { DomainTopGrid } from "./domain-top-grid";
+export { DomainTopList } from "./domain-top-list";
diff --git a/apps/web/components/features/proxies/index.ts b/apps/web/components/features/proxies/index.ts
new file mode 100644
index 0000000..4d21d09
--- /dev/null
+++ b/apps/web/components/features/proxies/index.ts
@@ -0,0 +1,5 @@
+export { InteractiveProxyStats } from "./interactive-proxy-stats";
+export { ProxyChainBadge } from "./proxy-chain-badge";
+export { ProxyStatsChart } from "./proxy-stats-chart";
+export { ProxyTopGrid } from "./proxy-top-grid";
+export { ProxyTopList } from "./proxy-top-list";
diff --git a/apps/web/components/interactive-proxy-stats.tsx b/apps/web/components/features/proxies/interactive-proxy-stats.tsx
similarity index 98%
rename from apps/web/components/interactive-proxy-stats.tsx
rename to apps/web/components/features/proxies/interactive-proxy-stats.tsx
index e619b26..db7435e 100644
--- a/apps/web/components/interactive-proxy-stats.tsx
+++ b/apps/web/components/features/proxies/interactive-proxy-stats.tsx
@@ -8,7 +8,7 @@ import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip, B
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
-import { CountryFlag, extractCountryCodeFromText, stripLeadingFlagEmoji } from "@/components/country-flag";
+import { CountryFlag, extractCountryCodeFromText, stripLeadingFlagEmoji } from "@/components/features/countries/country-flag";
import { formatBytes, formatNumber } from "@/lib/utils";
import { cn } from "@/lib/utils";
import { api, type TimeRange } from "@/lib/api";
@@ -20,11 +20,11 @@ import {
getProxyDomainsQueryKey,
getProxyIPsQueryKey,
} from "@/lib/stats-query-keys";
-import { Favicon } from "@/components/favicon";
-import { DomainStatsTable, IPStatsTable } from "@/components/stats-tables";
+import { Favicon } from "@/components/common";
+import { DomainStatsTable, IPStatsTable } from "@/components/features/stats/table";
import { InsightChartSkeleton, InsightThreePanelSkeleton } from "@/components/ui/insight-skeleton";
import { COLORS, type PageSize } from "@/lib/stats-utils";
-import type { DomainStats, IPStats, ProxyStats, StatsSummary } from "@clashmaster/shared";
+import type { DomainStats, IPStats, ProxyStats, StatsSummary } from "@neko-master/shared";
interface InteractiveProxyStatsProps {
data?: ProxyStats[];
diff --git a/apps/web/components/proxy-chain-badge.tsx b/apps/web/components/features/proxies/proxy-chain-badge.tsx
similarity index 100%
rename from apps/web/components/proxy-chain-badge.tsx
rename to apps/web/components/features/proxies/proxy-chain-badge.tsx
diff --git a/apps/web/components/proxy-stats-chart.tsx b/apps/web/components/features/proxies/proxy-stats-chart.tsx
similarity index 99%
rename from apps/web/components/proxy-stats-chart.tsx
rename to apps/web/components/features/proxies/proxy-stats-chart.tsx
index 29c7888..4a86998 100644
--- a/apps/web/components/proxy-stats-chart.tsx
+++ b/apps/web/components/features/proxies/proxy-stats-chart.tsx
@@ -6,7 +6,7 @@ import { Server, Link2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { formatBytes, formatNumber } from "@/lib/utils";
-import type { ProxyStats } from "@clashmaster/shared";
+import type { ProxyStats } from "@neko-master/shared";
interface ProxyStatsChartProps {
data: ProxyStats[];
diff --git a/apps/web/components/proxy-top-grid.tsx b/apps/web/components/features/proxies/proxy-top-grid.tsx
similarity index 98%
rename from apps/web/components/proxy-top-grid.tsx
rename to apps/web/components/features/proxies/proxy-top-grid.tsx
index f88659b..56e136f 100644
--- a/apps/web/components/proxy-top-grid.tsx
+++ b/apps/web/components/features/proxies/proxy-top-grid.tsx
@@ -9,9 +9,9 @@ import {
CountryFlag,
extractCountryCodeFromText,
stripLeadingFlagEmoji,
-} from "@/components/country-flag";
+} from "@/components/features/countries";
import { formatBytes, formatNumber } from "@/lib/utils";
-import type { ProxyStats } from "@clashmaster/shared";
+import type { ProxyStats } from "@neko-master/shared";
interface ProxyTopGridProps {
data: ProxyStats[];
diff --git a/apps/web/components/proxy-top-list.tsx b/apps/web/components/features/proxies/proxy-top-list.tsx
similarity index 95%
rename from apps/web/components/proxy-top-list.tsx
rename to apps/web/components/features/proxies/proxy-top-list.tsx
index 50a2f01..f349602 100644
--- a/apps/web/components/proxy-top-list.tsx
+++ b/apps/web/components/features/proxies/proxy-top-list.tsx
@@ -3,12 +3,12 @@
import { useMemo, useState } from "react";
import { Server, Link2, ArrowUpDown } from "lucide-react";
import { useTranslations } from "next-intl";
-import { CountryFlag, extractCountryCodeFromText, stripLeadingFlagEmoji } from "@/components/country-flag";
-import { OverviewCard } from "./overview-card";
-import { TopListItem } from "./top-list-item";
+import { CountryFlag, extractCountryCodeFromText, stripLeadingFlagEmoji } from "@/components/features/countries";
+import { OverviewCard } from "@/components/common";
+import { TopListItem } from "@/components/common";
import { Button } from "@/components/ui/button";
import { formatBytes, formatNumber } from "@/lib/utils";
-import type { ProxyStats } from "@clashmaster/shared";
+import type { ProxyStats } from "@neko-master/shared";
interface ProxyTopListProps {
data: ProxyStats[];
diff --git a/apps/web/components/features/rules/index.ts b/apps/web/components/features/rules/index.ts
new file mode 100644
index 0000000..79a863b
--- /dev/null
+++ b/apps/web/components/features/rules/index.ts
@@ -0,0 +1,3 @@
+export { InteractiveRuleStats } from "./interactive-rule-stats";
+export { RuleChainFlow } from "./rule-chain-flow";
+export { RuleChainChart } from "./rule-chain-chart";
diff --git a/apps/web/components/interactive-rule-stats.tsx b/apps/web/components/features/rules/interactive-rule-stats.tsx
similarity index 98%
rename from apps/web/components/interactive-rule-stats.tsx
rename to apps/web/components/features/rules/interactive-rule-stats.tsx
index 49a7856..eed6170 100644
--- a/apps/web/components/interactive-rule-stats.tsx
+++ b/apps/web/components/features/rules/interactive-rule-stats.tsx
@@ -19,7 +19,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { formatBytes, formatNumber } from "@/lib/utils";
import { cn } from "@/lib/utils";
-import { api, type ClashRulesResponse, type TimeRange } from "@/lib/api";
+import { api, type GatewayRulesResponse, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { keepPreviousByIdentity } from "@/lib/query-placeholder";
import { useStatsWebSocket } from "@/lib/websocket";
@@ -32,15 +32,15 @@ import {
getDomainProxyStatsQueryKey,
getRulesQueryKey,
} from "@/lib/stats-query-keys";
-import { CountryFlag } from "@/components/country-flag";
-import { Favicon } from "@/components/favicon";
-import { DomainPreview } from "@/components/domain-preview";
-import { ProxyChainBadge } from "@/components/proxy-chain-badge";
-import { DomainExpandedDetails, IPExpandedDetails } from "@/components/stats-tables/expanded-details";
+import { CountryFlag } from "@/components/features/countries/country-flag";
+import { Favicon } from "@/components/common/favicon";
+import { DomainPreview } from "@/components/features/domains/domain-preview";
+import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badge";
+import { DomainExpandedDetails, IPExpandedDetails } from "@/components/features/stats/table/expanded-details";
import { ExpandReveal } from "@/components/ui/expand-reveal";
-import { UnifiedRuleChainFlow } from "@/components/rule-chain-flow";
+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 "@clashmaster/shared";
+import type { RuleStats, DomainStats, IPStats, StatsSummary } from "@neko-master/shared";
interface InteractiveRuleStatsProps {
data?: RuleStats[];
@@ -169,7 +169,7 @@ export function InteractiveRuleStats({
const [ipPage, setIpPage] = useState(1);
const [ipSearch, setIpSearch] = useState("");
const [showDomainBarLabels, setShowDomainBarLabels] = useState(true);
- const [clashRules, setClashRules] = useState<ClashRulesResponse | null>(null);
+ const [gatewayRules, setGatewayRules] = useState<GatewayRulesResponse | null>(null);
const [wsRuleDomains, setWsRuleDomains] = useState<DomainStats[] | null>(null);
const [wsRuleIPs, setWsRuleIPs] = useState<IPStats[] | null>(null);
const pendingRuleDomainsRef = useRef<DomainStats[] | null>(null);
@@ -195,19 +195,19 @@ export function InteractiveRuleStats({
return () => media.removeEventListener("change", update);
}, []);
- // Fetch Clash rules to find zero-traffic rules.
+ // Fetch Gateway rules to find zero-traffic rules.
// Ruleset metadata changes infrequently, so load on mount/backend switch only.
useEffect(() => {
let cancelled = false;
- async function fetchClashRules() {
+ async function fetchGatewayRules() {
try {
- const result = await api.getClashRules(activeBackendId);
- if (!cancelled) setClashRules(result);
+ const result = await api.getGatewayRules(activeBackendId);
+ if (!cancelled) setGatewayRules(result);
} catch {
- // Silent - Clash API may not be available
+ // Silent - Gateway API may not be available
}
}
- fetchClashRules();
+ fetchGatewayRules();
return () => { cancelled = true; };
}, [activeBackendId]);
@@ -227,13 +227,13 @@ export function InteractiveRuleStats({
hasTraffic: true,
}));
- // Append zero-traffic rules from Clash API, using the target proxy group name
+ // Append zero-traffic rules from Gateway API, using the target proxy group name
// (rule.proxy) which matches how traffic data stores rule names.
// Multiple low-level rules (RuleSet, ProcessName, etc.) can target the same
// proxy group, so we deduplicate by proxy group name.
- if (clashRules?.rules) {
+ if (gatewayRules?.rules) {
const zeroTrafficItems: typeof trafficItems = [];
- for (const rule of clashRules.rules) {
+ for (const rule of gatewayRules.rules) {
const proxyGroup = rule.proxy;
if (existingRuleNames.has(proxyGroup)) continue;
existingRuleNames.add(proxyGroup);
@@ -254,7 +254,7 @@ export function InteractiveRuleStats({
}
return trafficItems;
- }, [rulesData, clashRules]);
+ }, [rulesData, gatewayRules]);
const totalTraffic = useMemo(() => {
return chartData.reduce((sum, item) => sum + item.value, 0);
diff --git a/apps/web/components/rule-chain-chart.tsx b/apps/web/components/features/rules/rule-chain-chart.tsx
similarity index 99%
rename from apps/web/components/rule-chain-chart.tsx
rename to apps/web/components/features/rules/rule-chain-chart.tsx
index 84cca09..7a69640 100644
--- a/apps/web/components/rule-chain-chart.tsx
+++ b/apps/web/components/features/rules/rule-chain-chart.tsx
@@ -5,7 +5,7 @@ import { Network, ArrowRight } from "lucide-react";
import { useTranslations } from "next-intl";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { formatBytes, formatNumber } from "@/lib/utils";
-import type { RuleStats } from "@clashmaster/shared";
+import type { RuleStats } from "@neko-master/shared";
interface RuleChainChartProps {
data: RuleStats[];
diff --git a/apps/web/components/rule-chain-flow.tsx b/apps/web/components/features/rules/rule-chain-flow.tsx
similarity index 99%
rename from apps/web/components/rule-chain-flow.tsx
rename to apps/web/components/features/rules/rule-chain-flow.tsx
index 19e2d90..2f638a0 100644
--- a/apps/web/components/rule-chain-flow.tsx
+++ b/apps/web/components/features/rules/rule-chain-flow.tsx
@@ -37,7 +37,7 @@ import { useStatsWebSocket } from "@/lib/websocket";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { resolveActiveChains, type ActiveChainInfo } from "@/lib/active-chain";
import { useTranslations } from "next-intl";
-import type { StatsSummary } from "@clashmaster/shared";
+import type { StatsSummary } from "@neko-master/shared";
// ---------- Types ----------
@@ -1007,12 +1007,15 @@ function UnifiedRuleChainFlowInner({
async function fetchActiveChains() {
try {
- const [providers, rules] = await Promise.all([
- api.getClashProviders(activeBackendId),
- api.getClashRules(activeBackendId),
+ const [gatewayProviders, gatewayRules] = await Promise.all([
+ api.getGatewayProviders(activeBackendId),
+ api.getGatewayRules(activeBackendId),
]);
+
if (cancelled) return;
- setActiveChainInfo(resolveActiveChains(providers, rules));
+
+ const { activeNodeNames, activeLinkKeys, activeChains } =
+ resolveActiveChains(gatewayProviders, gatewayRules);
} catch {
if (!cancelled) setActivePolicyOnly(false);
}
diff --git a/apps/web/components/features/stats/charts/index.ts b/apps/web/components/features/stats/charts/index.ts
new file mode 100644
index 0000000..18a323b
--- /dev/null
+++ b/apps/web/components/features/stats/charts/index.ts
@@ -0,0 +1,2 @@
+export { TrafficChart } from "./traffic-chart";
+export { TopDomainsChart } from "./proxy-chart";
diff --git a/apps/web/components/top-domains-chart.tsx b/apps/web/components/features/stats/charts/proxy-chart.tsx
similarity index 98%
rename from apps/web/components/top-domains-chart.tsx
rename to apps/web/components/features/stats/charts/proxy-chart.tsx
index 1fd294a..eb0aa53 100644
--- a/apps/web/components/top-domains-chart.tsx
+++ b/apps/web/components/features/stats/charts/proxy-chart.tsx
@@ -17,12 +17,12 @@ import { BarChart3 } from "lucide-react";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { Favicon } from "@/components/favicon";
+import { Favicon } from "@/components/common";
import { formatBytes } from "@/lib/utils";
import { api, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { getDomainsQueryKey } from "@/lib/stats-query-keys";
-import type { DomainStats } from "@clashmaster/shared";
+import type { DomainStats } from "@neko-master/shared";
interface TopDomainsChartProps {
data?: DomainStats[];
diff --git a/apps/web/components/traffic-chart.tsx b/apps/web/components/features/stats/charts/traffic-chart.tsx
similarity index 98%
rename from apps/web/components/traffic-chart.tsx
rename to apps/web/components/features/stats/charts/traffic-chart.tsx
index a2142fc..cb7b726 100644
--- a/apps/web/components/traffic-chart.tsx
+++ b/apps/web/components/features/stats/charts/traffic-chart.tsx
@@ -11,7 +11,7 @@ import {
ResponsiveContainer,
} from "recharts";
import { useTranslations } from "next-intl";
-import type { HourlyStats } from "@clashmaster/shared";
+import type { HourlyStats } from "@neko-master/shared";
import { formatBytes } from "@/lib/utils";
interface TrafficChartProps {
diff --git a/apps/web/components/traffic-trend-chart.tsx b/apps/web/components/features/stats/charts/trend-chart.tsx
similarity index 99%
rename from apps/web/components/traffic-trend-chart.tsx
rename to apps/web/components/features/stats/charts/trend-chart.tsx
index 026e7a5..34d7b18 100644
--- a/apps/web/components/traffic-trend-chart.tsx
+++ b/apps/web/components/features/stats/charts/trend-chart.tsx
@@ -15,7 +15,7 @@ import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { cn, formatBytes } from "@/lib/utils";
-import type { TrafficTrendPoint } from "@clashmaster/shared";
+import type { TrafficTrendPoint } from "@neko-master/shared";
type TimeRange = "30m" | "1h" | "24h";
type TrendGranularity = "minute" | "day";
diff --git a/apps/web/components/features/stats/index.ts b/apps/web/components/features/stats/index.ts
new file mode 100644
index 0000000..99d98b3
--- /dev/null
+++ b/apps/web/components/features/stats/index.ts
@@ -0,0 +1,3 @@
+export { StatsCards } from "./stats-cards";
+export * from "./charts";
+export * from "./table";
diff --git a/apps/web/components/stats-cards.tsx b/apps/web/components/features/stats/stats-cards.tsx
similarity index 99%
rename from apps/web/components/stats-cards.tsx
rename to apps/web/components/features/stats/stats-cards.tsx
index 70e24ac..ccc3292 100644
--- a/apps/web/components/stats-cards.tsx
+++ b/apps/web/components/features/stats/stats-cards.tsx
@@ -5,7 +5,7 @@ import { Download, Upload, Globe, Activity, Server, Route } from "lucide-react";
import { useTranslations } from "next-intl";
import { motion, useSpring, useTransform, useMotionValue } from "framer-motion";
import { formatBytes } from "@/lib/utils";
-import type { StatsSummary } from "@clashmaster/shared";
+import type { StatsSummary } from "@neko-master/shared";
interface StatsCardsProps {
data: StatsSummary | null;
diff --git a/apps/web/components/stats-tables/domain-stats-table.tsx b/apps/web/components/features/stats/table/domain-stats-table.tsx
similarity index 98%
rename from apps/web/components/stats-tables/domain-stats-table.tsx
rename to apps/web/components/features/stats/table/domain-stats-table.tsx
index acb6a66..3c36d52 100644
--- a/apps/web/components/stats-tables/domain-stats-table.tsx
+++ b/apps/web/components/features/stats/table/domain-stats-table.tsx
@@ -32,10 +32,10 @@ import {
getDomainIPDetailsQueryKey,
getDomainProxyStatsQueryKey,
} from "@/lib/stats-query-keys";
-import { Favicon } from "@/components/favicon";
-import { DomainPreview } from "@/components/domain-preview";
-import { DomainExpandedDetails } from "@/components/stats-tables/expanded-details";
-import { ProxyChainBadge } from "@/components/proxy-chain-badge";
+import { Favicon } from "@/components/common";
+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 { InsightTableSkeleton } from "@/components/ui/insight-skeleton";
import {
@@ -45,7 +45,7 @@ import {
type DomainSortKey,
type SortOrder,
} from "@/lib/stats-utils";
-import type { DomainStats } from "@clashmaster/shared";
+import type { DomainStats } from "@neko-master/shared";
const DETAIL_QUERY_STALE_MS = 30_000;
interface DomainStatsTableProps {
diff --git a/apps/web/components/domains-table.tsx b/apps/web/components/features/stats/table/domain-table.tsx
similarity index 98%
rename from apps/web/components/domains-table.tsx
rename to apps/web/components/features/stats/table/domain-table.tsx
index 5ba9536..354b04c 100644
--- a/apps/web/components/domains-table.tsx
+++ b/apps/web/components/features/stats/table/domain-table.tsx
@@ -7,14 +7,14 @@ import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { InsightTableSkeleton } from "@/components/ui/insight-skeleton";
-import { Favicon } from "@/components/favicon";
-import { DomainPreview } from "@/components/domain-preview";
-import { DomainExpandedDetails } from "@/components/stats-tables/expanded-details";
-import { ProxyChainBadge } from "@/components/proxy-chain-badge";
+import { Favicon } from "@/components/common/favicon";
+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 { formatBytes, formatNumber, formatDuration } from "@/lib/utils";
import { cn } from "@/lib/utils";
-import type { DomainStats, StatsSummary } from "@clashmaster/shared";
+import type { DomainStats, StatsSummary } from "@neko-master/shared";
import { api, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { useStatsWebSocket } from "@/lib/websocket";
@@ -41,8 +41,7 @@ interface DomainsTableProps {
type SortKey = "domain" | "totalDownload" | "totalUpload" | "totalConnections" | "lastSeen";
type SortOrder = "asc" | "desc";
-const PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
-type PageSize = typeof PAGE_SIZE_OPTIONS[number];
+import { PAGE_SIZE_OPTIONS, type PageSize } from "@/lib/stats-utils";
const DETAIL_QUERY_STALE_MS = 30_000;
const DOMAINS_WS_MIN_PUSH_MS = 3_000;
type DomainsPageQueryState = {
diff --git a/apps/web/components/stats-tables/expanded-details.tsx b/apps/web/components/features/stats/table/expanded-details.tsx
similarity index 98%
rename from apps/web/components/stats-tables/expanded-details.tsx
rename to apps/web/components/features/stats/table/expanded-details.tsx
index c6646aa..4e3fc1c 100644
--- a/apps/web/components/stats-tables/expanded-details.tsx
+++ b/apps/web/components/features/stats/table/expanded-details.tsx
@@ -2,12 +2,12 @@
import { Globe, Link2, Loader2, Server, Waypoints } from "lucide-react";
import { useTranslations } from "next-intl";
-import { CountryFlag } from "@/components/country-flag";
-import { Favicon } from "@/components/favicon";
-import { DomainPreview } from "@/components/domain-preview";
+import { CountryFlag } from "@/components/features/countries";
+import { Favicon } from "@/components/common";
+import { DomainPreview } from "@/components/features/domains";
import { getDomainColor, getIPGradient } from "@/lib/stats-utils";
import { formatBytes, formatNumber } from "@/lib/utils";
-import type { DomainStats, IPStats, ProxyTrafficStats } from "@clashmaster/shared";
+import type { DomainStats, IPStats, ProxyTrafficStats } from "@neko-master/shared";
interface DomainExpandedDetailsProps {
domain: Pick<
diff --git a/apps/web/components/features/stats/table/index.tsx b/apps/web/components/features/stats/table/index.tsx
new file mode 100644
index 0000000..7918cda
--- /dev/null
+++ b/apps/web/components/features/stats/table/index.tsx
@@ -0,0 +1,5 @@
+export { DomainsTable } from "./domain-table";
+export { IPsTable } from "./ip-table";
+export { DomainStatsTable } from "./domain-stats-table";
+export { IPStatsTable } from "./ip-stats-table";
+export { DomainExpandedDetails, IPExpandedDetails } from "./expanded-details";
diff --git a/apps/web/components/stats-tables/ip-stats-table.tsx b/apps/web/components/features/stats/table/ip-stats-table.tsx
similarity index 98%
rename from apps/web/components/stats-tables/ip-stats-table.tsx
rename to apps/web/components/features/stats/table/ip-stats-table.tsx
index ef2d1dd..cdb8de7 100644
--- a/apps/web/components/stats-tables/ip-stats-table.tsx
+++ b/apps/web/components/features/stats/table/ip-stats-table.tsx
@@ -18,7 +18,7 @@ import { useTranslations } from "next-intl";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
-import { CountryFlag } from "@/components/country-flag";
+import { CountryFlag } from "@/components/features/countries";
import {
DropdownMenu,
DropdownMenuContent,
@@ -34,8 +34,8 @@ import {
getIPDomainDetailsQueryKey,
getIPProxyStatsQueryKey,
} from "@/lib/stats-query-keys";
-import { IPExpandedDetails } from "@/components/stats-tables/expanded-details";
-import { ProxyChainBadge } from "@/components/proxy-chain-badge";
+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 {
@@ -46,7 +46,7 @@ import {
type IPSortKey,
type SortOrder,
} from "@/lib/stats-utils";
-import type { IPStats } from "@clashmaster/shared";
+import type { IPStats } from "@neko-master/shared";
const DETAIL_QUERY_STALE_MS = 30_000;
interface IPStatsTableProps {
diff --git a/apps/web/components/ips-table.tsx b/apps/web/components/features/stats/table/ip-table.tsx
similarity index 98%
rename from apps/web/components/ips-table.tsx
rename to apps/web/components/features/stats/table/ip-table.tsx
index 3017bec..2ed00ac 100644
--- a/apps/web/components/ips-table.tsx
+++ b/apps/web/components/features/stats/table/ip-table.tsx
@@ -20,13 +20,13 @@ import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { InsightTableSkeleton } from "@/components/ui/insight-skeleton";
-import { CountryFlag } from "@/components/country-flag";
+import { CountryFlag } from "@/components/features/countries/country-flag";
import { formatBytes, formatNumber } from "@/lib/utils";
import { cn } from "@/lib/utils";
-import { IPExpandedDetails } from "@/components/stats-tables/expanded-details";
-import { ProxyChainBadge } from "@/components/proxy-chain-badge";
+import { IPExpandedDetails } from "@/components/features/stats/table/expanded-details";
+import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badge";
import { ExpandReveal } from "@/components/ui/expand-reveal";
-import type { IPStats, StatsSummary } from "@clashmaster/shared";
+import type { IPStats, StatsSummary } from "@neko-master/shared";
import { api, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { useStatsWebSocket } from "@/lib/websocket";
@@ -58,8 +58,7 @@ type SortKey =
| "lastSeen";
type SortOrder = "asc" | "desc";
-const PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
-type PageSize = (typeof PAGE_SIZE_OPTIONS)[number];
+import { PAGE_SIZE_OPTIONS, type PageSize } from "@/lib/stats-utils";
const DETAIL_QUERY_STALE_MS = 30_000;
const IPS_WS_MIN_PUSH_MS = 3_000;
type IPsPageQueryState = {
diff --git a/apps/web/components/layout/index.ts b/apps/web/components/layout/index.ts
new file mode 100644
index 0000000..896195e
--- /dev/null
+++ b/apps/web/components/layout/index.ts
@@ -0,0 +1 @@
+export { Navigation } from "./navigation";
diff --git a/apps/web/components/navigation.tsx b/apps/web/components/layout/navigation.tsx
similarity index 98%
rename from apps/web/components/navigation.tsx
rename to apps/web/components/layout/navigation.tsx
index 156322d..361a982 100644
--- a/apps/web/components/navigation.tsx
+++ b/apps/web/components/layout/navigation.tsx
@@ -20,7 +20,7 @@ import {
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { BackendConfigDialog } from "./backend-config-dialog";
+import { BackendConfigDialog } from "@/components/features/backend";
import {
Tooltip,
TooltipContent,
@@ -38,7 +38,7 @@ interface NavigationProps {
}
const APP_VERSION = process.env.NEXT_PUBLIC_APP_VERSION || "0.0.0";
-const GITHUB_URL = "https://github.com/foru17/clash-master";
+const GITHUB_URL = "https://github.com/foru17/neko-master";
const NAV_ITEMS = [
{ id: "overview", icon: LayoutDashboard },
@@ -101,8 +101,8 @@ export function Navigation({
<div className="flex items-start gap-3 p-6 border-b border-border/40">
<div className="w-14 h-14 rounded-xl shrink-0 flex items-center justify-center overflow-hidden hover:opacity-80">
<Image
- src="/clash-master.png"
- alt="Clash Master"
+ src="/logo.png"
+ alt="Neko Master"
width={40}
height={40}
className="w-full h-full object-cover"
@@ -310,8 +310,8 @@ export function Navigation({
<div className="flex items-center gap-4 mb-4">
<div className="w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center overflow-hidden shrink-0">
<Image
- src="/clash-master.png"
- alt="Clash Master"
+ src="/logo.png"
+ alt="Neko Master"
width={64}
height={64}
className="w-full h-full object-cover"
diff --git a/apps/web/components/overview/index.tsx b/apps/web/components/overview/index.tsx
index 99a9ebd..7a6a8d8 100644
--- a/apps/web/components/overview/index.tsx
+++ b/apps/web/components/overview/index.tsx
@@ -5,36 +5,28 @@ import { useTranslations } from "next-intl";
import { TopDomainsSimple } from "./top-domains-simple";
import { TopProxiesSimple } from "./top-proxies-simple";
import { TopCountriesSimple } from "./top-countries-simple";
-import { TrafficTrendChart } from "@/components/traffic-trend-chart";
+import { TrafficTrendChart } from "@/components/features/stats/charts/trend-chart";
import { useStatsWebSocket } from "@/lib/websocket";
import { api, type TimeRange } from "@/lib/api";
+import type { TimePreset } from "@/lib/types/dashboard";
import type {
DomainStats,
ProxyStats,
CountryStats,
TrafficTrendPoint,
StatsSummary,
-} from "@clashmaster/shared";
+} from "@neko-master/shared";
type TrendTimeRange = "30m" | "1h" | "24h";
type TrendGranularity = "minute" | "day";
-type GlobalTimePreset =
- | "1m"
- | "5m"
- | "15m"
- | "30m"
- | "24h"
- | "7d"
- | "30d"
- | "today"
- | "custom";
+export type GlobalTimePreset = TimePreset;
interface OverviewTabProps {
domains: DomainStats[];
proxies: ProxyStats[];
countries: CountryStats[];
timeRange: TimeRange;
- timePreset: GlobalTimePreset;
+ timePreset: TimePreset;
activeBackendId?: number;
autoRefresh?: boolean;
onNavigate?: (tab: string) => void;
diff --git a/apps/web/components/overview/top-countries-simple.tsx b/apps/web/components/overview/top-countries-simple.tsx
index 3e737e7..99cd65e 100644
--- a/apps/web/components/overview/top-countries-simple.tsx
+++ b/apps/web/components/overview/top-countries-simple.tsx
@@ -4,9 +4,9 @@ import React, { useMemo } from "react";
import { Globe, ArrowRight, BarChart3, Link2 } from "lucide-react";
import { useTranslations, useLocale } from "next-intl";
import { Button } from "@/components/ui/button";
-import { CountryFlag } from "@/components/country-flag";
+import { CountryFlag } from "@/components/features/countries";
import { formatBytes, formatNumber, cn } from "@/lib/utils";
-import type { CountryStats } from "@clashmaster/shared";
+import type { CountryStats } from "@neko-master/shared";
interface TopCountriesSimpleProps {
countries: CountryStats[];
diff --git a/apps/web/components/overview/top-domains-simple.tsx b/apps/web/components/overview/top-domains-simple.tsx
index 5ba3545..7ca9a30 100644
--- a/apps/web/components/overview/top-domains-simple.tsx
+++ b/apps/web/components/overview/top-domains-simple.tsx
@@ -6,7 +6,7 @@ import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { cn, formatBytes, formatNumber } from "@/lib/utils";
import { useSettings, getFaviconUrl } from "@/lib/settings";
-import type { DomainStats } from "@clashmaster/shared";
+import type { DomainStats } from "@neko-master/shared";
interface TopDomainsSimpleProps {
domains: DomainStats[];
diff --git a/apps/web/components/overview/top-proxies-simple.tsx b/apps/web/components/overview/top-proxies-simple.tsx
index d57b5d3..d8ddae6 100644
--- a/apps/web/components/overview/top-proxies-simple.tsx
+++ b/apps/web/components/overview/top-proxies-simple.tsx
@@ -5,7 +5,7 @@ import { Server, ArrowRight, BarChart3, Link2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { cn, formatBytes, formatNumber } from "@/lib/utils";
-import type { ProxyStats } from "@clashmaster/shared";
+import type { ProxyStats } from "@neko-master/shared";
interface TopProxiesSimpleProps {
proxies: ProxyStats[];
diff --git a/apps/web/components/stats-tables/index.ts b/apps/web/components/stats-tables/index.ts
deleted file mode 100644
index 793d7aa..0000000
--- a/apps/web/components/stats-tables/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { DomainStatsTable } from "./domain-stats-table";
-export { IPStatsTable } from "./ip-stats-table";
diff --git a/apps/web/eslint.config.mjs b/apps/web/eslint.config.mjs
index 295a825..ffb2243 100644
--- a/apps/web/eslint.config.mjs
+++ b/apps/web/eslint.config.mjs
@@ -1,6 +1,6 @@
import { defineConfig, globalIgnores } from "eslint/config";
-import { default as nextVitals } from "eslint-config-next/core-web-vitals.js";
-import { default as nextTs } from "eslint-config-next/typescript.js";
+import { default as nextVitals } from "eslint-config-next/core-web-vitals";
+import { default as nextTs } from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
diff --git a/apps/web/hooks/use-version-check.ts b/apps/web/hooks/use-version-check.ts
index 15b9dd2..8ca6d39 100644
--- a/apps/web/hooks/use-version-check.ts
+++ b/apps/web/hooks/use-version-check.ts
@@ -3,9 +3,9 @@
import { useState, useEffect, useCallback } from "react";
const GITHUB_PACKAGE_URL =
- "https://raw.githubusercontent.com/foru17/clash-master/refs/heads/main/package.json";
+ "https://raw.githubusercontent.com/foru17/neko-master/refs/heads/main/package.json";
const GITHUB_API_URL =
- "https://api.github.com/repos/foru17/clash-master";
+ "https://api.github.com/repos/foru17/neko-master";
const CHECK_INTERVAL = 30 * 60 * 1000; // Check every 30 minutes
const FETCH_TIMEOUT = 10000; // 10 seconds
diff --git a/apps/web/lib/active-chain.ts b/apps/web/lib/active-chain.ts
index 0e31664..2b91565 100644
--- a/apps/web/lib/active-chain.ts
+++ b/apps/web/lib/active-chain.ts
@@ -1,4 +1,4 @@
-import type { ClashProvidersResponse, ClashRulesResponse } from "./api";
+import type { GatewayProvidersResponse, GatewayRulesResponse } from "./api";
export interface ActiveChainInfo {
/** Set of node names that are part of active chains */
@@ -13,7 +13,7 @@ export interface ActiveChainInfo {
* Build a map of group name → currently selected proxy/group name
* from the providers/proxies response.
*/
-function buildGroupNowMap(providers: ClashProvidersResponse): Map<string, string> {
+function buildGroupNowMap(providers: GatewayProvidersResponse): Map<string, string> {
const map = new Map<string, string>();
for (const provider of Object.values(providers.providers)) {
if (!provider.proxies) continue;
@@ -47,7 +47,7 @@ function followChain(startGroup: string, groupNowMap: Map<string, string>): stri
}
/**
- * Resolve active policy chains from Clash providers and rules data.
+ * Resolve active policy chains from Gateway providers and rules data.
*
* Uses the target proxy group name (rule.proxy) as the chain start,
* NOT the internal rule type+payload (e.g. "RuleSet,netflix").
@@ -55,8 +55,8 @@ function followChain(startGroup: string, groupNowMap: Map<string, string>): stri
* Multiple low-level rules can target the same proxy group, so we deduplicate.
*/
export function resolveActiveChains(
- providers: ClashProvidersResponse,
- rules: ClashRulesResponse
+ providers: GatewayProvidersResponse,
+ rules: GatewayRulesResponse
): ActiveChainInfo {
const groupNowMap = buildGroupNowMap(providers);
const activeNodeNames = new Set<string>();
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index c85521a..b0dfada 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -5,12 +5,10 @@ import type {
ProxyStats,
RuleStats,
CountryStats,
- HourlyStats,
- DailyStats,
TrafficTrendPoint,
ProxyTrafficStats,
DeviceStats,
-} from "@clashmaster/shared";
+} from "@neko-master/shared";
type RuntimeConfig = {
API_URL?: string;
@@ -43,7 +41,27 @@ const API_BASE = resolveApiBase();
const DETAIL_FETCH_LIMIT = 5000;
const inflightGetRequests = new Map<string, Promise<unknown>>();
-async function fetchJson<T>(url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET', body?: any): Promise<T> {
+class ApiError extends Error {
+ status: number;
+ url: string;
+
+ constructor(status: number, url: string) {
+ super(`API error: ${status}`);
+ this.name = "ApiError";
+ this.status = status;
+ this.url = url;
+ }
+}
+
+function isApiStatus(error: unknown, status: number): boolean {
+ return error instanceof ApiError && error.status === status;
+}
+
+async function fetchJson<T>(
+ url: string,
+ method: "GET" | "POST" | "PUT" | "DELETE" = "GET",
+ body?: unknown,
+): Promise<T> {
if (method === "GET") {
const inflight = inflightGetRequests.get(url);
if (inflight) {
@@ -67,8 +85,7 @@ async function fetchJson<T>(url: string, method: 'GET' | 'POST' | 'PUT' | 'DELET
const requestPromise = (async () => {
const res = await fetch(url, options);
if (!res.ok) {
- console.error(`[API] Error ${res.status}: ${url}`);
- throw new Error(`API error: ${res.status}`);
+ throw new ApiError(res.status, url);
}
return await res.json() as T;
})();
@@ -104,7 +121,7 @@ export interface Backend {
updated_at: string;
}
-export interface ClashProviderProxy {
+export interface GatewayProviderProxy {
alive: boolean;
name: string;
type: string;
@@ -113,27 +130,38 @@ export interface ClashProviderProxy {
history?: Array<{ time: string; delay: number }>;
}
-export interface ClashProvider {
+export interface GatewayProvider {
name: string;
type: string;
vehicleType: string;
- proxies: ClashProviderProxy[];
+ proxies: GatewayProviderProxy[];
}
-export interface ClashProvidersResponse {
- providers: Record<string, ClashProvider>;
+export interface GatewayProvidersResponse {
+ providers: Record<string, GatewayProvider>;
}
-export interface ClashRule {
+export interface GatewayRule {
type: string;
payload: string;
proxy: string;
}
-export interface ClashRulesResponse {
- rules: ClashRule[];
+export interface GatewayRulesResponse {
+ rules: GatewayRule[];
}
+const DEFAULT_DB_STATS = {
+ size: 0,
+ totalConnectionsCount: 0,
+} as const;
+
+const DEFAULT_RETENTION_CONFIG = {
+ connectionLogsDays: 7,
+ hourlyStatsDays: 30,
+ autoCleanup: true,
+} as const;
+
function buildUrl(base: string, params: Record<string, string | number | undefined>): string {
// Use simple URL construction for client-side relative URLs
const searchParams = new URLSearchParams();
@@ -157,16 +185,6 @@ export const api = {
})
),
- getGlobalSummary: () =>
- fetchJson<{
- totalConnections: number;
- totalUpload: number;
- totalDownload: number;
- uniqueDomains: number;
- uniqueIPs: number;
- backendCount: number;
- }>(`${API_BASE}/stats/global`),
-
getDomains: (backendId?: number, opts?: {
offset?: number; limit?: number;
sortBy?: string; sortOrder?: string; search?: string;
@@ -209,30 +227,6 @@ export const api = {
end: range?.end,
})),
- getRuleProxies: (backendId?: number) =>
- fetchJson<{ rule: string; proxies: string[] }[]>(
- buildUrl(`${API_BASE}/stats/rule-proxy-map`, { backendId })
- ),
-
- getHourly: (backendId?: number, hours = 24, range?: TimeRange) =>
- fetchJson<HourlyStats[]>(buildUrl(`${API_BASE}/stats/hourly`, {
- backendId,
- hours,
- start: range?.start,
- end: range?.end,
- })),
-
- getDaily: (backendId?: number, days = 7) =>
- fetchJson<DailyStats[]>(buildUrl(`${API_BASE}/stats/daily`, { backendId, days })),
-
- getTrafficTrend: (backendId?: number, minutes = 30, range?: TimeRange) =>
- fetchJson<TrafficTrendPoint[]>(buildUrl(`${API_BASE}/stats/trend`, {
- backendId,
- minutes,
- start: range?.start,
- end: range?.end,
- })),
-
getTrafficTrendAggregated: (backendId?: number, minutes = 30, bucketMinutes = 1, range?: TimeRange) =>
fetchJson<TrafficTrendPoint[]>(
buildUrl(`${API_BASE}/stats/trend/aggregated`, {
@@ -244,11 +238,6 @@ export const api = {
})
),
- getConnections: (backendId?: number, limit = 100) =>
- fetchJson<Array<{ id: number; domain: string; ip: string; chain: string; upload: number; download: number; timestamp: string }>>(
- buildUrl(`${API_BASE}/stats/connections`, { backendId, limit })
- ),
-
getDomainProxyStats: (
domain: string,
backendId?: number,
@@ -463,16 +452,6 @@ export const api = {
})
),
- getRuleChainFlow: (rule: string, backendId?: number, range?: TimeRange) =>
- fetchJson<{ nodes: Array<{ name: string; totalUpload: number; totalDownload: number; totalConnections: number }>; links: Array<{ source: number; target: number }> }>(
- buildUrl(`${API_BASE}/stats/rules/chain-flow`, {
- rule,
- backendId,
- start: range?.start,
- end: range?.end,
- })
- ),
-
getAllRuleChainFlows: (backendId?: number, range?: TimeRange) =>
fetchJson<{
nodes: Array<{ name: string; layer: number; nodeType: 'rule' | 'group' | 'proxy'; totalUpload: number; totalDownload: number; totalConnections: number; rules: string[] }>;
@@ -487,27 +466,16 @@ export const api = {
})
),
- getClashProviders: (backendId?: number) =>
- fetchJson<ClashProvidersResponse>(buildUrl(`${API_BASE}/clash/providers/proxies`, { backendId })),
-
- getClashRules: (backendId?: number) =>
- fetchJson<ClashRulesResponse>(buildUrl(`${API_BASE}/clash/rules`, { backendId })),
+ getGatewayProviders: (backendId?: number) =>
+ fetchJson<GatewayProvidersResponse>(buildUrl(`${API_BASE}/gateway/providers/proxies`, { backendId })),
- search: (q: string) =>
- fetchJson<DomainStats[]>(
- `${API_BASE}/search?q=${encodeURIComponent(q)}`
- ),
+ getGatewayRules: (backendId?: number) =>
+ fetchJson<GatewayRulesResponse>(buildUrl(`${API_BASE}/gateway/rules`, { backendId })),
// Backend management
getBackends: () =>
fetchJson<Backend[]>(`${API_BASE}/backends`),
- getActiveBackend: () =>
- fetchJson<Backend | { error: string }>(`${API_BASE}/backends/active`),
-
- getListeningBackends: () =>
- fetchJson<Backend[]>(`${API_BASE}/backends/listening`),
-
createBackend: (backend: { name: string; url: string; token?: string }) =>
fetchJson<{ id: number; isActive?: boolean; message: string }>(`${API_BASE}/backends`, 'POST', backend),
@@ -533,17 +501,32 @@ export const api = {
fetchJson<{ success: boolean; message: string }>(`${API_BASE}/backends/${id}/test`, 'POST'),
// Database management
- getDbStats: () =>
- fetchJson<{ size: number; totalConnectionsCount: number }>(`${API_BASE}/db/stats`),
+ getDbStats: async () => {
+ try {
+ return await fetchJson<{ size: number; totalConnectionsCount: number }>(`${API_BASE}/db/stats`);
+ } catch (error) {
+ if (isApiStatus(error, 404)) {
+ return { ...DEFAULT_DB_STATS };
+ }
+ throw error;
+ }
+ },
clearLogs: (days: number, backendId?: number) =>
fetchJson<{ message: string; deleted: number }>(`${API_BASE}/db/cleanup`, 'POST', { days, backendId }),
- vacuumDatabase: () =>
- fetchJson<{ message: string }>(`${API_BASE}/db/vacuum`, 'POST'),
-
- getRetentionConfig: () =>
- fetchJson<{ connectionLogsDays: number; hourlyStatsDays: number; autoCleanup: boolean }>(`${API_BASE}/db/retention`),
+ getRetentionConfig: async () => {
+ try {
+ return await fetchJson<{ connectionLogsDays: number; hourlyStatsDays: number; autoCleanup: boolean }>(
+ `${API_BASE}/db/retention`
+ );
+ } catch (error) {
+ if (isApiStatus(error, 404)) {
+ return { ...DEFAULT_RETENTION_CONFIG };
+ }
+ throw error;
+ }
+ },
updateRetentionConfig: (config: { connectionLogsDays: number; hourlyStatsDays: number; autoCleanup?: boolean }) =>
fetchJson<{ message: string }>(`${API_BASE}/db/retention`, 'PUT', config),
diff --git a/apps/web/lib/settings.ts b/apps/web/lib/settings.ts
index bad88c8..b21047b 100644
--- a/apps/web/lib/settings.ts
+++ b/apps/web/lib/settings.ts
@@ -12,7 +12,7 @@ const DEFAULT_SETTINGS: UserSettings = {
faviconProvider: "faviconim",
};
-const STORAGE_KEY = "clash-master-settings";
+const STORAGE_KEY = "neko-master-settings";
// Cached settings for sync access
let cachedSettings: UserSettings = DEFAULT_SETTINGS;
diff --git a/apps/web/lib/types/dashboard.ts b/apps/web/lib/types/dashboard.ts
new file mode 100644
index 0000000..8cf5ecd
--- /dev/null
+++ b/apps/web/lib/types/dashboard.ts
@@ -0,0 +1,21 @@
+export type TimePreset =
+ | "1m"
+ | "5m"
+ | "15m"
+ | "30m"
+ | "24h"
+ | "7d"
+ | "30d"
+ | "today"
+ | "custom";
+
+export type BackendStatus = "healthy" | "unhealthy" | "unknown";
+
+export type TabId =
+ | "overview"
+ | "domains"
+ | "countries"
+ | "devices"
+ | "proxies"
+ | "rules"
+ | "network";
diff --git a/apps/web/lib/websocket.ts b/apps/web/lib/websocket.ts
index 5df3c8d..48a7aef 100644
--- a/apps/web/lib/websocket.ts
+++ b/apps/web/lib/websocket.ts
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState, useCallback } from 'react';
-import type { StatsSummary } from '@clashmaster/shared';
+import type { StatsSummary } from '@neko-master/shared';
import type { TimeRange } from '@/lib/api';
export type ConnectionStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index 1283c6c..6055c11 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -1,7 +1,7 @@
{
"metadata": {
- "title": "Clash Master - Traffic Analytics",
- "description": "Real-time network traffic statistics and analytics"
+ "title": "Neko Master - Network Visualization",
+ "description": "Modern Network Traffic Analytics"
},
"nav": {
"overview": "Overview",
@@ -14,8 +14,8 @@
"settings": "Settings"
},
"header": {
- "title": "Clash Master",
- "subtitle": "Modern network visualization dashboard"
+ "title": "Neko Master",
+ "subtitle": "Modern Network Traffic Analytics"
},
"dashboard": {
"title": "Dashboard",
@@ -276,10 +276,10 @@
"about": {
"title": "About",
"version": "Version",
- "projectName": "Clash Master",
- "description": "Modern network visualization dashboard",
+ "projectName": "Neko Master",
+ "description": "Modern Network Traffic Analytics",
"github": "GitHub",
- "openSource": "Clash Master",
+ "openSource": "Neko Master",
"license": "MIT License",
"currentVersion": "Current Version",
"latestVersion": "Latest Version",
@@ -330,8 +330,8 @@
},
"backend": {
"title": "Settings",
- "firstTimeTitle": "Configure Clash Backend",
- "firstTimeDescription": "Enter your Clash connection information to start monitoring traffic",
+ "firstTimeTitle": "Configure Gateway Backend",
+ "firstTimeDescription": "Enter your gateway connection information to start monitoring traffic",
"description": "Manage backend connections and database",
"backendsTab": "Backends",
"databaseTab": "Database",
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index 0030316..d9e4014 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -1,7 +1,7 @@
{
"metadata": {
- "title": "Clash Master - 流量分析",
- "description": "实时网络流量统计与分析"
+ "title": "Neko Master - 流量分析",
+ "description": "现代网络流量分析平台"
},
"nav": {
"overview": "概览",
@@ -14,8 +14,8 @@
"settings": "设置"
},
"header": {
- "title": "Clash Master",
- "subtitle": "现代网络可视化分析面板"
+ "title": "Neko Master",
+ "subtitle": "现代网络流量分析平台"
},
"dashboard": {
"title": "仪表盘",
@@ -275,10 +275,10 @@
"about": {
"title": "关于",
"version": "版本",
- "projectName": "Clash Master",
- "description": "现代的网络可视化分析面板",
+ "projectName": "Neko Master",
+ "description": "现代网络流量分析平台",
"github": "GitHub",
- "openSource": "开源项目",
+ "openSource": "Neko Master",
"license": "MIT 许可证",
"currentVersion": "当前版本",
"latestVersion": "最新版本",
diff --git a/apps/web/package.json b/apps/web/package.json
index 8a19c15..44e3ecb 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -1,5 +1,5 @@
{
- "name": "@clashmaster/web",
+ "name": "@neko-master/web",
"version": "1.0.1",
"description": "A modern and elegant dashboard for network traffic visualization and analysis.",
"private": true,
@@ -10,7 +10,7 @@
"lint": "eslint"
},
"dependencies": {
- "@clashmaster/shared": "workspace:*",
+ "@neko-master/shared": "workspace:*",
"@ducanh2912/next-pwa": "^10.2.9",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-popover": "^1.1.15",
diff --git a/apps/web/public/clash-master.png b/apps/web/public/logo.png
similarity index 100%
rename from apps/web/public/clash-master.png
rename to apps/web/public/logo.png
diff --git a/apps/web/public/sw.js b/apps/web/public/sw.js
index c489527..00262dc 100644
--- a/apps/web/public/sw.js
+++ b/apps/web/public/sw.js
@@ -1,6 +1,6 @@
/// <reference lib="webworker" />
-const CACHE_NAME = "clash-master-v1";
+const CACHE_NAME = "neko-master-v1";
// Assets to pre-cache on install
const PRECACHE_ASSETS = ["/", "/manifest.webmanifest"];
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
index e83516c..8d112ba 100644
--- a/apps/web/tsconfig.json
+++ b/apps/web/tsconfig.json
@@ -37,6 +37,7 @@
"**/*.mts"
],
"exclude": [
- "node_modules"
+ "node_modules",
+ "components-backup"
]
}
diff --git a/assets/icon-clash-master.png b/assets/icon-neko-master.png
similarity index 100%
rename from assets/icon-clash-master.png
rename to assets/icon-neko-master.png
diff --git a/assets/clash-master-overview.png b/assets/neko-master-overview.png
similarity index 100%
rename from assets/clash-master-overview.png
rename to assets/neko-master-overview.png
diff --git a/assets/clash-master-regions.png b/assets/neko-master-regions.png
similarity index 100%
rename from assets/clash-master-regions.png
rename to assets/neko-master-regions.png
diff --git a/assets/clash-master-rules.png b/assets/neko-master-rules.png
similarity index 100%
rename from assets/clash-master-rules.png
rename to assets/neko-master-rules.png
diff --git a/assets/clash-master-setup.png b/assets/neko-master-setup.png
similarity index 100%
rename from assets/clash-master-setup.png
rename to assets/neko-master-setup.png
diff --git a/docker-compose.yml b/docker-compose.yml
index 42ea2b9..9b03a85 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,7 +1,7 @@
services:
- clash-master:
- image: foru17/clash-master:latest
- container_name: clash-master
+ neko-master:
+ image: foru17/neko-master:latest
+ container_name: neko-master
restart: unless-stopped
ports:
# 外部端口 : 内部端口
@@ -22,7 +22,7 @@ services:
- WS_EXTERNAL_PORT=${WS_EXTERNAL_PORT:-3002}
- DB_PATH=/app/data/stats.db
networks:
- - clash-master-network
+ - neko-master-network
# 健康检查
healthcheck:
test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:${API_PORT:-3001}/health || exit 1"]
@@ -32,5 +32,5 @@ services:
start_period: 40s
networks:
- clash-master-network:
+ neko-master-network:
driver: bridge
diff --git a/docker-start.sh b/docker-start.sh
index de13cc9..412be40 100755
--- a/docker-start.sh
+++ b/docker-start.sh
@@ -12,7 +12,7 @@ DB_PATH="${DB_PATH:-/app/data/stats.db}"
export API_PORT COLLECTOR_WS_PORT DB_PATH
echo "╔════════════════════════════════════════════════════════╗"
-echo "║ Clash Master - Starting... ║"
+echo "║ Neko Master - Starting... ║"
echo "╚════════════════════════════════════════════════════════╝"
echo
echo "📊 Web UI: http://0.0.0.0:${WEB_PORT}"
@@ -91,7 +91,7 @@ echo "════════════════════════
echo " ✅ All services started successfully!"
echo
echo " 📝 Access the dashboard at: http://<your-host>:${WEB_PORT}"
-echo " 🔧 Configure your OpenClash backend in the web UI"
+echo " 🔧 Configure your Gateway backend in the web UI"
echo "════════════════════════════════════════════════════════"
echo
diff --git a/package.json b/package.json
index d7716d4..44805f6 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
- "name": "clash-master",
- "version": "1.1.5",
- "description": "A modern and elegant dashboard for network traffic visualization and analysis.",
+ "name": "neko-master",
+ "version": "1.2.0",
+ "description": "Modern Network Traffic Analytics",
"private": true,
"workspaces": [
"apps/*",
@@ -11,7 +11,8 @@
"scripts": {
"build": "turbo build",
"dev": "turbo dev",
- "lint": "turbo lint"
+ "lint": "turbo lint",
+ "check:api-routes": "node scripts/check-api-routes.mjs"
},
"devDependencies": {
"turbo": "^2.8.0"
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 3d977bf..19e0568 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -1,5 +1,5 @@
{
- "name": "@clashmaster/shared",
+ "name": "@neko-master/shared",
"version": "1.0.0",
"type": "module",
"main": "./dist/index.js",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index b5eabe8..3f193fb 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -1,4 +1,4 @@
-// OpenClash Connection Metadata
+// Gateway Connection Metadata
export interface ConnectionMetadata {
network: string;
type: string;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c41b678..cec6cd1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -14,7 +14,7 @@ importers:
apps/collector:
dependencies:
- '@clashmaster/shared':
+ '@neko-master/shared':
specifier: workspace:*
version: link:../../packages/shared
'@fastify/cors':
@@ -51,7 +51,7 @@ importers:
apps/web:
dependencies:
- '@clashmaster/shared':
+ '@neko-master/shared':
specifier: workspace:*
version: link:../../packages/shared
'@ducanh2912/next-pwa':
diff --git a/scripts/check-api-routes.mjs b/scripts/check-api-routes.mjs
new file mode 100755
index 0000000..751cf30
--- /dev/null
+++ b/scripts/check-api-routes.mjs
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const ROOT = process.cwd();
+
+const FRONTEND_API_FILE = path.join(ROOT, 'apps/web/lib/api.ts');
+const BACKEND_SOURCES = [
+ { file: 'apps/collector/src/app.ts', prefix: '' },
+ { file: 'apps/collector/src/modules/stats/stats.controller.ts', prefix: '/api/stats' },
+ { file: 'apps/collector/src/modules/backend/backend.controller.ts', prefix: '/api/backends' },
+];
+
+function read(file) {
+ return fs.readFileSync(path.join(ROOT, file), 'utf8');
+}
+
+function normalizeRoute(route) {
+ return route
+ .replace(/\?.*$/, '')
+ .replace(/\$\{[^}]+\}/g, ':param')
+ .replace(/\/:[^/]+/g, '/:param')
+ .replace(/\/+/g, '/')
+ .replace(/\/$/, '');
+}
+
+function extractFrontendRoutes(code) {
+ const routes = new Set();
+ const routePattern = /\$\{API_BASE\}\/([^`]+)/g;
+
+ for (const match of code.matchAll(routePattern)) {
+ const raw = `/api/${match[1]}`;
+ routes.add(normalizeRoute(raw));
+ }
+
+ return routes;
+}
+
+function extractBackendRoutes(code, prefix) {
+ const routes = new Set();
+ const routePattern = /(?:app|fastify)\.(?:get|post|put|delete)(?:<[^>\n\r]*>)?\(\s*['"]([^'"]+)['"]/g;
+
+ for (const match of code.matchAll(routePattern)) {
+ const raw = `${prefix}${match[1]}`;
+ const normalized = normalizeRoute(raw);
+ if (normalized.startsWith('/api/')) {
+ routes.add(normalized);
+ }
+ }
+
+ return routes;
+}
+
+function main() {
+ const frontendCode = fs.readFileSync(FRONTEND_API_FILE, 'utf8');
+ const frontendRoutes = extractFrontendRoutes(frontendCode);
+
+ const backendRoutes = new Set();
+ for (const source of BACKEND_SOURCES) {
+ const code = read(source.file);
+ const routes = extractBackendRoutes(code, source.prefix);
+ for (const route of routes) {
+ backendRoutes.add(route);
+ }
+ }
+
+ const missing = [...frontendRoutes].filter((route) => !backendRoutes.has(route)).sort();
+ const extra = [...backendRoutes].filter((route) => !frontendRoutes.has(route)).sort();
+
+ console.log(`[api-routes] frontend routes: ${frontendRoutes.size}`);
+ console.log(`[api-routes] backend routes: ${backendRoutes.size}`);
+
+ if (missing.length > 0) {
+ console.error(`[api-routes] missing backend routes: ${missing.length}`);
+ for (const route of missing) {
+ console.error(` - ${route}`);
+ }
+ process.exit(1);
+ }
+
+ console.log('[api-routes] missing backend routes: 0');
+ console.log(`[api-routes] backend-only routes: ${extra.length}`);
+}
+
+main();
diff --git a/scripts/refactor-backend.sh b/scripts/refactor-backend.sh
new file mode 100644
index 0000000..02046f3
--- /dev/null
+++ b/scripts/refactor-backend.sh
@@ -0,0 +1,62 @@
+#!/bin/bash
+# 后端代码重构脚本
+# 此脚本协助将代码从旧结构迁移到新结构
+
+set -e
+
+echo "🚀 开始后端代码重构..."
+
+# 颜色定义
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+RED='\033[0;31m'
+NC='\033[0m' # No Color
+
+# ==================== 步骤 1: 备份原文件 ====================
+echo -e "${YELLOW}步骤 1: 备份原文件...${NC}"
+
+mkdir -p apps/collector/src/_legacy
+cp apps/collector/src/db.ts apps/collector/src/_legacy/db.ts.bak
+cp apps/collector/src/api.ts apps/collector/src/_legacy/api.ts.bak
+cp apps/collector/src/realtime.ts apps/collector/src/_legacy/realtime.ts.bak
+cp apps/collector/src/websocket.ts apps/collector/src/_legacy/websocket.ts.bak
+
+echo -e "${GREEN}✓ 备份完成${NC}"
+
+# ==================== 步骤 2: 创建基础数据库文件 ====================
+echo -e "${YELLOW}步骤 2: 创建基础数据库文件...${NC}"
+
+# 这些文件已经通过 create-new-structure.sh 创建了空文件
+# 现在需要填充基础内容
+
+echo -e "${GREEN}✓ 基础文件已创建${NC}"
+
+# ==================== 步骤 3: 提示下一步操作 ====================
+echo ""
+echo -e "${GREEN}============================================${NC}"
+echo -e "${GREEN} 目录结构和基础文件准备完成!${NC}"
+echo -e "${GREEN}============================================${NC}"
+echo ""
+echo "下一步手动操作:"
+echo ""
+echo "1. 迁移数据库连接层:"
+echo " - 查看 apps/collector/src/database/connection.ts (已创建)"
+echo " - 从 _legacy/db.ts.bak 提取表结构到 database/schema.ts"
+echo ""
+echo "2. 创建 Repository 基类:"
+echo " - 编辑 apps/collector/src/database/repositories/base.repository.ts"
+echo ""
+echo "3. 逐个迁移 Repository:"
+echo " - domain.repository.ts (从 db.ts 提取 domain 相关方法)"
+echo " - ip.repository.ts"
+echo " - backend.repository.ts"
+echo " - stats.repository.ts"
+echo " - device.repository.ts"
+echo " - ..."
+echo ""
+echo "4. 迁移完成后:"
+echo " - 更新 apps/collector/src/index.ts 使用新的模块"
+echo " - 删除旧的 db.ts"
+echo " - 运行测试验证"
+echo ""
+echo "详细指南参考: CODE_ORGANIZATION_REFACTOR.md"
diff --git a/setup.sh b/setup.sh
index c1b8b51..18dbe0b 100755
--- a/setup.sh
+++ b/setup.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Clash Master One-Click Setup Script
+# Neko Master One-Click Setup Script
# Automatically detects port conflicts and provides solutions
set -e
@@ -65,10 +65,10 @@ find_available_port() {
show_welcome() {
echo ""
echo "╔════════════════════════════════════════════════════════╗"
- echo "║ Clash Master - One-Click Setup ║"
+ echo "║ Neko Master - One-Click Setup ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""
- print_info "This script will help you quickly configure Clash Master"
+ print_info "This script will help you quickly configure Neko Master"
echo ""
}
@@ -158,7 +158,7 @@ create_env_file() {
cat > .env << EOF
# =============================================================================
-# Clash Master Environment Configuration
+# Neko Master Environment Configuration
# =============================================================================
# Generated at: $(date)
@@ -172,10 +172,10 @@ create_env_file() {
WEB_EXTERNAL_PORT=$WEB_PORT
# API port (default: 3001)
-API_EXTERNAL_PORT=$API_PORT
+# API_EXTERNAL_PORT=$API_PORT
# WebSocket port (default: 3002)
-WS_EXTERNAL_PORT=$WS_PORT
+# WS_EXTERNAL_PORT=$WS_PORT
# -----------------------------------------------------------------------------
# Advanced Configuration (Usually don't need to change)
@@ -236,7 +236,7 @@ ask_start() {
if [[ $start_now =~ ^[Yy]$ ]]; then
echo ""
- print_info "Starting Clash Master..."
+ print_info "Starting Neko Master..."
echo ""
if command -v docker-compose &> /dev/null; then
@@ -252,7 +252,7 @@ ask_start() {
echo " Then access: http://localhost:$WEB_PORT"
echo ""
echo " Common commands:"
- echo " View logs: docker logs -f clash-master"
+ echo " View logs: docker logs -f neko-master"
echo " Stop: docker compose down"
echo " Restart: docker compose restart"
echo ""
@@ -269,9 +269,9 @@ download_compose_file() {
if [ ! -f "docker-compose.yml" ]; then
print_info "Downloading docker-compose.yml..."
if command -v curl &> /dev/null; then
- curl -fsSL -o docker-compose.yml https://raw.githubusercontent.com/foru17/clash-master/main/docker-compose.yml
+ curl -fsSL -o docker-compose.yml https://raw.githubusercontent.com/foru17/neko-master/main/docker-compose.yml
elif command -v wget &> /dev/null; then
- wget -qO docker-compose.yml https://raw.githubusercontent.com/foru17/clash-master/main/docker-compose.yml
+ wget -qO docker-compose.yml https://raw.githubusercontent.com/foru17/neko-master/main/docker-compose.yml
else
print_error "Neither curl nor wget is available"
exit 1
diff --git a/start.sh b/start.sh
index 71c267d..a66c6d8 100755
--- a/start.sh
+++ b/start.sh
@@ -1,11 +1,11 @@
#!/bin/bash
-# Clash Master 启动脚本
+# Neko Master 启动脚本
set -e
echo "╔════════════════════════════════════════════════════════╗"
-echo "║ OpenClash Traffic Statistics System ║"
+echo "║ Neko Master Traffic Statistics System ║"
echo "╚════════════════════════════════════════════════════════╝"
echo
@@ -34,7 +34,7 @@ if [ ! -f "apps/collector/.env" ]; then
echo -e "${YELLOW}Warning: .env file not found in apps/collector/${NC}"
echo "Creating from template..."
cp apps/collector/.env.example apps/collector/.env
- echo -e "${YELLOW}Please edit apps/collector/.env with your OpenClash configuration${NC}"
+ echo -e "${YELLOW}Please edit apps/collector/.env with your Gateway configuration${NC}"
exit 1
fi