From c47391a5af78974806336122bf522d2cf9399fd7 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Thu, 8 Oct 2026 17:38:17 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E8=AE=BF=E5=AE=A2/?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E5=91=98=E4=B8=A4=E7=BA=A7=E9=89=B4=E6=9D=83?= =?UTF-8?q?=EF=BC=8C=E8=AE=BF=E5=AE=A2=E4=BB=85=E8=A7=81=E5=AE=B9=E5=99=A8?= =?UTF-8?q?=E6=95=B0=E9=87=8F=E4=B8=8E=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后端采用单管理员密码 + HMAC 签名会话 Cookie(HttpOnly/SameSite,HTTPS 自动 Secure,登录失败节流);/api/system/stats 需登录,/api/docker/stats 对访客脱敏(隐藏占用/端口/版本/ID)。前端增加全局登录态、登录弹窗,以及访客与管理员两套视图。compose 注入 ADMIN_PASSWORD / SESSION_SECRET,并补充 .env.example 与 README。 --- .env.example | 15 ++ README.md | 66 +++++++ backend/auth.go | 232 ++++++++++++++++++++++++ backend/docker.go | 35 ++++ backend/main.go | 17 +- dashboard/src/App.tsx | 26 ++- dashboard/src/components/LoginModal.tsx | 80 ++++++++ dashboard/src/components/NavBar.tsx | 123 +++++++++---- dashboard/src/lib/api.ts | 3 +- dashboard/src/lib/auth.tsx | 76 ++++++++ dashboard/src/pages/Dashboard.tsx | 114 ++++++++---- dashboard/src/pages/Home.tsx | 42 ++++- docker-compose.yml | 5 + 13 files changed, 740 insertions(+), 94 deletions(-) create mode 100644 .env.example create mode 100644 backend/auth.go create mode 100644 dashboard/src/components/LoginModal.tsx create mode 100644 dashboard/src/lib/auth.tsx diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..560e36a --- /dev/null +++ b/.env.example @@ -0,0 +1,15 @@ +# JuiceWorkStation 部署环境变量示例 +# +# 用法:复制为 .env(与 docker-compose.yml 同目录),按需填写。 +# docker compose 会自动读取同目录下的 .env 文件。 + +# 管理员登录密码。不设置则禁止登录,访客只能看到容器数量与列表。 +ADMIN_PASSWORD= + +# 会话 Cookie 的签名密钥。不设置会随机生成,导致每次重启都需要重新登录。 +# 建议填写一段足够长的随机字符串,例如:openssl rand -hex 32 +SESSION_SECRET= + +# 宿主机 docker 组 GID。一般不用手填:Jenkinsfile 会自动读取 /var/run/docker.sock 的组 GID。 +# 手动部署时可用:stat -c '%g' /var/run/docker.sock +DOCKER_GID=999 diff --git a/README.md b/README.md index 629d865..79db7c1 100644 --- a/README.md +++ b/README.md @@ -1 +1,67 @@ # JuiceWorkStation + +个人服务器 / 工作站控制面板。Go 后端 + React 前端,通过 Docker Compose + Jenkins 部署。 + +## 目录结构 + +``` +backend/ Go 后端(系统状态 + Docker 监控 + 鉴权) +dashboard/ React + Vite 前端 +docker-compose.yml +Jenkinsfile +``` + +## 访问权限模型 + +采用「公开只读 + 管理员登录」两级模型,未登录访客与管理员看到的内容不同: + +| 内容 | 访客 | 管理员 | +| --- | :-: | :-: | +| 容器数量统计(总数 / 运行中 / 停止) | ✅ | ✅ | +| 容器列表(名称 / 镜像 / 状态) | ✅ | ✅ | +| 容器资源占用(CPU / 内存 / 网络 / 磁盘) | ❌ | ✅ | +| 端口分配、容器 ID | ❌ | ✅ | +| Docker 版本 | ❌ | ✅ | +| 系统状态(CPU / 内存 / 开机时间) | ❌ | ✅ | + +脱敏在后端完成:访客拿到的 JSON 里敏感字段已被抹掉,而不是靠前端隐藏。 + +## 后端接口 + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| GET | `/api/system/stats` | 系统状态(仅管理员,未登录返回 401) | +| GET | `/api/docker/stats` | Docker 容器监控(访客自动脱敏) | +| POST | `/api/auth/login` | 管理员登录,成功后下发 HttpOnly 会话 Cookie | +| POST | `/api/auth/logout` | 退出登录 | +| GET | `/api/auth/status` | 查询登录状态 | +| GET | `/healthz` | 健康检查 | + +## 环境变量 + +见 [`.env.example`](.env.example),复制为 `.env` 后填写: + +- `ADMIN_PASSWORD`:管理员密码。**不设置则禁止登录**,访客仍可看公开数据。 +- `SESSION_SECRET`:会话 Cookie 签名密钥。不设置会随机生成,重启后需重新登录。 +- `DOCKER_GID`:宿主机 docker 组 GID,一般由 Jenkinsfile 自动注入。 + +## 本地开发 + +后端: + +```bash +cd backend +ADMIN_PASSWORD=dev go run . # Linux/macOS +``` + +前端(Vite 已把 `/api` 代理到 `localhost:9018`): + +```bash +cd dashboard +npm install +npm run dev +``` + +## 部署 + +Jenkins 流水线会构建镜像并 `docker compose up -d`。生产环境通过 nginx 同源反代 `/api/`,会话 Cookie 无需额外跨域配置。 diff --git a/backend/auth.go b/backend/auth.go new file mode 100644 index 0000000..abf226a --- /dev/null +++ b/backend/auth.go @@ -0,0 +1,232 @@ +// 鉴权 +// +// 采用「单管理员密码 + HMAC 签名会话 Cookie」的轻量方案: +// - ADMIN_PASSWORD 通过环境变量配置;未设置时禁止登录(访客仍可看公开数据)。 +// - 登录成功签发无状态 Cookie,值为 <过期时间戳>.。 +// - SESSION_SECRET 用作签名密钥;未设置时随机生成(重启后已有登录失效)。 +// +// 权限模型: +// - 访客(未登录):只能看到容器数量与容器列表(名称/镜像/状态)。 +// - 管理员(已登录):可看到系统状态、容器资源占用、端口等全部信息。 +package main + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/json" + "log" + "net/http" + "os" + "strconv" + "strings" + "sync" + "time" +) + +const ( + sessionCookieName = "jws_session" + sessionTTL = 7 * 24 * time.Hour + + // 登录失败超过 maxLoginFailures 次后锁定 loginLockDuration。 + maxLoginFailures = 5 + loginLockDuration = time.Minute +) + +var sessionSecret = loadSessionSecret() + +func loadSessionSecret() []byte { + if s := strings.TrimSpace(os.Getenv("SESSION_SECRET")); s != "" { + sum := sha256.Sum256([]byte(s)) + return sum[:] + } + // 没有配置就随机生成:重启后现有登录失效,但至少不是可预测的默认密钥。 + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + log.Fatalf("生成会话密钥失败: %v", err) + } + log.Printf("警告:未设置 SESSION_SECRET,已生成临时密钥,重启后所有登录会失效") + return b +} + +func adminPassword() string { + return os.Getenv("ADMIN_PASSWORD") +} + +// --------------------------------------------------------------------------- +// 会话令牌 +// --------------------------------------------------------------------------- + +func makeSessionToken(exp time.Time) string { + payload := strconv.FormatInt(exp.Unix(), 10) + mac := hmac.New(sha256.New, sessionSecret) + mac.Write([]byte(payload)) + sig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) + return payload + "." + sig +} + +func verifySessionToken(token string) bool { + parts := strings.SplitN(token, ".", 2) + if len(parts) != 2 { + return false + } + expUnix, err := strconv.ParseInt(parts[0], 10, 64) + if err != nil || time.Now().Unix() > expUnix { + return false + } + mac := hmac.New(sha256.New, sessionSecret) + mac.Write([]byte(parts[0])) + got, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + return false + } + return hmac.Equal(mac.Sum(nil), got) +} + +// isAuthenticated 判断当前请求是否携带有效的管理员会话。 +func isAuthenticated(r *http.Request) bool { + c, err := r.Cookie(sessionCookieName) + if err != nil { + return false + } + return verifySessionToken(c.Value) +} + +// requireAuth 用于只允许管理员访问的接口。 +func requireAuth(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !isAuthenticated(r) { + writeJSON(w, http.StatusUnauthorized, map[string]any{ + "error": "unauthorized", + }) + return + } + next(w, r) + } +} + +// --------------------------------------------------------------------------- +// 登录失败节流(简单的内存计数,防暴力破解) +// --------------------------------------------------------------------------- + +var ( + loginMu sync.Mutex + loginFailures int + loginLockedUntil time.Time +) + +func loginLocked() bool { + loginMu.Lock() + defer loginMu.Unlock() + return time.Now().Before(loginLockedUntil) +} + +func recordLoginFailure() { + loginMu.Lock() + defer loginMu.Unlock() + loginFailures++ + if loginFailures >= maxLoginFailures { + loginLockedUntil = time.Now().Add(loginLockDuration) + loginFailures = 0 + } +} + +func resetLoginFailures() { + loginMu.Lock() + loginFailures = 0 + loginLockedUntil = time.Time{} + loginMu.Unlock() +} + +// --------------------------------------------------------------------------- +// HTTP 处理 +// --------------------------------------------------------------------------- + +func handleAuthStatus(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{ + "authenticated": isAuthenticated(r), + }) +} + +func handleLogin(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + + if adminPassword() == "" { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{ + "error": "服务端未配置 ADMIN_PASSWORD", + }) + return + } + + if loginLocked() { + writeJSON(w, http.StatusTooManyRequests, map[string]any{ + "error": "尝试过于频繁,请稍后再试", + }) + return + } + + var body struct { + Password string `json:"password"` + } + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&body); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "请求格式错误"}) + return + } + + if subtle.ConstantTimeCompare([]byte(body.Password), []byte(adminPassword())) != 1 { + recordLoginFailure() + // 让暴力破解变慢。 + time.Sleep(300 * time.Millisecond) + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "密码错误"}) + return + } + + resetLoginFailures() + exp := time.Now().Add(sessionTTL) + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, + Value: makeSessionToken(exp), + Path: "/", + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: isTLS(r), + Expires: exp, + MaxAge: int(sessionTTL.Seconds()), + }) + writeJSON(w, http.StatusOK, map[string]any{"authenticated": true}) +} + +func handleLogout(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, + Value: "", + Path: "/", + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: isTLS(r), + MaxAge: -1, + }) + writeJSON(w, http.StatusOK, map[string]any{"authenticated": false}) +} + +// isTLS 判断原始请求是否为 HTTPS(生产环境由 nginx 反代,需要看 X-Forwarded-Proto)。 +func isTLS(r *http.Request) bool { + return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + if err := json.NewEncoder(w).Encode(v); err != nil { + log.Printf("序列化响应失败: %v", err) + } +} diff --git a/backend/docker.go b/backend/docker.go index bff309d..883ad76 100644 --- a/backend/docker.go +++ b/backend/docker.go @@ -32,6 +32,9 @@ type DockerStats struct { Message string `json:"message"` Version string `json:"version"` + // Authenticated 表示当前请求是否来自已登录管理员。访客只会拿到脱敏后的数据。 + Authenticated bool `json:"authenticated"` + ContainersTotal int `json:"containersTotal"` ContainersRunning int `json:"containersRunning"` ContainersStopped int `json:"containersStopped"` @@ -249,13 +252,45 @@ func pruneDockerSamples(live map[string]struct{}) { // --------------------------------------------------------------------------- func handleDockerStats(w http.ResponseWriter, r *http.Request) { + authed := isAuthenticated(r) stats := collectDockerStats(r.Context()) + stats.Authenticated = authed + if !authed { + redactDockerStats(&stats) + } w.Header().Set("Content-Type", "application/json; charset=utf-8") if err := json.NewEncoder(w).Encode(stats); err != nil { log.Printf("序列化 Docker 响应失败: %v", err) } } +// redactDockerStats 把访客不该看到的信息抹掉,只保留容器数量与列表(名称/镜像/状态)。 +// 注意:这里不改变 available 与各类计数,访客仍能看出"服务在不在跑"。 +func redactDockerStats(s *DockerStats) { + // 版本号与底层错误信息(可能含 socket 路径)不对访客暴露。 + s.Version = "" + if s.Available { + s.Message = "" + } else { + s.Message = "监控服务暂不可用" + } + + for i := range s.Containers { + c := &s.Containers[i] + c.ID = "" + c.Created = 0 + c.CPUPercent = 0 + c.MemUsage = 0 + c.MemLimit = 0 + c.MemPercent = 0 + c.NetRx = 0 + c.NetTx = 0 + c.BlockRead = 0 + c.BlockWrite = 0 + c.Ports = []string{} + } +} + func collectDockerStats(parent context.Context) DockerStats { out := DockerStats{Containers: []ContainerStats{}} diff --git a/backend/main.go b/backend/main.go index 6855756..f12a612 100644 --- a/backend/main.go +++ b/backend/main.go @@ -2,9 +2,12 @@ // // 这是原 Spring Boot 版本的 Go 重写,对外接口与 JSON 结构保持一致: // -// GET /api/system/stats 返回系统状态 JSON -// GET /api/docker/stats 返回 Docker 容器监控 JSON(见 docker.go) -// GET /healthz 健康检查(给容器编排/探活用) +// GET /api/system/stats 返回系统状态 JSON(仅管理员) +// GET /api/docker/stats 返回 Docker 容器监控 JSON(见 docker.go,访客只读脱敏) +// POST /api/auth/login 管理员登录 +// POST /api/auth/logout 退出登录 +// GET /api/auth/status 查询当前登录状态 +// GET /healthz 健康检查(给容器编排/探活用) // // 相比 Java 版,运行时只占十几 MB 内存,且不依赖 JVM。 package main @@ -349,8 +352,11 @@ func main() { startCPUSampler() mux := http.NewServeMux() - mux.HandleFunc("/api/system/stats", handleSystemStats) + mux.HandleFunc("/api/system/stats", requireAuth(handleSystemStats)) mux.HandleFunc("/api/docker/stats", handleDockerStats) + mux.HandleFunc("/api/auth/login", handleLogin) + mux.HandleFunc("/api/auth/logout", handleLogout) + mux.HandleFunc("/api/auth/status", handleAuthStatus) mux.HandleFunc("/healthz", handleHealthz) server := &http.Server{ @@ -360,6 +366,9 @@ func main() { } log.Printf("workstation-server (Go %s) 启动,监听 %s", runtime.Version(), listenAddr) + if adminPassword() == "" { + log.Printf("警告:未设置 ADMIN_PASSWORD,管理员登录已禁用,仅对外公开只读监控") + } if err := server.ListenAndServe(); err != nil { log.Fatal(err) } diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx index 338d098..18cc762 100644 --- a/dashboard/src/App.tsx +++ b/dashboard/src/App.tsx @@ -1,15 +1,27 @@ import { Outlet } from 'react-router-dom' import NavBar from './components/NavBar' import Footer from './components/Footer' +import LoginModal from './components/LoginModal' +import { AuthProvider, useAuth } from './lib/auth' + +// 独立的登录弹窗容器,放在 Provider 内部以便读取全局开关。 +function GlobalLoginModal() { + const { loginOpen, closeLogin } = useAuth() + // key 让弹窗在每次打开时重新挂载,天然清空上次的输入与错误。 + return +} export default function App() { return ( -
- -
- -
-
-
+ +
+ +
+ +
+
+
+ +
) } diff --git a/dashboard/src/components/LoginModal.tsx b/dashboard/src/components/LoginModal.tsx new file mode 100644 index 0000000..7cd14e4 --- /dev/null +++ b/dashboard/src/components/LoginModal.tsx @@ -0,0 +1,80 @@ +import { useState } from 'react' +import { useAuth } from '../lib/auth' + +export default function LoginModal({ open, onClose }: { open: boolean; onClose: () => void }) { + const { login } = useAuth() + const [password, setPassword] = useState('') + const [error, setError] = useState('') + const [submitting, setSubmitting] = useState(false) + + if (!open) return null + + async function handleSubmit(e: React.FormEvent) { + e.preventDefault() + if (submitting) return + setSubmitting(true) + setError('') + try { + const ok = await login(password) + if (ok) { + onClose() + return + } + setError('密码错误') + } catch { + setError('网络错误,请稍后再试') + } finally { + setSubmitting(false) + } + } + + return ( +
+
e.stopPropagation()} + > +

管理员登录

+

登录后可查看资源占用与端口等完整信息

+ +
+ + setPassword(e.target.value)} + className="mt-2 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none transition-colors focus:border-indigo-500 focus:ring-2 focus:ring-indigo-100" + placeholder="请输入管理员密码" + /> + + {error &&

{error}

} + +
+ + +
+
+
+
+ ) +} diff --git a/dashboard/src/components/NavBar.tsx b/dashboard/src/components/NavBar.tsx index e617f31..b91a703 100644 --- a/dashboard/src/components/NavBar.tsx +++ b/dashboard/src/components/NavBar.tsx @@ -1,5 +1,6 @@ import { useState } from 'react' import { NavLink } from 'react-router-dom' +import { useAuth } from '../lib/auth' const links = [ { to: '/', label: '首页' }, @@ -17,6 +18,26 @@ function linkClassName({ isActive }: { isActive: boolean }) { export default function NavBar() { const [open, setOpen] = useState(false) + const { authenticated, loading, logout, openLogin } = useAuth() + + const authAction = authenticated ? ( + + ) : ( + + ) return (
@@ -28,42 +49,51 @@ export default function NavBar() { JuiceWorkStation -
    - {links.map((link) => ( -
  • - - {link.label} - -
  • - ))} -
+
+
    + {links.map((link) => ( +
  • + + {link.label} + +
  • + ))} +
- + + +
{open && ( @@ -81,6 +111,31 @@ export default function NavBar() { ))} +
  • + {authenticated ? ( + + ) : ( + + )} +
  • )} diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index d18bb3a..dbe9255 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -12,5 +12,6 @@ export function resolveApiUrl(path: string): string { } export function apiFetch(path: string, init?: RequestInit): Promise { - return fetch(resolveApiUrl(path), init) + // credentials: 'include' 让浏览器带上会话 Cookie(同源反代下必需)。 + return fetch(resolveApiUrl(path), { credentials: 'include', ...init }) } diff --git a/dashboard/src/lib/auth.tsx b/dashboard/src/lib/auth.tsx new file mode 100644 index 0000000..d8cee49 --- /dev/null +++ b/dashboard/src/lib/auth.tsx @@ -0,0 +1,76 @@ +import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react' +import { apiFetch } from './api' + +interface AuthContextValue { + authenticated: boolean + /** 首次向服务端确认登录状态期间为 true */ + loading: boolean + login: (password: string) => Promise + logout: () => Promise + /** 全局登录弹窗开关,避免各页面各自维护一份 */ + loginOpen: boolean + openLogin: () => void + closeLogin: () => void +} + +const AuthContext = createContext(null) + +export function AuthProvider({ children }: { children: React.ReactNode }) { + const [authenticated, setAuthenticated] = useState(false) + const [loading, setLoading] = useState(true) + const [loginOpen, setLoginOpen] = useState(false) + + useEffect(() => { + let cancelled = false + apiFetch('/api/auth/status') + .then((res) => res.json()) + .then((data: { authenticated?: boolean }) => { + if (!cancelled) setAuthenticated(!!data.authenticated) + }) + .catch(() => { + if (!cancelled) setAuthenticated(false) + }) + .finally(() => { + if (!cancelled) setLoading(false) + }) + return () => { + cancelled = true + } + }, []) + + const login = useCallback(async (password: string) => { + const res = await apiFetch('/api/auth/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ password }), + }) + const data = (await res.json().catch(() => ({}))) as { authenticated?: boolean } + const ok = res.ok && !!data.authenticated + setAuthenticated(ok) + return ok + }, []) + + const logout = useCallback(async () => { + await apiFetch('/api/auth/logout', { method: 'POST' }).catch(() => undefined) + setAuthenticated(false) + }, []) + + const openLogin = useCallback(() => setLoginOpen(true), []) + const closeLogin = useCallback(() => setLoginOpen(false), []) + + const value = useMemo( + () => ({ authenticated, loading, login, logout, loginOpen, openLogin, closeLogin }), + [authenticated, loading, login, logout, loginOpen, openLogin, closeLogin], + ) + + return {children} +} + +// useAuth 是 hook 而非组件,和 Provider 放在同一文件更方便使用; +// 这里显式豁免 react-refresh 的“只导出组件”规则。 +// eslint-disable-next-line react-refresh/only-export-components +export function useAuth(): AuthContextValue { + const ctx = useContext(AuthContext) + if (!ctx) throw new Error('useAuth 必须在 AuthProvider 内使用') + return ctx +} diff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsx index 135ea3a..517203c 100644 --- a/dashboard/src/pages/Dashboard.tsx +++ b/dashboard/src/pages/Dashboard.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react' import { apiFetch } from '../lib/api' +import { useAuth } from '../lib/auth' const navItems = [ { key: 'overview', label: '概览' }, @@ -32,6 +33,7 @@ interface DockerStats { available: boolean message: string version: string + authenticated: boolean containersTotal: number containersRunning: number containersStopped: number @@ -101,7 +103,7 @@ function SummaryCard({ ) } -function ContainerCard({ container }: { container: ContainerStats }) { +function ContainerCard({ container, detailed }: { container: ContainerStats; detailed: boolean }) { const info = stateInfo(container.state) return ( @@ -122,48 +124,56 @@ function ContainerCard({ container }: { container: ContainerStats }) {

    {container.status}

    -
    - - {container.cpuPercent.toFixed(1)}% - - - - {formatBytes(container.memUsage)} - - {' '} - / {container.memLimit ? formatBytes(container.memLimit) : '—'} - - - - - ↓ {formatBytes(container.netRx)} -
    - ↑ {formatBytes(container.netTx)} -
    - - R {formatBytes(container.blockRead)} -
    - W {formatBytes(container.blockWrite)} -
    -
    - -
    - ID {container.id} - {container.ports.length > 0 && ( - - {container.ports.map((port) => ( - - {port} + {detailed && ( + <> +
    + + {container.cpuPercent.toFixed(1)}% + + + + {formatBytes(container.memUsage)} + + {' '} + / {container.memLimit ? formatBytes(container.memLimit) : '—'} - ))} - - )} -
    + + + + ↓ {formatBytes(container.netRx)} +
    + ↑ {formatBytes(container.netTx)} +
    + + R {formatBytes(container.blockRead)} +
    + W {formatBytes(container.blockWrite)} +
    +
    + +
    + ID {container.id} + {container.ports.length > 0 && ( + + {container.ports.map((port) => ( + + {port} + + ))} + + )} +
    + + )} ) } function DockerOverview() { + const { authenticated, openLogin } = useAuth() const [stats, setStats] = useState(null) const [error, setError] = useState(false) const [lastUpdated, setLastUpdated] = useState(null) @@ -191,7 +201,8 @@ function DockerOverview() { cancelled = true clearInterval(timer) } - }, []) + // 登录/退出后重新拉取,切换脱敏与完整视图。 + }, [authenticated]) if (error) { return ( @@ -232,10 +243,29 @@ function DockerOverview() { value={`${stats.containersStopped} / ${stats.containersPaused}`} accent="text-slate-500" /> - + + {!stats.authenticated && ( +
    +

    + 当前为访客视图,仅展示容器数量与列表。登录后可查看资源占用、端口等信息。 +

    + +
    + )} + {lastUpdated && (

    最后更新于 {lastUpdated.toLocaleTimeString()} · 每 {REFRESH_INTERVAL / 1000} 秒自动刷新 @@ -249,7 +279,11 @@ function DockerOverview() { ) : (

    {stats.containers.map((container) => ( - + ))}
    )} diff --git a/dashboard/src/pages/Home.tsx b/dashboard/src/pages/Home.tsx index 7c03ee2..52cd8fe 100644 --- a/dashboard/src/pages/Home.tsx +++ b/dashboard/src/pages/Home.tsx @@ -1,6 +1,7 @@ import { useEffect, useState } from 'react' import { Link } from 'react-router-dom' import { apiFetch } from '../lib/api' +import { useAuth } from '../lib/auth' interface CpuStats { model: string @@ -80,11 +81,18 @@ const iconProps = { } as const export default function Home() { + const { authenticated, loading, openLogin } = useAuth() const [stats, setStats] = useState(null) const [error, setError] = useState(false) const [lastUpdated, setLastUpdated] = useState(null) useEffect(() => { + // 系统状态仅管理员可见:未登录时直接跳过请求,渲染层会展示锁定提示。 + // 这里不同步清空已有 state,避免 effect 内 setState 造成级联渲染。 + if (!authenticated) { + return + } + let cancelled = false async function load() { @@ -107,7 +115,7 @@ export default function Home() { cancelled = true clearInterval(timer) } - }, []) + }, [authenticated]) return (
    @@ -131,14 +139,16 @@ export default function Home() {

    系统状态

    - {error - ? '无法获取系统信息,请确认后端服务已启动' - : stats - ? `实时运行状态一览,每 ${REFRESH_INTERVAL / 1000} 秒自动刷新` - : '正在获取系统信息…'} + {!authenticated + ? '系统状态仅对管理员可见' + : error + ? '无法获取系统信息,请确认后端服务已启动' + : stats + ? `实时运行状态一览,每 ${REFRESH_INTERVAL / 1000} 秒自动刷新` + : '正在获取系统信息…'}

    - {stats && lastUpdated && ( + {authenticated && stats && lastUpdated && (

    最后更新于 {lastUpdated.toLocaleTimeString()}

    @@ -146,7 +156,23 @@ export default function Home() {
    - {stats ? ( + {!authenticated ? ( +
    +
    + 🔒 +
    +

    需要管理员登录

    +

    登录后可查看 CPU、内存与开机时间等系统状态

    + +
    + ) : stats ? (
    diff --git a/docker-compose.yml b/docker-compose.yml index c2b1d47..b17c134 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,6 +8,11 @@ services: expose: - "9018" mem_limit: 128m + environment: + # 管理员登录密码;不设置则禁止登录,仅对外公开只读监控。 + ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} + # 会话 Cookie 签名密钥;不设置会随机生成,重启后需重新登录。 + SESSION_SECRET: ${SESSION_SECRET:-} # 后端镜像以 nonroot 运行,而 docker.sock 属于 root:docker(0660), # 这里把宿主机的 docker 组 GID 追加为附加组,让其有权限读取 socket。 # DOCKER_GID 由 Jenkinsfile 在部署时按宿主机实际 GID 注入,默认 999(Debian 常见值)。