mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-09-24 16:05:44 +08:00
新增 admin「渠道监控」模块(参考 BingZi-233/check-cx),独立于现有 Channel 体系。
admin 配置 + 后台定时调用上游 LLM chat completions 健康检查 + 所有登录用户只读可见。
后端:
- ent: channel_monitor + channel_monitor_history(AES-256-GCM 加密 api_key)
- service 按职责拆分:service/aggregator/validate/checker/runner/ssrf
- provider strategy map 替代 switch(openai/anthropic/gemini)
- repository batch 聚合(ListLatestForMonitorIDs + ComputeAvailabilityForMonitors)消除 N+1
- runner: ticker(5s) + pond worker pool(5) + inFlight 防并发 + TrySubmit 防雪崩
+ 凌晨 3 点 cron 清理 30 天历史
- SSRF 防护:强制 https + 私网/loopback/云元数据 IP 拒绝(127/8、10/8、172.16/12、
192.168/16、169.254/16、100.64/10、::1、fc00::/7、fe80::/10)+ DialContext
在 socket 层防 DNS rebinding
- API key sanitize:擦除 url.Error 与上游响应 body 中的 sk-/sk-ant-/AIza/JWT 模式
- APIKeyDecryptFailed 标志位 + 单 monitor 路径检测,避免空 key 调用上游
handler:
- admin: CRUD + 手动触发 + 历史接口(api_key 脱敏)
- user: 只读列表 + 状态详情(去除 api_key/endpoint)
- ParseChannelMonitorID 共用 + dto.ChannelMonitorExtraModelStatus 共用
前端:
- 路由 /admin/channels/{pricing,monitor} + /monitor(用户只读)
- AppSidebar 父项 expandOnly 支持
- ChannelMonitorView 拆为 8 个子组件 + ChannelStatusView 拆出 detail dialog
- composables/useChannelMonitorFormat + constants/channelMonitor 共享
- i18n monitorCommon namespace 消除 admin/user 两 view 重复
合规:所有文件符合 CLAUDE.md(Go ≤ 500 行 / Vue ≤ 300 行 / 函数 ≤ 30 行)
CI: go build / gofmt / golangci-lint(0 issues) / make test-unit / pnpm build 全绿
Vue Router Configuration
Overview
This directory contains the Vue Router configuration for the Sub2API frontend application. The router implements a comprehensive navigation system with authentication guards, role-based access control, and lazy loading.
Files
- index.ts: Main router configuration with route definitions and navigation guards
- meta.d.ts: TypeScript type definitions for route meta fields
Route Structure
Public Routes (No Authentication Required)
| Path | Component | Description |
|---|---|---|
/login |
LoginView | User login page |
/register |
RegisterView | User registration page |
User Routes (Authentication Required)
| Path | Component | Description |
|---|---|---|
/ |
- | Redirects to /dashboard |
/dashboard |
DashboardView | User dashboard with stats |
/keys |
KeysView | API key management |
/usage |
UsageView | Usage records and statistics |
/redeem |
RedeemView | Redeem code interface |
/profile |
ProfileView | User profile settings |
Admin Routes (Admin Role Required)
| Path | Component | Description |
|---|---|---|
/admin |
- | Redirects to /admin/dashboard |
/admin/dashboard |
AdminDashboardView | Admin dashboard |
/admin/users |
AdminUsersView | User management |
/admin/groups |
AdminGroupsView | Group management |
/admin/accounts |
AdminAccountsView | Account management |
/admin/proxies |
AdminProxiesView | Proxy management |
/admin/redeem |
AdminRedeemView | Redeem code management |
Special Routes
| Path | Component | Description |
|---|---|---|
/:pathMatch(.*) |
NotFoundView | 404 error page |
Navigation Guards
Authentication Guard (beforeEach)
The router implements a comprehensive navigation guard that:
- Sets Page Title: Updates document title based on route meta
- Checks Authentication:
- Public routes (
requiresAuth: false) are accessible without login - Protected routes require authentication
- Redirects to
/loginif not authenticated
- Public routes (
- Prevents Double Login:
- Redirects authenticated users away from login/register pages
- Role-Based Access Control:
- Admin routes (
requiresAdmin: true) require admin role - Non-admin users are redirected to
/dashboard
- Admin routes (
- Preserves Intended Destination:
- Saves original URL in query parameter for post-login redirect
Flow Diagram
User navigates to route
↓
Set page title from meta
↓
Is route public? ──Yes──→ Already authenticated? ──Yes──→ Redirect to /dashboard
↓ No ↓ No
↓ Allow access
↓
Is user authenticated? ──No──→ Redirect to /login with redirect query
↓ Yes
↓
Requires admin role? ──Yes──→ Is user admin? ──No──→ Redirect to /dashboard
↓ No ↓ Yes
↓ ↓
Allow access ←────────────────────────────────┘
Route Meta Fields
Each route can define the following meta fields:
interface RouteMeta {
requiresAuth?: boolean // Default: true (requires authentication)
requiresAdmin?: boolean // Default: false (admin access only)
title?: string // Page title
breadcrumbs?: Array<{
// Breadcrumb navigation
label: string
to?: string
}>
icon?: string // Icon for navigation menu
hideInMenu?: boolean // Hide from navigation menu
}
Lazy Loading
All route components use dynamic imports for code splitting:
component: () => import('@/views/user/DashboardView.vue')
Benefits:
- Reduced initial bundle size
- Faster initial page load
- Components loaded on-demand
- Automatic code splitting by Vite
Authentication Store Integration
The router integrates with the Pinia auth store (@/stores/auth):
const authStore = useAuthStore()
// Check authentication status
authStore.isAuthenticated
// Check admin role
authStore.isAdmin
Usage Examples
Programmatic Navigation
import { useRouter } from 'vue-router'
const router = useRouter()
// Navigate to a route
router.push('/dashboard')
// Navigate with query parameters
router.push({
path: '/usage',
query: { filter: 'today' }
})
// Navigate to admin route (will be blocked if not admin)
router.push('/admin/users')
Route Links
<template>
<!-- Simple link -->
<router-link to="/dashboard">Dashboard</router-link>
<!-- Named route -->
<router-link :to="{ name: 'Keys' }">API Keys</router-link>
<!-- With query parameters -->
<router-link :to="{ path: '/usage', query: { page: 1 } }"> Usage </router-link>
</template>
Checking Current Route
import { useRoute } from 'vue-router'
const route = useRoute()
// Check if on admin page
const isAdminPage = route.path.startsWith('/admin')
// Get route meta
const requiresAdmin = route.meta.requiresAdmin
Scroll Behavior
The router implements automatic scroll management:
- Browser Navigation: Restores saved scroll position
- New Routes: Scrolls to top of page
- Hash Links: Scrolls to anchor (when implemented)
Error Handling
The router includes error handling for navigation failures:
router.onError((error) => {
console.error('Router error:', error)
})
Testing Routes
To test navigation guards and route access:
- Public Route Access: Visit
/loginwithout authentication - Protected Route: Try accessing
/dashboardwithout login (should redirect) - Admin Access: Login as regular user, try
/admin/users(should redirect to dashboard) - Admin Success: Login as admin, access
/admin/users(should succeed) - 404 Handling: Visit non-existent route (should show 404 page)
Development Tips
Adding New Routes
- Add route definition in
routesarray - Create corresponding view component
- Set appropriate meta fields (
requiresAuth,requiresAdmin) - Use lazy loading with
() => import() - Update this README with route documentation
Debugging Navigation
Enable Vue Router debug mode:
// In browser console
window.__VUE_ROUTER__ = router
// Check current route
router.currentRoute.value
Common Issues
Issue: 404 on page refresh
- Cause: Server not configured for SPA
- Solution: Configure server to serve
index.htmlfor all routes
Issue: Navigation guard runs twice
- Cause: Multiple
next()calls - Solution: Ensure only one
next()call per code path
Issue: User data not loaded
- Cause: Auth store not initialized
- Solution: Call
authStore.checkAuth()in App.vue or main.ts
Security Considerations
- Client-Side Only: Navigation guards are client-side; server must also validate
- Token Validation: API should verify JWT token on every request
- Role Checking: Backend must verify admin role, not just frontend
- XSS Protection: Vue automatically escapes template content
- CSRF Protection: Use CSRF tokens for state-changing operations
Performance Optimization
- Lazy Loading: All routes use dynamic imports
- Code Splitting: Vite automatically splits route chunks
- Prefetching: Consider adding route prefetch for common paths
- Route Caching: Vue Router caches component instances
Future Enhancements
- Add breadcrumb navigation system
- Implement route-based permissions beyond admin/user
- Add route transition animations
- Implement route prefetching for anticipated navigation
- Add navigation analytics tracking