Skip to content

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

feat: Implement frontend runtime configuration for API and WebSocket URLs, update Docker port configuration, and refactor collector cleanup to use minute stats.

luolei5fc22b7eebb3
diff --git a/.env.example b/.env.example
index 1d9f463..6a385c9 100644
--- a/.env.example
+++ b/.env.example
@@ -22,6 +22,10 @@ API_EXTERNAL_PORT=3001
# WebSocket 端口 - 实时数据传输端口
WS_EXTERNAL_PORT=3002
+# 说明:
+# 上述外部端口会传入容器用于前端运行时配置。
+# 一般不需要修改容器内部端口(WEB_PORT/API_PORT/COLLECTOR_WS_PORT)。
+
# -----------------------------------------------------------------------------
# 高级配置(一般不需要修改)
# -----------------------------------------------------------------------------
diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml
index 5a55e0d..39e9489 100644
--- a/.github/workflows/docker-build.yml
+++ b/.github/workflows/docker-build.yml
@@ -82,4 +82,4 @@ jobs:
password: ${{ secrets.DOCKERHUB_TOKEN }}
repository: foru17/clash-master
readme-filepath: ./README.md
- short-description: "Modern and beautiful traffic analysis dashboard for OpenClash"
+ short-description: "Modern traffic analysis dashboard for Clash"
diff --git a/Dockerfile b/Dockerfile
index 008d54c..356e2ec 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -76,7 +76,7 @@ VOLUME ["/app/data"]
# Health check - verify API is responding
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
- CMD wget -q --spider http://127.0.0.1:3001/health || exit 1
+ CMD ["/bin/sh", "-c", "wget -q --spider http://127.0.0.1:${API_PORT}/health || exit 1"]
# Start script
COPY docker-start.sh ./
diff --git a/README.en.md b/README.en.md
index 285fddd..4ffb06e 100644
--- a/README.en.md
+++ b/README.en.md
@@ -72,8 +72,10 @@ services:
- ./data:/app/data
environment:
- NODE_ENV=production
- - API_PORT=3001
- - COLLECTOR_WS_PORT=3002
+ # External ports (optional; defaults are 3000/3001/3002)
+ - WEB_EXTERNAL_PORT=3000
+ - API_EXTERNAL_PORT=3001
+ - WS_EXTERNAL_PORT=3002
- DB_PATH=/app/data/stats.db
```
@@ -100,6 +102,9 @@ docker run -d \
Open <http://localhost:3000> to get started.
+> If you use custom external ports with `docker run`, also pass:
+> `-e WEB_EXTERNAL_PORT=8080 -e API_EXTERNAL_PORT=8081 -e WS_EXTERNAL_PORT=8082`
+
### Option 3: One-Click Script
Automatically detects port conflicts and configures everything:
@@ -181,10 +186,10 @@ ports:
- "8080:3000" # External 8080 → Internal 3000
- "8081:3001" # External 8081 → Internal 3001
- "8082:3002" # External 8082 → Internal 3002
-environment:
- - NEXT_PUBLIC_WS_PORT=8082 # Tell frontend to use 8082
```
+> Note: the frontend reads external ports at runtime, so `NEXT_PUBLIC_WS_PORT` is no longer required.
+
### Solution 3: Use One-Click Script
```bash
@@ -203,6 +208,9 @@ The script will automatically detect and suggest available ports.
| 3001 | API | ✅ | REST API port |
| 3002 | WebSocket | ✅ | Real-time data transmission |
+> Recommended: change **external ports only** (`WEB_EXTERNAL_PORT / API_EXTERNAL_PORT / WS_EXTERNAL_PORT`)
+> and keep internal ports at 3000/3001/3002. This avoids rebuilds and prevents `/api` 500 errors.
+
### Multi-Architecture Support
Docker images support both `linux/amd64` and `linux/arm64`.
diff --git a/README.md b/README.md
index 04822b5..22a0e9e 100644
--- a/README.md
+++ b/README.md
@@ -57,8 +57,10 @@ services:
- ./data:/app/data
environment:
- NODE_ENV=production
- - API_PORT=3001
- - COLLECTOR_WS_PORT=3002
+ # 外部端口(可选,默认即为 3000/3001/3002)
+ - WEB_EXTERNAL_PORT=3000
+ - API_EXTERNAL_PORT=3001
+ - WS_EXTERNAL_PORT=3002
- DB_PATH=/app/data/stats.db
```
@@ -85,6 +87,9 @@ docker run -d \
访问 <http://localhost:3000>
+> 如需自定义外部端口(docker run),请额外传入:
+> `-e WEB_EXTERNAL_PORT=8080 -e API_EXTERNAL_PORT=8081 -e WS_EXTERNAL_PORT=8082`
+
### 方式三:一键脚本
自动检测端口冲突并配置,适合不熟悉 Docker 的用户:
@@ -166,10 +171,10 @@ ports:
- "8080:3000" # 外部 8080 → 内部 3000
- "8081:3001" # 外部 8081 → 内部 3001
- "8082:3002" # 外部 8082 → 内部 3002
-environment:
- - NEXT_PUBLIC_WS_PORT=8082 # 告诉前端使用 8082
```
+> 说明:前端会在运行时读取外部端口配置,无需再设置 `NEXT_PUBLIC_WS_PORT`。
+
### 方案 3:使用一键脚本
```bash
@@ -188,6 +193,9 @@ curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh |
| 3001 | API 接口 | ✅ | REST API 端口 |
| 3002 | WebSocket | ✅ | 实时数据传输 |
+> 建议只修改 **外部端口**(`WEB_EXTERNAL_PORT / API_EXTERNAL_PORT / WS_EXTERNAL_PORT`),
+> 容器内部端口保持默认值(3000/3001/3002)。这样无需重新构建镜像,也不会出现 `/api` 500。
+
### 多架构支持
Docker 镜像同时支持 `linux/amd64` 和 `linux/arm64`。
diff --git a/apps/collector/.env.example b/apps/collector/.env.example
index 9dfe932..7319ede 100644
--- a/apps/collector/.env.example
+++ b/apps/collector/.env.example
@@ -5,7 +5,7 @@
# API_PORT=3001
# WebSocket 推送端口(默认 3002)
-# WS_PORT=3002
+# COLLECTOR_WS_PORT=3002
# SQLite 数据库路径(默认当前目录)
# DB_PATH=./stats.db
diff --git a/apps/collector/src/cleanup-service.ts b/apps/collector/src/cleanup-service.ts
index d5794e9..1ef6dfd 100644
--- a/apps/collector/src/cleanup-service.ts
+++ b/apps/collector/src/cleanup-service.ts
@@ -111,7 +111,7 @@ export class CleanupService {
}
/**
- * Clean up old connection logs
+ * Clean up old minute stats (replaced connection logs)
*/
private cleanupConnectionLogs(): number {
const config = this.getConfig();
@@ -119,7 +119,7 @@ export class CleanupService {
cutoffDate.setDate(cutoffDate.getDate() - config.connectionLogsDays);
const cutoff = cutoffDate.toISOString();
- return this.db.deleteOldConnectionLogs(cutoff);
+ return this.db.deleteOldMinuteStats(cutoff);
}
/**
diff --git a/apps/collector/src/collector.ts b/apps/collector/src/collector.ts
index 700f62b..86626d2 100644
--- a/apps/collector/src/collector.ts
+++ b/apps/collector/src/collector.ts
@@ -229,7 +229,7 @@ export function createCollector(
let lastBroadcastTime = 0;
const broadcastThrottleMs = 500;
let flushInterval: NodeJS.Timeout | null = null;
- const FLUSH_INTERVAL_MS = parseInt(process.env.FLUSH_INTERVAL_MS || '2000');
+ const FLUSH_INTERVAL_MS = parseInt(process.env.FLUSH_INTERVAL_MS || '5000');
// Start batch flush interval
flushInterval = setInterval(() => {
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index b4a9f40..f7538ad 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -197,6 +197,52 @@ export class StatsDatabase {
);
`);
+ // Minute-level traffic aggregation (replaces connection_logs for trend queries)
+ this.db.exec(`
+ 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
+ );
+ `);
+
+ // Domain×proxy traffic aggregation (replaces connection_logs domain+chain GROUP BY)
+ this.db.exec(`
+ 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
+ );
+ `);
+ this.db.exec(`CREATE INDEX IF NOT EXISTS idx_domain_proxy_chain ON domain_proxy_stats(backend_id, chain);`);
+
+ // IP×proxy traffic aggregation (replaces connection_logs ip+chain GROUP BY)
+ this.db.exec(`
+ 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
+ );
+ `);
+ this.db.exec(`CREATE INDEX IF NOT EXISTS idx_ip_proxy_chain ON ip_proxy_stats(backend_id, chain);`);
+
// Rule-specific cross-reference tables for accurate per-rule traffic
this.db.exec(`
CREATE TABLE IF NOT EXISTS rule_chain_traffic (
@@ -335,6 +381,86 @@ export class StatsDatabase {
console.log('[DB] Adding chains column to ip_stats...');
this.db.exec(`ALTER TABLE ip_stats ADD COLUMN chains TEXT;`);
}
+
+ // Check if ip_stats has rules column (added for per-rule IP traffic)
+ const ipStatsInfo2 = this.db.prepare(`PRAGMA table_info(ip_stats)`).all() as { name: string }[];
+ const hasIPRules = ipStatsInfo2.some(col => col.name === 'rules');
+
+ if (!hasIPRules) {
+ console.log('[DB] Adding rules column to ip_stats...');
+ this.db.exec(`ALTER TABLE ip_stats ADD COLUMN rules TEXT;`);
+ }
+
+ // Check if domain_stats has rules column
+ const domainStatsInfo = this.db.prepare(`PRAGMA table_info(domain_stats)`).all() as { name: string }[];
+ const hasDomainRules = domainStatsInfo.some(col => col.name === 'rules');
+
+ if (!hasDomainRules) {
+ console.log('[DB] Adding rules column to domain_stats...');
+ this.db.exec(`ALTER TABLE domain_stats ADD COLUMN rules TEXT;`);
+ }
+
+ // Check if domain_stats has chains column
+ const hasDomainChains = domainStatsInfo.some(col => col.name === 'chains');
+
+ if (!hasDomainChains) {
+ console.log('[DB] Adding chains column to domain_stats...');
+ this.db.exec(`ALTER TABLE domain_stats ADD COLUMN chains TEXT;`);
+ }
+
+ // Migrate connection_logs data to new aggregation tables (one-time backfill)
+ this.migrateConnectionLogsToAggregation();
+ }
+
+ // Backfill minute_stats, domain_proxy_stats, ip_proxy_stats from connection_logs
+ private migrateConnectionLogsToAggregation() {
+ // Check if minute_stats is empty and connection_logs has data
+ const minuteCount = (this.db.prepare(`SELECT COUNT(*) as c FROM minute_stats`).get() as { c: number }).c;
+ const logCount = (this.db.prepare(`SELECT COUNT(*) as c FROM connection_logs`).get() as { c: number }).c;
+
+ if (minuteCount > 0 || logCount === 0) return;
+
+ console.log(`[DB] Migrating ${logCount} connection_logs rows to aggregation tables...`);
+
+ try {
+ this.db.exec(`BEGIN TRANSACTION`);
+
+ // Backfill minute_stats
+ this.db.exec(`
+ INSERT INTO minute_stats (backend_id, minute, upload, download, connections)
+ SELECT backend_id,
+ strftime('%Y-%m-%dT%H:%M:00', timestamp) as minute,
+ SUM(upload), SUM(download), COUNT(*)
+ FROM connection_logs
+ GROUP BY backend_id, strftime('%Y-%m-%dT%H:%M:00', timestamp)
+ `);
+
+ // Backfill domain_proxy_stats
+ this.db.exec(`
+ INSERT INTO domain_proxy_stats (backend_id, domain, chain, total_upload, total_download, total_connections, last_seen)
+ SELECT backend_id, domain, chain,
+ SUM(upload), SUM(download), COUNT(*), MAX(timestamp)
+ FROM connection_logs
+ WHERE domain IS NOT NULL AND domain != 'unknown'
+ GROUP BY backend_id, domain, chain
+ `);
+
+ // Backfill ip_proxy_stats
+ this.db.exec(`
+ INSERT INTO ip_proxy_stats (backend_id, ip, chain, total_upload, total_download, total_connections, last_seen, domains)
+ SELECT backend_id, ip, chain,
+ SUM(upload), SUM(download), COUNT(*), MAX(timestamp),
+ GROUP_CONCAT(DISTINCT CASE WHEN domain IS NOT NULL AND domain != 'unknown' THEN domain END)
+ FROM connection_logs
+ GROUP BY backend_id, ip, chain
+ `);
+
+ this.db.exec(`COMMIT`);
+ console.log('[DB] Migration to aggregation tables completed successfully');
+ } catch (error) {
+ this.db.exec(`ROLLBACK`);
+ console.error('[DB] Migration to aggregation tables failed:', error);
+ }
}
private performMigration() {
@@ -759,18 +885,63 @@ export class StatsDatabase {
`);
hourlyStmt.run({ backendId, hour, upload: update.upload, download: update.download });
- // Insert connection log with backend_id
- const logStmt = this.db.prepare(`
- INSERT INTO connection_logs (backend_id, domain, ip, chain, upload, download)
- VALUES (@backendId, @domain, @ip, @chain, @upload, @download)
+ // UPSERT minute_stats
+ const minute = timestamp.slice(0, 16) + ':00'; // 'YYYY-MM-DDTHH:MM:00'
+ const minuteStmt = this.db.prepare(`
+ INSERT INTO minute_stats (backend_id, minute, upload, download, connections)
+ VALUES (@backendId, @minute, @upload, @download, 1)
+ ON CONFLICT(backend_id, minute) DO UPDATE SET
+ upload = upload + @upload,
+ download = download + @download,
+ connections = connections + 1
+ `);
+ minuteStmt.run({ backendId, minute, upload: update.upload, download: update.download });
+
+ // UPSERT domain_proxy_stats (only when domain is known)
+ if (domainName !== 'unknown') {
+ const domainProxyStmt = this.db.prepare(`
+ INSERT INTO domain_proxy_stats (backend_id, domain, chain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @domain, @chain, @upload, @download, 1, @timestamp)
+ ON CONFLICT(backend_id, domain, chain) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + 1,
+ last_seen = @timestamp
+ `);
+ domainProxyStmt.run({
+ backendId,
+ domain: domainName,
+ chain: update.chain,
+ upload: update.upload,
+ download: update.download,
+ timestamp
+ });
+ }
+
+ // UPSERT ip_proxy_stats
+ const ipProxyStmt = this.db.prepare(`
+ INSERT INTO ip_proxy_stats (backend_id, ip, chain, total_upload, total_download, total_connections, last_seen, domains)
+ VALUES (@backendId, @ip, @chain, @upload, @download, 1, @timestamp, @domain)
+ ON CONFLICT(backend_id, ip, chain) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + 1,
+ last_seen = @timestamp,
+ domains = CASE
+ WHEN ip_proxy_stats.domains IS NULL THEN @domain
+ WHEN @domain = 'unknown' THEN ip_proxy_stats.domains
+ WHEN INSTR(ip_proxy_stats.domains, @domain) > 0 THEN ip_proxy_stats.domains
+ ELSE ip_proxy_stats.domains || ',' || @domain
+ END
`);
- logStmt.run({
+ ipProxyStmt.run({
backendId,
- domain: update.domain || 'unknown',
ip: update.ip,
chain: update.chain,
upload: update.upload,
- download: update.download
+ download: update.download,
+ timestamp,
+ domain: update.domain || 'unknown'
});
});
@@ -794,6 +965,9 @@ export class StatsDatabase {
const ruleChainMap = new Map<string, { rule: string; chain: string; upload: number; download: number; count: number }>();
const ruleDomainMap = new Map<string, { rule: string; domain: string; upload: number; download: number; count: number }>();
const ruleIPMap = new Map<string, { rule: string; ip: string; upload: number; download: number; count: number }>();
+ const minuteMap = new Map<string, { upload: number; download: number; connections: number }>();
+ const domainProxyMap = new Map<string, { domain: string; chain: string; upload: number; download: number; count: number }>();
+ const ipProxyMap = new Map<string, { ip: string; chain: string; upload: number; download: number; count: number; domains: Set<string> }>();
for (const update of updates) {
if (update.upload === 0 && update.download === 0) continue;
@@ -905,6 +1079,49 @@ export class StatsDatabase {
} else {
ruleIPMap.set(ruleIPKey, { rule: ruleName, ip: update.ip, upload: update.upload, download: update.download, count: 1 });
}
+
+ // Aggregate minute_stats
+ const minute = timestamp.slice(0, 16) + ':00'; // 'YYYY-MM-DDTHH:MM:00'
+ const existingMinute = minuteMap.get(minute);
+ if (existingMinute) {
+ existingMinute.upload += update.upload;
+ existingMinute.download += update.download;
+ existingMinute.connections++;
+ } else {
+ minuteMap.set(minute, { upload: update.upload, download: update.download, connections: 1 });
+ }
+
+ // Aggregate domain_proxy_stats (only when domain exists)
+ const proxyChain = update.chain;
+ if (update.domain) {
+ const dpKey = `${update.domain}:${proxyChain}`;
+ const existingDP = domainProxyMap.get(dpKey);
+ if (existingDP) {
+ existingDP.upload += update.upload;
+ existingDP.download += update.download;
+ existingDP.count++;
+ } else {
+ domainProxyMap.set(dpKey, { domain: update.domain, chain: proxyChain, upload: update.upload, download: update.download, count: 1 });
+ }
+ }
+
+ // Aggregate ip_proxy_stats
+ const ipPKey = `${update.ip}:${proxyChain}`;
+ const existingIPP = ipProxyMap.get(ipPKey);
+ if (existingIPP) {
+ existingIPP.upload += update.upload;
+ existingIPP.download += update.download;
+ existingIPP.count++;
+ if (update.domain && update.domain !== 'unknown') {
+ existingIPP.domains.add(update.domain);
+ }
+ } else {
+ const domains = new Set<string>();
+ if (update.domain && update.domain !== 'unknown') {
+ domains.add(update.domain);
+ }
+ ipProxyMap.set(ipPKey, { ip: update.ip, chain: proxyChain, upload: update.upload, download: update.download, count: 1, domains });
+ }
}
// Execute batch upserts in a single transaction
@@ -1144,53 +1361,90 @@ export class StatsDatabase {
});
}
- // Batch insert into connection_logs for detailed analytics
- // All records are preserved for accuracy
- const logStmt = this.db.prepare(`
- INSERT INTO connection_logs (backend_id, domain, ip, chain, upload, download)
- VALUES (@backendId, @domain, @ip, @chain, @upload, @download)
+ // UPSERT minute_stats
+ const minuteStmt = this.db.prepare(`
+ INSERT INTO minute_stats (backend_id, minute, upload, download, connections)
+ VALUES (@backendId, @minute, @upload, @download, @connections)
+ ON CONFLICT(backend_id, minute) DO UPDATE SET
+ upload = upload + @upload,
+ download = download + @download,
+ connections = connections + @connections
`);
- for (const [key, data] of domainMap) {
- logStmt.run({
+ for (const [minute, data] of minuteMap) {
+ minuteStmt.run({
backendId,
- domain: data.domain || 'unknown',
- ip: data.ip,
- chain: data.chain,
+ minute,
upload: data.upload,
- download: data.download
+ download: data.download,
+ connections: data.connections
});
}
- });
- transaction();
- }
+ // UPSERT domain_proxy_stats
+ const domainProxyStmt = this.db.prepare(`
+ INSERT INTO domain_proxy_stats (backend_id, domain, chain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @domain, @chain, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, domain, chain) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp
+ `);
- // Batch insert connection logs (for optimized bulk writing)
- batchInsertConnectionLogs(backendId: number, logs: Array<{
- domain: string;
- ip: string;
- chain: string;
- upload: number;
- download: number;
- }>): void {
- if (logs.length === 0) return;
+ for (const [key, data] of domainProxyMap) {
+ domainProxyStmt.run({
+ backendId,
+ domain: data.domain,
+ chain: data.chain,
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp
+ });
+ }
- const stmt = this.db.prepare(`
- INSERT INTO connection_logs (backend_id, domain, ip, chain, upload, download)
- VALUES (@backendId, @domain, @ip, @chain, @upload, @download)
- `);
+ // UPSERT ip_proxy_stats (traffic only; domains are updated separately with dedupe)
+ const ipProxyStmt = this.db.prepare(`
+ INSERT INTO ip_proxy_stats (backend_id, ip, chain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @ip, @chain, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, ip, chain) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp
+ `);
+ const ipProxyDomainStmt = this.db.prepare(`
+ UPDATE ip_proxy_stats
+ SET domains = CASE
+ WHEN domains IS NULL OR domains = '' THEN @domain
+ WHEN INSTR(',' || domains || ',', ',' || @domain || ',') > 0 THEN domains
+ ELSE domains || ',' || @domain
+ END
+ WHERE backend_id = @backendId AND ip = @ip AND chain = @chain
+ `);
- const transaction = this.db.transaction(() => {
- for (const log of logs) {
- stmt.run({
+ for (const [key, data] of ipProxyMap) {
+ ipProxyStmt.run({
backendId,
- domain: log.domain || 'unknown',
- ip: log.ip,
- chain: log.chain,
- upload: log.upload,
- download: log.download,
+ ip: data.ip,
+ chain: data.chain,
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp
});
+
+ if (data.domains.size > 0) {
+ for (const domain of data.domains) {
+ ipProxyDomainStmt.run({
+ backendId,
+ ip: data.ip,
+ chain: data.chain,
+ domain
+ });
+ }
+ }
}
});
@@ -1257,9 +1511,10 @@ export class StatsDatabase {
// Get IP stats for specific IPs (used for domain IP details)
getIPStatsByIPs(backendId: number, ips: string[]): IPStats[] {
- if (ips.length === 0) return [];
+ const filteredIps = ips.filter(ip => ip && ip.trim() !== '');
+ if (filteredIps.length === 0) return [];
- const placeholders = ips.map(() => '?').join(',');
+ const placeholders = filteredIps.map(() => '?').join(',');
const stmt = this.db.prepare(`
SELECT
i.ip,
@@ -1288,7 +1543,7 @@ export class StatsDatabase {
WHERE i.backend_id = ? AND i.ip IN (${placeholders})
ORDER BY (i.total_upload + i.total_download) DESC
`);
- const rows = stmt.all(backendId, ...ips) as Array<{
+ const rows = stmt.all(backendId, ...filteredIps) as Array<{
ip: string;
domains: string;
totalUpload: number;
@@ -1336,7 +1591,7 @@ export class StatsDatabase {
i.chains
FROM ip_stats i
LEFT JOIN geoip_cache g ON i.ip = g.ip
- WHERE i.backend_id = ?
+ WHERE i.backend_id = ? AND i.ip != ''
ORDER BY (i.total_upload + i.total_download) DESC
LIMIT ?
`);
@@ -1386,37 +1641,46 @@ export class StatsDatabase {
// Get traffic trend for a specific backend (for time range selection)
getTrafficTrend(backendId: number, minutes = 30): Array<{ time: string; upload: number; download: number }> {
- const cutoff = new Date(Date.now() - minutes * 60 * 1000).toISOString();
+ const cutoff = new Date(Date.now() - minutes * 60 * 1000);
+ const cutoffStr = cutoff.toISOString().slice(0, 16) + ':00';
const stmt = this.db.prepare(`
- SELECT strftime('%Y-%m-%dT%H:%M:%S', timestamp) as time, upload, download
- FROM connection_logs
- WHERE backend_id = ? AND datetime(timestamp) > datetime(?)
- ORDER BY timestamp ASC
+ SELECT minute as time, upload, download
+ FROM minute_stats
+ WHERE backend_id = ? AND minute >= ?
+ ORDER BY minute ASC
`);
- return stmt.all(backendId, cutoff) as Array<{ time: string; upload: number; download: number }>;
+ return stmt.all(backendId, cutoffStr) as Array<{ time: string; upload: number; download: number }>;
}
// Get traffic trend aggregated by time buckets for chart display
getTrafficTrendAggregated(backendId: number, minutes = 30, bucketMinutes = 1): Array<{ time: string; upload: number; download: number }> {
- const cutoff = new Date(Date.now() - minutes * 60 * 1000).toISOString();
-
- // SQLite datetime formatting for bucketing
- // Use strftime to bucket by minute intervals
- const bucketExpr = bucketMinutes === 1
- ? `strftime('%Y-%m-%dT%H:%M:00', datetime(timestamp))`
- : `strftime('%Y-%m-%dT%H:%M:00', datetime((strftime('%s', datetime(timestamp)) / ${bucketMinutes * 60}) * ${bucketMinutes * 60}, 'unixepoch'))`;
+ const cutoff = new Date(Date.now() - minutes * 60 * 1000);
+ const cutoffStr = cutoff.toISOString().slice(0, 16) + ':00';
+
+ if (bucketMinutes <= 1) {
+ // Direct query - each row is already 1-minute granularity
+ const stmt = this.db.prepare(`
+ SELECT minute as time, upload, download
+ FROM minute_stats
+ WHERE backend_id = ? AND minute >= ?
+ ORDER BY minute ASC
+ `);
+ return stmt.all(backendId, cutoffStr) as Array<{ time: string; upload: number; download: number }>;
+ }
+ // Aggregate multiple minutes into larger buckets
+ const bucketExpr = `strftime('%Y-%m-%dT%H:%M:00', datetime((strftime('%s', datetime(minute)) / ${bucketMinutes * 60}) * ${bucketMinutes * 60}, 'unixepoch'))`;
const stmt = this.db.prepare(`
- SELECT
+ SELECT
${bucketExpr} as time,
SUM(upload) as upload,
SUM(download) as download
- FROM connection_logs
- WHERE backend_id = ? AND datetime(timestamp) > datetime(?)
+ FROM minute_stats
+ WHERE backend_id = ? AND minute >= ?
GROUP BY ${bucketExpr}
ORDER BY time ASC
`);
- return stmt.all(backendId, cutoff) as Array<{ time: string; upload: number; download: number }>;
+ return stmt.all(backendId, cutoffStr) as Array<{ time: string; upload: number; download: number }>;
}
// Get country stats for a specific backend
@@ -1567,8 +1831,8 @@ export class StatsDatabase {
const sortColumn = sortColumnMap[opts.sortBy || 'totalDownload'] || 'i.total_download';
const whereClause = search
- ? 'WHERE i.backend_id = ? AND (i.ip LIKE ? OR i.domains LIKE ?)'
- : 'WHERE i.backend_id = ?';
+ ? "WHERE i.backend_id = ? AND i.ip != '' AND (i.ip LIKE ? OR i.domains LIKE ?)"
+ : "WHERE i.backend_id = ? AND i.ip != ''";
const params: any[] = search
? [backendId, `%${search}%`, `%${search}%`]
: [backendId];
@@ -1760,14 +2024,13 @@ export class StatsDatabase {
// Get summary stats for a specific backend
getSummary(backendId: number): { totalConnections: number; totalUpload: number; totalDownload: number; uniqueDomains: number; uniqueIPs: number } {
- // Calculate totals from domain_stats (aggregated data) instead of connection_logs
- // This is more efficient and works with batch writing
+ // 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 domain_stats
+ FROM ip_stats
WHERE backend_id = ?
`);
const { connections, upload, download } = trafficStmt.get(backendId) as {
@@ -1798,14 +2061,13 @@ export class StatsDatabase {
// Get per-proxy traffic breakdown for a specific domain
getDomainProxyStats(backendId: number, domain: string): ProxyTrafficStats[] {
const stmt = this.db.prepare(`
- SELECT chain,
- SUM(upload) as totalUpload,
- SUM(download) as totalDownload,
- COUNT(*) as totalConnections
- FROM connection_logs
+ SELECT chain,
+ total_upload as totalUpload,
+ total_download as totalDownload,
+ total_connections as totalConnections
+ FROM domain_proxy_stats
WHERE backend_id = ? AND domain = ?
- GROUP BY chain
- ORDER BY (SUM(upload) + SUM(download)) DESC
+ ORDER BY (total_upload + total_download) DESC
`);
return stmt.all(backendId, domain) as ProxyTrafficStats[];
}
@@ -1813,33 +2075,31 @@ export class StatsDatabase {
// Get per-proxy traffic breakdown for a specific IP
getIPProxyStats(backendId: number, ip: string): ProxyTrafficStats[] {
const stmt = this.db.prepare(`
- SELECT chain,
- SUM(upload) as totalUpload,
- SUM(download) as totalDownload,
- COUNT(*) as totalConnections
- FROM connection_logs
+ SELECT chain,
+ total_upload as totalUpload,
+ total_download as totalDownload,
+ total_connections as totalConnections
+ FROM ip_proxy_stats
WHERE backend_id = ? AND ip = ?
- GROUP BY chain
- ORDER BY (SUM(upload) + SUM(download)) DESC
+ ORDER BY (total_upload + total_download) DESC
`);
return stmt.all(backendId, ip) as ProxyTrafficStats[];
}
// Get domains for a specific proxy/node
getProxyDomains(backendId: number, chain: string, limit = 50): DomainStats[] {
- // First get domains from connection_logs
const stmt = this.db.prepare(`
- SELECT
- domain,
- SUM(upload) as totalUpload,
- SUM(download) as totalDownload,
- COUNT(*) as totalConnections,
- MAX(timestamp) as lastSeen,
- GROUP_CONCAT(DISTINCT ip) as ips
- FROM connection_logs
- WHERE backend_id = ? AND chain = ? AND domain IS NOT NULL AND domain != 'unknown'
- GROUP BY domain
- ORDER BY (SUM(upload) + SUM(download)) DESC
+ 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 = ?
+ ORDER BY (dps.total_upload + dps.total_download) DESC
LIMIT ?
`);
const rows = stmt.all(backendId, chain, limit) as Array<{
@@ -1850,7 +2110,7 @@ export class StatsDatabase {
lastSeen: string;
ips: string | null;
}>;
-
+
return rows.map(row => ({
...row,
ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
@@ -1861,19 +2121,17 @@ export class StatsDatabase {
// Get IPs for a specific proxy/node
getProxyIPs(backendId: number, chain: string, limit = 50): IPStats[] {
- // First get IPs from connection_logs
const stmt = this.db.prepare(`
- SELECT
- ip,
- SUM(upload) as totalUpload,
- SUM(download) as totalDownload,
- COUNT(*) as totalConnections,
- MAX(timestamp) as lastSeen,
- GROUP_CONCAT(DISTINCT domain) as domains
- FROM connection_logs
- WHERE backend_id = ? AND chain = ?
- GROUP BY ip
- ORDER BY (SUM(upload) + SUM(download)) DESC
+ SELECT
+ ips.ip,
+ ips.total_upload as totalUpload,
+ ips.total_download as totalDownload,
+ ips.total_connections as totalConnections,
+ ips.last_seen as lastSeen,
+ ips.domains
+ FROM ip_proxy_stats ips
+ WHERE ips.backend_id = ? AND ips.chain = ? AND ips.ip != ''
+ ORDER BY (ips.total_upload + ips.total_download) DESC
LIMIT ?
`);
const rows = stmt.all(backendId, chain, limit) as Array<{
@@ -1884,26 +2142,26 @@ export class StatsDatabase {
lastSeen: string;
domains: string | null;
}>;
-
+
// Get geoIP info for each IP
- const ipList = rows.map(r => r.ip);
+ const ipList = rows.map(r => r.ip).filter(ip => ip && ip.trim() !== '');
if (ipList.length === 0) {
return [];
}
-
+
const placeholders = ipList.map(() => '?').join(',');
const geoStmt = this.db.prepare(`
- SELECT
+ SELECT
ip,
- CASE
- WHEN country IS NOT NULL THEN
+ CASE
+ WHEN country IS NOT NULL THEN
json_array(
country,
COALESCE(country_name, country),
COALESCE(city, ''),
COALESCE(as_name, '')
)
- ELSE
+ ELSE
NULL
END as geoIP
FROM geoip_cache
@@ -1913,9 +2171,9 @@ export class StatsDatabase {
ip: string;
geoIP: string | null;
}>;
-
+
const geoMap = new Map(geoRows.map(r => [r.ip, r.geoIP]));
-
+
return rows.map(row => ({
...row,
domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
@@ -2228,15 +2486,9 @@ export class StatsDatabase {
}
// Get recent connections for a specific backend
+ // Returns empty array - connection_logs is no longer written to (replaced by aggregation tables)
getRecentConnections(backendId: number, limit = 100): Connection[] {
- const stmt = this.db.prepare(`
- SELECT id, domain, ip, chain, upload, download, timestamp
- FROM connection_logs
- WHERE backend_id = ?
- ORDER BY timestamp DESC
- LIMIT ?
- `);
- return stmt.all(backendId, limit) as Connection[];
+ return [];
}
// Clean old data for a specific backend (or all backends if backendId is null)
@@ -2253,10 +2505,11 @@ export class StatsDatabase {
// Clean specific backend
if (days === 0) {
// Clear all data for this backend
- const connectionsStmt = this.db.prepare(`DELETE FROM connection_logs WHERE backend_id = ?`);
- const result = connectionsStmt.run(backendId);
- deletedConnections = result.changes;
- deletedLogs = result.changes;
+ const minuteResult = this.db.prepare(`DELETE FROM minute_stats WHERE backend_id = ?`).run(backendId);
+ deletedConnections = minuteResult.changes;
+ deletedLogs = minuteResult.changes;
+ // Also clean old connection_logs if any remain from before migration
+ this.db.prepare(`DELETE FROM connection_logs WHERE backend_id = ?`).run(backendId);
// Clear stats tables
const domainsStmt = this.db.prepare(`DELETE FROM domain_stats WHERE backend_id = ?`);
@@ -2271,26 +2524,39 @@ export class StatsDatabase {
const rulesStmt = this.db.prepare(`DELETE FROM rule_stats WHERE backend_id = ?`);
deletedRules = rulesStmt.run(backendId).changes;
+ // Clear country stats (Regions)
+ this.db.prepare(`DELETE FROM country_stats WHERE backend_id = ?`).run(backendId);
+
+ // Clear rule to proxy mapping
+ this.db.prepare(`DELETE FROM rule_proxy_map WHERE backend_id = ?`).run(backendId);
+
// Clear rule cross-reference tables
this.db.prepare(`DELETE FROM rule_chain_traffic WHERE backend_id = ?`).run(backendId);
this.db.prepare(`DELETE FROM rule_domain_traffic WHERE backend_id = ?`).run(backendId);
this.db.prepare(`DELETE FROM rule_ip_traffic WHERE backend_id = ?`).run(backendId);
+
+ // Clear new aggregation tables
+ this.db.prepare(`DELETE FROM domain_proxy_stats WHERE backend_id = ?`).run(backendId);
+ this.db.prepare(`DELETE FROM ip_proxy_stats WHERE backend_id = ?`).run(backendId);
} else {
- const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
- const connectionsStmt = this.db.prepare(`DELETE FROM connection_logs WHERE backend_id = ? AND timestamp < ?`);
- const result = connectionsStmt.run(backendId, cutoff);
- deletedConnections = result.changes;
- deletedLogs = result.changes;
- // For partial cleanup, we keep the stats tables as they are aggregated data
+ const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
+ const minuteCutoff = cutoff.toISOString().slice(0, 16) + ':00';
+ const minuteResult = this.db.prepare(`DELETE FROM minute_stats WHERE backend_id = ? AND minute < ?`).run(backendId, minuteCutoff);
+ deletedConnections = minuteResult.changes;
+ deletedLogs = minuteResult.changes;
+ // Also clean old connection_logs if any remain
+ this.db.prepare(`DELETE FROM connection_logs WHERE backend_id = ? AND timestamp < ?`).run(backendId, cutoff.toISOString());
+ // domain_proxy_stats and ip_proxy_stats are permanent aggregation tables (no time-based cleanup)
}
} else {
// Clean all backends
if (days === 0) {
// Clear all data
- const connectionsStmt = this.db.prepare(`DELETE FROM connection_logs`);
- const result = connectionsStmt.run();
- deletedConnections = result.changes;
- deletedLogs = result.changes;
+ const minuteResult = this.db.prepare(`DELETE FROM minute_stats`).run();
+ deletedConnections = minuteResult.changes;
+ deletedLogs = minuteResult.changes;
+ // Also clean old connection_logs if any remain
+ this.db.prepare(`DELETE FROM connection_logs`).run();
// Clear all stats tables
const domainsStmt = this.db.prepare(`DELETE FROM domain_stats`);
@@ -2305,17 +2571,29 @@ export class StatsDatabase {
const rulesStmt = this.db.prepare(`DELETE FROM rule_stats`);
deletedRules = rulesStmt.run().changes;
+ // Clear country stats (Regions)
+ this.db.prepare(`DELETE FROM country_stats`).run();
+
+ // Clear rule to proxy mapping
+ this.db.prepare(`DELETE FROM rule_proxy_map`).run();
+
// Clear rule cross-reference tables
this.db.prepare(`DELETE FROM rule_chain_traffic`).run();
this.db.prepare(`DELETE FROM rule_domain_traffic`).run();
this.db.prepare(`DELETE FROM rule_ip_traffic`).run();
+
+ // Clear new aggregation tables
+ this.db.prepare(`DELETE FROM domain_proxy_stats`).run();
+ this.db.prepare(`DELETE FROM ip_proxy_stats`).run();
} else {
- const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
- const connectionsStmt = this.db.prepare(`DELETE FROM connection_logs WHERE timestamp < ?`);
- const result = connectionsStmt.run(cutoff);
- deletedConnections = result.changes;
- deletedLogs = result.changes;
- // For partial cleanup, we keep the stats tables as they are aggregated data
+ const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
+ const minuteCutoff = cutoff.toISOString().slice(0, 16) + ':00';
+ const minuteResult = this.db.prepare(`DELETE FROM minute_stats WHERE minute < ?`).run(minuteCutoff);
+ deletedConnections = minuteResult.changes;
+ deletedLogs = minuteResult.changes;
+ // Also clean old connection_logs if any remain
+ this.db.prepare(`DELETE FROM connection_logs WHERE timestamp < ?`).run(cutoff.toISOString());
+ // domain_proxy_stats and ip_proxy_stats are permanent aggregation tables (no time-based cleanup)
}
}
@@ -2345,18 +2623,18 @@ export class StatsDatabase {
}
}
- // Get connection logs count for a specific backend
+ // Get minute stats count for a specific backend
getConnectionLogsCount(backendId: number): number {
const stmt = this.db.prepare(`
- SELECT COUNT(*) as count FROM connection_logs WHERE backend_id = ?
+ SELECT COUNT(*) as count FROM minute_stats WHERE backend_id = ?
`);
const result = stmt.get(backendId) as { count: number };
return result.count;
}
- // Get total connection logs count (all backends)
+ // Get total minute stats count (all backends)
getTotalConnectionLogsCount(): number {
- const stmt = this.db.prepare(`SELECT COUNT(*) as count FROM connection_logs`);
+ const stmt = this.db.prepare(`SELECT COUNT(*) as count FROM minute_stats`);
const result = stmt.get() as { count: number };
return result.count;
}
@@ -2557,6 +2835,9 @@ export class StatsDatabase {
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 domain_proxy_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM ip_proxy_stats WHERE backend_id = ?`).run(id);
this.db.exec('COMMIT');
} catch (error) {
this.db.exec('ROLLBACK');
@@ -2566,13 +2847,13 @@ export class StatsDatabase {
// Get total stats across all backends
getGlobalSummary(): { totalConnections: number; totalUpload: number; totalDownload: number; uniqueDomains: number; uniqueIPs: number; backendCount: number } {
- // Calculate totals from domain_stats (aggregated data) instead of connection_logs
+ // 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 domain_stats
+ FROM ip_stats
`);
const { connections, upload, download } = trafficStmt.get() as {
connections: number;
@@ -2610,11 +2891,19 @@ export class StatsDatabase {
}
// Cleanup methods for data retention
- deleteOldConnectionLogs(cutoff: string): number {
+ deleteOldMinuteStats(cutoff: string): number {
+ const minuteCutoff = cutoff.slice(0, 16) + ':00';
const stmt = this.db.prepare(`
- DELETE FROM connection_logs WHERE timestamp < ?
+ DELETE FROM minute_stats WHERE minute < ?
`);
- return stmt.run(cutoff).changes;
+ // Also clean old connection_logs if any remain from before migration
+ this.db.prepare(`DELETE FROM connection_logs WHERE timestamp < ?`).run(cutoff);
+ return stmt.run(minuteCutoff).changes;
+ }
+
+ // Keep old method name as alias for backward compatibility
+ deleteOldConnectionLogs(cutoff: string): number {
+ return this.deleteOldMinuteStats(cutoff);
}
deleteOldHourlyStats(cutoff: string): number {
@@ -2630,9 +2919,9 @@ export class StatsDatabase {
oldestConnectionLog: string | null;
oldestHourlyStat: string | null;
} {
- const logsCountStmt = this.db.prepare('SELECT COUNT(*) as count FROM connection_logs');
+ const logsCountStmt = this.db.prepare('SELECT COUNT(*) as count FROM minute_stats');
const hourlyCountStmt = this.db.prepare('SELECT COUNT(*) as count FROM hourly_stats');
- const oldestLogStmt = this.db.prepare('SELECT MIN(timestamp) as ts FROM connection_logs');
+ const oldestLogStmt = this.db.prepare('SELECT MIN(minute) as ts FROM minute_stats');
const oldestHourlyStmt = this.db.prepare('SELECT MIN(hour) as hr FROM hourly_stats');
return {
diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.ts
index e997390..77c0b5d 100644
--- a/apps/collector/src/index.ts
+++ b/apps/collector/src/index.ts
@@ -61,7 +61,7 @@ async function main() {
const connCutoff = new Date(Date.now() - config.connectionLogsDays * 86400000).toISOString();
const hourlyCutoff = new Date(Date.now() - config.hourlyStatsDays * 86400000).toISOString();
- const deletedLogs = db.deleteOldConnectionLogs(connCutoff);
+ const deletedLogs = db.deleteOldMinuteStats(connCutoff);
const deletedHourly = db.deleteOldHourlyStats(hourlyCutoff);
if (deletedLogs > 0 || deletedHourly > 0) {
diff --git a/apps/web/app/[locale]/layout.tsx b/apps/web/app/[locale]/layout.tsx
index 575297e..bdad835 100644
--- a/apps/web/app/[locale]/layout.tsx
+++ b/apps/web/app/[locale]/layout.tsx
@@ -21,7 +21,7 @@ const geistMono = Geist_Mono({
export const metadata: Metadata = {
title: "Clash Master",
- description: "Modern and beautiful traffic analysis dashboard for OpenClash",
+ description: "Modern traffic analysis dashboard for Clash",
icons: {
icon: "/clash-master.png",
shortcut: "/clash-master.png",
@@ -55,7 +55,7 @@ export default async function RootLayout({
}) {
const { locale } = await params;
if (!routing.locales.includes(locale as any)) notFound();
-
+
const messages = await getMessages();
return (
@@ -64,12 +64,15 @@ export default async function RootLayout({
<link rel="apple-touch-icon" href="/icons/icon-192x192.png" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
- <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
+ <meta
+ name="apple-mobile-web-app-status-bar-style"
+ content="black-translucent"
+ />
<meta name="apple-mobile-web-app-title" content="Clash Master" />
+ <script src="/runtime-config.js" />
</head>
<body
- className={`${geistSans.variable} ${geistMono.variable} antialiased`}
- >
+ className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem>
<NextIntlClientProvider messages={messages}>
{children}
diff --git a/apps/web/app/manifest.ts b/apps/web/app/manifest.ts
index b38f765..5b4277e 100644
--- a/apps/web/app/manifest.ts
+++ b/apps/web/app/manifest.ts
@@ -4,7 +4,7 @@ export default function manifest(): MetadataRoute.Manifest {
return {
name: "Clash Master",
short_name: "Clash Master",
- description: "Modern and beautiful traffic analysis dashboard for OpenClash",
+ description: "Modern traffic analysis dashboard for Clash",
start_url: "/",
scope: "/",
display: "standalone",
diff --git a/apps/web/components/backend-config-dialog.tsx b/apps/web/components/backend-config-dialog.tsx
index 9671d18..7f23b64 100644
--- a/apps/web/components/backend-config-dialog.tsx
+++ b/apps/web/components/backend-config-dialog.tsx
@@ -178,6 +178,44 @@ function FaviconProviderPreview({
))}
</div>
</div>
+
+ {/* Off Option */}
+ <div
+ className={cn(
+ "flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4 p-3 rounded-lg border transition-all cursor-pointer",
+ selected === "off"
+ ? "border-primary bg-primary/5"
+ : "border-border hover:bg-muted/50",
+ )}
+ onClick={() => onChange("off")}>
+ {/* Top row: Radio + Icon + Label */}
+ <div className="flex items-center gap-3 sm:gap-4 flex-1 min-w-0">
+ <RadioGroupItem value="off" id="off" className="shrink-0" />
+
+ {/* Provider Icon - Off */}
+ <div className="w-10 h-10 rounded-lg bg-muted flex items-center justify-center overflow-hidden shrink-0">
+ <Globe className="w-5 h-5 text-muted-foreground" />
+ </div>
+
+ {/* Label */}
+ <Label
+ htmlFor="off"
+ className="font-medium cursor-pointer flex-1 min-w-0">
+ {t("faviconOff")}
+ </Label>
+ </div>
+
+ {/* Preview Icons - Default placeholders */}
+ <div className="flex items-center gap-2 pl-7 sm:pl-0">
+ {previewDomains.map((domain) => (
+ <div
+ key={domain}
+ className="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-muted flex items-center justify-center overflow-hidden">
+ <Globe className="w-4 h-4 text-muted-foreground" />
+ </div>
+ ))}
+ </div>
+ </div>
</RadioGroup>
);
}
diff --git a/apps/web/components/domain-top-grid.tsx b/apps/web/components/domain-top-grid.tsx
index 296ccf0..cddc63a 100644
--- a/apps/web/components/domain-top-grid.tsx
+++ b/apps/web/components/domain-top-grid.tsx
@@ -26,6 +26,7 @@ export function DomainTopGrid({ data, limit = 5, onViewAll }: DomainTopGridProps
const t = useTranslations("topDomains");
const proxiesT = useTranslations("proxies");
const { settings } = useSettings();
+ const faviconDisabled = settings.faviconProvider === "off";
const domains = useMemo(() => {
if (!data) return [];
@@ -82,19 +83,25 @@ export function DomainTopGrid({ data, limit = 5, onViewAll }: DomainTopGridProps
{index + 1}
</span>
- <img
- src={getFaviconForDomain(domain.domain)}
- alt=""
- className="w-5 h-5 rounded"
- onError={(e) => {
- const target = e.target as HTMLImageElement;
- target.style.display = "none";
- const parent = target.parentElement;
- if (parent) {
- parent.innerHTML = `<span class="w-5 h-5 rounded bg-muted flex items-center justify-center text-[9px] font-bold text-muted-foreground">${getInitials(domain.domain)}</span>`;
- }
- }}
- />
+ {faviconDisabled ? (
+ <span className="w-5 h-5 rounded bg-muted flex items-center justify-center">
+ <Globe className="w-3 h-3 text-muted-foreground" />
+ </span>
+ ) : (
+ <img
+ src={getFaviconForDomain(domain.domain)}
+ alt=""
+ className="w-5 h-5 rounded"
+ onError={(e) => {
+ const target = e.target as HTMLImageElement;
+ target.style.display = "none";
+ const parent = target.parentElement;
+ if (parent) {
+ parent.innerHTML = `<span class="w-5 h-5 rounded bg-muted flex items-center justify-center text-[9px] font-bold text-muted-foreground">${getInitials(domain.domain)}</span>`;
+ }
+ }}
+ />
+ )}
<span className="flex-1 text-sm font-medium truncate" title={domain.domain}>
{domain.domain}
diff --git a/apps/web/components/domain-top-list.tsx b/apps/web/components/domain-top-list.tsx
index 4a84666..980d562 100644
--- a/apps/web/components/domain-top-list.tsx
+++ b/apps/web/components/domain-top-list.tsx
@@ -32,6 +32,7 @@ export function DomainTopList({ data, limit = 7, onViewAll }: DomainTopListProps
const t = useTranslations("topDomains");
const proxiesT = useTranslations("proxies");
const { settings } = useSettings();
+ const faviconDisabled = settings.faviconProvider === "off";
const { domains, totalTraffic, totalConnections } = useMemo(() => {
if (!data) return { domains: [], totalTraffic: 0, totalConnections: 0 };
@@ -109,16 +110,22 @@ export function DomainTopList({ data, limit = 7, onViewAll }: DomainTopListProps
key={domain.domain}
rank={index + 1}
icon={
- <img
- src={getFaviconForDomain(domain.domain)}
- alt=""
- className="w-5 h-5"
- onError={(e) => {
- const target = e.target as HTMLImageElement;
- target.style.display = "none";
- target.parentElement!.innerHTML = `<span class="text-xs font-bold text-muted-foreground">${getInitials(domain.domain)}</span>`;
- }}
- />
+ faviconDisabled ? (
+ <span className="w-5 h-5 rounded bg-muted flex items-center justify-center">
+ <Globe className="w-3 h-3 text-muted-foreground" />
+ </span>
+ ) : (
+ <img
+ src={getFaviconForDomain(domain.domain)}
+ alt=""
+ className="w-5 h-5"
+ onError={(e) => {
+ const target = e.target as HTMLImageElement;
+ target.style.display = "none";
+ target.parentElement!.innerHTML = `<span class="text-xs font-bold text-muted-foreground">${getInitials(domain.domain)}</span>`;
+ }}
+ />
+ )
}
title={domain.domain}
subtitle={sortBy === "traffic"
diff --git a/apps/web/components/domains-table.tsx b/apps/web/components/domains-table.tsx
index 51582d9..eb28051 100644
--- a/apps/web/components/domains-table.tsx
+++ b/apps/web/components/domains-table.tsx
@@ -16,6 +16,12 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
interface DomainsTableProps {
activeBackendId?: number;
@@ -313,6 +319,11 @@ export function DomainsTable({ activeBackendId }: DomainsTableProps) {
) : (
data.map((domain, index) => {
const isExpanded = expandedDomain === domain.domain;
+ const fullChain = domain.chains && domain.chains.length > 0 ? domain.chains[0] : "";
+ const lastProxy = fullChain ? fullChain.split(" > ").pop()?.trim() || fullChain : "";
+ const chainTooltip = domain.chains && domain.chains.length > 0
+ ? domain.chains.map((chain, idx) => (idx === 0 ? chain : `(${idx + 1}) ${chain}`)).join("\n")
+ : "";
return (
<div key={domain.domain} className="group">
@@ -338,20 +349,31 @@ export function DomainsTable({ activeBackendId }: DomainsTableProps) {
{/* Proxy */}
<div className="col-span-2 flex items-center gap-1.5 min-w-0">
{domain.chains && domain.chains.length > 0 ? (
- <div className="flex items-center gap-1.5">
- <span
- className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-orange-500/10 text-orange-600 dark:text-orange-400 text-[11px] font-medium truncate max-w-[120px]"
- title={domain.chains[0]}
- >
- <Waypoints className="h-2.5 w-2.5 shrink-0" />
- {domain.chains[0]}
- </span>
- {domain.chains.length > 1 && (
- <span className="text-[11px] text-muted-foreground shrink-0">
- +{domain.chains.length - 1}
- </span>
- )}
- </div>
+ <TooltipProvider delayDuration={300}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex items-center gap-1.5 min-w-0">
+ <span
+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium truncate max-w-[120px]"
+ >
+ <Waypoints className="h-2.5 w-2.5 shrink-0" />
+ {lastProxy}
+ </span>
+ {domain.chains.length > 1 && (
+ <span className="text-[11px] text-muted-foreground shrink-0">
+ +{domain.chains.length - 1}
+ </span>
+ )}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent
+ side="top"
+ className="max-w-[360px] whitespace-pre-wrap"
+ >
+ {chainTooltip}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
) : (
<span className="text-xs text-muted-foreground">-</span>
)}
@@ -447,18 +469,31 @@ export function DomainsTable({ activeBackendId }: DomainsTableProps) {
{/* Row 2: Proxy tag - full width, no truncation */}
{domain.chains && domain.chains.length > 0 && (
<div className="flex items-center gap-1.5 mb-2 pl-[30px]">
- <span
- className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-orange-500/10 text-orange-600 dark:text-orange-400 text-[11px] font-medium whitespace-nowrap"
- title={domain.chains[0]}
- >
- <Waypoints className="h-2.5 w-2.5 shrink-0" />
- {domain.chains[0]}
- </span>
- {domain.chains.length > 1 && (
- <span className="text-[11px] text-muted-foreground shrink-0">
- +{domain.chains.length - 1}
- </span>
- )}
+ <TooltipProvider delayDuration={300}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex items-center gap-1.5">
+ <span
+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium whitespace-nowrap"
+ >
+ <Waypoints className="h-2.5 w-2.5 shrink-0" />
+ {lastProxy}
+ </span>
+ {domain.chains.length > 1 && (
+ <span className="text-[11px] text-muted-foreground shrink-0">
+ +{domain.chains.length - 1}
+ </span>
+ )}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent
+ side="top"
+ className="max-w-[360px] whitespace-pre-wrap"
+ >
+ {chainTooltip}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
</div>
)}
@@ -535,7 +570,7 @@ export function DomainsTable({ activeBackendId }: DomainsTableProps) {
{domain.chains.map((chain) => (
<span
key={chain}
- className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-orange-500/10 text-orange-600 dark:text-orange-400 text-xs font-medium max-w-full min-w-0"
+ className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-xs font-medium max-w-full min-w-0"
title={chain}
>
<Waypoints className="h-3 w-3 shrink-0" />
diff --git a/apps/web/components/favicon.tsx b/apps/web/components/favicon.tsx
index 71e8ed5..6de32b4 100644
--- a/apps/web/components/favicon.tsx
+++ b/apps/web/components/favicon.tsx
@@ -64,7 +64,7 @@ export function Favicon({ domain, size = "md", className }: FaviconProps) {
setLoading(true);
}, [settings.faviconProvider, domain]);
- if (error || !cleanedDomain) {
+ if (settings.faviconProvider === "off" || error || !cleanedDomain) {
return (
<div
className={cn(
diff --git a/apps/web/components/ips-table.tsx b/apps/web/components/ips-table.tsx
index b23ed25..245a9c1 100644
--- a/apps/web/components/ips-table.tsx
+++ b/apps/web/components/ips-table.tsx
@@ -1,7 +1,22 @@
"use client";
import { useState, useCallback, useEffect, useRef } from "react";
-import { Search, ArrowUpDown, ArrowDown, ArrowUp, ChevronLeft, ChevronRight, Rows3, Globe, Server, ChevronDown, ChevronUp, Link2, Waypoints, Loader2 } from "lucide-react";
+import {
+ Search,
+ ArrowUpDown,
+ ArrowDown,
+ ArrowUp,
+ ChevronLeft,
+ ChevronRight,
+ Rows3,
+ Globe,
+ Server,
+ ChevronDown,
+ ChevronUp,
+ Link2,
+ Waypoints,
+ Loader2,
+} from "lucide-react";
import { useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
@@ -15,16 +30,27 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
interface IPsTableProps {
activeBackendId?: number;
}
-type SortKey = "ip" | "totalDownload" | "totalUpload" | "totalConnections" | "lastSeen";
+type SortKey =
+ | "ip"
+ | "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];
+type PageSize = (typeof PAGE_SIZE_OPTIONS)[number];
// Color palette for IP icons - solid colors that work in both light/dark modes
const IP_COLORS = [
@@ -58,10 +84,26 @@ const getDomainColor = (domain: string) => {
// Country flag emoji mapping
const COUNTRY_FLAGS: Record<string, string> = {
- US: "🇺🇸", CN: "🇨🇳", JP: "🇯🇵", SG: "🇸🇬", HK: "🇭🇰",
- TW: "🇹🇼", KR: "🇰🇷", GB: "🇬🇧", DE: "🇩🇪", FR: "🇫🇷",
- NL: "🇳🇱", CA: "🇨🇦", AU: "🇦🇺", IN: "🇮🇳", BR: "🇧🇷",
- RU: "🇷🇺", SE: "🇸🇪", CH: "🇨🇭", IL: "🇮🇱", ID: "🇮🇩",
+ US: "🇺🇸",
+ CN: "🇨🇳",
+ JP: "🇯🇵",
+ SG: "🇸🇬",
+ HK: "🇭🇰",
+ TW: "🇹🇼",
+ KR: "🇰🇷",
+ GB: "🇬🇧",
+ DE: "🇩🇪",
+ FR: "🇫🇷",
+ NL: "🇳🇱",
+ CA: "🇨🇦",
+ AU: "🇦🇺",
+ IN: "🇮🇳",
+ BR: "🇧🇷",
+ RU: "🇷🇺",
+ SE: "🇸🇪",
+ CH: "🇨🇭",
+ IL: "🇮🇱",
+ ID: "🇮🇩",
LOCAL: "🏠",
};
@@ -81,8 +123,12 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState<PageSize>(10);
const [expandedIP, setExpandedIP] = useState<string | null>(null);
- const [proxyStats, setProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});
- const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);
+ const [proxyStats, setProxyStats] = useState<
+ Record<string, ProxyTrafficStats[]>
+ >({});
+ const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(
+ null,
+ );
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Debounce search input
@@ -91,7 +137,9 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
setDebouncedSearch(search);
setCurrentPage(1);
}, 300);
- return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
+ return () => {
+ if (debounceRef.current) clearTimeout(debounceRef.current);
+ };
}, [search]);
// Fetch data from server
@@ -122,23 +170,35 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
}
};
fetchData();
- return () => { cancelled = true; };
- }, [activeBackendId, currentPage, pageSize, sortKey, sortOrder, debouncedSearch]);
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ activeBackendId,
+ currentPage,
+ pageSize,
+ sortKey,
+ sortOrder,
+ debouncedSearch,
+ ]);
// Fetch proxy stats when an IP is expanded
- const fetchProxyStats = useCallback(async (ip: string) => {
- if (proxyStats[ip]) return;
- setProxyStatsLoading(ip);
- try {
- const stats = await api.getIPProxyStats(ip);
- setProxyStats(prev => ({ ...prev, [ip]: stats }));
- } catch (err) {
- console.error(`Failed to fetch proxy stats for ${ip}:`, err);
- setProxyStats(prev => ({ ...prev, [ip]: [] }));
- } finally {
- setProxyStatsLoading(null);
- }
- }, [proxyStats]);
+ const fetchProxyStats = useCallback(
+ async (ip: string) => {
+ if (proxyStats[ip]) return;
+ setProxyStatsLoading(ip);
+ try {
+ const stats = await api.getIPProxyStats(ip);
+ setProxyStats((prev) => ({ ...prev, [ip]: stats }));
+ } catch (err) {
+ console.error(`Failed to fetch proxy stats for ${ip}:`, err);
+ setProxyStats((prev) => ({ ...prev, [ip]: [] }));
+ } finally {
+ setProxyStatsLoading(null);
+ }
+ },
+ [proxyStats],
+ );
const handleSort = (key: SortKey) => {
if (sortKey === key) {
@@ -170,7 +230,8 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
};
const SortIcon = ({ column }: { column: SortKey }) => {
- if (sortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
+ if (sortKey !== column)
+ return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
return sortOrder === "asc" ? (
<ArrowUp className="ml-1 h-3 w-3 text-primary" />
) : (
@@ -188,17 +249,17 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
} else {
if (currentPage <= 3) {
for (let i = 1; i <= 4; i++) pages.push(i);
- pages.push('...');
+ pages.push("...");
pages.push(totalPages);
} else if (currentPage >= totalPages - 2) {
pages.push(1);
- pages.push('...');
+ pages.push("...");
for (let i = totalPages - 3; i <= totalPages; i++) pages.push(i);
} else {
pages.push(1);
- pages.push('...');
+ pages.push("...");
for (let i = currentPage - 1; i <= currentPage + 1; i++) pages.push(i);
- pages.push('...');
+ pages.push("...");
pages.push(totalPages);
}
}
@@ -232,34 +293,27 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
<div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
<div
className="col-span-3 flex items-center cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("ip")}
- >
+ onClick={() => handleSort("ip")}>
{t("ipAddress")}
<SortIcon column="ip" />
</div>
- <div className="col-span-2 flex items-center">
- {t("proxy")}
- </div>
- <div className="col-span-1 flex items-center">
- {t("location")}
- </div>
+ <div className="col-span-2 flex items-center">{t("proxy")}</div>
+ <div className="col-span-1 flex items-center">{t("location")}</div>
<div
className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("totalDownload")}
- >
+ onClick={() => handleSort("totalDownload")}>
{t("download")}
<SortIcon column="totalDownload" />
</div>
<div
className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("totalUpload")}
- >
+ onClick={() => handleSort("totalUpload")}>
{t("upload")}
<SortIcon column="totalUpload" />
</div>
- <div className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("totalConnections")}
- >
+ <div
+ className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ onClick={() => handleSort("totalConnections")}>
{t("conn")}
<SortIcon column="totalConnections" />
</div>
@@ -270,26 +324,28 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
{/* Mobile Sort Bar */}
<div className="sm:hidden flex items-center gap-2 px-4 py-2 bg-secondary/30 overflow-x-auto scrollbar-hide">
- {([
+ {[
{ key: "ip" as SortKey, label: t("ipAddress") },
{ key: "totalDownload" as SortKey, label: t("download") },
{ key: "totalUpload" as SortKey, label: t("upload") },
{ key: "totalConnections" as SortKey, label: t("conn") },
- ]).map(({ key, label }) => (
+ ].map(({ key, label }) => (
<button
key={key}
className={cn(
"flex items-center gap-0.5 px-2 py-1 rounded-md text-xs font-medium whitespace-nowrap transition-colors",
sortKey === key
? "bg-primary/10 text-primary"
- : "text-muted-foreground hover:text-foreground"
+ : "text-muted-foreground hover:text-foreground",
)}
- onClick={() => handleSort(key)}
- >
+ onClick={() => handleSort(key)}>
{label}
- {sortKey === key && (
- sortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
- )}
+ {sortKey === key &&
+ (sortOrder === "asc" ? (
+ <ArrowUp className="h-3 w-3" />
+ ) : (
+ <ArrowDown className="h-3 w-3" />
+ ))}
</button>
))}
</div>
@@ -308,6 +364,19 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
data.map((ip, index) => {
const ipColor = getIPColor(ip.ip);
const isExpanded = expandedIP === ip.ip;
+ const fullChain =
+ ip.chains && ip.chains.length > 0 ? ip.chains[0] : "";
+ const lastProxy = fullChain
+ ? fullChain.split(" > ").pop()?.trim() || fullChain
+ : "";
+ const chainTooltip =
+ ip.chains && ip.chains.length > 0
+ ? ip.chains
+ .map((chain, idx) =>
+ idx === 0 ? chain : `(${idx + 1}) ${chain}`,
+ )
+ .join("\n")
+ : "";
return (
<div key={ip.ip} className="group">
@@ -315,38 +384,48 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
<div
className={cn(
"hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer min-w-0",
- isExpanded && "bg-secondary/10"
+ isExpanded && "bg-secondary/10",
)}
style={{ animationDelay: `${index * 50}ms` }}
- onClick={() => toggleExpand(ip.ip)}
- >
+ onClick={() => toggleExpand(ip.ip)}>
{/* IP with Icon */}
<div className="col-span-3 flex items-center gap-3 min-w-0">
- <div className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}>
+ <div
+ className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}>
<Server className="w-3 h-3" />
</div>
<div className="min-w-0">
- <code className="text-sm font-medium truncate block">{ip.ip}</code>
+ <code className="text-sm font-medium truncate block">
+ {ip.ip}
+ </code>
</div>
</div>
{/* Proxy */}
<div className="col-span-2 flex items-center gap-1.5 min-w-0">
{ip.chains && ip.chains.length > 0 ? (
- <div className="flex items-center gap-1.5">
- <span
- className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-orange-500/10 text-orange-600 dark:text-orange-400 text-[11px] font-medium truncate max-w-[120px]"
- title={ip.chains[0]}
- >
- <Waypoints className="h-2.5 w-2.5 shrink-0" />
- {ip.chains[0]}
- </span>
- {ip.chains.length > 1 && (
- <span className="text-[11px] text-muted-foreground shrink-0">
- +{ip.chains.length - 1}
- </span>
- )}
- </div>
+ <TooltipProvider delayDuration={300}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex items-center gap-1.5 min-w-0">
+ <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium truncate max-w-[120px]">
+ <Waypoints className="h-2.5 w-2.5 shrink-0" />
+ {lastProxy}
+ </span>
+ {ip.chains.length > 1 && (
+ <span className="text-[11px] text-muted-foreground shrink-0">
+ +{ip.chains.length - 1}
+ </span>
+ )}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent
+ side="top"
+ className="max-w-[360px] whitespace-pre-wrap">
+ {chainTooltip}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
) : (
<span className="text-xs text-muted-foreground">-</span>
)}
@@ -356,10 +435,14 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
<div className="col-span-1 flex items-center">
{ip.geoIP && ip.geoIP.length > 0 ? (
<div className="flex items-center gap-1.5">
- <span className="text-sm" title={ip.geoIP[1] || ip.geoIP[0]}>
+ <span
+ className="text-sm"
+ title={ip.geoIP[1] || ip.geoIP[0]}>
{getCountryFlag(ip.geoIP[0])}
</span>
- <span className="text-xs truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>
+ <span className="text-xs truncate">
+ {ip.geoIP[1] || ip.geoIP[0]}
+ </span>
</div>
) : (
<span className="text-xs text-muted-foreground">-</span>
@@ -368,12 +451,16 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
{/* Download */}
<div className="col-span-2 text-right tabular-nums text-sm">
- <span className="text-blue-500">{formatBytes(ip.totalDownload)}</span>
+ <span className="text-blue-500">
+ {formatBytes(ip.totalDownload)}
+ </span>
</div>
{/* Upload */}
<div className="col-span-1 text-right tabular-nums text-sm">
- <span className="text-purple-500">{formatBytes(ip.totalUpload)}</span>
+ <span className="text-purple-500">
+ {formatBytes(ip.totalUpload)}
+ </span>
</div>
{/* Connections */}
@@ -392,13 +479,12 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
"h-7 px-2 gap-1 text-xs font-medium transition-all",
isExpanded
? "bg-primary/10 text-primary hover:bg-primary/20"
- : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary"
+ : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary",
)}
onClick={(e) => {
e.stopPropagation();
toggleExpand(ip.ip);
- }}
- >
+ }}>
<Link2 className="h-3 w-3" />
{ip.domains.length}
{isExpanded ? (
@@ -414,17 +500,19 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
<div
className={cn(
"sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",
- isExpanded && "bg-secondary/10"
+ isExpanded && "bg-secondary/10",
)}
- onClick={() => toggleExpand(ip.ip)}
- >
+ onClick={() => toggleExpand(ip.ip)}>
{/* Row 1: IP Icon + IP (truncate) + Domain Count */}
<div className="flex items-center gap-2.5 mb-2">
- <div className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}>
+ <div
+ className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}>
<Server className="w-3 h-3" />
</div>
<div className="flex-1 min-w-0">
- <code className="text-sm font-medium truncate block">{ip.ip}</code>
+ <code className="text-sm font-medium truncate block">
+ {ip.ip}
+ </code>
</div>
<Button
variant="ghost"
@@ -433,16 +521,19 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
"h-7 px-2 gap-1 text-xs font-medium shrink-0",
isExpanded
? "bg-primary/10 text-primary"
- : "bg-secondary/50 text-muted-foreground"
+ : "bg-secondary/50 text-muted-foreground",
)}
onClick={(e) => {
e.stopPropagation();
toggleExpand(ip.ip);
- }}
- >
+ }}>
<Link2 className="h-3 w-3" />
{ip.domains.length}
- {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
+ {isExpanded ? (
+ <ChevronUp className="h-3 w-3" />
+ ) : (
+ <ChevronDown className="h-3 w-3" />
+ )}
</Button>
</div>
@@ -451,29 +542,45 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
{ip.geoIP && ip.geoIP.length > 0 && (
<span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground">
<span>{getCountryFlag(ip.geoIP[0])}</span>
- <span className="truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>
+ <span className="truncate">
+ {ip.geoIP[1] || ip.geoIP[0]}
+ </span>
</span>
)}
{ip.chains && ip.chains.length > 0 && (
- <span
- className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-orange-500/10 text-orange-600 dark:text-orange-400 text-[11px] font-medium whitespace-nowrap"
- title={ip.chains[0]}
- >
- <Waypoints className="h-2.5 w-2.5 shrink-0" />
- {ip.chains[0]}
- </span>
- )}
- {ip.chains && ip.chains.length > 1 && (
- <span className="text-[11px] text-muted-foreground">
- +{ip.chains.length - 1}
- </span>
+ <TooltipProvider delayDuration={300}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex items-center gap-1.5">
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium whitespace-nowrap">
+ <Waypoints className="h-2.5 w-2.5 shrink-0" />
+ {lastProxy}
+ </span>
+ {ip.chains.length > 1 && (
+ <span className="text-[11px] text-muted-foreground">
+ +{ip.chains.length - 1}
+ </span>
+ )}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent
+ side="top"
+ className="max-w-[360px] whitespace-pre-wrap">
+ {chainTooltip}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
)}
</div>
{/* Row 3: Traffic stats - compact layout */}
<div className="flex items-center gap-3 text-[11px] pl-[30px]">
- <span className="text-blue-500 tabular-nums">↓ {formatBytes(ip.totalDownload)}</span>
- <span className="text-purple-500 tabular-nums">↑ {formatBytes(ip.totalUpload)}</span>
+ <span className="text-blue-500 tabular-nums">
+ ↓ {formatBytes(ip.totalDownload)}
+ </span>
+ <span className="text-purple-500 tabular-nums">
+ ↑ {formatBytes(ip.totalUpload)}
+ </span>
<span className="text-muted-foreground tabular-nums ml-auto">
{formatNumber(ip.totalConnections)} {t("conn")}
</span>
@@ -494,22 +601,36 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
<div className="flex items-center justify-center py-4">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
- ) : (proxyStats[ip.ip] && proxyStats[ip.ip].length > 0) ? (
+ ) : proxyStats[ip.ip] &&
+ proxyStats[ip.ip].length > 0 ? (
<div className="space-y-2">
{proxyStats[ip.ip].map((ps) => {
- const totalTraffic = ip.totalDownload + ip.totalUpload;
- const proxyTraffic = ps.totalDownload + ps.totalUpload;
- const percent = totalTraffic > 0 ? (proxyTraffic / totalTraffic) * 100 : 0;
- const proxyTotal = ps.totalDownload + ps.totalUpload;
- const downloadPercent = proxyTotal > 0 ? (ps.totalDownload / proxyTotal) * 100 : 0;
- const uploadPercent = proxyTotal > 0 ? (ps.totalUpload / proxyTotal) * 100 : 0;
+ const totalTraffic =
+ ip.totalDownload + ip.totalUpload;
+ const proxyTraffic =
+ ps.totalDownload + ps.totalUpload;
+ const percent =
+ totalTraffic > 0
+ ? (proxyTraffic / totalTraffic) * 100
+ : 0;
+ const proxyTotal =
+ ps.totalDownload + ps.totalUpload;
+ const downloadPercent =
+ proxyTotal > 0
+ ? (ps.totalDownload / proxyTotal) * 100
+ : 0;
+ const uploadPercent =
+ proxyTotal > 0
+ ? (ps.totalUpload / proxyTotal) * 100
+ : 0;
return (
<div
key={ps.chain}
- className="px-3 py-2 rounded-lg bg-card border border-border/50"
- >
+ className="px-3 py-2 rounded-lg bg-card border border-border/50">
<div className="flex items-center justify-between mb-1.5">
- <span className="inline-flex items-center gap-1.5 text-xs font-medium truncate max-w-[60%]" title={ps.chain}>
+ <span
+ className="inline-flex items-center gap-1.5 text-xs font-medium truncate max-w-[60%]"
+ title={ps.chain}>
<Waypoints className="h-3 w-3 text-orange-500 shrink-0" />
{ps.chain}
</span>
@@ -520,30 +641,40 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
<div className="w-full h-1.5 rounded-full bg-secondary/80 mb-1.5 overflow-hidden flex">
<div
className="h-full bg-blue-500 transition-all"
- style={{ width: `${Math.max(percent * (downloadPercent / 100), 0.5)}%` }}
+ style={{
+ width: `${Math.max(percent * (downloadPercent / 100), 0.5)}%`,
+ }}
/>
<div
className="h-full bg-purple-500 transition-all"
- style={{ width: `${Math.max(percent * (uploadPercent / 100), 0.5)}%` }}
+ style={{
+ width: `${Math.max(percent * (uploadPercent / 100), 0.5)}%`,
+ }}
/>
</div>
<div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[11px] tabular-nums">
- <span className="text-blue-500">↓ {formatBytes(ps.totalDownload)}</span>
- <span className="text-purple-500">↑ {formatBytes(ps.totalUpload)}</span>
- <span className="text-muted-foreground">{formatNumber(ps.totalConnections)} {t("conn")}</span>
+ <span className="text-blue-500">
+ ↓ {formatBytes(ps.totalDownload)}
+ </span>
+ <span className="text-purple-500">
+ ↑ {formatBytes(ps.totalUpload)}
+ </span>
+ <span className="text-muted-foreground">
+ {formatNumber(ps.totalConnections)}{" "}
+ {t("conn")}
+ </span>
</div>
</div>
);
})}
</div>
- ) : (ip.chains && ip.chains.length > 0) ? (
+ ) : ip.chains && ip.chains.length > 0 ? (
<div className="flex flex-wrap gap-1.5">
{ip.chains.map((chain) => (
<span
key={chain}
- className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-orange-500/10 text-orange-600 dark:text-orange-400 text-xs font-medium max-w-full min-w-0"
- title={chain}
- >
+ className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-xs font-medium max-w-full min-w-0"
+ title={chain}>
<Waypoints className="h-3 w-3 shrink-0" />
<span className="truncate min-w-0">
{chain}
@@ -552,7 +683,9 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
))}
</div>
) : (
- <span className="text-xs text-muted-foreground">-</span>
+ <span className="text-xs text-muted-foreground">
+ -
+ </span>
)}
</div>
@@ -568,12 +701,14 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
return (
<div
key={domain}
- className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
- >
- <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md ${domainColor.bg} ${domainColor.text} flex items-center justify-center shrink-0`}>
+ className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all">
+ <div
+ className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md ${domainColor.bg} ${domainColor.text} flex items-center justify-center shrink-0`}>
<Globe className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
</div>
- <span className="text-xs font-medium truncate max-w-[180px] sm:max-w-[200px]">{domain}</span>
+ <span className="text-xs font-medium truncate max-w-[180px] sm:max-w-[200px]">
+ {domain}
+ </span>
</div>
);
})}
@@ -596,9 +731,14 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
<div className="flex items-center gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm" className="h-8 gap-1.5 text-muted-foreground hover:text-foreground">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 gap-1.5 text-muted-foreground hover:text-foreground">
<Rows3 className="h-4 w-4" />
- <span>{pageSize} / {t("page")}</span>
+ <span>
+ {pageSize} / {t("page")}
+ </span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
@@ -606,8 +746,7 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
<DropdownMenuItem
key={size}
onClick={() => handlePageSizeChange(size)}
- className={pageSize === size ? "bg-primary/10" : ""}
- >
+ className={pageSize === size ? "bg-primary/10" : ""}>
{size} / {t("page")}
</DropdownMenuItem>
))}
@@ -621,10 +760,13 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
{/* Pagination info and controls */}
<div className="flex items-center gap-2 sm:gap-3">
<p className="text-xs sm:text-sm text-muted-foreground hidden sm:block">
- {t("showing")} {Math.min((currentPage - 1) * pageSize + 1, total)} - {Math.min(currentPage * pageSize, total)} {t("of")} {total}
+ {t("showing")}{" "}
+ {Math.min((currentPage - 1) * pageSize + 1, total)} -{" "}
+ {Math.min(currentPage * pageSize, total)} {t("of")} {total}
</p>
<p className="text-xs text-muted-foreground sm:hidden">
- {Math.min((currentPage - 1) * pageSize + 1, total)}-{Math.min(currentPage * pageSize, total)} / {total}
+ {Math.min((currentPage - 1) * pageSize + 1, total)}-
+ {Math.min(currentPage * pageSize, total)} / {total}
</p>
<div className="flex items-center gap-1">
@@ -632,35 +774,38 @@ export function IPsTable({ activeBackendId }: IPsTableProps) {
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
- disabled={currentPage === 1}
- >
+ onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
+ disabled={currentPage === 1}>
<ChevronLeft className="h-4 w-4" />
</Button>
- {getPageNumbers().map((page, idx) => (
- page === '...' ? (
- <span key={`ellipsis-${idx}`} className="px-1 sm:px-2 text-muted-foreground text-xs">...</span>
+ {getPageNumbers().map((page, idx) =>
+ page === "..." ? (
+ <span
+ key={`ellipsis-${idx}`}
+ className="px-1 sm:px-2 text-muted-foreground text-xs">
+ ...
+ </span>
) : (
<Button
key={page}
variant={currentPage === page ? "default" : "ghost"}
size="sm"
className="h-8 w-8 px-0 text-xs"
- onClick={() => setCurrentPage(page as number)}
- >
+ onClick={() => setCurrentPage(page as number)}>
{page}
</Button>
- )
- ))}
+ ),
+ )}
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
- disabled={currentPage === totalPages}
- >
+ onClick={() =>
+ setCurrentPage((p) => Math.min(totalPages, p + 1))
+ }
+ disabled={currentPage === totalPages}>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
diff --git a/apps/web/components/overview/top-domains-simple.tsx b/apps/web/components/overview/top-domains-simple.tsx
index 1840384..574bcb5 100644
--- a/apps/web/components/overview/top-domains-simple.tsx
+++ b/apps/web/components/overview/top-domains-simple.tsx
@@ -27,6 +27,7 @@ export const TopDomainsSimple = React.memo(function TopDomainsSimple({
}: TopDomainsSimpleProps) {
const t = useTranslations("topDomains");
const { settings } = useSettings();
+ const faviconDisabled = settings.faviconProvider === "off";
const sortedDomains = useMemo(() => {
if (!domains?.length) return [];
@@ -119,20 +120,24 @@ export const TopDomainsSimple = React.memo(function TopDomainsSimple({
{/* Favicon */}
<div className="w-5 h-5 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden">
- <img
- src={getFaviconForDomain(domain.domain)}
- alt=""
- className="w-4 h-4"
- loading="lazy"
- onError={(e) => {
- const target = e.target as HTMLImageElement;
- target.style.display = "none";
- const parent = target.parentElement;
- if (parent) {
- parent.innerHTML = `<span class="text-[9px] font-bold text-muted-foreground">${getInitials(domain.domain)}</span>`;
- }
- }}
- />
+ {faviconDisabled ? (
+ <Globe className="w-3 h-3 text-muted-foreground" />
+ ) : (
+ <img
+ src={getFaviconForDomain(domain.domain)}
+ alt=""
+ className="w-4 h-4"
+ loading="lazy"
+ onError={(e) => {
+ const target = e.target as HTMLImageElement;
+ target.style.display = "none";
+ const parent = target.parentElement;
+ if (parent) {
+ parent.innerHTML = `<span class="text-[9px] font-bold text-muted-foreground">${getInitials(domain.domain)}</span>`;
+ }
+ }}
+ />
+ )}
</div>
<span className="flex-1 text-sm font-medium truncate" title={domain.domain}>
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index fc243bb..b050ad5 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -11,7 +11,41 @@ import type {
ProxyTrafficStats,
} from "@clashmaster/shared";
-const API_BASE = "/api";
+type RuntimeConfig = {
+ API_URL?: string;
+ API_PORT?: string | number;
+ API_HOST?: string;
+};
+
+function getRuntimeConfig(): RuntimeConfig | undefined {
+ if (typeof window === "undefined") return undefined;
+ return (window as any).__RUNTIME_CONFIG__ as RuntimeConfig | undefined;
+}
+
+function normalizeApiBase(url: string): string {
+ if (!url) return "/api";
+ const trimmed = url.replace(/\/+$/, "");
+ return trimmed.endsWith("/api") ? trimmed : `${trimmed}/api`;
+}
+
+function resolveApiBase(): string {
+ const runtime = getRuntimeConfig();
+ if (runtime?.API_URL) {
+ return normalizeApiBase(runtime.API_URL);
+ }
+ if (runtime?.API_PORT && typeof window !== "undefined") {
+ const protocol = window.location.protocol;
+ const host = runtime.API_HOST || window.location.hostname;
+ return `${protocol}//${host}:${runtime.API_PORT}/api`;
+ }
+ const envUrl = process.env.NEXT_PUBLIC_API_URL || process.env.API_URL;
+ if (envUrl) {
+ return normalizeApiBase(envUrl);
+ }
+ return "/api";
+}
+
+const API_BASE = resolveApiBase();
async function fetchJson<T>(url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET', body?: any): Promise<T> {
const options: RequestInit = {
diff --git a/apps/web/lib/settings.ts b/apps/web/lib/settings.ts
index af5f9f8..bad88c8 100644
--- a/apps/web/lib/settings.ts
+++ b/apps/web/lib/settings.ts
@@ -2,7 +2,7 @@
import { useState, useEffect, useCallback, useSyncExternalStore, useMemo } from "react";
-export type FaviconProvider = "google" | "faviconim";
+export type FaviconProvider = "google" | "faviconim" | "off";
export interface UserSettings {
faviconProvider: FaviconProvider;
@@ -133,6 +133,9 @@ export function useSettings() {
// Generate favicon URL based on provider
export function getFaviconUrl(domain: string, provider: FaviconProvider): string {
+ if (provider === "off") {
+ return "";
+ }
const cleanDomain = domain
.replace(/^https?:\/\//, "")
.replace(/^www\./, "")
diff --git a/apps/web/lib/websocket.ts b/apps/web/lib/websocket.ts
index 8f2ef3e..575ee5d 100644
--- a/apps/web/lib/websocket.ts
+++ b/apps/web/lib/websocket.ts
@@ -16,6 +16,17 @@ interface UseWebSocketOptions {
onError?: (error: Event) => void;
}
+type RuntimeConfig = {
+ WS_URL?: string;
+ WS_PORT?: string | number;
+ WS_HOST?: string;
+};
+
+function getRuntimeConfig(): RuntimeConfig | undefined {
+ if (typeof window === 'undefined') return undefined;
+ return (window as any).__RUNTIME_CONFIG__ as RuntimeConfig | undefined;
+}
+
export function useStatsWebSocket(options: UseWebSocketOptions = {}) {
const [status, setStatus] = useState<ConnectionStatus>('disconnected');
const [lastMessage, setLastMessage] = useState<StatsSummary | null>(null);
@@ -34,13 +45,16 @@ export function useStatsWebSocket(options: UseWebSocketOptions = {}) {
setStatus('connecting');
// Support dynamic WebSocket URL configuration
- // Priority: NEXT_PUBLIC_WS_URL > host-relative WS > default localhost
- const wsPort = process.env.NEXT_PUBLIC_WS_PORT || '3002';
- const wsUrl = process.env.NEXT_PUBLIC_WS_URL
- ? process.env.NEXT_PUBLIC_WS_URL
- : typeof window !== 'undefined'
- ? `ws://${window.location.hostname}:${wsPort}`
- : `ws://localhost:${wsPort}`;
+ // Priority: runtime WS_URL > runtime WS_PORT > NEXT_PUBLIC_WS_URL > NEXT_PUBLIC_WS_PORT > default localhost
+ const runtime = getRuntimeConfig();
+ const wsPort = runtime?.WS_PORT || process.env.NEXT_PUBLIC_WS_PORT || '3002';
+ const wsUrl = runtime?.WS_URL
+ ? runtime.WS_URL
+ : process.env.NEXT_PUBLIC_WS_URL
+ ? process.env.NEXT_PUBLIC_WS_URL
+ : typeof window !== 'undefined'
+ ? `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${runtime?.WS_HOST || window.location.hostname}:${wsPort}`
+ : `ws://localhost:${wsPort}`;
console.log('[WebSocket] Connecting to:', wsUrl);
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index 70fd443..8a7eb83 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -14,7 +14,7 @@
},
"header": {
"title": "Clash Master",
- "subtitle": "Modern and beautiful traffic analysis tool for Clash"
+ "subtitle": "Modern traffic analysis dashboard for Clash"
},
"dashboard": {
"title": "Dashboard",
@@ -204,7 +204,7 @@
"title": "About",
"version": "Version",
"projectName": "Clash Master",
- "description": "Modern and beautiful traffic analysis dashboard for OpenClash",
+ "description": "Modern traffic analysis dashboard for Clash",
"github": "GitHub",
"openSource": "Clash Master",
"license": "MIT License",
@@ -308,6 +308,7 @@
"faviconProviderDescription": "Choose the service used to display website icons in the domain list. favicon.im is recommended for users in China.",
"faviconGoogle": "Google Favicon",
"faviconIm": "favicon.im (Recommended for China)",
+ "faviconOff": "Off (Use default icons)",
"dataRetention": "Data Storage Time",
"dataRetentionDescription": "Control how long detailed connection records are kept. Domain and IP statistics are always preserved. Longer storage uses more disk space but allows troubleshooting older issues.",
"retentionPresetMinimal": "Minimal",
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index 7e80697..76e0cfd 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -307,6 +307,7 @@
"faviconProviderDescription": "选择在域名列表中显示网站图标时使用的服务。favicon.im 在国内访问更快。",
"faviconGoogle": "Google Favicon",
"faviconIm": "favicon.im (国内推荐)",
+ "faviconOff": "关闭(使用默认图标)",
"dataRetention": "数据存储时间",
"dataRetentionDescription": "控制详细连接记录的保存时长。域名和IP的统计数据将永久保留。存储时间越长占用磁盘空间越多,但可用于排查更早的问题。",
"retentionPresetMinimal": "极简",
diff --git a/apps/web/public/runtime-config.js b/apps/web/public/runtime-config.js
new file mode 100644
index 0000000..39d4256
--- /dev/null
+++ b/apps/web/public/runtime-config.js
@@ -0,0 +1,3 @@
+// Runtime configuration injected by docker-start.sh (if present)
+// This file is safe to ship with defaults and can be overwritten at container start.
+window.__RUNTIME_CONFIG__ = window.__RUNTIME_CONFIG__ || {};
diff --git a/docker-compose.yml b/docker-compose.yml
index faa3a5d..42ea2b9 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -16,14 +16,16 @@ services:
- WEB_PORT=3000
- API_PORT=3001
- COLLECTOR_WS_PORT=3002
- # 告诉前端浏览器应该连接哪个 WebSocket 端口
- - NEXT_PUBLIC_WS_PORT=${WS_EXTERNAL_PORT:-3002}
+ # 将外部端口传入容器,用于运行时前端配置
+ - WEB_EXTERNAL_PORT=${WEB_EXTERNAL_PORT:-3000}
+ - API_EXTERNAL_PORT=${API_EXTERNAL_PORT:-3001}
+ - WS_EXTERNAL_PORT=${WS_EXTERNAL_PORT:-3002}
- DB_PATH=/app/data/stats.db
networks:
- clash-master-network
# 健康检查
healthcheck:
- test: ["CMD", "wget", "-q", "--spider", "http://127.0.0.1:3001/health"]
+ test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:${API_PORT:-3001}/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
diff --git a/docker-start.sh b/docker-start.sh
index 3e37d47..de13cc9 100755
--- a/docker-start.sh
+++ b/docker-start.sh
@@ -21,6 +21,21 @@ echo "📡 WebSocket: ws://0.0.0.0:${COLLECTOR_WS_PORT}"
echo "💾 Database: ${DB_PATH}"
echo
+# ─── Runtime config for web (dynamic ports) ───────────────────────────
+RUNTIME_CONFIG_PATH="/app/apps/web/.next/standalone/apps/web/public/runtime-config.js"
+RUNTIME_API_PORT="${API_EXTERNAL_PORT:-$API_PORT}"
+RUNTIME_WS_PORT="${WS_EXTERNAL_PORT:-$COLLECTOR_WS_PORT}"
+
+mkdir -p "$(dirname "$RUNTIME_CONFIG_PATH")"
+cat > "$RUNTIME_CONFIG_PATH" <<EOF
+window.__RUNTIME_CONFIG__ = {
+ API_PORT: "${RUNTIME_API_PORT}",
+ WS_PORT: "${RUNTIME_WS_PORT}",
+ API_URL: "${NEXT_PUBLIC_API_URL:-}",
+ WS_URL: "${NEXT_PUBLIC_WS_URL:-}"
+};
+EOF
+
# Ensure data directory exists
mkdir -p "$(dirname "$DB_PATH")"
diff --git a/package.json b/package.json
index f76b79a..ee9a03d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "clash-master",
- "version": "1.0.6",
+ "version": "1.0.7",
"private": true,
"workspaces": [
"apps/*",