Skip to content

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

feat: Implement token-based authentication system with a new login dialog, auth guard, and corresponding backend services.

luolei62e664fa3ad0
diff --git a/README.md b/README.md
index b53a110..33cf5e7 100644
--- a/README.md
+++ b/README.md
@@ -352,6 +352,61 @@ docker compose pull
docker compose up -d
```
+## 🔐 认证与安全
+
+Neko Master 支持访问鉴权功能,保护你的面板数据安全。
+
+### 开启/关闭鉴权
+
+1. 进入面板,点击左侧边栏底部的「设置」。
+2. 切换到「安全」标签页。
+3. 在此页面可以开启/关闭访问控制,并设置访问令牌(Token)。
+
+### 忘记密码(重置访问令牌)
+
+如果你忘记了访问令牌,可以通过环境变量 `FORCE_ACCESS_CONTROL_OFF` 强制进入**紧急访问模式**。
+
+#### Docker Compose 用户
+
+1. 修改 `docker-compose.yml`,在 `environment` 下添加:
+
+ ```yaml
+ environment:
+ - FORCE_ACCESS_CONTROL_OFF=true
+ ```
+
+2. 重启容器:
+
+ ```bash
+ docker compose up -d
+ ```
+
+3. 刷新页面,你将看到“紧急访问模式”警告。此时无需旧密码即可在「设置 -> 安全」中重置新令牌。
+
+4. **重要**:重置完成后,务必删除该环境变量并再次重启容器,以恢复访问控制。
+
+#### Docker 命令行用户
+
+1. 停止并删除旧容器(数据在挂载卷中,不会丢失):
+
+ ```bash
+ docker stop neko-master
+ docker rm neko-master
+ ```
+
+2. 添加 `-e FORCE_ACCESS_CONTROL_OFF=true` 参数重新启动:
+
+ ```bash
+ docker run -d \
+ --name neko-master \
+ -p 3000:3000 \
+ -v $(pwd)/data:/app/data \
+ -e FORCE_ACCESS_CONTROL_OFF=true \
+ foru17/neko-master:latest
+ ```
+
+3. 重置密码后,再次停止容器,去除该参数并重启,恢复正常保护模式。
+
## ❓ 常见问题
### Q: 提示 "端口已被占用" 怎么办?
diff --git a/README_EN.md b/README_EN.md
new file mode 100644
index 0000000..9d81097
--- /dev/null
+++ b/README_EN.md
@@ -0,0 +1,479 @@
+<p align="center">
+ <img src="./assets/icon-neko-master.png" width="200" alt="Neko Master Logo" style="margin-bottom: 16px;">
+ <br>
+ <b style="font-size: 32px;">Neko Master</b>
+</p>
+
+<p align="center">
+ <b>Visualize your network traffic at a glance.</b><br>
+ <span>Real-time Monitoring · Traffic Auditing · Multi-gateway Management</span>
+</p>
+
+<p align="center">
+ <a href="https://github.com/foru17/neko-master/stargazers"><img src="https://img.shields.io/github/stars/foru17/neko-master?style=flat-square&color=yellow" alt="Stars"></a>
+ <a href="https://hub.docker.com/r/foru17/neko-master"><img src="https://img.shields.io/docker/pulls/foru17/neko-master?style=flat-square&color=blue&logo=docker" alt="Docker Pulls"></a>
+ <a href="https://hub.docker.com/r/foru17/neko-master"><img src="https://img.shields.io/docker/v/foru17/neko-master?style=flat-square&label=Docker&color=2496ED" alt="Docker Version"></a>
+ <a href="https://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">
+</p>
+
+> [!IMPORTANT]
+> **Disclaimer**
+>
+> This project is a **network traffic analysis and visualization tool**, designed to display and audit traffic data from your local gateway.
+>
+> This project **does NOT provide any network access services, proxy subscriptions, or cross-network connection capabilities**.
+> All data comes from the user's own network environment.
+>
+> Please use this software in compliance with local laws and regulations.
+
+![Neko Master Overview](./assets/neko-master-overview.png)
+![Neko Master Rules](./assets/neko-master-rules.png)
+![Neko Master Regions](./assets/neko-master-regions.png)
+
+## About the Name
+
+**Neko** (ねこ) means "cat" in Japanese, pronounced as **/ˈneɪkoʊ/** (NEH-ko).
+
+Just like a cat—quiet yet keen—Neko Master focuses on lightweight, precise analysis and visualization of network traffic.
+
+## 📋 Table of Contents
+
+- [🚀 Quick Start](#-quick-start)
+- [📖 First Time Setup](#-first-time-setup)
+- [🔧 Port Conflict Resolution](#-port-conflict-resolution)
+- [🔐 Authentication & Security](#-authentication--security)
+- [🐳 Docker Configuration](#-docker-configuration)
+- [🌐 Reverse Proxy & Tunnel](#-reverse-proxy--tunnel)
+- [❓ FAQ](#-faq)
+- [📁 Project Structure](#-project-structure)
+- [🛠️ Tech Stack](#️-tech-stack)
+- [📄 License](#-license)
+
+## 🚀 Quick Start
+
+### Method 1: Docker Compose (Recommended)
+
+#### Scenario A: Minimal Deployment (Expose 3000 Only)
+
+```yaml
+services:
+ neko-master:
+ image: foru17/neko-master:latest
+ container_name: neko-master
+ restart: unless-stopped
+ ports:
+ - "3000:3000" # Web UI
+ volumes:
+ - ./data:/app/data
+ environment:
+ - NODE_ENV=production
+ - DB_PATH=/app/data/stats.db
+```
+
+> This mode is fully compatible with upgrades.
+> It will automatically fall back to HTTP polling refreshing if WebSocket is not connected.
+
+#### Scenario B: Real-time WebSocket (Recommended with Reverse Proxy)
+
+```yaml
+services:
+ neko-master:
+ image: foru17/neko-master:latest
+ container_name: neko-master
+ restart: unless-stopped
+ ports:
+ - "3000:3000" # Web UI
+ - "3002:3002" # WebSocket (For Nginx / Tunnel forwarding)
+ volumes:
+ - ./data:/app/data
+ environment:
+ - NODE_ENV=production
+ - DB_PATH=/app/data/stats.db
+```
+
+Start the service:
+
+```bash
+docker compose up -d
+```
+
+Visit <http://localhost:3000>
+
+### Method 2: Docker Run
+
+```bash
+# Minimal (3000 only)
+docker run -d \
+ --name neko-master \
+ -p 3000:3000 \
+ -v $(pwd)/data:/app/data \
+ --restart unless-stopped \
+ foru17/neko-master:latest
+
+# Real-time WS (with reverse proxy)
+docker run -d \
+ --name neko-master \
+ -p 3000:3000 \
+ -p 3002:3002 \
+ -v $(pwd)/data:/app/data \
+ --restart unless-stopped \
+ foru17/neko-master:latest
+```
+
+> The API uses the same domain `/api` by default, so exposing 3001 is usually unnecessary.
+> If you want Real-time WebSocket, ensure the reverse proxy can access `3002`. It falls back to HTTP polling (approx. 5s interval) if not connected.
+
+Visit <http://localhost:3000>
+
+> To customize external ports (docker run), add:
+> `-e WEB_EXTERNAL_PORT=8080 -e API_EXTERNAL_PORT=8081 -e WS_EXTERNAL_PORT=8082`
+
+### Method 3: One-Click Script
+
+Automatically detects port conflicts and configures accordingly. Suitable for users unfamiliar with Docker:
+
+```bash
+# Using curl
+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash
+
+# Or using wget
+wget -qO- https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash
+```
+
+The script will automatically:
+
+- ✅ Download `docker-compose.yml`
+- ✅ Check if default ports (3000/3001/3002) are occupied
+- ✅ Provide available alternative ports
+- ✅ Create configuration file and start the service
+
+### Method 4: Run from Source
+
+```bash
+# 1. Clone repo
+git clone https://github.com/foru17/neko-master.git
+cd neko-master
+
+# 2. Install dependencies
+pnpm install
+
+# 3. Start development server
+pnpm dev
+```
+
+Visit <http://localhost:3000>
+
+## 📖 First Time Setup
+
+![First Time Setup](./assets/neko-master-setup.png)
+
+1. Open <http://localhost:3000>
+2. A **Gateway Configuration** dialog will appear on first visit.
+3. Fill in your network gateway (e.g., OpenClash) connection info:
+ - **Name**: Custom name (e.g., "Home Gateway")
+ - **Host**: Gateway backend IP (e.g., `192.168.101.1`)
+ - **Port**: Gateway backend port (e.g., `9090`)
+ - **Token**: Fill in if Secret is configured, otherwise leave empty
+4. Click "Add Backend" to save.
+5. The system will start collecting and analyzing traffic data.
+
+> 💡 **Get Gateway Address**: Go to your gateway panel (e.g., OpenClash) → Open "External Control" → Copy API Address.
+
+## 🔧 Port Conflict Resolution
+
+If you see an error about ports being occupied, here are the solutions:
+
+### Option 1: Use .env File
+
+Create a `.env` file (same directory as `docker-compose.yml`):
+
+```env
+WEB_EXTERNAL_PORT=8080 # Modify Web UI port
+API_EXTERNAL_PORT=8081 # Modify API port
+WS_EXTERNAL_PORT=8082 # Modify WebSocket external port (for direct connection)
+```
+
+Then restart:
+
+```bash
+docker compose down
+docker compose up -d
+```
+
+Now visit <http://localhost:8080>
+
+### Option 2: Modify docker-compose.yml Directly
+
+```yaml
+ports:
+ - "8080:3000" # External 8080 -> Internal 3000
+ - "8082:3002" # External 8082 -> Internal 3002 (for reverse proxy/tunnel forwarding WS)
+```
+
+> Note: The frontend reads the external port configuration at runtime, no need to set `NEXT_PUBLIC_WS_PORT` manually.
+
+### Option 3: Use One-Click Script
+
+```bash
+curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/setup.sh | bash
+```
+
+The script automatically detects and provides available ports.
+
+## 🔐 Authentication & Security
+
+Neko Master supports access authentication to protect your dashboard data security.
+
+### Enable/Disable Authentication
+
+1. Enter the dashboard and click "Settings" at the bottom of the left sidebar.
+2. Switch to the "Security" tab.
+3. On this page, you can enable/disable access control and set an access token.
+
+### Forgot Password (Reset Access Token)
+
+If you forget your access token, you can force entering **Emergency Access Mode** via the environment variable `FORCE_ACCESS_CONTROL_OFF`.
+
+#### Docker Compose Users
+
+1. Modify `docker-compose.yml` and add under `environment`:
+
+ ```yaml
+ environment:
+ - FORCE_ACCESS_CONTROL_OFF=true
+ ```
+
+2. Restart the container:
+
+ ```bash
+ docker compose up -d
+ ```
+
+3. Refresh the page, and you will see an "Emergency Access Mode" warning. You can now reset a new token in "Settings -> Security" without the old password.
+
+4. **IMPORTANT**: After resetting, make sure to remove this environment variable and restart the container again to restore access control.
+
+#### Docker CLI Users
+
+1. Stop and remove the old container (data in mounted volumes will not be lost):
+
+ ```bash
+ docker stop neko-master
+ docker rm neko-master
+ ```
+
+2. Add the `-e FORCE_ACCESS_CONTROL_OFF=true` parameter and restart:
+
+ ```bash
+ docker run -d \
+ --name neko-master \
+ -p 3000:3000 \
+ -v $(pwd)/data:/app/data \
+ -e FORCE_ACCESS_CONTROL_OFF=true \
+ foru17/neko-master:latest
+ ```
+
+3. After resetting the password, stop the container again, remove the parameter, and restart to restore normal protection mode.
+
+## 🐳 Docker Configuration
+
+### Ports
+
+| Port | Usage | Required Externally | Description |
+| :--: | :---: | :---: | :--- |
+| 3000 | Web UI | ✅ | Frontend access entry |
+| 3001 | API | Optional | Default same-origin `/api`, usually no need to expose |
+| 3002 | WebSocket | Optional | Real-time push port, recommended for reverse proxy forwarding only |
+
+### Environment Variables (Docker)
+
+| Variable | Default | Description | When to Set |
+| :-------------------- | :------------------- | :----------------------------------------------- | :------------------------ |
+| `WEB_PORT` | `3000` | Web service listening port (internal) | Usually unchanged |
+| `API_PORT` | `3001` | API service listening port (internal) | Usually unchanged |
+| `COLLECTOR_WS_PORT` | `3002` | WS service listening port (internal) | Usually unchanged |
+| `DB_PATH` | `/app/data/stats.db` | SQLite data file path | Custom data directory |
+| `WEB_EXTERNAL_PORT` | `3000` | Injected external Web port for frontend display | External mapping change |
+| `API_EXTERNAL_PORT` | `3001` | Injected external API port for frontend | Direct API connection |
+| `WS_EXTERNAL_PORT` | `3002` | Injected external WS port for frontend | Direct WS connection |
+| `NEXT_PUBLIC_API_URL` | Empty | Force frontend API base URL (override `/api`) | API not same-origin |
+| `NEXT_PUBLIC_WS_URL` | Auto `/_cm_ws` | Custom frontend WS URL (override default) | Custom path/domain only |
+
+### API / WS Address Resolution Priority
+
+1. API: `runtime-config(API_URL)` → `NEXT_PUBLIC_API_URL` → Default same-origin `/api`
+2. WS: `runtime-config(WS_URL)` → `NEXT_PUBLIC_WS_URL` → Auto-inferred
+3. Default uses same-origin `/_cm_ws`, generally no manual config needed unless using custom routing.
+
+## 🌐 Reverse Proxy & Tunnel
+
+Recommended to host Web and WS under the same domain, forwarding via different paths: `/` → `3000`, `/_cm_ws` → `3002`.
+
+### Nginx Example (Recommended)
+
+```nginx
+server {
+ listen 443 ssl http2;
+ server_name neko.example.com;
+
+ location / {
+ proxy_pass http://<neko-master-host>:3000;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ }
+
+ location ^~ /_cm_ws {
+ proxy_pass http://<neko-master-host>:3002;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection "upgrade";
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_read_timeout 86400;
+ proxy_send_timeout 86400;
+ proxy_buffering off;
+ }
+}
+```
+
+配套 Docker environment:
+
+```env
+# Default no config needed (defaults to /_cm_ws)
+# If custom path needed:
+# NEXT_PUBLIC_WS_URL=/custom_ws
+```
+
+### Cloudflare Tunnel Example
+
+`~/.cloudflared/config.yml`:
+
+```yaml
+tunnel: <your-tunnel-name-or-id>
+credentials-file: /path/to/<credentials>.json
+
+ingress:
+ - hostname: neko.example.com
+ path: /_cm_ws*
+ service: http://localhost:3002
+ - hostname: neko.example.com
+ path: /*
+ service: http://localhost:3000
+ - service: http_status:404
+```
+
+Start:
+
+```bash
+cloudflared tunnel --config ~/.cloudflared/config.yml run <your-tunnel-name-or-id>
+```
+
+If using Zero Trust Dashboard, ensure `/_cm_ws*` rule is placed **before** `/*`.
+
+### Key Notes
+
+1. Do NOT use `ws` (without leading `/`) for WS path, it may match static assets like `/_next/static/...` causing `426 Upgrade Required`.
+2. WS route must have higher priority than catch-all route (`/*`).
+3. `NEXT_PUBLIC_WS_URL` is usually not needed; if customized, restart frontend.
+4. Mapping only `3000` works but falls back to HTTP polling (slower).
+5. Third-party script failures (e.g., `beacon.min.js`) usually don't affect main functionality.
+6. No separate `/api` proxy needed by default (frontend forwards `/api` internally to `3001`).
+
+### Multi-Arch Support
+
+Docker image supports both `linux/amd64` and `linux/arm64`.
+
+### Data Persistence
+
+Data defaults to `/app/data` inside container. Map it to host recommended:
+
+```yaml
+volumes:
+ - ./data:/app/data
+```
+
+### Update to Latest
+
+```bash
+docker compose pull
+docker compose up -d
+```
+
+## ❓ FAQ
+
+### Q: "Port already occupied" error?
+
+**A:** See [Port Conflict Resolution](#-port-conflict-resolution). Easiest way is to modify ports via `.env`.
+
+### Q: Cannot access after changing port?
+
+**A:** Ensure:
+1. `.env` file updated.
+2. Service restarted: `docker compose restart`.
+3. Visiting with new port (e.g., `http://localhost:8080`).
+
+### Q: Upgrading from old version, only mapping 3000?
+
+**A:** Compatible. Page works, automatically falls back to HTTP polling if WS not connected.
+For real-time experience, configure reverse proxy path (e.g., `/_cm_ws`) to `3002`.
+
+### Q: Unstable connection / Upgrade Required error?
+
+**A:** Often due to WS route matching too broadly (catching static files). Check:
+1. Use `/_cm_ws*` path for WS.
+2. Priority higher than `/*`.
+
+### Q: OpenClash connection failed?
+
+**A:** Check:
+1. OpenClash "External Control" enabled.
+2. Correct Host/Port.
+3. Secret Token matches (if set).
+4. Container network connectivity to OpenClash.
+
+### Q: How to view logs?
+
+**A:** `docker logs -f neko-master`
+
+### Q: How to backup data?
+
+**A:** Backup the mapped directory (default `./data/stats.db`).
+
+### Q: How to clear history?
+
+**A:** Settings -> Database -> Select range to clear.
+
+## 📁 Project Structure
+
+```
+neko-master/
+├── docker-compose.yml # Docker Compose config
+├── Dockerfile # Docker build
+├── setup.sh # Setup script
+├── docker-start.sh # Container start script
+├── start.sh # Dev start script
+├── assets/ # Assets
+├── apps/
+│ ├── collector/ # Node.js + WebSocket service
+│ └── web/ # Next.js frontend
+└── packages/
+ └── shared/ # Shared types
+```
+
+## 🛠️ Tech Stack
+
+- **Frontend**: Next.js 16 + React 19 + TypeScript + Tailwind CSS
+- **UI**: shadcn/ui
+- **Collector**: Node.js + Fastify + WebSocket + SQLite
+- **Viz**: Recharts + D3.js
+- **i18n**: next-intl
+- **Deploy**: Docker + Docker Compose
+
+## 📄 License
+
+MIT License © 2024 [foru17](https://github.com/foru17)
diff --git a/apps/collector/.env.example b/apps/collector/.env.example
index 3a1502e..94b7455 100644
--- a/apps/collector/.env.example
+++ b/apps/collector/.env.example
@@ -12,3 +12,7 @@
# ⚠️ 注意:Gateway 后端配置通过 Web 界面动态添加
# 无需在此文件配置 GATEWAY_URL 或 GATEWAY_TOKEN
+
+# ⚠️ 紧急访问控制(仅在忘记密码且无法找回时使用)
+# 设置为 true 以强制关闭访问控制,允许无密码登录并重置密码
+# FORCE_ACCESS_CONTROL_OFF=false
diff --git a/apps/collector/src/app.ts b/apps/collector/src/app.ts
index b507dc1..36c5fac 100644
--- a/apps/collector/src/app.ts
+++ b/apps/collector/src/app.ts
@@ -12,6 +12,7 @@ import type { RealtimeStore } from './realtime.js';
// Import modules
import { BackendService, backendController } from './modules/backend/index.js';
import { StatsService, statsController } from './modules/stats/index.js';
+import { AuthService, authController } from './modules/auth/index.js';
// Extend Fastify instance to include services
declare module 'fastify' {
@@ -43,10 +44,12 @@ export async function createApp(options: AppOptions) {
// Create services
const backendService = new BackendService(db, realtimeStore);
const statsService = new StatsService(db, realtimeStore);
+ const authService = new AuthService(db);
// Decorate Fastify instance with services
app.decorate('backendService', backendService);
app.decorate('statsService', statsService);
+ app.decorate('authService', authService);
const getBackendIdFromQuery = (query: Record<string, unknown>): number | null => {
const backendId = typeof query.backendId === 'string' ? query.backendId : undefined;
@@ -206,9 +209,43 @@ export async function createApp(options: AppOptions) {
}
});
+ // Auth middleware - protects API routes
+ app.addHook('onRequest', async (request, reply) => {
+ // Skip auth for public routes
+ const publicRoutes = [
+ '/health',
+ '/api/auth/state',
+ '/api/auth/verify',
+ ];
+
+ // Check if route is public
+ if (publicRoutes.some(route => request.url.startsWith(route))) {
+ return;
+ }
+
+ // Check if auth is required
+ if (!authService.isAuthRequired()) {
+ return;
+ }
+
+ // Get token from header
+ const authHeader = request.headers.authorization;
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
+ return reply.status(401).send({ error: 'Authentication required' });
+ }
+
+ const token = authHeader.slice(7);
+ const verifyResult = await authService.verifyToken(token);
+
+ if (!verifyResult.valid) {
+ return reply.status(401).send({ error: verifyResult.message || 'Invalid token' });
+ }
+ });
+
// Register controllers
await app.register(backendController, { prefix: '/api/backends' });
await app.register(statsController, { prefix: '/api/stats' });
+ await app.register(authController, { prefix: '/api/auth' });
// Start server
await app.listen({ port, host: '0.0.0.0' });
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index 6ba6233..8cfbb1a 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -431,6 +431,22 @@ export class StatsDatabase {
('retention.auto_cleanup', '1');
`);
+ // Auth configuration table - stores authentication settings
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS auth_config (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ `);
+
+ // Insert default auth config if not exists
+ this.db.exec(`
+ INSERT OR IGNORE INTO auth_config (key, value) VALUES
+ ('enabled', '0'),
+ ('token_hash', '');
+ `);
+
// Migrate existing data if needed (from single-backend schema)
this.migrateIfNeeded();
}
@@ -5234,6 +5250,44 @@ export class StatsDatabase {
};
}
+ // Auth Configuration Methods
+
+ // Get auth configuration
+ getAuthConfig(): { enabled: boolean; tokenHash: string | null; updatedAt: string } {
+ const enabledStmt = this.db.prepare(`
+ SELECT value, updated_at FROM auth_config WHERE key = 'enabled'
+ `);
+ const tokenStmt = this.db.prepare(`
+ SELECT value, updated_at FROM auth_config WHERE key = 'token_hash'
+ `);
+
+ const enabledRow = enabledStmt.get() as { value: string; updated_at: string } | undefined;
+ const tokenRow = tokenStmt.get() as { value: string; updated_at: string } | undefined;
+
+ return {
+ enabled: enabledRow?.value === '1',
+ tokenHash: tokenRow?.value || null,
+ updatedAt: tokenRow?.updated_at || enabledRow?.updated_at || new Date().toISOString(),
+ };
+ }
+
+ // Update auth configuration
+ updateAuthConfig(updates: { enabled?: boolean; tokenHash?: string | null }): void {
+ if (updates.enabled !== undefined) {
+ this.db.prepare(`
+ INSERT INTO auth_config (key, value) VALUES ('enabled', ?)
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP
+ `).run(updates.enabled ? '1' : '0');
+ }
+
+ if (updates.tokenHash !== undefined) {
+ this.db.prepare(`
+ INSERT INTO auth_config (key, value) VALUES ('token_hash', ?)
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP
+ `).run(updates.tokenHash || '');
+ }
+ }
+
close() {
this.db.close();
}
diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.ts
index e254fe0..3a70353 100644
--- a/apps/collector/src/index.ts
+++ b/apps/collector/src/index.ts
@@ -1,4 +1,14 @@
import { config } from 'dotenv';
+import path from 'path';
+import fs from 'fs';
+
+// Load .env.local if it exists (takes precedence over .env, but not shell)
+const envLocalPath = path.join(process.cwd(), '.env.local');
+if (fs.existsSync(envLocalPath)) {
+ config({ path: envLocalPath });
+}
+
+// Load .env (defaults)
config();
import { StatsDatabase, BackendConfig } from './db.js';
@@ -10,7 +20,6 @@ let wsServer: StatsWebSocketServer;
import { APIServer } from './app.js';
import { GeoIPService } from './geo-service.js';
-import path from 'path';
const COLLECTOR_WS_PORT = parseInt(process.env.COLLECTOR_WS_PORT || '3002');
const API_PORT = parseInt(process.env.API_PORT || '3001');
diff --git a/apps/collector/src/modules/auth/auth.controller.ts b/apps/collector/src/modules/auth/auth.controller.ts
new file mode 100644
index 0000000..e74f5ef
--- /dev/null
+++ b/apps/collector/src/modules/auth/auth.controller.ts
@@ -0,0 +1,148 @@
+/**
+ * Auth Controller
+ *
+ * Fastify routes for authentication management.
+ */
+
+import type { FastifyInstance } from 'fastify';
+import type { AuthService } from './auth.service.js';
+
+// Extend Fastify instance
+declare module 'fastify' {
+ interface FastifyInstance {
+ authService: AuthService;
+ }
+}
+
+export async function authController(app: FastifyInstance) {
+ const authService = app.authService;
+
+ /**
+ * GET /api/auth/state
+ * Get current auth state (public - no token required)
+ */
+ app.get('/state', async () => {
+ return authService.getAuthState();
+ });
+
+ /**
+ * POST /api/auth/verify
+ * Verify a token (public - used for login)
+ */
+ app.post('/verify', async (request, reply) => {
+ const body = request.body as { token?: string };
+ const token = body?.token;
+
+ if (!token) {
+ return reply.status(400).send({
+ valid: false,
+ message: 'Token is required'
+ });
+ }
+
+ const result = await authService.verifyToken(token);
+ return result;
+ });
+
+ /**
+ * POST /api/auth/enable
+ * Enable authentication (requires no auth when first enabling,
+ * but requires existing token if already enabled)
+ */
+ app.post('/enable', async (request, reply) => {
+ const body = request.body as { token?: string };
+ const token = body?.token;
+
+ if (!token) {
+ return reply.status(400).send({
+ error: 'Token is required'
+ });
+ }
+
+ try {
+ await authService.enableAuth(token);
+ return {
+ success: true,
+ message: 'Authentication enabled successfully'
+ };
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : 'Failed to enable authentication';
+ return reply.status(400).send({ error: message });
+ }
+ });
+
+ /**
+ * POST /api/auth/disable
+ * Disable authentication (requires valid token)
+ */
+ app.post('/disable', async (request, reply) => {
+ const body = request.body as { token?: string };
+ const token = body?.token;
+
+ // If auth is required, verify token first
+ // Skip verification if forced off
+ if (authService.isAuthRequired() && !authService.isForceAccessControlOff()) {
+ if (!token) {
+ return reply.status(401).send({
+ error: 'Token is required to disable authentication'
+ });
+ }
+
+ const verifyResult = await authService.verifyToken(token);
+ if (!verifyResult.valid) {
+ return reply.status(401).send({
+ error: verifyResult.message || 'Invalid token'
+ });
+ }
+ }
+
+ authService.disableAuth();
+ return {
+ success: true,
+ message: 'Authentication disabled successfully'
+ };
+ });
+
+ /**
+ * PUT /api/auth/token
+ * Update token (requires valid existing token)
+ */
+ app.put('/token', async (request, reply) => {
+ const body = request.body as { currentToken?: string; newToken?: string };
+ const { currentToken, newToken } = body;
+
+ // Verify current token if auth is enabled
+ // Skip verification if forced off
+ if (authService.isAuthRequired() && !authService.isForceAccessControlOff()) {
+ if (!currentToken) {
+ return reply.status(401).send({
+ error: 'Current token is required'
+ });
+ }
+
+ const verifyResult = await authService.verifyToken(currentToken);
+ if (!verifyResult.valid) {
+ return reply.status(401).send({
+ error: verifyResult.message || 'Invalid current token'
+ });
+ }
+ }
+
+ if (!newToken) {
+ return reply.status(400).send({
+ error: 'New token is required'
+ });
+ }
+
+ try {
+ await authService.updateToken(newToken);
+ return {
+ success: true,
+ message: 'Token updated successfully'
+ };
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : 'Failed to update token';
+ return reply.status(400).send({ error: message });
+ }
+ });
+}
diff --git a/apps/collector/src/modules/auth/auth.service.ts b/apps/collector/src/modules/auth/auth.service.ts
new file mode 100644
index 0000000..3d4d8cf
--- /dev/null
+++ b/apps/collector/src/modules/auth/auth.service.ts
@@ -0,0 +1,146 @@
+/**
+ * Auth Service
+ *
+ * Handles authentication configuration and token verification.
+ * Uses SHA-256 hashing for token storage (not encryption, but one-way hash).
+ */
+
+import type { StatsDatabase } from '../../db.js';
+import type { AuthConfig, AuthVerifyResult, AuthState } from './auth.types.js';
+
+// Simple hash function for token storage
+async function hashToken(token: string): Promise<string> {
+ // Use Node.js crypto for hashing
+ const crypto = await import('crypto');
+ return crypto.createHash('sha256').update(token).digest('hex');
+}
+
+export class AuthService {
+ private db: StatsDatabase;
+
+ constructor(db: StatsDatabase) {
+ this.db = db;
+ }
+
+ /**
+ * Get current auth configuration
+ */
+ getAuthConfig(): AuthConfig {
+ const config = this.db.getAuthConfig();
+ return config;
+ }
+
+ /**
+ * Check if access control is forced off via environment variable
+ */
+ isForceAccessControlOff(): boolean {
+ return process.env.FORCE_ACCESS_CONTROL_OFF === 'true';
+ }
+
+ /**
+ * Get auth state (for public API - doesn't expose hash)
+ */
+ getAuthState(): AuthState {
+ const config = this.db.getAuthConfig();
+ const forcedOff = this.isForceAccessControlOff();
+
+ return {
+ enabled: forcedOff ? false : config.enabled,
+ hasToken: !!config.tokenHash,
+ forceAccessControlOff: forcedOff,
+ };
+ }
+
+ /**
+ * Verified token if valid
+ */
+ async verifyToken(token: string): Promise<AuthVerifyResult> {
+ if (this.isForceAccessControlOff()) {
+ return { valid: true };
+ }
+
+ const config = this.db.getAuthConfig();
+
+ if (!config.enabled || !config.tokenHash) {
+ return { valid: true };
+ }
+
+ const tokenHash = await hashToken(token);
+
+ if (tokenHash === config.tokenHash) {
+ return { valid: true };
+ }
+
+ return { valid: false, message: 'Invalid token' };
+ }
+
+ /**
+ * Enable authentication with a new token
+ */
+ async enableAuth(token: string): Promise<void> {
+ if (!this.isValidTokenFormat(token)) {
+ throw new Error('Invalid token format. Token must be at least 6 characters and contain both letters and numbers.');
+ }
+
+ const tokenHash = await hashToken(token);
+ this.db.updateAuthConfig({
+ enabled: true,
+ tokenHash,
+ });
+ }
+
+ /**
+ * Disable authentication
+ */
+ disableAuth(): void {
+ this.db.updateAuthConfig({
+ enabled: false,
+ tokenHash: null,
+ });
+ }
+
+ /**
+ * Update token (when auth is already enabled)
+ */
+ async updateToken(token: string): Promise<void> {
+ if (!this.isValidTokenFormat(token)) {
+ throw new Error('Invalid token format. Token must be at least 6 characters and contain both letters and numbers.');
+ }
+
+ const tokenHash = await hashToken(token);
+ this.db.updateAuthConfig({
+ tokenHash,
+ });
+ }
+
+ /**
+ * Validate token format
+ * - At least 6 characters
+ * - Contains at least one letter
+ * - Contains at least one number
+ * - Not purely numbers or purely letters
+ */
+ isValidTokenFormat(token: string): boolean {
+ if (!token || token.length < 6) {
+ return false;
+ }
+
+ // Check for at least one letter
+ const hasLetter = /[a-zA-Z]/.test(token);
+ // Check for at least one number
+ const hasNumber = /[0-9]/.test(token);
+
+ return hasLetter && hasNumber;
+ }
+
+ /**
+ * Check if authentication is required
+ */
+ isAuthRequired(): boolean {
+ if (this.isForceAccessControlOff()) {
+ return false;
+ }
+ const config = this.db.getAuthConfig();
+ return config.enabled && !!config.tokenHash;
+ }
+}
diff --git a/apps/collector/src/modules/auth/auth.types.ts b/apps/collector/src/modules/auth/auth.types.ts
new file mode 100644
index 0000000..aeadf80
--- /dev/null
+++ b/apps/collector/src/modules/auth/auth.types.ts
@@ -0,0 +1,20 @@
+/**
+ * Auth Module Type Definitions
+ */
+
+export interface AuthConfig {
+ enabled: boolean;
+ tokenHash: string | null;
+ updatedAt: string;
+}
+
+export interface AuthVerifyResult {
+ valid: boolean;
+ message?: string;
+}
+
+export interface AuthState {
+ enabled: boolean;
+ hasToken: boolean;
+ forceAccessControlOff?: boolean;
+}
diff --git a/apps/collector/src/modules/auth/index.ts b/apps/collector/src/modules/auth/index.ts
new file mode 100644
index 0000000..f29aaf5
--- /dev/null
+++ b/apps/collector/src/modules/auth/index.ts
@@ -0,0 +1,9 @@
+/**
+ * Auth Module
+ *
+ * Authentication and authorization for the dashboard.
+ */
+
+export { AuthService } from './auth.service.js';
+export { authController } from './auth.controller.js';
+export type { AuthConfig, AuthVerifyResult, AuthState } from './auth.types.js';
diff --git a/apps/collector/src/websocket.ts b/apps/collector/src/websocket.ts
index dff1c6c..8bc218f 100644
--- a/apps/collector/src/websocket.ts
+++ b/apps/collector/src/websocket.ts
@@ -2,6 +2,9 @@ import { WebSocketServer as WSServer, WebSocket } from 'ws';
import type { StatsSummary } from '@neko-master/shared';
import type { StatsDatabase } from './db.js';
import { realtimeStore } from './realtime.js';
+import { AuthService } from './modules/auth/auth.service.js';
+import { IncomingMessage } from 'http';
+import { URL } from 'url';
export interface WebSocketMessage {
type: 'stats' | 'ping' | 'pong' | 'subscribe';
@@ -97,6 +100,7 @@ interface ClientInfo {
export class StatsWebSocketServer {
private wss: WSServer | null = null;
private db: StatsDatabase;
+ private authService: AuthService;
private clients: Map<WebSocket, ClientInfo> = new Map();
private port: number;
private lastBroadcastTime = 0;
@@ -105,6 +109,7 @@ export class StatsWebSocketServer {
constructor(port: number, db: StatsDatabase) {
this.port = port;
this.db = db;
+ this.authService = new AuthService(db);
}
start() {
@@ -114,8 +119,36 @@ export class StatsWebSocketServer {
perMessageDeflate: false,
});
- this.wss.on('connection', (ws: WebSocket, req) => {
- console.log(`[WebSocket] Connection from ${req.socket.remoteAddress}`);
+ this.wss.on('connection', async (ws: WebSocket, req: IncomingMessage) => {
+ console.log(`[WebSocket] Connection attempt from ${req.socket.remoteAddress}`);
+
+ // Verify authentication
+ try {
+ const url = new URL(req.url || '', `http://${req.headers.host}`);
+ const token = url.searchParams.get('token');
+
+ // Check if auth is required and verify token
+ if (this.authService.isAuthRequired()) {
+ if (!token) {
+ console.log(`[WebSocket] Rejected connection from ${req.socket.remoteAddress}: Missing token`);
+ ws.close(4001, 'Authentication required');
+ return;
+ }
+
+ const verifyResult = await this.authService.verifyToken(token);
+ if (!verifyResult.valid) {
+ console.log(`[WebSocket] Rejected connection from ${req.socket.remoteAddress}: Invalid token`);
+ ws.close(4003, 'Invalid token');
+ return;
+ }
+ }
+ } catch (error) {
+ console.error('[WebSocket] Error verifying auth:', error);
+ ws.close(4000, 'Internal server error');
+ return;
+ }
+
+ console.log(`[WebSocket] connection authorized from ${req.socket.remoteAddress}`);
console.log(`[WebSocket] Client connected, total: ${this.clients.size + 1}`);
const clientInfo: ClientInfo = {
diff --git a/apps/web/app/[locale]/dashboard/components/header/index.tsx b/apps/web/app/[locale]/dashboard/components/header/index.tsx
index 7c8d1e4..1bee880 100644
--- a/apps/web/app/[locale]/dashboard/components/header/index.tsx
+++ b/apps/web/app/[locale]/dashboard/components/header/index.tsx
@@ -13,6 +13,7 @@ import {
Monitor,
MoreVertical,
Info,
+ LogOut,
} from "lucide-react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
@@ -49,6 +50,8 @@ interface Backend {
listening: boolean;
}
+import { useAuth } from "@/lib/auth";
+
interface HeaderProps {
// Backend data
backends: Backend[];
@@ -113,6 +116,8 @@ export function Header({
backendT,
dashboardT,
}: HeaderProps) {
+ const { logout, authState } = useAuth();
+
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">
@@ -276,7 +281,19 @@ export function Header({
onChange={onTimeRangeChange}
/>
<LanguageSwitcher />
+
<ThemeToggle />
+ {authState?.enabled && (
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={logout}
+ title={dashboardT("logout")}
+ className="h-9 w-9 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
+ >
+ <LogOut className="w-4 h-4" />
+ </Button>
+ )}
</div>
{/* Mobile: Time range picker */}
@@ -435,6 +452,15 @@ export function Header({
<Info className="w-4 h-4 mr-2 text-primary" />
About
</DropdownMenuItem>
+ {authState?.enabled && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={logout} className="text-destructive focus:text-destructive focus:bg-destructive/10">
+ <LogOut className="w-4 h-4 mr-2" />
+ {dashboardT("logout")}
+ </DropdownMenuItem>
+ </>
+ )}
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/apps/web/app/[locale]/dashboard/hooks/use-dashboard.ts b/apps/web/app/[locale]/dashboard/hooks/use-dashboard.ts
index 2234023..208e9be 100644
--- a/apps/web/app/[locale]/dashboard/hooks/use-dashboard.ts
+++ b/apps/web/app/[locale]/dashboard/hooks/use-dashboard.ts
@@ -22,6 +22,7 @@ import {
} from "@/lib/stats-query-keys";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { useStatsWebSocket } from "@/lib/websocket";
+import { useRequireAuth } from "@/lib/auth-queries";
import type {
StatsSummary,
CountryStats,
@@ -115,6 +116,10 @@ export function useDashboard(): UseDashboardReturn {
const stableTimeRange = useStableTimeRange(timeRange);
const isWsSummaryTab = activeTab === "overview" || activeTab === "countries";
+
+ // Auth check
+ const { showLogin, isLoading: isAuthLoading } = useRequireAuth();
+ const shouldFetch = !showLogin && !isAuthLoading;
// Backends Query
const backendsQuery = useQuery({
@@ -122,6 +127,7 @@ export function useDashboard(): UseDashboardReturn {
queryFn: () => api.getBackends(),
refetchInterval: autoRefresh ? 5000 : false,
refetchIntervalInBackground: true,
+ enabled: shouldFetch,
});
const backends = backendsQuery.data ?? [];
@@ -287,8 +293,14 @@ export function useDashboard(): UseDashboardReturn {
// Open setup dialog automatically when no backend is configured
useEffect(() => {
+ // Don't open backend dialog if we need to login
+ if (showLogin) return;
+
if (backendsQuery.isError) return;
+ // Strictly check if data is present to avoid "empty" state during initial loading/idle
+ if (!backendsQuery.data && !backendsQuery.isSuccess) return;
if (backendsQuery.isLoading || backendsQuery.isFetching) return;
+
if (backends.length === 0) {
setIsFirstTime(true);
setShowBackendDialog(true);
@@ -303,6 +315,7 @@ export function useDashboard(): UseDashboardReturn {
backendsQuery.isFetching,
backendsQuery.isLoading,
isFirstTime,
+ showLogin,
]);
// Rolling presets: keep the time window moving
diff --git a/apps/web/app/[locale]/dashboard/layout.tsx b/apps/web/app/[locale]/dashboard/layout.tsx
index a7f4b62..56d2a91 100644
--- a/apps/web/app/[locale]/dashboard/layout.tsx
+++ b/apps/web/app/[locale]/dashboard/layout.tsx
@@ -1,9 +1,74 @@
-import { ReactNode } from "react";
+"use client";
+
+import { ReactNode, useEffect } from "react";
+import { useRequireAuth, useLogin, authKeys } from "@/lib/auth-queries";
+import { LoginDialog } from "@/components/features/auth";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+import { useQueryClient } from "@tanstack/react-query";
export default function DashboardLayout({
children,
}: {
children: ReactNode;
}) {
- return children;
+ const t = useTranslations("auth");
+ const queryClient = useQueryClient();
+ const { showLogin, isLoading, authEnabled, error } = useRequireAuth();
+ const loginMutation = useLogin();
+
+ // Listen for 401 errors from API requests
+ useEffect(() => {
+ const handleUnauthorized = () => {
+ // Invalidate auth state to trigger re-check
+ queryClient.invalidateQueries({ queryKey: authKeys.state() });
+ };
+
+ window.addEventListener("api:unauthorized", handleUnauthorized);
+ return () => window.removeEventListener("api:unauthorized", handleUnauthorized);
+ }, [queryClient]);
+
+ // Also check when error changes
+ useEffect(() => {
+ if (error) {
+ console.log("Auth state error:", error);
+ }
+ }, [error]);
+
+ const handleLogin = async (token: string): Promise<boolean> => {
+ try {
+ await loginMutation.mutateAsync(token);
+ return true;
+ } catch (error) {
+ toast.error(t("invalidToken"));
+ return false;
+ }
+ };
+
+ // Show loading state while checking auth
+ if (isLoading) {
+ return (
+ <div className="flex items-center justify-center min-h-screen">
+ <div className="animate-pulse text-muted-foreground">
+ Loading...
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <>
+ {children}
+ <LoginDialog
+ open={showLogin}
+ onOpenChange={(open) => {
+ // Prevent closing the dialog when auth is required
+ if (!open && showLogin) {
+ return;
+ }
+ }}
+ onLogin={handleLogin}
+ />
+ </>
+ );
}
diff --git a/apps/web/app/[locale]/layout.tsx b/apps/web/app/[locale]/layout.tsx
index 9cfdcd7..8e56fcf 100644
--- a/apps/web/app/[locale]/layout.tsx
+++ b/apps/web/app/[locale]/layout.tsx
@@ -3,6 +3,8 @@ import { Geist, Geist_Mono } from "next/font/google";
import "../globals.css";
import { ThemeProvider } from "@/components/providers/theme-provider";
import { QueryProvider } from "@/components/providers/query-provider";
+import { AuthProvider } from "@/lib/auth";
+import { AuthGuard } from "@/components/features/auth/auth-guard";
import { NextIntlClientProvider } from "next-intl";
import { getMessages } from "next-intl/server";
import { notFound } from "next/navigation";
@@ -76,11 +78,14 @@ export default async function RootLayout({
</head>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
- <ThemeProvider attribute="class" defaultTheme="dark" enableSystem>
+ <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
<QueryProvider>
- <NextIntlClientProvider messages={messages}>
- {children}
- </NextIntlClientProvider>
+ <AuthProvider>
+ <NextIntlClientProvider messages={messages}>
+ <AuthGuard />
+ {children}
+ </NextIntlClientProvider>
+ </AuthProvider>
</QueryProvider>
</ThemeProvider>
<ServiceWorkerRegister />
diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css
index 3219e50..24aba02 100644
--- a/apps/web/app/globals.css
+++ b/apps/web/app/globals.css
@@ -327,3 +327,21 @@
.chain-flow-graph .react-flow__node {
transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}
+
+/* Custom Gradient Animation */
+@keyframes gradient-x {
+ 0% {
+ background-position: 0% 50%;
+ }
+ 50% {
+ background-position: 100% 50%;
+ }
+ 100% {
+ background-position: 0% 50%;
+ }
+}
+
+.animate-gradient-x {
+ background-size: 200% 200%;
+ animation: gradient-x 3s linear infinite;
+}
diff --git a/apps/web/components/features/auth/auth-guard.tsx b/apps/web/components/features/auth/auth-guard.tsx
new file mode 100644
index 0000000..fc94392
--- /dev/null
+++ b/apps/web/components/features/auth/auth-guard.tsx
@@ -0,0 +1,28 @@
+"use client";
+
+import { useRequireAuth, useLogin } from "@/lib/auth-queries";
+import { LoginDialog } from "./login-dialog";
+
+export function AuthGuard() {
+ const { showLogin } = useRequireAuth();
+ const loginMutation = useLogin();
+
+ const handleLogin = async (token: string) => {
+ try {
+ await loginMutation.mutateAsync(token);
+ return true;
+ } catch (e) {
+ return false;
+ }
+ };
+
+ if (!showLogin) return null;
+
+ return (
+ <LoginDialog
+ open={true}
+ onOpenChange={() => {}}
+ onLogin={handleLogin}
+ />
+ );
+}
diff --git a/apps/web/components/features/auth/index.ts b/apps/web/components/features/auth/index.ts
new file mode 100644
index 0000000..496f262
--- /dev/null
+++ b/apps/web/components/features/auth/index.ts
@@ -0,0 +1 @@
+export { LoginDialog } from "./login-dialog";
diff --git a/apps/web/components/features/auth/login-dialog.tsx b/apps/web/components/features/auth/login-dialog.tsx
new file mode 100644
index 0000000..89a9593
--- /dev/null
+++ b/apps/web/components/features/auth/login-dialog.tsx
@@ -0,0 +1,241 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { Lock, Eye, EyeOff, AlertCircle, Check, Loader2 } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { motion, AnimatePresence } from "framer-motion";
+import Image from "next/image";
+import { Input } from "@/components/ui/input";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { cn } from "@/lib/utils";
+
+const CAT_OPEN_EYE = "/images/neko-open-eye.png";
+const CAT_CLOSE_EYE = "/images/neko-open-close.png";
+
+interface LoginDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onLogin: (token: string) => Promise<boolean>;
+}
+
+export function LoginDialog({ open, onOpenChange, onLogin }: LoginDialogProps) {
+ const t = useTranslations("auth");
+ const [token, setToken] = useState("");
+ const [showToken, setShowToken] = useState(false);
+ const [isFocused, setIsFocused] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
+ const [isSuccess, setIsSuccess] = useState(false);
+ const [error, setError] = useState("");
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+
+ if (!token.trim()) {
+ setError(t("tokenRequired"));
+ return;
+ }
+
+ setIsLoading(true);
+ setError("");
+
+ try {
+ const success = await onLogin(token);
+ if (success) {
+ setIsSuccess(true);
+ // Wait for animation
+ setTimeout(() => {
+ setToken("");
+ setIsSuccess(false);
+ onOpenChange(false);
+ }, 1500);
+ } else {
+ setError(t("invalidToken"));
+ setIsLoading(false);
+ }
+ } catch (err) {
+ setError(t("loginError"));
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent
+ className="sm:max-w-md overflow-visible bg-transparent shadow-none border-none p-0"
+ showCloseButton={!isSuccess}
+ aria-describedby={undefined}
+ >
+ <AnimatePresence mode="wait">
+ {isSuccess ? (
+ <motion.div
+ key="success"
+ initial={{ opacity: 0, scale: 0.9 }}
+ animate={{ opacity: 1, scale: 1 }}
+ exit={{ opacity: 0, scale: 0.9 }}
+ className="flex flex-col items-center justify-center py-10 space-y-4 bg-background border shadow-lg rounded-lg p-6"
+ >
+ <div className="relative w-32 h-32 mb-4">
+ <Image
+ src={CAT_OPEN_EYE}
+ alt="Success Cat"
+ fill
+ className="object-contain drop-shadow-xl"
+ priority
+ />
+ <motion.div
+ initial={{ scale: 0 }}
+ animate={{ scale: 1 }}
+ transition={{ type: "spring", stiffness: 200, damping: 10, delay: 0.1 }}
+ className="absolute -bottom-2 -right-2 w-10 h-10 rounded-full bg-green-500 flex items-center justify-center text-white shadow-lg shadow-green-500/20 z-10"
+ >
+ <Check className="w-6 h-6 stroke-[3]" />
+ </motion.div>
+ </div>
+ <motion.div
+ initial={{ opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ delay: 0.2 }}
+ className="text-center"
+ >
+ <h3 className="text-xl font-bold text-green-600 dark:text-green-400">
+ {t("loginSuccess") || "Login Successful"}
+ </h3>
+ <p className="text-sm text-muted-foreground mt-1">
+ {t("redirecting") || "Redirecting to dashboard..."}
+ </p>
+ </motion.div>
+ </motion.div>
+ ) : (
+ <motion.div
+ key="form"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ className="relative"
+ >
+ {/* Cat Animation - Behind the card */}
+ <div className="absolute -top-28 left-1/2 -translate-x-1/2 z-0 pointer-events-none">
+ <div className="relative w-40 h-32 transition-transform duration-300 ease-in-out hover:scale-105">
+ {/* Closed Eye Cat (Always present as base) */}
+ <div className="absolute inset-0">
+ <Image
+ src={CAT_CLOSE_EYE}
+ alt="Cat Closed Eyes"
+ fill
+ className="object-contain drop-shadow-2xl filter brightness-110"
+ priority
+ />
+ </div>
+
+ {/* Open Eye Cat (Overlay that fades out) */}
+ <motion.div
+ className="absolute inset-0"
+ initial={{ opacity: 1 }}
+ animate={{ opacity: isFocused ? 0 : 1 }}
+ transition={{ duration: 0.2 }}
+ >
+ <Image
+ src={CAT_OPEN_EYE}
+ alt="Cat Open Eyes"
+ fill
+ className="object-contain drop-shadow-2xl filter brightness-110"
+ priority
+ />
+ </motion.div>
+ </div>
+ </div>
+
+ {/* Card Content - In front of the cat */}
+ <div className="relative z-10 bg-background border shadow-lg rounded-lg p-6 pt-10">
+ <DialogTitle className="sr-only">
+ {t("loginTitle")}
+ </DialogTitle>
+
+ <form onSubmit={handleSubmit} className="space-y-4 mt-4">
+ <div className="space-y-2">
+ <div className="relative">
+ <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
+ <Input
+ type={showToken ? "text" : "password"}
+ placeholder={t("tokenPlaceholder")}
+ value={token}
+ onChange={(e) => setToken(e.target.value)}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ className={cn(
+ "pl-10 pr-10",
+ error && "border-destructive focus-visible:ring-destructive"
+ )}
+ disabled={isLoading}
+ autoComplete="off"
+ autoFocus
+ />
+ <button
+ type="button"
+ onClick={() => setShowToken(!showToken)}
+ className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
+ tabIndex={-1}
+ >
+ {showToken ? (
+ <EyeOff className="w-4 h-4" />
+ ) : (
+ <Eye className="w-4 h-4" />
+ )}
+ </button>
+ </div>
+
+ {error && (
+ <div className="flex items-center gap-2 text-sm text-destructive">
+ <AlertCircle className="w-4 h-4 flex-shrink-0" />
+ <span>{error}</span>
+ </div>
+ )}
+ </div>
+
+ <Button
+ type="submit"
+ className="w-full relative overflow-hidden bg-gradient-to-r from-[#181878] via-[#668af4] to-[#181878] hover:opacity-90 transition-all border-none animate-gradient-x disabled:opacity-100"
+ disabled={isLoading || !token.trim()}
+ >
+ <AnimatePresence mode="wait">
+ {isLoading ? (
+ <motion.div
+ key="loading"
+ initial={{ opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: -10 }}
+ className="flex items-center gap-2"
+ >
+ <Loader2 className="w-4 h-4 animate-spin" />
+ {t("loggingIn")}
+ </motion.div>
+ ) : (
+ <motion.span
+ key="label"
+ initial={{ opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: -10 }}
+ >
+ {t("login")}
+ </motion.span>
+ )}
+ </AnimatePresence>
+ </Button>
+ </form>
+
+ </div>
+ </motion.div>
+
+ )}
+ </AnimatePresence>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/web/components/features/backend/backend-config-dialog.tsx b/apps/web/components/features/backend/backend-config-dialog.tsx
index 144ecd6..725ab59 100644
--- a/apps/web/components/features/backend/backend-config-dialog.tsx
+++ b/apps/web/components/features/backend/backend-config-dialog.tsx
@@ -1,7 +1,8 @@
"use client";
-import { useState, useEffect } from "react";
+import { useState, useEffect, useRef } from "react";
import { useTranslations } from "next-intl";
+import { useQueryClient } from "@tanstack/react-query";
import {
Server,
Plus,
@@ -11,6 +12,7 @@ import {
X,
RefreshCw,
AlertCircle,
+ ShieldAlert,
CheckCircle2,
Database,
HardDrive,
@@ -20,6 +22,10 @@ import {
Eye,
SlidersHorizontal,
Globe,
+ Shield,
+ Lock,
+ EyeOff,
+ Key,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -35,6 +41,14 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
import { cn, formatBytes, formatNumber } from "@/lib/utils";
import { api } from "@/lib/api";
import { toast } from "sonner";
@@ -43,6 +57,7 @@ import { useSettings, FaviconProvider, getFaviconUrl } from "@/lib/settings";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Separator } from "@/components/ui/separator";
+import { useAuthState, authKeys, getStoredToken } from "@/lib/auth-queries";
// Favicon Provider Preview Component
function FaviconProviderPreview({
@@ -302,7 +317,7 @@ export function BackendConfigDialog({
message: string;
} | null>(null);
const [activeTab, setActiveTab] = useState<
- "backends" | "database" | "preferences"
+ "backends" | "database" | "preferences" | "security"
>("backends");
const { settings, setSettings } = useSettings();
const [dbStats, setDbStats] = useState<DbStats | null>(null);
@@ -332,8 +347,27 @@ export function BackendConfigDialog({
const [errorMessage, setErrorMessage] = useState("");
// Success Alert Dialog State
- const [successDialogOpen, setSuccessDialogOpen] = useState(false);
- const [successMessage, setSuccessMessage] = useState("");
+
+
+ // React Query Client
+ const queryClient = useQueryClient();
+
+ // Auth State from React Query
+ const { data: authState } = useAuthState();
+ const authEnabled = authState?.enabled ?? false;
+
+ // Local auth form state
+ const [authToken, setAuthToken] = useState("");
+ const [showAuthToken, setShowAuthToken] = useState(false);
+ const [authLoading, setAuthLoading] = useState(false);
+ const [confirmEnableAuthDialogOpen, setConfirmEnableAuthDialogOpen] = useState(false);
+ const [confirmDisableAuthDialogOpen, setConfirmDisableAuthDialogOpen] = useState(false);
+ const [changeTokenDialogOpen, setChangeTokenDialogOpen] = useState(false);
+ const [changeTokenForm, setChangeTokenForm] = useState({
+ current: "",
+ new: "",
+ confirm: "",
+ });
// Verify Animation State
const [showVerifyAnimation, setShowVerifyAnimation] = useState(false);
@@ -693,8 +727,7 @@ export function BackendConfigDialog({
await api.clearLogs(clearLogsDays);
await loadDbStats();
setClearLogsDialogOpen(false);
- setSuccessMessage(t("logsCleared"));
- setSuccessDialogOpen(true);
+ toast.success(t("logsCleared"));
} catch (error: any) {
setErrorMessage(error.message || "Failed to clear logs");
setErrorDialogOpen(true);
@@ -703,6 +736,97 @@ export function BackendConfigDialog({
}
};
+ const [isTokenInvalid, setIsTokenInvalid] = useState(false);
+ const tokenInputRef = useRef<HTMLInputElement>(null);
+
+ // Validate token format
+ const isValidToken = (token: string): boolean => {
+ if (token.length < 6) return false;
+ const hasLetter = /[a-zA-Z]/.test(token);
+ const hasNumber = /[0-9]/.test(token);
+ return hasLetter && hasNumber;
+ };
+
+ // Handle enable auth
+ const handleEnableAuth = async () => {
+ if (!isValidToken(authToken)) {
+ // toast.error(t("invalidToken"));
+ setIsTokenInvalid(true);
+ tokenInputRef.current?.focus();
+ return;
+ }
+ setConfirmEnableAuthDialogOpen(true);
+ };
+
+ // Confirm enable auth
+ const confirmEnableAuth = async () => {
+ setAuthLoading(true);
+ try {
+ await api.enableAuth(authToken);
+ setAuthToken("");
+ setConfirmEnableAuthDialogOpen(false);
+ // Invalidate auth state cache to trigger refetch
+ queryClient.invalidateQueries({ queryKey: authKeys.state() });
+ toast.success(t("auth.enabledSuccess"));
+ } catch (error: any) {
+ toast.error(error.message || t("auth.enableFailed"));
+ } finally {
+ setAuthLoading(false);
+ }
+ };
+
+ // Handle disable auth
+ const handleDisableAuth = async () => {
+ setConfirmDisableAuthDialogOpen(true);
+ };
+
+ // Confirm disable auth
+ const confirmDisableAuth = async () => {
+ setAuthLoading(true);
+ try {
+ // Try to get stored token for verification
+ const storedToken = getStoredToken();
+ await api.disableAuth(storedToken || undefined);
+ setAuthToken("");
+ setConfirmDisableAuthDialogOpen(false);
+ // Invalidate auth state cache to trigger refetch
+ queryClient.invalidateQueries({ queryKey: authKeys.state() });
+ toast.success(t("auth.disabledSuccess"));
+ } catch (error: any) {
+ toast.error(error.message || t("auth.disableFailed"));
+ } finally {
+ setAuthLoading(false);
+ }
+ };
+
+ const handleChangeToken = async () => {
+ if (!changeTokenForm.new || changeTokenForm.new.length < 6) {
+ toast.error(t("auth.invalidToken"));
+ return;
+ }
+ if (changeTokenForm.new !== changeTokenForm.confirm) {
+ toast.error(t("auth.passwordsDoNotMatch"));
+ return;
+ }
+
+ setAuthLoading(true);
+ try {
+ const res = await api.updateToken(changeTokenForm.current, changeTokenForm.new);
+ if (res.success) {
+ setChangeTokenForm({ current: "", new: "", confirm: "" });
+ setChangeTokenDialogOpen(false);
+ toast.success(t("auth.tokenUpdated"));
+ } else {
+ throw new Error(res.message || commonT("error"));
+ }
+ } catch (error: any) {
+ setErrorMessage(error.message || t("auth.updateTokenFailed"));
+ setErrorDialogOpen(true);
+ } finally {
+ setAuthLoading(false);
+ }
+ };
+
const startEdit = (backend: Backend) => {
setEditingId(backend.id);
setEditFormData({
@@ -754,13 +878,6 @@ export function BackendConfigDialog({
<Server className="w-4 h-4 mr-2" />
{t("backendsTab")}
</Button>
- <Button
- variant={activeTab === "database" ? "default" : "ghost"}
- size="sm"
- onClick={() => setActiveTab("database")}>
- <Database className="w-4 h-4 mr-2" />
- {t("databaseTab")}
- </Button>
<Button
variant={activeTab === "preferences" ? "default" : "ghost"}
size="sm"
@@ -768,6 +885,20 @@ export function BackendConfigDialog({
<SlidersHorizontal className="w-4 h-4 mr-2" />
{t("preferencesTab")}
</Button>
+ <Button
+ variant={activeTab === "security" ? "default" : "ghost"}
+ size="sm"
+ onClick={() => setActiveTab("security")}>
+ <Shield className="w-4 h-4 mr-2" />
+ {t("securityTab")}
+ </Button>
+ <Button
+ variant={activeTab === "database" ? "default" : "ghost"}
+ size="sm"
+ onClick={() => setActiveTab("database")}>
+ <Database className="w-4 h-4 mr-2" />
+ {t("databaseTab")}
+ </Button>
</div>
</CardHeader>
@@ -1134,6 +1265,149 @@ export function BackendConfigDialog({
</Button>
) : null}
</div>
+ ) : activeTab === "preferences" ? (
+ <div className="space-y-6">
+ {/* Favicon Provider */}
+ <div className="p-4 rounded-lg border bg-card">
+ <h4 className="text-sm font-medium mb-2 flex items-center gap-2">
+ <Globe className="w-4 h-4" />
+ {t("faviconProvider")}
+ </h4>
+ <p className="text-sm text-muted-foreground mb-4">
+ {t("faviconProviderDescription")}
+ </p>
+
+ {/* Favicon Preview */}
+ <FaviconProviderPreview
+ selected={settings.faviconProvider}
+ onChange={(value) =>
+ setSettings({ faviconProvider: value })
+ }
+ t={t}
+ />
+ </div>
+ </div>
+ ) : activeTab === "security" ? (
+ <div className="space-y-6">
+ {authState?.forceAccessControlOff && (
+ <div className="rounded-md bg-destructive/15 p-3 text-sm text-destructive dark:bg-destructive/10">
+ <div className="flex items-center gap-2 font-medium">
+ <ShieldAlert className="h-4 w-4" />
+ {t("auth.forceOffWarningTitle") || "Emergency Access Mode Active"}
+ </div>
+ <p className="mt-1 ml-6 text-xs opacity-90">
+ {t("auth.forceOffWarningDescription") || "Authentication is forced off via environment variable. You can reset your password without providing the current one."}
+ </p>
+ </div>
+ )}
+
+ {/* Authentication Settings */}
+ <div className="p-4 rounded-lg border bg-card">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-2">
+ <Shield className="w-4 h-4 text-primary" />
+ <h4 className="text-sm font-medium">{t("auth.title")}</h4>
+ </div>
+ <Switch
+ checked={authEnabled}
+ onCheckedChange={(checked) => {
+ if (checked) {
+ handleEnableAuth();
+ } else {
+ handleDisableAuth();
+ }
+ }}
+ disabled={authLoading}
+ />
+ </div>
+
+ <p className="text-sm text-muted-foreground mb-4">
+ {t("auth.description")}
+ </p>
+
+ {/* Show set password UI when auth is disabled OR forced off */}
+ {(!authEnabled || (authState?.forceAccessControlOff && !authEnabled)) && (
+ <div className="space-y-3">
+ <div className="relative">
+ <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
+ <Input
+ ref={tokenInputRef}
+ type={showAuthToken ? "text" : "password"}
+ placeholder={t("auth.tokenPlaceholder")}
+ value={authToken}
+ onChange={(e) => {
+ setAuthToken(e.target.value);
+ setIsTokenInvalid(false);
+ }}
+ className={cn(
+ "pl-10 pr-10 transition-all duration-200",
+ isTokenInvalid && "border-destructive ring-destructive/20 focus-visible:ring-destructive"
+ )}
+ disabled={authLoading}
+ />
+ <button
+ type="button"
+ onClick={() => setShowAuthToken(!showAuthToken)}
+ className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
+ >
+ {showAuthToken ? (
+ <EyeOff className="w-4 h-4" />
+ ) : (
+ <Eye className="w-4 h-4" />
+ )}
+ </button>
+ </div>
+
+ {isTokenInvalid && (
+ <p className="text-xs text-destructive animate-in slide-in-from-top-1 duration-200">
+ {t("auth.tokenRequirements") || "Token must be at least 6 characters and contain both letters and numbers"}
+ </p>
+ )}
+
+ {!isTokenInvalid && authToken && !isValidToken(authToken) && (
+ <p className="text-xs text-destructive">
+ {t("auth.tokenRequirements")}
+ </p>
+ )}
+
+ <p className="text-xs text-muted-foreground">
+ {t("auth.tokenHint")}
+ </p>
+ </div>
+ )}
+
+ {authEnabled && (
+ <div className="flex items-center justify-between p-3 rounded-lg bg-green-500/10 border border-green-500/20">
+ <div className="flex items-center gap-2 text-sm text-green-600">
+ <CheckCircle2 className="w-4 h-4" />
+ <span>{t("auth.enabled")}</span>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8 bg-background/50 hover:bg-background/80 border-green-500/30 text-green-700 dark:text-green-400"
+ onClick={() => setChangeTokenDialogOpen(true)}
+ >
+ <Key className="w-3.5 h-3.5 mr-1.5" />
+ {authState?.forceAccessControlOff ? "Reset Password" : t("auth.changeToken")}
+ </Button>
+ </div>
+ )}
+ </div>
+
+ {/* Warning when auth is enabled */}
+ {authEnabled && !authState?.forceAccessControlOff && (
+ <div className="p-4 rounded-lg border border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900">
+ <div className="flex items-start gap-3">
+ <AlertCircle className="w-4 h-4 text-amber-600 mt-0.5" />
+ <div className="text-sm text-amber-800 dark:text-amber-200">
+ <p className="font-medium">{t("auth.warningTitle")}</p>
+ <p className="mt-1">{t("auth.warningDescription")}</p>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
) : activeTab === "database" ? (
// Database Tab
<div className="space-y-6">
@@ -1144,16 +1418,16 @@ export function BackendConfigDialog({
{t("databaseStats")}
</h4>
<div className="grid grid-cols-2 gap-4">
- <div className="p-3 rounded-lg bg-muted">
- <div className="text-xs text-muted-foreground">
+ <div className="p-3 rounded-lg bg-muted flex flex-col justify-between h-full">
+ <div className="text-xs text-muted-foreground mb-1">
{t("dbSize")}
</div>
<div className="text-lg font-semibold">
{dbStats ? formatBytes(dbStats.size) : "--"}
</div>
</div>
- <div className="p-3 rounded-lg bg-muted">
- <div className="text-xs text-muted-foreground">
+ <div className="p-3 rounded-lg bg-muted flex flex-col justify-between h-full">
+ <div className="text-xs text-muted-foreground mb-1">
{t("connectionsCount")}
</div>
<div className="text-lg font-semibold">
@@ -1275,30 +1549,7 @@ export function BackendConfigDialog({
</div>
</div>
</div>
- ) : (
- // Preferences Tab
- <div className="space-y-6">
- {/* Favicon Provider */}
- <div className="p-4 rounded-lg border bg-card">
- <h4 className="text-sm font-medium mb-2 flex items-center gap-2">
- <Globe className="w-4 h-4" />
- {t("faviconProvider")}
- </h4>
- <p className="text-sm text-muted-foreground mb-4">
- {t("faviconProviderDescription")}
- </p>
-
- {/* Favicon Preview */}
- <FaviconProviderPreview
- selected={settings.faviconProvider}
- onChange={(value) =>
- setSettings({ faviconProvider: value })
- }
- t={t}
- />
- </div>
- </div>
- )}
+ ) : null}
{/* Close button for non-first-time */}
{!isFirstTime && (
@@ -1380,24 +1631,143 @@ export function BackendConfigDialog({
</AlertDialogContent>
</AlertDialog>
- {/* Success Alert Dialog */}
- <AlertDialog open={successDialogOpen} onOpenChange={setSuccessDialogOpen}>
+
+
+ {/* Confirm Enable Auth Dialog */}
+ <AlertDialog
+ open={confirmEnableAuthDialogOpen}
+ onOpenChange={setConfirmEnableAuthDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
- <CheckCircle2 className="h-5 w-5 text-green-500" />
- {commonT("success") || "Success"}
+ <Shield className="h-5 w-5 text-amber-500" />
+ {authState?.forceAccessControlOff
+ ? t("auth.emergencyResetTitle")
+ : t("auth.confirmEnableTitle")}
</AlertDialogTitle>
- <AlertDialogDescription>{successMessage}</AlertDialogDescription>
+ <AlertDialogDescription asChild className="space-y-2">
+ <div className="text-sm text-muted-foreground">
+ <p>
+ {authState?.forceAccessControlOff
+ ? t("auth.emergencyResetDescription")
+ : t("auth.confirmEnableDescription")}
+ </p>
+ <p className="font-medium text-amber-600 dark:text-amber-400">
+ {authState?.forceAccessControlOff
+ ? t("auth.emergencyResetWarning")
+ : t("auth.rememberTokenWarning")}
+ </p>
+ </div>
+ </AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
- <AlertDialogAction onClick={() => setSuccessDialogOpen(false)}>
- {commonT("ok") || "OK"}
+ <AlertDialogCancel
+ onClick={() => setConfirmEnableAuthDialogOpen(false)}>
+ {commonT("cancel")}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ onClick={confirmEnableAuth}
+ className="bg-primary">
+ {authState?.forceAccessControlOff ? t("auth.changeToken") : t("auth.confirmEnable")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
+ {/* Confirm Disable Auth Dialog */}
+ <AlertDialog
+ open={confirmDisableAuthDialogOpen}
+ onOpenChange={setConfirmDisableAuthDialogOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle className="flex items-center gap-2">
+ <Shield className="h-5 w-5 text-destructive" />
+ {t("auth.confirmDisableTitle")}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t("auth.confirmDisableDescription")}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel
+ onClick={() => setConfirmDisableAuthDialogOpen(false)}>
+ {commonT("cancel")}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ onClick={confirmDisableAuth}
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
+ {t("auth.confirmDisable")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
+ {/* Change Token Dialog */}
+ <Dialog open={changeTokenDialogOpen} onOpenChange={setChangeTokenDialogOpen}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t("auth.changeTokenTitle")}</DialogTitle>
+ <DialogDescription>
+ {t("auth.changeTokenDescription")}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4 py-2">
+ {!authState?.forceAccessControlOff && (
+ <div className="space-y-2">
+ <label className="text-sm font-medium">{t("auth.currentToken")}</label>
+ <div className="relative">
+ <Lock className="absolute left-3 top-2.5 w-4 h-4 text-muted-foreground" />
+ <Input
+ type="password"
+ value={changeTokenForm.current}
+ onChange={(e) => setChangeTokenForm({ ...changeTokenForm, current: e.target.value })}
+ className="pl-9"
+ />
+ </div>
+ </div>
+ )}
+ <div className="space-y-2">
+ <label className="text-sm font-medium">{t("auth.newToken")}</label>
+ <div className="relative">
+ <Key className="absolute left-3 top-2.5 w-4 h-4 text-muted-foreground" />
+ <Input
+ type="password"
+ value={changeTokenForm.new}
+ onChange={(e) => setChangeTokenForm({ ...changeTokenForm, new: e.target.value })}
+ className="pl-9"
+ />
+ </div>
+ {changeTokenForm.new && !isValidToken(changeTokenForm.new) && (
+ <p className="text-xs text-destructive">{t("auth.tokenRequirements")}</p>
+ )}
+ </div>
+ <div className="space-y-2">
+ <label className="text-sm font-medium">{t("auth.confirmNewToken")}</label>
+ <div className="relative">
+ <Key className="absolute left-3 top-2.5 w-4 h-4 text-muted-foreground" />
+ <Input
+ type="password"
+ value={changeTokenForm.confirm}
+ onChange={(e) => setChangeTokenForm({ ...changeTokenForm, confirm: e.target.value })}
+ className="pl-9"
+ />
+ </div>
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setChangeTokenDialogOpen(false)}>
+ {commonT("cancel")}
+ </Button>
+ <Button
+ onClick={handleChangeToken}
+ disabled={authLoading || (!authState?.forceAccessControlOff && !changeTokenForm.current) || !changeTokenForm.new || !isValidToken(changeTokenForm.new)}
+ >
+ {commonT("confirm")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
{/* Verification Animation */}
<BackendVerifyAnimation
show={showVerifyAnimation}
diff --git a/apps/web/components/ui/alert-dialog.tsx b/apps/web/components/ui/alert-dialog.tsx
index 7855f00..ce36b29 100644
--- a/apps/web/components/ui/alert-dialog.tsx
+++ b/apps/web/components/ui/alert-dialog.tsx
@@ -17,7 +17,7 @@ const AlertDialogOverlay = React.forwardRef<
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
- "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ "fixed inset-0 z-[80] bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
@@ -35,7 +35,7 @@ const AlertDialogContent = React.forwardRef<
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
- "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
+ "fixed left-[50%] top-[50%] z-[100] grid w-[calc(100%-2rem)] max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:w-full rounded-lg",
className
)}
{...props}
diff --git a/apps/web/components/ui/dialog.tsx b/apps/web/components/ui/dialog.tsx
index 80d7ad6..5e422b8 100644
--- a/apps/web/components/ui/dialog.tsx
+++ b/apps/web/components/ui/dialog.tsx
@@ -39,7 +39,7 @@ function DialogOverlay({
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50 backdrop-blur-sm transition-all duration-300",
className
)}
{...props}
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index b0dfada..e4cbfca 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -9,6 +9,7 @@ import type {
ProxyTrafficStats,
DeviceStats,
} from "@neko-master/shared";
+import { getAuthHeaders } from "./auth-queries";
type RuntimeConfig = {
API_URL?: string;
@@ -71,12 +72,15 @@ async function fetchJson<T>(
const options: RequestInit = {
method,
- headers: {},
+ headers: {
+ ...getAuthHeaders(),
+ },
};
// Only set Content-Type when there's a body
if (body && method !== 'GET') {
options.headers = {
+ ...options.headers,
'Content-Type': 'application/json',
};
options.body = JSON.stringify(body);
@@ -85,6 +89,12 @@ async function fetchJson<T>(
const requestPromise = (async () => {
const res = await fetch(url, options);
if (!res.ok) {
+ // If 401, dispatch an event to notify auth system
+ if (res.status === 401) {
+ if (typeof window !== "undefined") {
+ window.dispatchEvent(new CustomEvent("api:unauthorized"));
+ }
+ }
throw new ApiError(res.status, url);
}
return await res.json() as T;
@@ -530,6 +540,22 @@ export const api = {
updateRetentionConfig: (config: { connectionLogsDays: number; hourlyStatsDays: number; autoCleanup?: boolean }) =>
fetchJson<{ message: string }>(`${API_BASE}/db/retention`, 'PUT', config),
+
+ // Auth management
+ getAuthState: () =>
+ fetchJson<{ enabled: boolean; hasToken: boolean }>(`${API_BASE}/auth/state`),
+
+ enableAuth: (token: string) =>
+ fetchJson<{ success: boolean; message: string }>(`${API_BASE}/auth/enable`, 'POST', { token }),
+
+ disableAuth: (token?: string) =>
+ fetchJson<{ success: boolean; message: string }>(`${API_BASE}/auth/disable`, 'POST', token ? { token } : undefined),
+
+ verifyAuth: (token: string) =>
+ fetchJson<{ valid: boolean; message?: string }>(`${API_BASE}/auth/verify`, 'POST', { token }),
+
+ updateToken: (currentToken: string, newToken: string) =>
+ fetchJson<{ success: boolean; message: string }>(`${API_BASE}/auth/token`, 'PUT', { currentToken, newToken }),
};
// Helper functions for time range
diff --git a/apps/web/lib/auth-queries.ts b/apps/web/lib/auth-queries.ts
new file mode 100644
index 0000000..5d86bda
--- /dev/null
+++ b/apps/web/lib/auth-queries.ts
@@ -0,0 +1,179 @@
+"use client";
+
+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import { useCallback } from "react";
+
+const AUTH_TOKEN_KEY = "neko-master-auth-token";
+
+export interface AuthState {
+ enabled: boolean;
+ hasToken: boolean;
+ forceAccessControlOff?: boolean;
+}
+
+// API functions
+async function fetchAuthState(): Promise<AuthState> {
+ const response = await fetch("/api/auth/state");
+ if (!response.ok) {
+ throw new Error("Failed to fetch auth state");
+ }
+ return response.json();
+}
+
+async function verifyToken(token: string): Promise<boolean> {
+ const response = await fetch("/api/auth/verify", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ token }),
+ });
+ if (!response.ok) {
+ return false;
+ }
+ const result = await response.json();
+ return result.valid;
+}
+
+// Storage helpers
+export function getStoredToken(): string | null {
+ if (typeof window === "undefined") return null;
+ return localStorage.getItem(AUTH_TOKEN_KEY);
+}
+
+export function storeToken(token: string): void {
+ if (typeof window === "undefined") return;
+ localStorage.setItem(AUTH_TOKEN_KEY, token);
+}
+
+export function removeToken(): void {
+ if (typeof window === "undefined") return;
+ localStorage.removeItem(AUTH_TOKEN_KEY);
+}
+
+export function getAuthHeaders(): Record<string, string> {
+ const token = getStoredToken();
+ if (token) {
+ return { Authorization: `Bearer ${token}` };
+ }
+ return {};
+}
+
+// Query keys
+export const authKeys = {
+ all: ["auth"] as const,
+ state: () => [...authKeys.all, "state"] as const,
+};
+
+// React Query hooks
+export function useAuthState() {
+ return useQuery({
+ queryKey: authKeys.state(),
+ queryFn: fetchAuthState,
+ // Don't set initialData - let it load from server
+ // If error occurs, we need to know about it
+ retry: (failureCount, error) => {
+ // Don't retry on 401/403
+ if ((error as any)?.status === 401 || (error as any)?.message?.includes('401')) return false;
+ return failureCount < 3;
+ },
+ // Refetch on window focus to keep auth state in sync
+ refetchOnWindowFocus: true,
+ // Refetch when reconnecting
+ refetchOnReconnect: true,
+ // Stale time - consider data fresh for 5 minutes
+ staleTime: 5 * 60 * 1000,
+ });
+}
+
+export function useLogin() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (token: string) => {
+ const isValid = await verifyToken(token);
+ if (!isValid) {
+ throw new Error("Invalid token");
+ }
+ storeToken(token);
+ return true;
+ },
+ onSuccess: () => {
+ // Invalidate auth state to trigger a refetch
+ queryClient.invalidateQueries({ queryKey: authKeys.state() });
+ },
+ });
+}
+
+export function useLogout() {
+ const queryClient = useQueryClient();
+
+ return useCallback(() => {
+ removeToken();
+ // Invalidate and refetch auth state
+ queryClient.invalidateQueries({ queryKey: authKeys.state() });
+ }, [queryClient]);
+}
+
+// Hook to check if user is authenticated
+export function useIsAuthenticated() {
+ const { data: authState, isLoading, error } = useAuthState();
+ const token = getStoredToken();
+
+ // If still loading, return loading state
+ if (isLoading) {
+ return { isAuthenticated: false, isLoading: true };
+ }
+
+ // If error occurred (e.g., 401), check if it's an auth error
+ // If the error is 401, it means auth is enabled but we don't have valid token
+ if (error) {
+ // Check if it's a 401 error
+ const isAuthError = (error as any)?.message?.includes("401") ||
+ (error as any)?.status === 401;
+
+ if (isAuthError) {
+ // Auth is enabled but we need to login
+ return { isAuthenticated: !!token, isLoading: false };
+ }
+
+ // Other errors, assume no auth required to prevent lockout
+ return { isAuthenticated: true, isLoading: false };
+ }
+
+ // If auth is not enabled, user is authenticated
+ if (!authState?.enabled) {
+ return { isAuthenticated: true, isLoading: false };
+ }
+
+ // Auth is enabled, check if we have a token
+ // The token will be verified by the API on each request
+ return { isAuthenticated: !!token, isLoading: false };
+}
+
+// Hook to determine if login dialog should be shown
+export function useRequireAuth() {
+ const { data: authState, isLoading, error } = useAuthState();
+ const { isAuthenticated } = useIsAuthenticated();
+ const token = getStoredToken();
+
+ // Check if error is 401 (auth required)
+ const isAuthError = error && (
+ (error as any)?.message?.includes("401") ||
+ (error as any)?.status === 401
+ );
+
+ // If we got 401 on auth state check, auth is definitely enabled
+ const authEnabled = authState?.enabled || isAuthError;
+
+ // Show login if:
+ // 1. Not loading
+ // 2. Auth is enabled (from state or from 401 error)
+ // 3. User is not authenticated (no valid token)
+ const showLogin = !isLoading && authEnabled && !isAuthenticated && !token;
+
+ return {
+ showLogin,
+ isLoading: isLoading || (!authState && !error), // Still loading if no data and no error
+ authEnabled,
+ error,
+ };
+}
diff --git a/apps/web/lib/auth.tsx b/apps/web/lib/auth.tsx
new file mode 100644
index 0000000..5658517
--- /dev/null
+++ b/apps/web/lib/auth.tsx
@@ -0,0 +1,224 @@
+"use client";
+
+import {
+ createContext,
+ useContext,
+ useState,
+ useEffect,
+ useCallback,
+ type ReactNode,
+} from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { authKeys } from "./auth-queries";
+
+interface AuthState {
+ enabled: boolean;
+ hasToken: boolean;
+ forceAccessControlOff?: boolean;
+}
+
+interface AuthContextType {
+ isAuthenticated: boolean;
+ authState: AuthState | null;
+ isLoading: boolean;
+ login: (token: string) => Promise<boolean>;
+ logout: () => void;
+ checkAuth: () => Promise<void>;
+}
+
+const AuthContext = createContext<AuthContextType | undefined>(undefined);
+
+const AUTH_TOKEN_KEY = "neko-master-auth-token";
+
+export function AuthProvider({ children }: { children: ReactNode }) {
+ const [isAuthenticated, setIsAuthenticated] = useState(false);
+ const [authState, setAuthState] = useState<AuthState | null>(null);
+ const [isLoading, setIsLoading] = useState(true);
+ const queryClient = useQueryClient();
+
+ // Get stored token
+ const getStoredToken = useCallback((): string | null => {
+ if (typeof window === "undefined") return null;
+ return localStorage.getItem(AUTH_TOKEN_KEY);
+ }, []);
+
+ // Store token
+ const storeToken = useCallback((token: string) => {
+ if (typeof window === "undefined") return;
+ localStorage.setItem(AUTH_TOKEN_KEY, token);
+ }, []);
+
+ // Remove token
+ const removeToken = useCallback(() => {
+ if (typeof window === "undefined") return;
+ localStorage.removeItem(AUTH_TOKEN_KEY);
+ }, []);
+
+ // Check auth state from server
+ const checkAuth = useCallback(async () => {
+ try {
+ const response = await fetch("/api/auth/state");
+ if (!response.ok) {
+ // If we can't reach the server, assume no auth required
+ setAuthState({ enabled: false, hasToken: false });
+ setIsAuthenticated(true);
+ return;
+ }
+
+ const state: AuthState = await response.json();
+ setAuthState(state);
+
+ if (!state.enabled) {
+ // Auth is not enabled, user is automatically authenticated
+ setIsAuthenticated(true);
+ return;
+ }
+
+ // Auth is enabled, check if we have a valid token
+ const token = getStoredToken();
+ if (token) {
+ // Verify token with server
+ const verifyResponse = await fetch("/api/auth/verify", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ token }),
+ });
+
+ if (verifyResponse.ok) {
+ const verifyResult = await verifyResponse.json();
+ if (verifyResult.valid) {
+ setIsAuthenticated(true);
+ return;
+ }
+ }
+ // Token is invalid, remove it
+ removeToken();
+ }
+
+ setIsAuthenticated(false);
+ } catch (error) {
+ console.error("Failed to check auth state:", error);
+ // On error, assume no auth required to prevent lockout
+ setAuthState({ enabled: false, hasToken: false });
+ setIsAuthenticated(true);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [getStoredToken, removeToken]);
+
+ // Login with token
+ const login = useCallback(
+ async (token: string): Promise<boolean> => {
+ try {
+ const response = await fetch("/api/auth/verify", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ token }),
+ });
+
+ if (!response.ok) {
+ return false;
+ }
+
+ const result = await response.json();
+ if (result.valid) {
+ storeToken(token);
+ setIsAuthenticated(true);
+ return true;
+ }
+
+ return false;
+ } catch (error) {
+ console.error("Login failed:", error);
+ return false;
+ }
+ },
+ [storeToken]
+ );
+
+ // Logout
+ const logout = useCallback(() => {
+ // Only reload if we actually had a token to clear
+ // This prevents infinite reload loops on 401 errors when already logged out
+ const hadToken = !!localStorage.getItem(AUTH_TOKEN_KEY);
+
+ removeToken();
+ setIsAuthenticated(false);
+
+ if (hadToken) {
+ // Force reload to ensure clean state and restart of correct components
+ window.location.reload();
+ }
+ }, [removeToken]);
+
+ // Check auth on mount
+ useEffect(() => {
+ checkAuth();
+ }, [checkAuth]);
+
+ // Listen for storage changes (for multi-tab support)
+ useEffect(() => {
+ const handleStorageChange = (e: StorageEvent) => {
+ if (e.key === AUTH_TOKEN_KEY) {
+ if (e.newValue === null) {
+ // Token was removed in another tab
+ setIsAuthenticated(false);
+ } else {
+ // Token was added/changed in another tab
+ checkAuth();
+ }
+ }
+ };
+
+ window.addEventListener("storage", handleStorageChange);
+ return () => window.removeEventListener("storage", handleStorageChange);
+ }, [checkAuth]);
+
+ // Listen for unauthorized events from API
+ useEffect(() => {
+ const handleUnauthorized = () => {
+ // Clear local state
+ logout();
+ // Invalidate queries to ensure fresh state across the app
+ queryClient.invalidateQueries({ queryKey: authKeys.state() });
+ };
+
+ window.addEventListener("api:unauthorized", handleUnauthorized);
+ return () => {
+ window.removeEventListener("api:unauthorized", handleUnauthorized);
+ };
+ }, [logout, queryClient]);
+
+ return (
+ <AuthContext.Provider
+ value={{
+ isAuthenticated,
+ authState,
+ isLoading,
+ login,
+ logout,
+ checkAuth,
+ }}
+ >
+ {children}
+ </AuthContext.Provider>
+ );
+}
+
+export function useAuth() {
+ const context = useContext(AuthContext);
+ if (context === undefined) {
+ throw new Error("useAuth must be used within an AuthProvider");
+ }
+ return context;
+}
+
+// Helper function to get auth headers for API requests
+export function getAuthHeaders(): Record<string, string> {
+ if (typeof window === "undefined") return {};
+ const token = localStorage.getItem(AUTH_TOKEN_KEY);
+ if (token) {
+ return { Authorization: `Bearer ${token}` };
+ }
+ return {};
+}
diff --git a/apps/web/lib/websocket.ts b/apps/web/lib/websocket.ts
index 48a7aef..ee559b4 100644
--- a/apps/web/lib/websocket.ts
+++ b/apps/web/lib/websocket.ts
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState, useCallback } from 'react';
import type { StatsSummary } from '@neko-master/shared';
import type { TimeRange } from '@/lib/api';
+import { getStoredToken } from '@/lib/auth-queries';
export type ConnectionStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
@@ -214,10 +215,16 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
wsUrlIndexRef.current = 0;
}
const wsUrl = wsUrls[wsUrlIndexRef.current]!;
+
+ const token = getStoredToken();
+ const urlWithToken = token
+ ? `${wsUrl}${wsUrl.includes('?') ? '&' : '?'}token=${token}`
+ : wsUrl;
+
console.log('[WebSocket] Connecting to:', wsUrl);
try {
- const ws = new WebSocket(wsUrl);
+ const ws = new WebSocket(urlWithToken);
wsRef.current = ws;
let opened = false;
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index fbded16..ac6c54d 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -42,7 +42,8 @@
"backendHealthy": "Backend healthy",
"backendUnavailable": "Backend unavailable",
"backendUnavailableHint": "Data collection is interrupted. Please check backend connectivity.",
- "backendStatusUnknown": "Backend status unknown"
+ "backendStatusUnknown": "Backend status unknown",
+ "logout": "Logout"
},
"timeRangePicker": {
"quickRange": "Quick Range",
@@ -328,6 +329,16 @@
"en": "English",
"zh": "中文"
},
+ "auth": {
+ "loginTitle": "Secure Login",
+ "loginDescription": "Please enter your access token to continue",
+ "tokenPlaceholder": "Enter access token",
+ "tokenRequired": "Please enter access token",
+ "invalidToken": "Invalid access token",
+ "loginError": "Login failed, please try again",
+ "loggingIn": "Logging in...",
+ "login": "Login"
+ },
"backend": {
"title": "Settings",
"firstTimeTitle": "Configure Gateway Backend",
@@ -335,6 +346,7 @@
"description": "Manage backend connections and database",
"backendsTab": "Backends",
"databaseTab": "Database",
+ "securityTab": "Security",
"name": "Name",
"host": "Host",
"port": "Port",
@@ -397,6 +409,42 @@
"retentionCustomDesc": "Set your own storage period (max 90 days)",
"retentionDays": "{days} days",
"retentionUpdated": "Storage settings saved",
- "retentionUpdateFailed": "Failed to save settings"
+ "retentionUpdateFailed": "Failed to save settings",
+ "invalidToken": "Invalid token format",
+ "auth": {
+ "title": "Access Control",
+ "description": "Enable access control to protect your dashboard data",
+ "tokenPlaceholder": "Set access token",
+ "tokenRequirements": "Token must be at least 6 characters with both letters and numbers",
+ "tokenHint": "Set a memorable but hard-to-guess token",
+ "enabled": "Access control enabled",
+ "enabledSuccess": "Access control enabled, please remember your token",
+ "enableFailed": "Failed to enable access control",
+ "disabledSuccess": "Access control disabled",
+ "disableFailed": "Failed to disable access control",
+ "warningTitle": "Important Notice",
+ "warningDescription": "Please keep your access token safe. If you lose it, you won't be able to access the dashboard.",
+ "confirmEnableTitle": "Confirm Enable Access Control",
+ "confirmEnableDescription": "After enabling access control, all users will need to enter the correct token to access the dashboard.",
+ "rememberTokenWarning": "Please remember this token! You won't be able to access the dashboard if you lose it!",
+ "confirmEnable": "I have remembered the token, confirm enable",
+ "confirmDisableTitle": "Confirm Disable Access Control",
+ "confirmDisableDescription": "After disabling access control, anyone can access your dashboard. Are you sure?",
+ "confirmDisable": "Confirm Disable",
+ "changeToken": "Change Token",
+ "changeTokenTitle": "Change Access Token",
+ "changeTokenDescription": "Update your access token to a new one",
+ "currentToken": "Current Token",
+ "newToken": "New Token",
+ "confirmNewToken": "Confirm New Token",
+ "tokenUpdated": "Access token updated successfully",
+ "updateTokenFailed": "Failed to update access token",
+ "passwordsDoNotMatch": "New tokens do not match",
+ "forceOffWarningTitle": "Emergency Access Mode Active",
+ "forceOffWarningDescription": "Authentication is forced off via environment variable. You can reset your password without providing the current one.",
+ "emergencyResetTitle": "Confirm Token Reset",
+ "emergencyResetDescription": "You are currently in Emergency Access Mode. After resetting the token, the old one will be invalid.",
+ "emergencyResetWarning": "For your security, please remove the backend environment variable FORCE_ACCESS_CONTROL_OFF and restart the service after the reset is complete."
+ }
}
}
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index 61d537a..9b0f8da 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -42,7 +42,8 @@
"backendHealthy": "后端运行正常",
"backendUnavailable": "后端连接异常",
"backendUnavailableHint": "数据采集中断,请检查后端联通状态。",
- "backendStatusUnknown": "后端状态未知"
+ "backendStatusUnknown": "后端状态未知",
+ "logout": "退出登录"
},
"timeRangePicker": {
"quickRange": "快捷范围",
@@ -327,6 +328,16 @@
"en": "English",
"zh": "中文"
},
+ "auth": {
+ "loginTitle": "安全登录",
+ "loginDescription": "请输入访问令牌以继续",
+ "tokenPlaceholder": "输入访问令牌",
+ "tokenRequired": "请输入访问令牌",
+ "invalidToken": "访问令牌无效",
+ "loginError": "登录失败,请重试",
+ "loggingIn": "登录中...",
+ "login": "登录"
+ },
"backend": {
"title": "设置",
"firstTimeTitle": "配置网关后端",
@@ -334,6 +345,7 @@
"description": "管理后端连接和数据库",
"backendsTab": "后端管理",
"databaseTab": "数据库",
+ "securityTab": "安全",
"name": "名称",
"host": "主机地址",
"port": "端口",
@@ -396,6 +408,42 @@
"retentionCustomDesc": "自定义存储时长(最多90天)",
"retentionDays": "{days} 天",
"retentionUpdated": "存储设置已保存",
- "retentionUpdateFailed": "设置保存失败"
+ "retentionUpdateFailed": "设置保存失败",
+ "invalidToken": "令牌格式无效",
+ "auth": {
+ "title": "访问控制",
+ "description": "启用访问控制以保护您的面板数据安全",
+ "tokenPlaceholder": "设置访问令牌",
+ "tokenRequirements": "令牌必须至少6位,且包含字母和数字",
+ "tokenHint": "建议设置一个容易记住但难以猜测的令牌",
+ "enabled": "访问控制已启用",
+ "enabledSuccess": "访问控制已启用,请牢记您的令牌",
+ "enableFailed": "启用访问控制失败",
+ "disabledSuccess": "访问控制已禁用",
+ "disableFailed": "禁用访问控制失败",
+ "warningTitle": "重要提示",
+ "warningDescription": "请妥善保管您的访问令牌。如果丢失令牌,您将无法访问面板。",
+ "confirmEnableTitle": "确认启用访问控制",
+ "confirmEnableDescription": "启用访问控制后,所有用户都需要输入正确的令牌才能访问面板。",
+ "rememberTokenWarning": "请务必牢记此令牌!丢失令牌将无法访问面板!",
+ "confirmEnable": "我已牢记令牌,确认启用",
+ "confirmDisableTitle": "确认禁用访问控制",
+ "confirmDisableDescription": "禁用访问控制后,任何人都可以访问您的面板。确定要禁用吗?",
+ "confirmDisable": "确认禁用",
+ "changeToken": "修改令牌",
+ "changeTokenTitle": "修改访问令牌",
+ "changeTokenDescription": "将您的访问令牌更新为新的令牌",
+ "currentToken": "当前令牌",
+ "newToken": "新令牌",
+ "confirmNewToken": "确认新令牌",
+ "tokenUpdated": "访问令牌已更新",
+ "updateTokenFailed": "更新访问令牌失败",
+ "passwordsDoNotMatch": "两次输入的新令牌不一致",
+ "forceOffWarningTitle": "紧急访问模式已激活",
+ "forceOffWarningDescription": "通过环境变量强制关闭了访问控制。您可以在不提供当前令牌的情况下重置令牌。",
+ "emergencyResetTitle": "确认重置访问令牌",
+ "emergencyResetDescription": "当前处于紧急访问模式。重置密码后,旧的令牌将失效。",
+ "emergencyResetWarning": "为了您的面板安全,请在重置完成后,务必删除后端环境变量 FORCE_ACCESS_CONTROL_OFF 并重启服务。"
+ }
}
}
diff --git a/apps/web/public/images/neko-open-close.png b/apps/web/public/images/neko-open-close.png
new file mode 100644
index 0000000..05ae9a5
Binary files /dev/null and b/apps/web/public/images/neko-open-close.png differ
diff --git a/apps/web/public/images/neko-open-eye.png b/apps/web/public/images/neko-open-eye.png
new file mode 100644
index 0000000..68ddd64
Binary files /dev/null and b/apps/web/public/images/neko-open-eye.png differ
diff --git a/package.json b/package.json
index 3df5087..69d3850 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "neko-master",
- "version": "1.2.0",
+ "version": "1.2.1",
"description": "Modern traffic analytics for edge gateways",
"private": true,
"workspaces": [