Compare commits

..
23 changed files with 2887 additions and 90 deletions
+14
View File
@@ -140,6 +140,20 @@ func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRunti
switch msg.Action { switch msg.Action {
case "mcp_list": case "mcp_list":
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: mcpRuntime.List()}) return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: mcpRuntime.List()})
case "mcp_test":
var p cluster.MCPService
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
start := time.Now()
tools, err := cluster.ProbeMCP(ctx, p)
duration := time.Since(start).Milliseconds()
if err != nil {
return writeJSON(cluster.Message{ID: msg.ID, Status: "error", Error: err.Error(), Payload: map[string]any{"duration_ms": duration}})
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: tools})
case "mcp_call": case "mcp_call":
var p struct { var p struct {
Server string `json:"server"` Server string `json:"server"`
+5
View File
@@ -18,6 +18,7 @@ import (
"github.com/wjyhk/vps-commander/internal/cluster" "github.com/wjyhk/vps-commander/internal/cluster"
"github.com/wjyhk/vps-commander/internal/executor" "github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/mcp" "github.com/wjyhk/vps-commander/internal/mcp"
"github.com/wjyhk/vps-commander/internal/notify"
"github.com/wjyhk/vps-commander/internal/storage" "github.com/wjyhk/vps-commander/internal/storage"
) )
@@ -52,12 +53,16 @@ func main() {
if err := store.UpsertLocal(local, runtime.GOARCH, runtime.GOOS); err != nil { if err := store.UpsertLocal(local, runtime.GOARCH, runtime.GOOS); err != nil {
log.Fatal(err) log.Fatal(err)
} }
notificationManager := notify.New(store)
notificationManager.Start()
defer notificationManager.Stop()
s := &api.Server{ s := &api.Server{
Auth: authManager, Auth: authManager,
Exec: executor.Local{MaxOutput: 1024 * 1024}, Exec: executor.Local{MaxOutput: 1024 * 1024},
Cluster: cluster.NewManager(clusterSecret, store), Cluster: cluster.NewManager(clusterSecret, store),
Store: store, Store: store,
LocalName: local, LocalName: local,
Notify: notificationManager,
} }
// MCP Server instance // MCP Server instance
+43
View File
@@ -0,0 +1,43 @@
# 运维事件记录:大文件逆向解析命令超时
- 日期:2026-09-30
- 项目:VPS-Commander
- 关联任务:N3450 / FNOS 飞牛音乐 `trim-music` API 逆向审计
- 严重级别:低(诊断任务超时,未造成系统变更)
- 状态:已恢复工作,继续执行
## 事件概述
在对 FNOS 飞牛音乐前端超大 JavaScript bundle 进行递归正则匹配时,VPS-Commander 执行器出现 `context deadline exceeded`。该命令属于只读分析操作,未执行写入、重启、删除、防火墙修改或服务停止。
## 触发原因
原命令同时对大量 JS bundle 做递归扫描,并尝试输出较大的上下文窗口。目标 bundle 中存在约数百 KB 至 1 MB 级别文件,导致远程执行持续时间超过工具上下文期限。
## 影响
1. 当前命令未得到完整输出。
2. N3450 飞牛音乐服务未被修改或重启。
3. 已完成的二进制/API 初步审计结果未受影响。
4. 无数据丢失、配置损坏或节点失联。
## 已采取措施
将后续逆向分析策略改为:
- 先建立候选 JS 文件集合;
- 单文件、单关键词定位;
- 只读取命中位置附近的小窗口;
- 避免递归 grep 输出大段 bundle;
- 对超过约 500 KB 的 bundle 优先使用 Python 字符串定位,而不是大范围正则输出;
- 每一步保持只读。
## 后续工程规则
对于 VPS-Commander 执行大型文本/二进制分析任务:
1. 优先“定位 → 小范围读取 → 再分析”,禁止一次性输出完整大文件。
2. 大文件分析命令默认拆分为多个短任务。
3. 若单次任务可能超过执行器上下文期限,应主动分片,而不是简单提高超时。
4. 工具返回 `context deadline exceeded` 时,默认判断为“执行结果不完整”,不得据此推断目标服务异常。
5. 所有超时事件均记录到项目 docs,便于后续优化执行器与任务编排策略。
+289 -4
View File
@@ -1,9 +1,11 @@
package api package api
import ( import (
"sort"
"context" "context"
"embed" "embed"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"net" "net"
"net/http" "net/http"
@@ -17,6 +19,7 @@ import (
"github.com/wjyhk/vps-commander/internal/cluster" "github.com/wjyhk/vps-commander/internal/cluster"
"github.com/wjyhk/vps-commander/internal/executor" "github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/model" "github.com/wjyhk/vps-commander/internal/model"
"github.com/wjyhk/vps-commander/internal/notify"
"github.com/wjyhk/vps-commander/internal/storage" "github.com/wjyhk/vps-commander/internal/storage"
"github.com/wjyhk/vps-commander/internal/sysinfo" "github.com/wjyhk/vps-commander/internal/sysinfo"
panelweb "github.com/wjyhk/vps-commander/internal/web" panelweb "github.com/wjyhk/vps-commander/internal/web"
@@ -36,6 +39,187 @@ type Server struct {
Cluster *cluster.Manager Cluster *cluster.Manager
Store *storage.Store Store *storage.Store
LocalName string LocalName string
Notify *notify.Manager
}
const (
SecurityLow = "low"
SecurityMedium = "medium"
SecurityHigh = "high"
SecurityInherit = "inherit"
)
func (s *Server) GetEffectiveSecurityMode(node string) string {
if s.Store == nil {
return SecurityMedium
}
if mode, ok := s.Store.GetNodeSecurityMode(node); ok && mode != "" && mode != SecurityInherit {
return mode
}
return s.Store.GetGlobalSecurityMode()
}
func securityAllows(mode, action string) bool {
switch action {
case "read", "probe":
return true
case "write", "mcp":
return mode == SecurityMedium || mode == SecurityHigh
case "exec":
return mode == SecurityHigh
default:
return false
}
}
func (s *Server) requireSecurity(w http.ResponseWriter, r *http.Request, device, action, detail string) bool {
mode := s.GetEffectiveSecurityMode(device)
if securityAllows(mode, action) {
return true
}
reason := fmt.Sprintf("security mode %s denies %s", mode, action)
if detail != "" {
reason += ": " + detail
}
_ = s.Store.Audit(clientIP(r), device, "security_denied", action, http.StatusForbidden, 0, reason)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(fmt.Sprintf(`{"error":"forbidden","device":%q,"mode":%q,"reason":%q}`, device, mode, reason)))
return false
}
func (s *Server) WebhookTargetsJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", 405)
return
}
items, err := s.Store.ListWebhookTargets()
if err != nil {
http.Error(w, "notification query failed", 500)
return
}
// 面板管理端需要查看与编辑配置,直接返回完整结构
jsonOut(w, items)
}
func maskWebhookURL(v string) string {
if len(v) <= 12 {
return "***"
}
return v[:8] + "***" + v[len(v)-4:]
}
func (s *Server) UpdateWebhookTargetJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var v storage.WebhookTarget
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32*1024)).Decode(&v); err != nil {
http.Error(w, "bad json", 400)
return
}
if err := s.Store.SaveWebhookTarget(v); err != nil {
http.Error(w, err.Error(), 400)
return
}
_ = s.Store.Audit(clientIP(r), "", "notification_setting", "webhook:"+v.ID, 0, 0, "")
jsonOut(w, map[string]any{"ok": true, "id": v.ID})
}
func (s *Server) DeleteWebhookTargetJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
http.Error(w, "method not allowed", 405)
return
}
id := r.URL.Query().Get("id")
if id == "" {
http.Error(w, "id required", 400)
return
}
if err := s.Store.DeleteWebhookTarget(id); err != nil {
http.Error(w, err.Error(), 500)
return
}
jsonOut(w, map[string]any{"ok": true})
}
func (s *Server) TestWebhookJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var v notify.Target
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32*1024)).Decode(&v); err != nil {
http.Error(w, "bad json", 400)
return
}
if s.Notify == nil {
http.Error(w, "notification engine unavailable", 503)
return
}
if err := s.Notify.TestTarget(v); err != nil {
http.Error(w, err.Error(), 502)
return
}
jsonOut(w, map[string]any{"ok": true})
}
func (s *Server) SecuritySettingsJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", 405)
return
}
nodes, err := s.Store.ListNodeSecurityModes()
if err != nil {
http.Error(w, "settings query failed", 500)
return
}
jsonOut(w, map[string]any{"global": s.Store.GetGlobalSecurityMode(), "nodes": nodes, "effective": func() map[string]string {
out := map[string]string{}
for _, d := range s.clusterDeviceNames() {
out[d] = s.GetEffectiveSecurityMode(d)
}
return out
}()})
}
func (s *Server) UpdateSecuritySettingsJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var q struct {
Global string `json:"global"`
Node string `json:"node"`
Mode string `json:"mode"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&q); err != nil {
http.Error(w, "bad json", 400)
return
}
if q.Global != "" {
if err := s.Store.SetGlobalSecurityMode(q.Global); err != nil {
http.Error(w, err.Error(), 400)
return
}
_ = s.Store.Audit(clientIP(r), "", "security_setting", "global="+q.Global, 0, 0, "")
}
if q.Node != "" {
if err := s.Store.SetNodeSecurityMode(q.Node, q.Mode); err != nil {
http.Error(w, err.Error(), 400)
return
}
_ = s.Store.Audit(clientIP(r), q.Node, "security_setting", "mode="+q.Mode, 0, 0, "")
}
jsonOut(w, map[string]any{"ok": true, "global": s.Store.GetGlobalSecurityMode(), "node": q.Node, "mode": q.Mode})
}
func (s *Server) clusterDeviceNames() []string {
out := []string{s.LocalName}
if s.Cluster == nil {
return out
}
for _, d := range s.Cluster.Devices() {
out = append(out, d["name"].(string))
}
return out
} }
func (s *Server) Panel(password string) http.Handler { func (s *Server) Panel(password string) http.Handler {
@@ -97,6 +281,68 @@ type MCPCallRequest struct {
Arguments any `json:"arguments"` Arguments any `json:"arguments"`
} }
type MCPTestRequest struct {
Device string `json:"device"`
Service MCPServiceRequest `json:"service"`
}
func (s *Server) TestMCPJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var q MCPTestRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&q); err != nil {
http.Error(w, "bad json", 400)
return
}
if q.Device == "" {
q.Device = s.LocalName
}
q.Service.Transport = strings.ToLower(strings.TrimSpace(q.Service.Transport))
if q.Service.Transport == "" {
http.Error(w, "transport required", 400)
return
}
if q.Service.Transport == "stdio" {
if strings.TrimSpace(q.Service.Command) == "" {
http.Error(w, "stdio command required", 400)
return
}
} else if q.Service.Transport == "http" || q.Service.Transport == "sse" {
if strings.TrimSpace(q.Service.URL) == "" {
http.Error(w, "HTTP/SSE URL required", 400)
return
}
} else {
http.Error(w, "unsupported transport", 400)
return
}
service := cluster.MCPService{ID: q.Service.ID, Name: q.Service.Name, Description: q.Service.Description, Transport: q.Service.Transport, Command: q.Service.Command, Args: q.Service.Args, Env: q.Service.Env, URL: q.Service.URL, Headers: q.Service.Headers}
start := time.Now()
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
var tools []map[string]any
var err error
if s.isRemote(q.Device) {
if s.Cluster == nil || !s.Cluster.Online(q.Device) {
err = fmt.Errorf("device %s is offline", q.Device)
} else {
tools, err = s.Cluster.TestMCP(ctx, q.Device, service)
}
} else {
tools, err = cluster.ProbeMCP(ctx, service)
}
ms := time.Since(start).Milliseconds()
if err != nil {
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_test", service.Name, 1, ms, err.Error())
jsonOut(w, map[string]any{"success": false, "device": q.Device, "transport": service.Transport, "duration_ms": ms, "tool_count": 0, "tools": []any{}, "error": map[string]any{"code": "MCP_TEST_FAILED", "message": err.Error()}})
return
}
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_test", service.Name, 0, ms, "")
jsonOut(w, map[string]any{"success": true, "device": q.Device, "transport": service.Transport, "duration_ms": ms, "tool_count": len(tools), "tools": tools, "error": nil})
}
func (s *Server) MCPServicesJSON(w http.ResponseWriter, r *http.Request) { func (s *Server) MCPServicesJSON(w http.ResponseWriter, r *http.Request) {
if s.Store == nil { if s.Store == nil {
http.Error(w, "storage unavailable", 500) http.Error(w, "storage unavailable", 500)
@@ -139,7 +385,7 @@ func (s *Server) MCPServicesJSON(w http.ResponseWriter, r *http.Request) {
if s.Cluster != nil { if s.Cluster != nil {
s.Cluster.SyncMCPServices() s.Cluster.SyncMCPServices()
} }
_ = s.Store.Audit(clientIP(r), "", "mcp_service_save", q.ID, 0, 0, "") _ = s.Store.Audit(clientIP(r), s.LocalName, "mcp_service_save", q.ID, 0, 0, "")
jsonOut(w, v) jsonOut(w, v)
default: default:
http.Error(w, "method not allowed", 405) http.Error(w, "method not allowed", 405)
@@ -162,7 +408,7 @@ func (s *Server) DeleteMCPService(w http.ResponseWriter, r *http.Request) {
if s.Cluster != nil { if s.Cluster != nil {
s.Cluster.SyncMCPServices() s.Cluster.SyncMCPServices()
} }
_ = s.Store.Audit(clientIP(r), "", "mcp_service_delete", id, 0, 0, "") _ = s.Store.Audit(clientIP(r), s.LocalName, "mcp_service_delete", id, 0, 0, "")
jsonOut(w, map[string]any{"ok": true}) jsonOut(w, map[string]any{"ok": true})
} }
func (s *Server) ListAgentMCPJSON(w http.ResponseWriter, r *http.Request) { func (s *Server) ListAgentMCPJSON(w http.ResponseWriter, r *http.Request) {
@@ -204,6 +450,9 @@ func (s *Server) CallAgentMCPJSON(w http.ResponseWriter, r *http.Request) {
http.Error(w, "device, server and tool required", 400) http.Error(w, "device, server and tool required", 400)
return return
} }
if !s.requireSecurity(w, r, q.Device, "mcp", q.Server+"/"+q.Tool) {
return
}
if s.isRemote(q.Device) && (s.Cluster == nil || !s.Cluster.Online(q.Device)) { if s.isRemote(q.Device) && (s.Cluster == nil || !s.Cluster.Online(q.Device)) {
if s.Store != nil { if s.Store != nil {
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 1, 0, "device offline") _ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 1, 0, "device offline")
@@ -238,6 +487,13 @@ func (s *Server) Routes() http.Handler {
mux.HandleFunc("/api/v1/mcp/service", s.DeleteMCPService) mux.HandleFunc("/api/v1/mcp/service", s.DeleteMCPService)
mux.HandleFunc("/api/v1/mcp/list", s.ListAgentMCPJSON) mux.HandleFunc("/api/v1/mcp/list", s.ListAgentMCPJSON)
mux.HandleFunc("/api/v1/mcp/call", s.CallAgentMCPJSON) mux.HandleFunc("/api/v1/mcp/call", s.CallAgentMCPJSON)
mux.HandleFunc("/api/v1/mcp/test", s.TestMCPJSON)
mux.HandleFunc("/api/v1/security/settings", s.SecuritySettingsJSON)
mux.HandleFunc("/api/v1/security/settings/update", s.UpdateSecuritySettingsJSON)
mux.HandleFunc("/api/v1/notifications/webhooks", s.WebhookTargetsJSON)
mux.HandleFunc("/api/v1/notifications/webhook/update", s.UpdateWebhookTargetJSON)
mux.HandleFunc("/api/v1/notifications/webhook/delete", s.DeleteWebhookTargetJSON)
mux.HandleFunc("/api/v1/notifications/webhook/test", s.TestWebhookJSON)
mux.HandleFunc("/agent/ws", s.agentWS) mux.HandleFunc("/agent/ws", s.agentWS)
mux.HandleFunc("/openapi.json", s.openapi) mux.HandleFunc("/openapi.json", s.openapi)
return mux return mux
@@ -261,15 +517,35 @@ func (s *Server) devices(w http.ResponseWriter, r *http.Request) {
return return
} }
localProf := sysinfo.Collect("CONTROL") localProf := sysinfo.Collect("CONTROL")
out := []model.Device{{Name: s.LocalName, Status: "online", Local: true, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &localProf}} localCC, localCountry := cluster.ResolveLocalPublicIP()
localDev := model.Device{
Name: s.LocalName,
Status: "online",
Local: true,
Arch: runtime.GOARCH,
OS: runtime.GOOS,
CountryCode: localCC,
Country: localCountry,
Profile: &localProf,
}
var remoteDevs []model.Device
if s.Cluster != nil { if s.Cluster != nil {
for _, d := range s.Cluster.Devices() { for _, d := range s.Cluster.Devices() {
b, _ := json.Marshal(d) b, _ := json.Marshal(d)
var v model.Device var v model.Device
_ = json.Unmarshal(b, &v) _ = json.Unmarshal(b, &v)
out = append(out, v) remoteDevs = append(remoteDevs, v)
} }
} }
// 稳定排序:远程节点按名称字典序排列
sort.Slice(remoteDevs, func(i, j int) bool {
return remoteDevs[i].Name < remoteDevs[j].Name
})
// 本机永远钉死在第 1 位
out := append([]model.Device{localDev}, remoteDevs...)
jsonOut(w, out) jsonOut(w, out)
} }
@@ -323,6 +599,9 @@ func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
if req.Device == "" { if req.Device == "" {
req.Device = s.LocalName req.Device = s.LocalName
} }
if !s.requireSecurity(w, r, req.Device, "exec", req.Command) {
return
}
if req.Timeout <= 0 { if req.Timeout <= 0 {
req.Timeout = 30 req.Timeout = 30
} }
@@ -365,6 +644,9 @@ func (s *Server) fileRead(w http.ResponseWriter, r *http.Request) {
if req.Device == "" { if req.Device == "" {
req.Device = s.LocalName req.Device = s.LocalName
} }
if !s.requireSecurity(w, r, req.Device, "read", req.Path) {
return
}
if req.Path == "" || !validPath(req.Path) || req.Offset < 0 { if req.Path == "" || !validPath(req.Path) || req.Offset < 0 {
http.Error(w, "invalid path or offset", 400) http.Error(w, "invalid path or offset", 400)
return return
@@ -437,6 +719,9 @@ func (s *Server) fileWrite(w http.ResponseWriter, r *http.Request) {
if req.Device == "" { if req.Device == "" {
req.Device = s.LocalName req.Device = s.LocalName
} }
if !s.requireSecurity(w, r, req.Device, "write", req.Path) {
return
}
if req.Path == "" || !validPath(req.Path) { if req.Path == "" || !validPath(req.Path) {
http.Error(w, "path required", 400) http.Error(w, "path required", 400)
return return
+40
View File
@@ -18,6 +18,9 @@ func TestExecConcurrent100AuditsPersisted(t *testing.T) {
} }
defer store.DB.Close() defer store.DB.Close()
if err := store.SetGlobalSecurityMode("high"); err != nil {
t.Fatal(err)
}
s := &Server{Exec: executor.Local{MaxOutput: 1024 * 1024}, Store: store, LocalName: "local"} s := &Server{Exec: executor.Local{MaxOutput: 1024 * 1024}, Store: store, LocalName: "local"}
const n = 100 const n = 100
@@ -48,3 +51,40 @@ func TestExecConcurrent100AuditsPersisted(t *testing.T) {
t.Fatalf("audit loss: got %d rows, want %d", len(logs), n) t.Fatalf("audit loss: got %d rows, want %d", len(logs), n)
} }
} }
func TestSecurityEffectiveModeAndExecGate(t *testing.T) {
store, err := storage.Open(filepath.Join(t.TempDir(), "commander.db"))
if err != nil {
t.Fatal(err)
}
defer store.DB.Close()
s := &Server{Exec: executor.Local{MaxOutput: 1024 * 1024}, Store: store, LocalName: "local"}
if got := s.GetEffectiveSecurityMode("node-a"); got != "medium" {
t.Fatalf("default mode=%s", got)
}
if err := store.SetNodeSecurityMode("node-a", "high"); err != nil {
t.Fatal(err)
}
if got := s.GetEffectiveSecurityMode("node-a"); got != "high" {
t.Fatalf("override=%s", got)
}
if err := store.SetNodeSecurityMode("node-a", "inherit"); err != nil {
t.Fatal(err)
}
if err := store.SetGlobalSecurityMode("low"); err != nil {
t.Fatal(err)
}
if got := s.GetEffectiveSecurityMode("node-a"); got != "low" {
t.Fatalf("inherit=%s", got)
}
req := httptest.NewRequest("POST", "/api/v1/exec", strings.NewReader(`{"device":"node-a","command":"true"}`))
rec := httptest.NewRecorder()
s.exec(rec, req)
if rec.Code != 403 {
t.Fatalf("low exec status=%d", rec.Code)
}
logs, _ := store.RecentAudits(10)
if len(logs) == 0 || logs[0].Action != "security_denied" {
t.Fatalf("missing denial audit: %+v", logs)
}
}
+143
View File
@@ -473,6 +473,149 @@
} }
} }
} }
},
"/api/v1/security/settings": {
"get": {
"summary": "Get security policy",
"responses": {
"200": {
"description": "Current global and per-node security policy"
}
}
}
},
"/api/v1/security/settings/update": {
"post": {
"summary": "Update security policy",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"global": {
"type": "string",
"enum": [
"low",
"medium",
"high"
]
},
"node": {
"type": "string"
},
"mode": {
"type": "string",
"enum": [
"inherit",
"low",
"medium",
"high"
]
}
}
}
}
}
},
"responses": {
"200": {
"description": "Updated"
}
}
}
},
"/api/v1/notifications/webhooks": {
"get": {
"summary": "List webhook targets",
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/notifications/webhook/update": {
"post": {
"summary": "Create or update webhook target",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"id",
"name",
"type",
"url"
],
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"type": {
"type": "string",
"enum": [
"generic",
"telegram",
"wecom"
]
},
"url": {
"type": "string"
},
"config_json": {
"type": "string"
},
"enabled": {
"type": "boolean"
}
}
}
}
}
},
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/notifications/webhook/delete": {
"delete": {
"summary": "Delete webhook target",
"parameters": [
{
"name": "id",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/notifications/webhook/test": {
"post": {
"summary": "Send webhook test message",
"responses": {
"200": {
"description": "OK"
}
}
}
} }
} }
} }
+115
View File
@@ -0,0 +1,115 @@
package cluster
import (
"encoding/json"
"net"
"net/http"
"strings"
"sync"
"time"
)
type GeoLocation struct {
CountryCode string `json:"countryCode"`
Country string `json:"country"`
Status string `json:"status"`
}
var (
geoCache sync.Map
client = &http.Client{Timeout: 4 * time.Second}
)
func isPrivateIP(ipStr string) bool {
ip := net.ParseIP(ipStr)
if ip == nil {
return false
}
if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() {
return true
}
return false
}
// ExtractIPFromRequest retrieves the real client IP from HTTP headers or RemoteAddr
func ExtractIPFromRequest(r *http.Request) string {
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
parts := strings.Split(fwd, ",")
for _, p := range parts {
clean := strings.TrimSpace(p)
if clean != "" && !isPrivateIP(clean) {
return clean
}
}
if len(parts) > 0 {
clean := strings.TrimSpace(parts[0])
if clean != "" {
return clean
}
}
}
if realIP := strings.TrimSpace(r.Header.Get("X-Real-IP")); realIP != "" {
return realIP
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err == nil {
return host
}
return r.RemoteAddr
}
// ResolveIP returns countryCode (e.g. "HK", "SG") and countryName (e.g. "Hong Kong", "Singapore")
func ResolveIP(ipStr string) (string, string) {
ipStr = strings.TrimSpace(ipStr)
if ipStr == "" {
return "", ""
}
if isPrivateIP(ipStr) {
return "CN", "中国"
}
if v, ok := geoCache.Load(ipStr); ok {
if g, ok := v.(GeoLocation); ok {
return g.CountryCode, g.Country
}
}
url := "http://ip-api.com/json/" + ipStr + "?fields=status,country,countryCode"
resp, err := client.Get(url)
if err != nil {
return "", ""
}
defer resp.Body.Close()
var g GeoLocation
if err := json.NewDecoder(resp.Body).Decode(&g); err != nil {
return "", ""
}
if g.Status == "success" && g.CountryCode != "" {
geoCache.Store(ipStr, g)
return g.CountryCode, g.Country
}
return "", ""
}
// ResolveLocalPublicIP queries the hub host's public IP location
func ResolveLocalPublicIP() (string, string) {
if v, ok := geoCache.Load("__local__"); ok {
if g, ok := v.(GeoLocation); ok {
return g.CountryCode, g.Country
}
}
resp, err := client.Get("http://ip-api.com/json/?fields=status,country,countryCode")
if err != nil {
return "HK", "中国香港"
}
defer resp.Body.Close()
var g GeoLocation
if err := json.NewDecoder(resp.Body).Decode(&g); err != nil {
return "HK", "中国香港"
}
if g.Status == "success" && g.CountryCode != "" {
geoCache.Store("__local__", g)
return g.CountryCode, g.Country
}
return "HK", "中国香港"
}
@@ -0,0 +1,175 @@
package cluster
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/wjyhk/vps-commander/internal/storage"
"github.com/wjyhk/vps-commander/internal/sysinfo"
)
func TestLifecycleAcceptance(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "acceptance.db")
store, err := storage.Open(dbPath)
if err != nil {
t.Fatalf("storage.Open failed: %v", err)
}
defer store.DB.Close()
secret := "acc-secret"
mgr := NewManager(secret, store)
mux := http.NewServeMux()
mux.HandleFunc("/agent/ws", mgr.ServeWS)
ts := httptest.NewServer(mux)
defer ts.Close()
wsURL := "ws" + ts.URL[4:] + "/agent/ws?device_name=node-test"
header := http.Header{"Authorization": []string{"Bearer " + secret}}
// [DoD 1] 初次注册持久化
t.Run("DoD 1: Register and Persist", func(t *testing.T) {
c, _, err := websocket.DefaultDialer.Dial(wsURL, header)
if err != nil {
t.Fatalf("dial failed: %v", err)
}
defer c.Close()
prof := sysinfo.Collect("APPLICATION")
bProf, _ := json.Marshal(prof)
_ = bProf
msg := Message{
Event: "hello",
Device: "node-test",
Arch: "amd64",
OS: "linux",
Profile: &prof,
TS: time.Now().Unix(),
}
if err := c.WriteJSON(msg); err != nil {
t.Fatalf("writeJSON failed: %v", err)
}
time.Sleep(150 * time.Millisecond)
rows, err := store.ListDevices()
if err != nil || len(rows) != 1 {
t.Fatalf("expected 1 row in DB, got: %d, err: %v", len(rows), err)
}
if rows[0].Status != "online" || rows[0].Arch != "amd64" || rows[0].OS != "linux" {
t.Fatalf("DB device mismatch: %+v", rows[0])
}
})
// [DoD 2] 离线状态保留
t.Run("DoD 2: Offline Persistence on Disconnect", func(t *testing.T) {
// 上个连接已 defer c.Close(),休眠等待触发 readLoop defer
time.Sleep(150 * time.Millisecond)
if mgr.Online("node-test") {
t.Fatalf("Online('node-test') should be false after disconnect")
}
devs := mgr.Devices()
var target map[string]any
for _, d := range devs {
if d["name"] == "node-test" {
target = d
break
}
}
if target == nil {
t.Fatalf("device vanished from mgr.Devices() on disconnect!")
}
if target["status"] != "offline" {
t.Fatalf("device status expected 'offline', got: %v", target["status"])
}
rows, _ := store.ListDevices()
if len(rows) != 1 || rows[0].Status != "offline" {
t.Fatalf("store device status expected 'offline', got: %+v", rows)
}
})
// [DoD 3] 离线执行防护
t.Run("DoD 3: Offline Exec Guard", func(t *testing.T) {
_, err := mgr.Exec(context.Background(), "node-test", ExecPayload{Command: "uname -a"})
if err == nil || err.Error() != "device offline" {
t.Fatalf("expected 'device offline' error, got: %v", err)
}
})
// [DoD 4] 自动重连恢复在线
t.Run("DoD 4: Reconnect Restore Online", func(t *testing.T) {
c, _, err := websocket.DefaultDialer.Dial(wsURL, header)
if err != nil {
t.Fatalf("dial failed: %v", err)
}
defer c.Close()
prof := sysinfo.Collect("APPLICATION")
_ = c.WriteJSON(Message{
Event: "ping",
Device: "node-test",
Profile: &prof,
TS: time.Now().Unix(),
})
time.Sleep(150 * time.Millisecond)
if !mgr.Online("node-test") {
t.Fatalf("expected Online('node-test') to be true after reconnect")
}
devs := mgr.Devices()
for _, d := range devs {
if d["name"] == "node-test" && d["status"] != "online" {
t.Fatalf("expected status 'online', got: %v", d["status"])
}
}
})
// [DoD 5] Hub 重启数据不丢 (从 DB 恢复)
t.Run("DoD 5: Hub Restart Restore from DB", func(t *testing.T) {
mgrNew := NewManager(secret, store)
devs := mgrNew.Devices()
var found map[string]any
for _, d := range devs {
if d["name"] == "node-test" {
found = d
break
}
}
if found == nil {
t.Fatalf("restarted Hub failed to restore device from DB")
}
if found["status"] != "offline" {
t.Fatalf("restarted Hub initial device status should be offline, got: %v", found["status"])
}
if found["profile"] == nil {
t.Fatalf("restarted Hub should restore profile snapshot")
}
})
// [DoD 6] 主动注销清理与黑名单
t.Run("DoD 6: Revoke Cleanup and Blacklist", func(t *testing.T) {
if err := mgr.RevokeDevice("node-test", "admin action"); err != nil {
t.Fatalf("RevokeDevice failed: %v", err)
}
if len(mgr.Devices()) != 0 {
t.Fatalf("expected 0 devices in mgr, got: %d", len(mgr.Devices()))
}
rows, _ := store.ListDevices()
if len(rows) != 0 {
t.Fatalf("expected 0 devices in DB, got: %d", len(rows))
}
revoked, _ := store.IsRevoked("node-test")
if !revoked {
t.Fatalf("expected device to be recorded in revoked_devices")
}
})
}
+42 -1
View File
@@ -2,6 +2,7 @@ package cluster
import ( import (
"context" "context"
"sort"
"crypto/subtle" "crypto/subtle"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -38,6 +39,9 @@ type Node struct {
Arch string Arch string
OS string OS string
IsLocal bool IsLocal bool
RemoteIP string
CountryCode string
Country string
MCP *MCPRuntime MCP *MCPRuntime
} }
@@ -114,7 +118,17 @@ func (m *Manager) ServeWS(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
return return
} }
n := &Node{Name: name, Conn: c, ConnectionID: fmt.Sprintf("%s-%d", name, time.Now().UnixNano()), MCP: NewMCPRuntime()} clientIP := ExtractIPFromRequest(r)
cc, countryName := ResolveIP(clientIP)
n := &Node{
Name: name,
Conn: c,
ConnectionID: fmt.Sprintf("%s-%d", name, time.Now().UnixNano()),
RemoteIP: clientIP,
CountryCode: cc,
Country: countryName,
MCP: NewMCPRuntime(),
}
n.LastSeen.Store(time.Now().UnixNano()) n.LastSeen.Store(time.Now().UnixNano())
n.LastHeartbeat.Store(time.Now().UnixNano()) n.LastHeartbeat.Store(time.Now().UnixNano())
n.Connected.Store(true) n.Connected.Store(true)
@@ -253,6 +267,9 @@ func (m *Manager) Devices() []map[string]any {
item := map[string]any{ item := map[string]any{
"name": name, "status": status, "is_local": n.IsLocal, "name": name, "status": status, "is_local": n.IsLocal,
"arch": n.Arch, "os": n.OS, "arch": n.Arch, "os": n.OS,
"remote_ip": n.RemoteIP,
"country_code": n.CountryCode,
"country": n.Country,
"last_heartbeat": n.LastHeartbeat.Load() / int64(time.Second), "last_heartbeat": n.LastHeartbeat.Load() / int64(time.Second),
} }
if n.LastProfile != nil { if n.LastProfile != nil {
@@ -260,6 +277,11 @@ func (m *Manager) Devices() []map[string]any {
} }
out = append(out, item) out = append(out, item)
} }
sort.Slice(out, func(i, j int) bool {
nameI := fmt.Sprintf("%v", out[i]["name"])
nameJ := fmt.Sprintf("%v", out[j]["name"])
return nameI < nameJ
})
return out return out
} }
@@ -407,6 +429,25 @@ func (m *Manager) CallMCP(ctx context.Context, name, server, tool string, args a
return out, nil return out, nil
} }
func (m *Manager) TestMCP(ctx context.Context, name string, service MCPService) ([]map[string]any, error) {
m.mu.RLock()
n := m.nodes[name]
m.mu.RUnlock()
if n == nil || !m.Online(name) {
return nil, fmt.Errorf("device %s is offline", name)
}
msg, err := m.call(ctx, name, "mcp_test", service)
if err != nil {
return nil, err
}
var out []map[string]any
b, _ := json.Marshal(msg.Payload)
if err := json.Unmarshal(b, &out); err != nil {
return nil, err
}
return out, nil
}
func (m *Manager) heartbeat(n *Node) { func (m *Manager) heartbeat(n *Node) {
t := time.NewTicker(30 * time.Second) t := time.NewTicker(30 * time.Second)
defer t.Stop() defer t.Stop()
+154
View File
@@ -105,6 +105,160 @@ func (r *MCPRuntime) Call(ctx context.Context, server, tool string, args any) (a
} }
} }
func ProbeMCP(ctx context.Context, s MCPService) ([]map[string]any, error) {
switch strings.ToLower(s.Transport) {
case "stdio":
return probeStdio(ctx, s)
case "http", "sse":
return probeHTTP(ctx, s)
default:
return nil, fmt.Errorf("unsupported MCP transport %q", s.Transport)
}
}
func probeStdio(ctx context.Context, s MCPService) ([]map[string]any, error) {
if s.Command == "" {
return nil, errors.New("MCP stdio command is empty")
}
cmd := exec.CommandContext(ctx, s.Command, s.Args...)
if len(s.Env) > 0 {
cmd.Env = append(os.Environ(), envList(s.Env)...)
}
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
cmd.Stderr = io.Discard
if err := cmd.Start(); err != nil {
return nil, err
}
defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }()
enc := json.NewEncoder(stdin)
dec := bufio.NewReaderSize(stdout, 64*1024)
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", ID: int64(1), Method: "initialize", Params: map[string]any{
"protocolVersion": "2024-11-05", "capabilities": map[string]any{},
"clientInfo": map[string]string{"name": "vps-commander-probe", "version": "1.0"},
}}); err != nil {
return nil, err
}
if _, err := readRPC(ctx, dec, 1); err != nil {
return nil, err
}
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", Method: "notifications/initialized", Params: map[string]any{}}); err != nil {
return nil, err
}
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", ID: int64(2), Method: "tools/list", Params: map[string]any{}}); err != nil {
return nil, err
}
out, err := readRPC(ctx, dec, 2)
if err != nil {
return nil, err
}
return extractMCPTools(out)
}
func probeHTTP(ctx context.Context, s MCPService) ([]map[string]any, error) {
if s.URL == "" {
return nil, errors.New("MCP HTTP URL is empty")
}
client := &http.Client{Timeout: 0}
var session string
post := func(req mcpRPC) (any, error) {
b, _ := json.Marshal(req)
hr, err := http.NewRequestWithContext(ctx, http.MethodPost, s.URL, bytes.NewReader(b))
if err != nil {
return nil, err
}
hr.Header.Set("Content-Type", "application/json")
hr.Header.Set("Accept", "application/json, text/event-stream")
for k, v := range s.Headers {
hr.Header.Set(k, v)
}
if session != "" {
hr.Header.Set("Mcp-Session-Id", session)
}
resp, err := client.Do(hr)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("MCP HTTP status %s", resp.Status)
}
if v := resp.Header.Get("Mcp-Session-Id"); v != "" {
session = v
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 4*1024*1024))
if err != nil {
return nil, err
}
if len(bytes.TrimSpace(data)) == 0 {
return nil, nil
}
if bytes.Contains(data, []byte("event:")) {
data = parseSSEData(data)
}
var rr mcpRPCResponse
if err := json.Unmarshal(bytes.TrimSpace(data), &rr); err != nil {
return nil, err
}
if rr.Error != nil {
return nil, fmt.Errorf("MCP error %d: %s", rr.Error.Code, rr.Error.Message)
}
var out any
if len(rr.Result) > 0 {
if err := json.Unmarshal(rr.Result, &out); err != nil {
return nil, err
}
}
return out, nil
}
if strings.EqualFold(s.Transport, "sse") {
endpoint, err := discoverSSEEndpoint(ctx, s)
if err != nil {
return nil, err
}
s.URL = endpoint
}
if _, err := post(mcpRPC{JSONRPC: "2.0", ID: int64(1), Method: "initialize", Params: map[string]any{
"protocolVersion": "2024-11-05", "capabilities": map[string]any{},
"clientInfo": map[string]string{"name": "vps-commander-probe", "version": "1.0"},
}}); err != nil {
return nil, err
}
if _, err := post(mcpRPC{JSONRPC: "2.0", Method: "notifications/initialized", Params: map[string]any{}}); err != nil {
return nil, err
}
out, err := post(mcpRPC{JSONRPC: "2.0", ID: int64(2), Method: "tools/list", Params: map[string]any{}})
if err != nil {
return nil, err
}
return extractMCPTools(out)
}
func extractMCPTools(v any) ([]map[string]any, error) {
obj, ok := v.(map[string]any)
if !ok {
return nil, errors.New("invalid tools/list response")
}
raw, ok := obj["tools"].([]any)
if !ok {
return []map[string]any{}, nil
}
out := make([]map[string]any, 0, len(raw))
for _, item := range raw {
if m, ok := item.(map[string]any); ok {
tool := map[string]any{"name": m["name"], "description": m["description"]}
out = append(out, tool)
}
}
return out, nil
}
func callStdio(ctx context.Context, s MCPService, tool string, args any) (any, error) { func callStdio(ctx context.Context, s MCPService, tool string, args any) (any, error) {
if s.Command == "" { if s.Command == "" {
return nil, errors.New("MCP stdio command is empty") return nil, errors.New("MCP stdio command is empty")
+3
View File
@@ -23,6 +23,9 @@ type Device struct {
Local bool `json:"is_local"` Local bool `json:"is_local"`
Arch string `json:"arch,omitempty"` Arch string `json:"arch,omitempty"`
OS string `json:"os,omitempty"` OS string `json:"os,omitempty"`
RemoteIP string `json:"remote_ip,omitempty"`
CountryCode string `json:"country_code,omitempty"`
Country string `json:"country,omitempty"`
Profile *sysinfo.Profile `json:"profile,omitempty"` Profile *sysinfo.Profile `json:"profile,omitempty"`
} }
+238
View File
@@ -0,0 +1,238 @@
package notify
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"regexp"
"sync"
"time"
"github.com/wjyhk/vps-commander/internal/storage"
)
type Target struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
URL string `json:"url"`
Config string `json:"config_json"`
Enabled bool `json:"enabled"`
}
type Event struct {
Type string `json:"type"`
Device string `json:"device,omitempty"`
Severity string `json:"severity"`
Message string `json:"message"`
At int64 `json:"timestamp"`
Data any `json:"data,omitempty"`
}
type Manager struct {
Store *storage.Store
Client *http.Client
stop chan struct{}
wg sync.WaitGroup
mu sync.Mutex
offline map[string]int64
sent map[string]time.Time
strikeCount map[string]int
lastSchedule string
}
func New(s *storage.Store) *Manager {
m := &Manager{Store: s, Client: &http.Client{Timeout: 8 * time.Second}, stop: make(chan struct{}), offline: map[string]int64{}, sent: map[string]time.Time{}, strikeCount: map[string]int{}}
m.importOpenClawWebhook()
return m
}
func (m *Manager) importOpenClawWebhook() {
if xs, err := m.Store.ListWebhookTargets(); err == nil && len(xs) > 0 {
return
}
b, err := os.ReadFile("/root/.openclaw/workspace/check_exchange_rate.py")
if err != nil {
return
}
re := regexp.MustCompile(`WEBHOOK_URL\s*=\s*[\"']([^\"']+)[\"']`)
match := re.FindSubmatch(b)
if len(match) != 2 || len(match[1]) == 0 {
return
}
_ = m.Store.SaveWebhookTarget(storage.WebhookTarget{ID: "openclaw-wecom", Name: "OpenClaw 企业微信", Type: "wecom", URL: string(match[1]), Config: "{}", Enabled: true})
}
func (m *Manager) Start() { m.wg.Add(1); go m.loop() }
func (m *Manager) Stop() { close(m.stop); m.wg.Wait() }
func (m *Manager) loop() {
defer m.wg.Done()
t := time.NewTicker(15 * time.Second)
defer t.Stop()
m.check()
for {
select {
case <-t.C:
m.check()
case <-m.stop:
return
}
}
}
func (m *Manager) check() {
devices, _ := m.Store.ListDevices()
now := time.Now().Unix()
for _, d := range devices {
if d.IsLocal {
continue
}
if d.Status == "offline" && d.OfflineAt != nil {
if now-*d.OfflineAt >= 60 {
m.mu.Lock()
m.offline[d.Name] = now
m.mu.Unlock()
m.emitOnce("offline:"+d.Name, Event{Type: "node_offline", Device: d.Name, Severity: "critical", Message: fmt.Sprintf("节点 %s 已离线超过 1 分钟", d.Name), At: now})
}
} else if d.Status == "online" {
m.mu.Lock()
was := m.offline[d.Name] > 0
delete(m.offline, d.Name)
m.mu.Unlock()
if was {
m.emit(Event{Type: "node_recovery", Device: d.Name, Severity: "info", Message: fmt.Sprintf("节点 %s 已恢复在线", d.Name), At: now})
}
}
}
m.checkSchedule(devices, now)
for _, d := range devices {
if d.ProfileJSON == "" {
continue
}
var p map[string]any
if json.Unmarshal([]byte(d.ProfileJSON), &p) != nil {
continue
}
mem, _ := p["mem_percent"].(float64)
disk, _ := p["disk_percent"].(float64)
cpu, _ := p["cpu_usage_percent"].(float64)
// 防抖逻辑:资源利用率需连续 3 次轮询(约 45 秒)超过阈值才触发告警
checkStrike := func(metric string, val float64, threshold float64, msg string) {
key := fmt.Sprintf("%s:%s", metric, d.Name)
m.mu.Lock()
if val >= threshold {
m.strikeCount[key]++
} else {
m.strikeCount[key] = 0
}
count := m.strikeCount[key]
m.mu.Unlock()
if count >= 3 {
m.emitOnce(key, Event{
Type: "resource_threshold",
Device: d.Name,
Severity: "warning",
Message: msg,
At: now,
Data: map[string]any{"metric": metric, "value": val, "threshold": threshold, "strikes": count},
})
}
}
checkStrike("mem", mem, 90, fmt.Sprintf("节点 %s 连续 45s 内存使用率超限: %.0f%%", d.Name, mem))
checkStrike("disk", disk, 90, fmt.Sprintf("节点 %s 磁盘使用率 %.0f%%", d.Name, disk))
checkStrike("cpu", cpu, 95, fmt.Sprintf("节点 %s 连续 45s CPU 使用率超限: %.0f%%", d.Name, cpu))
}
}
func (m *Manager) emitOnce(key string, e Event) {
m.mu.Lock()
last := m.sent[key]
if !last.IsZero() && time.Since(last) < 30*time.Minute {
m.mu.Unlock()
return
}
m.sent[key] = time.Now()
m.mu.Unlock()
m.emit(e)
}
func (m *Manager) emit(e Event) {
targets, _ := m.Store.ListWebhookTargets()
payload, _ := json.Marshal(e)
for _, t := range targets {
if !t.Enabled {
continue
}
body := payload
if t.Type == "telegram" {
var c struct {
ChatID string `json:"chat_id"`
}
_ = json.Unmarshal([]byte(t.Config), &c)
body, _ = json.Marshal(map[string]any{"chat_id": c.ChatID, "text": e.Message})
}
if t.Type == "wecom" {
body, _ = json.Marshal(map[string]any{"msgtype": "text", "text": map[string]any{"content": e.Message}})
}
req, _ := http.NewRequest(http.MethodPost, t.URL, bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
req = req.WithContext(ctx)
resp, err := m.Client.Do(req)
if err != nil {
_ = m.Store.Audit("127.0.0.1", e.Device, "notification", "webhook:"+t.ID, 1, 0, err.Error())
} else {
resp.Body.Close()
code := resp.StatusCode
_ = m.Store.Audit("127.0.0.1", e.Device, "notification", "webhook:"+t.ID, func() int {
if code >= 200 && code < 300 {
return 0
}
return code
}(), 0, "")
}
cancel()
}
}
func (m *Manager) TestTarget(t Target) error {
e := Event{Type: "test", Severity: "info", Message: "VPS-Commander Phase 3 Webhook 测试消息", At: time.Now().Unix()}
b, _ := json.Marshal(e)
req, _ := http.NewRequest(http.MethodPost, t.URL, bytes.NewReader(b))
req.Header.Set("Content-Type", "application/json")
resp, err := m.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("webhook http %d", resp.StatusCode)
}
return nil
}
func (m *Manager) checkSchedule(devices []storage.DeviceRecord, now int64) {
t := time.Now()
key := t.Format("2006-01-02") + ":" + t.Format("15:04")
minute := t.Hour()*60 + t.Minute()
if minute != 510 && minute != 1320 {
return
}
m.mu.Lock()
if m.lastSchedule == key {
m.mu.Unlock()
return
}
m.lastSchedule = key
m.mu.Unlock()
online, offline := 0, 0
for _, d := range devices {
if d.IsLocal {
continue
}
if d.Status == "online" {
online++
} else {
offline++
}
}
m.emit(Event{Type: "scheduled_report", Severity: "info", Message: fmt.Sprintf("VPS-Commander %s 报告:远程节点在线 %d,离线 %d", map[bool]string{true: "早间", false: "晚间"}[minute == 510], online, offline), At: now, Data: map[string]any{"report": "daily", "period": map[bool]string{true: "morning", false: "evening"}[minute == 510], "online": online, "offline": offline}})
}
+57
View File
@@ -0,0 +1,57 @@
package notify
import (
"github.com/wjyhk/vps-commander/internal/storage"
"net/http"
"net/http/httptest"
"testing"
)
func TestTestTargetAndPayload(t *testing.T) {
got := ""
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Errorf("method=%s", r.Method)
}
b := make([]byte, 4096)
n, _ := r.Body.Read(b)
got = string(b[:n])
w.WriteHeader(200)
}))
defer srv.Close()
db := t.TempDir() + "/test.db"
st, err := storage.Open(db)
if err != nil {
t.Fatal(err)
}
defer st.DB.Close()
m := New(st)
m.Client = srv.Client()
if err := m.TestTarget(Target{ID: "t", Name: "test", Type: "generic", URL: srv.URL, Enabled: true}); err != nil {
t.Fatal(err)
}
if len(got) == 0 {
t.Fatal("empty webhook body")
}
}
func TestWebhookStorage(t *testing.T) {
st, err := storage.Open(t.TempDir() + "/test.db")
if err != nil {
t.Fatal(err)
}
defer st.DB.Close()
if err := st.SaveWebhookTarget(storage.WebhookTarget{ID: "x", Name: "X", Type: "generic", URL: "http://127.0.0.1", Config: "{}", Enabled: true}); err != nil {
t.Fatal(err)
}
xs, err := st.ListWebhookTargets()
if err != nil {
t.Fatal(err)
}
if len(xs) != 1 || xs[0].ID != "x" {
t.Fatalf("unexpected targets: %#v", xs)
}
if err := st.DeleteWebhookTarget("x"); err != nil {
t.Fatal(err)
}
}
+126 -2
View File
@@ -7,6 +7,7 @@ import (
_ "modernc.org/sqlite" _ "modernc.org/sqlite"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"time" "time"
) )
@@ -37,14 +38,14 @@ func (s *Store) init() error {
if _, err := s.DB.Exec("PRAGMA busy_timeout = 5000"); err != nil { if _, err := s.DB.Exec("PRAGMA busy_timeout = 5000"); err != nil {
return err return err
} }
_, err := s.DB.Exec("CREATE TABLE IF NOT EXISTS devices (" + _, err := s.DB.Exec("CREATE TABLE IF NOT EXISTS webhook_targets (id TEXT PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, url TEXT NOT NULL, config_json TEXT, enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS idx_webhook_targets_enabled ON webhook_targets(enabled); CREATE TABLE IF NOT EXISTS devices (" +
"name TEXT PRIMARY KEY, status TEXT NOT NULL DEFAULT 'offline', is_local INTEGER NOT NULL DEFAULT 0, " + "name TEXT PRIMARY KEY, status TEXT NOT NULL DEFAULT 'offline', is_local INTEGER NOT NULL DEFAULT 0, " +
"arch TEXT, os TEXT, last_seen INTEGER NOT NULL DEFAULT 0, last_heartbeat INTEGER NOT NULL DEFAULT 0, " + "arch TEXT, os TEXT, last_seen INTEGER NOT NULL DEFAULT 0, last_heartbeat INTEGER NOT NULL DEFAULT 0, " +
"offline_at INTEGER, profile_json TEXT, created_at INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL DEFAULT 0); " + "offline_at INTEGER, profile_json TEXT, created_at INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL DEFAULT 0); " +
"CREATE TABLE IF NOT EXISTS audit_logs (" + "CREATE TABLE IF NOT EXISTS audit_logs (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER NOT NULL, caller_ip TEXT, device TEXT, action TEXT, command TEXT, " + "id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER NOT NULL, caller_ip TEXT, device TEXT, action TEXT, command TEXT, " +
"exit_code INTEGER, duration_ms INTEGER, error_msg TEXT); " + "exit_code INTEGER, duration_ms INTEGER, error_msg TEXT); " +
"CREATE TABLE IF NOT EXISTS revoked_devices (name TEXT PRIMARY KEY, revoked_at INTEGER NOT NULL, reason TEXT); CREATE TABLE IF NOT EXISTS mcp_services (id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, transport TEXT NOT NULL, command TEXT, args_json TEXT, env_json TEXT, url TEXT, headers_json TEXT, scope TEXT NOT NULL DEFAULT 'all', target_nodes_json TEXT, enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS idx_mcp_services_enabled ON mcp_services(enabled);") "CREATE TABLE IF NOT EXISTS revoked_devices (name TEXT PRIMARY KEY, revoked_at INTEGER NOT NULL, reason TEXT); CREATE TABLE IF NOT EXISTS security_settings (node_name TEXT PRIMARY KEY, mode TEXT NOT NULL, updated_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS mcp_services (id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, transport TEXT NOT NULL, command TEXT, args_json TEXT, env_json TEXT, url TEXT, headers_json TEXT, scope TEXT NOT NULL DEFAULT 'all', target_nodes_json TEXT, enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS idx_mcp_services_enabled ON mcp_services(enabled);")
if err != nil { if err != nil {
return err return err
} }
@@ -281,6 +282,52 @@ func (s *Store) Audit(ip, device, action, command string, code int, ms int64, ms
return err return err
} }
type WebhookTarget struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
URL string `json:"url"`
Config string `json:"config_json"`
Enabled bool `json:"enabled"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
func (s *Store) SaveWebhookTarget(v WebhookTarget) error {
now := time.Now().Unix()
if v.ID == "" || v.Name == "" || v.Type == "" || v.URL == "" {
return errors.New("id, name, type and url required")
}
if v.CreatedAt <= 0 {
v.CreatedAt = now
}
v.UpdatedAt = now
_, err := s.DB.Exec(`INSERT INTO webhook_targets(id,name,type,url,config_json,enabled,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,type=excluded.type,url=excluded.url,config_json=excluded.config_json,enabled=excluded.enabled,updated_at=excluded.updated_at`, v.ID, v.Name, v.Type, v.URL, v.Config, boolInt(v.Enabled), v.CreatedAt, v.UpdatedAt)
return err
}
func (s *Store) DeleteWebhookTarget(id string) error {
_, err := s.DB.Exec(`DELETE FROM webhook_targets WHERE id=?`, id)
return err
}
func (s *Store) ListWebhookTargets() ([]WebhookTarget, error) {
rows, err := s.DB.Query(`SELECT id,name,type,url,COALESCE(config_json,''),enabled,created_at,updated_at FROM webhook_targets ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []WebhookTarget{}
for rows.Next() {
var v WebhookTarget
var en int
if err := rows.Scan(&v.ID, &v.Name, &v.Type, &v.URL, &v.Config, &en, &v.CreatedAt, &v.UpdatedAt); err != nil {
return nil, err
}
v.Enabled = en != 0
out = append(out, v)
}
return out, rows.Err()
}
func (s *Store) RecentAudits(limit int) ([]AuditLog, error) { func (s *Store) RecentAudits(limit int) ([]AuditLog, error) {
if limit <= 0 { if limit <= 0 {
limit = 100 limit = 100
@@ -330,3 +377,80 @@ func (s *Store) IsRevoked(name string) (bool, error) {
err := s.DB.QueryRow("SELECT COUNT(*) FROM revoked_devices WHERE name = ?", name).Scan(&count) err := s.DB.QueryRow("SELECT COUNT(*) FROM revoked_devices WHERE name = ?", name).Scan(&count)
return count > 0, err return count > 0, err
} }
func normalizeSecurityMode(mode string) string {
mode = strings.ToLower(strings.TrimSpace(mode))
switch mode {
case "inherit", "low", "medium", "high":
return mode
}
return ""
}
func (s *Store) GetGlobalSecurityMode() string {
var mode string
err := s.DB.QueryRow("SELECT mode FROM security_settings WHERE node_name='' LIMIT 1").Scan(&mode)
if err != nil {
return "medium"
}
if m := normalizeSecurityMode(mode); m != "" && m != "inherit" {
return m
}
return "medium"
}
func (s *Store) SetGlobalSecurityMode(mode string) error {
mode = normalizeSecurityMode(mode)
if mode == "" || mode == "inherit" {
return errors.New("invalid global security mode")
}
_, err := s.DB.Exec("INSERT INTO security_settings(node_name,mode,updated_at) VALUES('',?,?) ON CONFLICT(node_name) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at", mode, time.Now().Unix())
return err
}
func (s *Store) GetNodeSecurityMode(node string) (string, bool) {
var mode string
err := s.DB.QueryRow("SELECT mode FROM security_settings WHERE node_name=?", node).Scan(&mode)
if err != nil {
return "inherit", false
}
m := normalizeSecurityMode(mode)
if m == "" {
return "inherit", false
}
return m, true
}
func (s *Store) SetNodeSecurityMode(node, mode string) error {
if node == "" {
return errors.New("node name required")
}
mode = normalizeSecurityMode(mode)
if mode == "" {
return errors.New("invalid security mode")
}
_, err := s.DB.Exec("INSERT INTO security_settings(node_name,mode,updated_at) VALUES(?,?,?) ON CONFLICT(node_name) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at", node, mode, time.Now().Unix())
return err
}
type SecuritySetting struct {
Node string `json:"node"`
Mode string `json:"mode"`
}
func (s *Store) ListNodeSecurityModes() ([]SecuritySetting, error) {
rows, err := s.DB.Query("SELECT node_name,mode FROM security_settings WHERE node_name<>'' ORDER BY node_name")
if err != nil {
return nil, err
}
defer rows.Close()
out := []SecuritySetting{}
for rows.Next() {
var v SecuritySetting
if err := rows.Scan(&v.Node, &v.Mode); err != nil {
return nil, err
}
out = append(out, v)
}
return out, rows.Err()
}
+134 -21
View File
@@ -7,15 +7,37 @@ import (
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
"sync"
"syscall" "syscall"
"time" "time"
) )
var netMu sync.Mutex
var lastNet = struct {
rx, tx uint64
at time.Time
}{}
var cpuMu sync.Mutex
var lastCPU = struct {
idle, total uint64
at time.Time
usage int
}{}
type Profile struct { type Profile struct {
Role string `json:"role,omitempty"` Role string `json:"role,omitempty"`
CPUCores int `json:"cpu_cores"` CPUCores int `json:"cpu_cores"`
CPUUsagePercent int `json:"cpu_usage_percent"` CPUUsagePercent int `json:"cpu_usage_percent"`
Load1M float64 `json:"load_1m"` Load1M float64 `json:"load_1m"`
Load5M float64 `json:"load_5m"`
Load15M float64 `json:"load_15m"`
NetRXRate float64 `json:"net_rx_rate"`
NetTXRate float64 `json:"net_tx_rate"`
NetRXTotal uint64 `json:"net_rx_total"`
NetTXTotal uint64 `json:"net_tx_total"`
UptimeSeconds float64 `json:"uptime_seconds"`
BootTime int64 `json:"boot_time"`
MemPercent int `json:"mem_percent"` MemPercent int `json:"mem_percent"`
MemAvailable string `json:"mem_available"` MemAvailable string `json:"mem_available"`
DiskPercent int `json:"disk_percent"` DiskPercent int `json:"disk_percent"`
@@ -36,7 +58,9 @@ func Collect(defaultRole string) Profile {
cores := runtime.NumCPU() cores := runtime.NumCPU()
cpuPercent := getCPUUsage() cpuPercent := getCPUUsage()
load1m := getLoad1M() load1m, load5m, load15m := getLoads()
netRX, netTX, netRXT, netTXT := getNetwork()
uptime, boot := getUptime()
memPct, memAvl := getMemInfo() memPct, memAvl := getMemInfo()
diskPct, diskFree := getDiskInfo() diskPct, diskFree := getDiskInfo()
psi := getIOPSI() psi := getIOPSI()
@@ -47,6 +71,14 @@ func Collect(defaultRole string) Profile {
CPUCores: cores, CPUCores: cores,
CPUUsagePercent: cpuPercent, CPUUsagePercent: cpuPercent,
Load1M: load1m, Load1M: load1m,
Load5M: load5m,
Load15M: load15m,
NetRXRate: netRX,
NetTXRate: netTX,
NetRXTotal: netRXT,
NetTXTotal: netTXT,
UptimeSeconds: uptime,
BootTime: boot,
MemPercent: memPct, MemPercent: memPct,
MemAvailable: memAvl, MemAvailable: memAvl,
DiskPercent: diskPct, DiskPercent: diskPct,
@@ -57,16 +89,70 @@ func Collect(defaultRole string) Profile {
} }
} }
func getLoad1M() float64 { func getLoads() (float64, float64, float64) {
if data, err := os.ReadFile("/proc/loadavg"); err == nil { data, err := os.ReadFile("/proc/loadavg")
fields := strings.Fields(string(data)) if err != nil {
if len(fields) > 0 { return 0, 0, 0
if val, err := strconv.ParseFloat(fields[0], 64); err == nil { }
return val f := strings.Fields(string(data))
if len(f) < 3 {
return 0, 0, 0
}
v := func(i int) float64 { x, _ := strconv.ParseFloat(f[i], 64); return x }
return v(0), v(1), v(2)
}
func getNetwork() (float64, float64, uint64, uint64) {
data, err := os.ReadFile("/proc/net/dev")
if err != nil {
return 0, 0, 0, 0
}
var rx, tx uint64
for _, line := range strings.Split(string(data), "\n") {
parts := strings.SplitN(line, ":", 2)
if len(parts) != 2 || strings.TrimSpace(parts[0]) == "lo" {
continue
}
f := strings.Fields(parts[1])
if len(f) < 9 {
continue
}
r, e1 := strconv.ParseUint(f[0], 10, 64)
t, e2 := strconv.ParseUint(f[8], 10, 64)
if e1 == nil && e2 == nil {
rx += r
tx += t
} }
} }
now := time.Now()
netMu.Lock()
defer netMu.Unlock()
var rr, tr float64
if !lastNet.at.IsZero() && now.After(lastNet.at) && rx >= lastNet.rx && tx >= lastNet.tx {
d := now.Sub(lastNet.at).Seconds()
if d > 0 {
rr = float64(rx-lastNet.rx) / d
tr = float64(tx-lastNet.tx) / d
} }
return 0.0 }
lastNet.rx, lastNet.tx, lastNet.at = rx, tx, now
return rr, tr, rx, tx
}
func getUptime() (float64, int64) {
data, err := os.ReadFile("/proc/uptime")
if err != nil {
return 0, time.Now().Unix()
}
f := strings.Fields(string(data))
if len(f) == 0 {
return 0, time.Now().Unix()
}
u, err := strconv.ParseFloat(f[0], 64)
if err != nil {
return 0, time.Now().Unix()
}
return u, time.Now().Add(-time.Duration(u * float64(time.Second))).Unix()
} }
func getCPUUsage() int { func getCPUUsage() int {
@@ -116,20 +202,19 @@ func sampleCPUStat() int {
return 0, 0, false return 0, 0, false
} }
idle1, total1, ok1 := readStat() idleCurr, totalCurr, ok := readStat()
if !ok1 { if !ok {
return -1 return -1
} }
time.Sleep(50 * time.Millisecond) now := time.Now()
idle2, total2, ok2 := readStat()
if !ok2 || total2 <= total1 { cpuMu.Lock()
return -1 defer cpuMu.Unlock()
}
deltaTotal := total2 - total1 if lastCPU.total > 0 && totalCurr > lastCPU.total && now.Sub(lastCPU.at) >= 500*time.Millisecond {
deltaIdle := idle2 - idle1 deltaTotal := totalCurr - lastCPU.total
if deltaTotal == 0 { deltaIdle := idleCurr - lastCPU.idle
return 0 if deltaTotal > 0 && deltaTotal >= deltaIdle {
}
busy := float64(deltaTotal-deltaIdle) / float64(deltaTotal) * 100 busy := float64(deltaTotal-deltaIdle) / float64(deltaTotal) * 100
if busy < 0 { if busy < 0 {
busy = 0 busy = 0
@@ -137,7 +222,35 @@ func sampleCPUStat() int {
if busy > 100 { if busy > 100 {
busy = 100 busy = 100
} }
return int(busy) lastCPU.usage = int(busy)
lastCPU.idle = idleCurr
lastCPU.total = totalCurr
lastCPU.at = now
return lastCPU.usage
}
}
if lastCPU.total == 0 {
// 初次初始化基线
lastCPU.idle = idleCurr
lastCPU.total = totalCurr
lastCPU.at = now
// 用 200ms 短采样作为初始值
time.Sleep(200 * time.Millisecond)
if idle2, total2, ok2 := readStat(); ok2 && total2 > totalCurr {
dTotal := total2 - totalCurr
dIdle := idle2 - idleCurr
if dTotal > 0 && dTotal >= dIdle {
busy := float64(dTotal-dIdle) / float64(dTotal) * 100
lastCPU.usage = int(busy)
lastCPU.idle = idle2
lastCPU.total = total2
lastCPU.at = time.Now()
}
}
}
return lastCPU.usage
} }
func getMemInfo() (memPct int, memAvl string) { func getMemInfo() (memPct int, memAvl string) {
+93 -1
View File
@@ -38,6 +38,9 @@ func (p *Panel) Handler() http.Handler {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/panel/login", p.login) mux.HandleFunc("/panel/login", p.login)
mux.HandleFunc("/panel/logout", p.logout) mux.HandleFunc("/panel/logout", p.logout)
mux.HandleFunc("/panel", p.index)
mux.HandleFunc("/panel/", p.index)
mux.HandleFunc("/probe/summary", p.probeSummary)
mux.HandleFunc("/static/", p.static) mux.HandleFunc("/static/", p.static)
mux.HandleFunc("/panel/api/devices", p.protected(p.handleDevices)) mux.HandleFunc("/panel/api/devices", p.protected(p.handleDevices))
mux.HandleFunc("/panel/api/audits", p.protected(p.Runner.AuditsJSON)) mux.HandleFunc("/panel/api/audits", p.protected(p.Runner.AuditsJSON))
@@ -47,15 +50,28 @@ func (p *Panel) Handler() http.Handler {
mux.HandleFunc("/panel/api/mcp/service", p.protected(p.deleteMCPService)) mux.HandleFunc("/panel/api/mcp/service", p.protected(p.deleteMCPService))
mux.HandleFunc("/panel/api/mcp/list", p.protected(p.listAgentMCP)) mux.HandleFunc("/panel/api/mcp/list", p.protected(p.listAgentMCP))
mux.HandleFunc("/panel/api/mcp/call", p.protected(p.callAgentMCP)) mux.HandleFunc("/panel/api/mcp/call", p.protected(p.callAgentMCP))
mux.HandleFunc("/", p.index) mux.HandleFunc("/panel/api/mcp/test", p.protected(p.testMCP))
mux.HandleFunc("/panel/api/security/settings", p.protected(p.securitySettings))
mux.HandleFunc("/panel/api/security/settings/update", p.protected(p.updateSecuritySettings))
mux.HandleFunc("/panel/api/notifications/webhooks", p.protected(p.webhookTargets))
mux.HandleFunc("/panel/api/notifications/webhook/update", p.protected(p.updateWebhookTarget))
mux.HandleFunc("/panel/api/notifications/webhook/delete", p.protected(p.deleteWebhookTarget))
mux.HandleFunc("/panel/api/notifications/webhook/test", p.protected(p.testWebhook))
mux.HandleFunc("/", p.probe)
return mux return mux
} }
type securityPanelRunner interface {
SecuritySettingsJSON(http.ResponseWriter, *http.Request)
UpdateSecuritySettingsJSON(http.ResponseWriter, *http.Request)
}
type mcpPanelRunner interface { type mcpPanelRunner interface {
MCPServicesJSON(http.ResponseWriter, *http.Request) MCPServicesJSON(http.ResponseWriter, *http.Request)
DeleteMCPService(http.ResponseWriter, *http.Request) DeleteMCPService(http.ResponseWriter, *http.Request)
ListAgentMCPJSON(http.ResponseWriter, *http.Request) ListAgentMCPJSON(http.ResponseWriter, *http.Request)
CallAgentMCPJSON(http.ResponseWriter, *http.Request) CallAgentMCPJSON(http.ResponseWriter, *http.Request)
TestMCPJSON(http.ResponseWriter, *http.Request)
} }
func (p *Panel) mcpServices(w http.ResponseWriter, r *http.Request) { func (p *Panel) mcpServices(w http.ResponseWriter, r *http.Request) {
@@ -86,6 +102,64 @@ func (p *Panel) callAgentMCP(w http.ResponseWriter, r *http.Request) {
} }
http.Error(w, "MCP API unavailable", 501) http.Error(w, "MCP API unavailable", 501)
} }
func (p *Panel) securitySettings(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(securityPanelRunner); ok {
v.SecuritySettingsJSON(w, r)
return
}
http.Error(w, "security API unavailable", 501)
}
func (p *Panel) updateSecuritySettings(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(securityPanelRunner); ok {
v.UpdateSecuritySettingsJSON(w, r)
return
}
http.Error(w, "security API unavailable", 501)
}
func (p *Panel) testMCP(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(mcpPanelRunner); ok {
v.TestMCPJSON(w, r)
return
}
http.Error(w, "MCP API unavailable", 501)
}
type notificationPanelRunner interface {
WebhookTargetsJSON(http.ResponseWriter, *http.Request)
UpdateWebhookTargetJSON(http.ResponseWriter, *http.Request)
DeleteWebhookTargetJSON(http.ResponseWriter, *http.Request)
TestWebhookJSON(http.ResponseWriter, *http.Request)
}
func (p *Panel) webhookTargets(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(notificationPanelRunner); ok {
v.WebhookTargetsJSON(w, r)
return
}
http.Error(w, "notification API unavailable", 501)
}
func (p *Panel) updateWebhookTarget(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(notificationPanelRunner); ok {
v.UpdateWebhookTargetJSON(w, r)
return
}
http.Error(w, "notification API unavailable", 501)
}
func (p *Panel) deleteWebhookTarget(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(notificationPanelRunner); ok {
v.DeleteWebhookTargetJSON(w, r)
return
}
http.Error(w, "notification API unavailable", 501)
}
func (p *Panel) testWebhook(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(notificationPanelRunner); ok {
v.TestWebhookJSON(w, r)
return
}
http.Error(w, "notification API unavailable", 501)
}
func (p *Panel) handleDevices(w http.ResponseWriter, r *http.Request) { func (p *Panel) handleDevices(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete { if r.Method == http.MethodDelete {
@@ -95,6 +169,24 @@ func (p *Panel) handleDevices(w http.ResponseWriter, r *http.Request) {
p.Runner.DevicesJSON(w, r) p.Runner.DevicesJSON(w, r)
} }
func (p *Panel) probeSummary(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", 405)
return
}
p.Runner.DevicesJSON(w, r)
}
func (p *Panel) probe(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
data, _ := staticFS.ReadFile("static/probe.html")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(data)
}
func (p *Panel) index(w http.ResponseWriter, r *http.Request) { func (p *Panel) index(w http.ResponseWriter, r *http.Request) {
if !p.valid(r) { if !p.valid(r) {
http.Redirect(w, r, "/panel/login", http.StatusFound) http.Redirect(w, r, "/panel/login", http.StatusFound)
+7 -3
View File
@@ -1,6 +1,6 @@
*{box-sizing:border-box} *{box-sizing:border-box}
:root{color-scheme:dark;--bg-body:#0b1020;--bg-card:#111a2d;--bg-sub:#0d1526;--border:#24304a;--border-strong:#34415d;--text-main:#e7ebf3;--text-muted:#7f8ba3;--text-status:#9aabc5;--pre-text:#b9c5da;--thead:#91a0bb;--dot-online:#4ade80;--dot-offline:#f87171;--shadow:0 8px 30px rgba(0,0,0,.2)} :root{color-scheme:dark;--bg-body:#0b1020;--bg-card:#111a2d;--bg-sub:#0d1526;--border:#24304a;--border-strong:#34415d;--text-main:#e7ebf3;--text-muted:#7f8ba3;--text-status:#9aabc5;--pre-text:#b9c5da;--thead:#91a0bb;--dot-online:#4ade80;--dot-offline:#f87171;--shadow:0 8px 30px rgba(0,0,0,.2);--card:var(--bg-sub);--line:var(--border)}
:root[data-theme="light"]{color-scheme:light;--bg-body:#f4f6fa;--bg-card:#fff;--bg-sub:#eef2f7;--border:#d1d9e4;--border-strong:#b8c3d3;--text-main:#172033;--text-muted:#647089;--text-status:#58657a;--pre-text:#26344b;--thead:#53627a;--dot-online:#16833d;--dot-offline:#c62828;--shadow:0 8px 26px rgba(28,45,72,.08)} :root[data-theme="light"]{color-scheme:light;--bg-body:#f4f6fa;--bg-card:#fff;--bg-sub:#eef2f7;--border:#d1d9e4;--border-strong:#b8c3d3;--text-main:#172033;--text-muted:#647089;--text-status:#58657a;--pre-text:#26344b;--thead:#53627a;--dot-online:#16833d;--dot-offline:#c62828;--shadow:0 8px 26px rgba(28,45,72,.08);--card:var(--bg-sub);--line:var(--border)}
html,body{min-height:100%}body{margin:0;background:var(--bg-body);color:var(--text-main);font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header{min-height:64px;padding:0 24px;display:flex;align-items:center;justify-content:space-between;gap:14px;border-bottom:1px solid var(--border);background:var(--bg-card);position:sticky;top:0;z-index:2} html,body{min-height:100%}body{margin:0;background:var(--bg-body);color:var(--text-main);font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header{min-height:64px;padding:0 24px;display:flex;align-items:center;justify-content:space-between;gap:14px;border-bottom:1px solid var(--border);background:var(--bg-card);position:sticky;top:0;z-index:2}
.brand-wrap{display:flex;align-items:center;gap:12px;min-width:0} .brand-wrap{display:flex;align-items:center;gap:12px;min-width:0}
.brand-logo{width:36px;height:36px;border-radius:8px;object-fit:cover;flex:none;box-shadow:0 2px 8px rgba(0,0,0,.15)} .brand-logo{width:36px;height:36px;border-radius:8px;object-fit:cover;flex:none;box-shadow:0 2px 8px rgba(0,0,0,.15)}
@@ -41,5 +41,9 @@ header strong{font-size:18px}header span{margin-left:12px;color:var(--text-muted
.device-card.offline{opacity:.62;filter:saturate(.45)} .device-card.offline{opacity:.62;filter:saturate(.45)}
.device-card.offline .btn-revoke{opacity:1} .device-card.offline .btn-revoke{opacity:1}
.mcp-toolbar{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:14px}.mcp-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px}.mcp-item{border:1px solid var(--line,#30343b);border-radius:10px;padding:14px;background:var(--card,#11151a)}.mcp-item h3{margin:0 0 6px;font-size:15px}.mcp-meta{font-size:12px;opacity:.72;line-height:1.7}.mcp-actions{display:flex;gap:8px;margin-top:10px}.mcp-form{display:grid;grid-template-columns:1fr 1fr;gap:10px}.mcp-form .full{grid-column:1/-1}.mcp-form label{display:flex;flex-direction:column;gap:5px;font-size:12px;opacity:.9}.mcp-form input,.mcp-form select,.mcp-form textarea{width:100%;box-sizing:border-box}.mcp-form textarea{min-height:72px;font-family:monospace}.mcp-nodes{display:flex;flex-wrap:wrap;gap:8px}.mcp-nodes label{flex-direction:row;align-items:center}.mcp-status{font-size:12px;margin-top:8px;min-height:18px} .mcp-toolbar{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:14px}.mcp-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px}.mcp-item{border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--bg-sub)}.mcp-item h3{margin:0 0 6px;font-size:15px}.mcp-meta{font-size:12px;opacity:.72;line-height:1.7}.mcp-actions{display:flex;gap:8px;margin-top:10px}.mcp-form{display:grid;grid-template-columns:1fr 1fr;gap:10px}.mcp-form .full{grid-column:1/-1}.mcp-form label{display:flex;flex-direction:column;gap:5px;font-size:12px;opacity:.9}.mcp-form input,.mcp-form select,.mcp-form textarea{width:100%;box-sizing:border-box}.mcp-form textarea{min-height:72px;font-family:monospace}.mcp-nodes{display:flex;flex-wrap:wrap;gap:8px}.mcp-nodes label{flex-direction:row;align-items:center}.mcp-status{font-size:12px;margin-top:8px;min-height:18px}.mcp-field-error{border-color:#e05252!important;outline:1px solid #e05252}.mcp-test-result{margin-top:12px;padding:12px;border:1px solid var(--border);border-radius:10px;white-space:normal}.mcp-test-result.ok{border-color:#3a9b68}.mcp-test-result.fail{border-color:#c44}.mcp-test-tools{margin:8px 0 0;padding-left:18px}.mcp-test-detail{margin-top:8px;white-space:pre-wrap;overflow:auto;max-height:220px;font-family:monospace;font-size:12px}
@media(max-width:700px){.mcp-form{grid-template-columns:1fr}.mcp-form .full{grid-column:auto}.mcp-toolbar{align-items:flex-start;flex-direction:column}} @media(max-width:700px){.mcp-form{grid-template-columns:1fr}.mcp-form .full{grid-column:auto}.mcp-toolbar{align-items:flex-start;flex-direction:column}}
.security-grid{display:flex;gap:12px;align-items:end;flex-wrap:wrap;margin-bottom:16px}.security-grid label{display:flex;flex-direction:column;gap:6px}.security-grid select,.tablewrap select{padding:7px 9px;border:1px solid var(--border);border-radius:6px;background:var(--bg-sub);color:inherit}.security-grid button{height:34px}
.notification-form{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:12px 0}.notification-form label{display:flex;flex-direction:column;gap:6px;font-size:12px}.notification-form .full{grid-column:1/-1}.notification-form input,.notification-form select,.notification-form textarea{width:100%;box-sizing:border-box}.notification-form textarea{min-height:72px}@media(max-width:700px){.notification-form{grid-template-columns:1fr}.notification-form .full{grid-column:auto}}
+287 -13
View File
@@ -11,7 +11,8 @@ const $=s=>document.querySelector(s);
})(); })();
async function api(path,opt={}){ async function api(path,opt={}){
let r=await fetch("/panel/api"+path,opt); const fetchOpt = Object.assign({ cache: "no-store" }, opt);
let r=await fetch("/panel/api"+path, fetchOpt);
if(r.status===401){location.href="/panel/login";throw Error("unauthorized")} if(r.status===401){location.href="/panel/login";throw Error("unauthorized")}
if(!r.ok)throw Error(await r.text()); if(!r.ok)throw Error(await r.text());
return r.json() return r.json()
@@ -31,12 +32,8 @@ async function removeDevice(name){
} }
} }
async function loadDevices(){ function renderSingleCard(d) {
let all=await api("/devices");
let ds=all.filter(d=>!d.is_local);
$("#devices").innerHTML=ds.map(d=>{
const p = d.profile || {}; const p = d.profile || {};
const role = p.role || "APPLICATION";
const isOnline = d.status === "online"; const isOnline = d.status === "online";
const statusText = isOnline ? "在线" : "离线"; const statusText = isOnline ? "在线" : "离线";
const lastText = d.last_heartbeat ? new Date(d.last_heartbeat*1000).toLocaleString() : ""; const lastText = d.last_heartbeat ? new Date(d.last_heartbeat*1000).toLocaleString() : "";
@@ -50,7 +47,6 @@ async function loadDevices(){
const dockerClass = p.docker ? 'yes' : 'no'; const dockerClass = p.docker ? 'yes' : 'no';
return ` return `
<div class="device-card ${isOnline ? "online" : "offline"}">
<div class="v1-head"> <div class="v1-head">
<div class="v1-row1"> <div class="v1-row1">
<div class="v1-title"> <div class="v1-title">
@@ -69,11 +65,43 @@ async function loadDevices(){
<div class="p-item"><span class="p-label">IO PSI</span><span class="p-val">${psiStr}</span></div> <div class="p-item"><span class="p-label">IO PSI</span><span class="p-val">${psiStr}</span></div>
<div class="p-item"><span class="p-label">DOCKER</span><span class="p-val badge-docker-text ${dockerClass}">${dockerVal}</span></div> <div class="p-item"><span class="p-label">DOCKER</span><span class="p-val badge-docker-text ${dockerClass}">${dockerVal}</span></div>
</div> </div>
</div>
`; `;
}).join(""); }
$("#device").innerHTML=ds.map(d=>`<option value="${esc(d.name)}" ${d.status==="offline" ? "disabled" : ""}>${esc(d.name)}${d.status==="offline" ? " [离线]" : ""}</option>`).join(""); async function loadDevices(){
let all = await api("/devices");
let ds = all.filter(d => !d.is_local);
// 严格固定名称字典序排列,杜绝乱跳
ds.sort((a, b) => String(a.name || "").localeCompare(String(b.name || "")));
const container = $("#devices");
const currentCardElements = container.querySelectorAll(".device-card[data-node]");
const currentNodes = Array.from(currentCardElements).map(el => el.getAttribute("data-node"));
const newNodes = ds.map(d => d.name);
// 如果节点列表结构未变,采用就地局部更新,卡片物理位置丝毫不动
const sameOrder = currentNodes.length === newNodes.length && currentNodes.every((n, i) => n === newNodes[i]);
if (sameOrder) {
ds.forEach(d => {
const card = container.querySelector(`.device-card[data-node="${CSS.escape(d.name)}"]`);
if (card) {
const isOnline = d.status === "online";
card.className = `device-card ${isOnline ? "online" : "offline"}`;
card.innerHTML = renderSingleCard(d);
}
});
} else {
// 首次渲染或增删节点时渲染
container.innerHTML = ds.map(d => {
const isOnline = d.status === "online";
return `<div class="device-card ${isOnline ? "online" : "offline"}" data-node="${esc(d.name)}">${renderSingleCard(d)}</div>`;
}).join("");
}
// 保持控制台 select 选项
const select = $("#device");
const selectedVal = select.value;
select.innerHTML = ds.map(d => `<option value="${esc(d.name)}" ${d.status==="offline" ? "disabled" : ""} ${d.name===selectedVal ? "selected" : ""}>${esc(d.name)}${d.status==="offline" ? " [离线]" : ""}</option>`).join("");
} }
async function loadAudits(){ async function loadAudits(){
@@ -111,20 +139,266 @@ $("#logout").onclick=async()=>{
loadDevices().then(loadAudits).catch(console.error); loadDevices().then(loadAudits).catch(console.error);
let mcpEditingId=""; let mcpEditingId="";
function mcpFieldError(id,message){
const el=$("#"+id); el.classList.add("mcp-field-error"); el.title=message;
const status=$("#mcpStatus"); status.textContent=message; status.style.color="#e05252";
el.focus();
}
function mcpClearErrors(){
["mcpId","mcpName","mcpCommand","mcpUrl","mcpArgs","mcpHeaders","mcpEnv"].forEach(id=>{const el=$("#"+id);if(el){el.classList.remove("mcp-field-error");el.removeAttribute("title")}});
$("#mcpStatus").textContent=""; $("#mcpStatus").style.color="";
}
function parseMCPField(id,label,kind){
const el=$("#"+id); let value;
try{value=JSON.parse(el.value||"");}catch(e){mcpFieldError(id,label+" 必须是合法的 JSON "+kind+",请检查格式。");throw e}
if(kind==="数组" && !Array.isArray(value)){mcpFieldError(id,label+" 必须是合法的 JSON 数组,如 []。");throw Error("invalid "+id)}
if(kind==="对象" && (value===null||Array.isArray(value)||typeof value!=="object")){mcpFieldError(id,label+" 必须是合法的 JSON 对象,如 {}。");throw Error("invalid "+id)}
return value;
}
function showMCPToast(message){
let t=$("#mcpToast"); if(!t){t=document.createElement("div");t.id="mcpToast";t.style.cssText="position:fixed;right:18px;top:18px;z-index:9999;padding:10px 14px;border:1px solid var(--border);border-radius:8px;background:var(--bg-sub);box-shadow:0 8px 30px rgba(0,0,0,.25)";document.body.appendChild(t)}
t.textContent=message; t.hidden=false; clearTimeout(t._timer); t._timer=setTimeout(()=>t.hidden=true,2600);
}
async function loadMCPServices(){ async function loadMCPServices(){
const services=await api("/mcp/services"); const services=await api("/mcp/services");
const devices=(await api("/devices")).filter(d=>!d.is_local); const allDevices=await api("/devices");
const devices=allDevices.filter(d=>!d.is_local);
$("#mcpTestNode").innerHTML='<option value="local">Hub 本机</option>'+devices.filter(d=>d.status==="online").map(d=>'<option value="'+esc(d.name)+'">'+esc(d.name)+'(在线)</option>').join("");
$("#mcpNodes").innerHTML=devices.map(d=>`<label><input type="checkbox" value="${esc(d.name)}">${esc(d.name)}</label>`).join(""); $("#mcpNodes").innerHTML=devices.map(d=>`<label><input type="checkbox" value="${esc(d.name)}">${esc(d.name)}</label>`).join("");
$("#mcpList").innerHTML=services.map(s=>`<div class="mcp-item"><h3>${esc(s.name)} <small>${esc(s.id)}</small></h3><div class="mcp-meta">${esc(s.transport)} · ${s.scope==='custom'?'指定节点':'全部节点'} · ${s.enabled?'启用':'停用'}${s.url?' · '+esc(s.url):s.command?' · '+esc(s.command):''}</div><div class="mcp-actions"><button type="button" onclick="editMCP('${esc(s.id)}')">编辑</button><button type="button" onclick="deleteMCP('${esc(s.id)}')">删除</button></div></div>`).join("")||'<div class="mcp-meta">暂无 MCP 服务配置。</div>'; $("#mcpList").innerHTML=services.map(s=>`<div class="mcp-item"><h3>${esc(s.name)} <small>${esc(s.id)}</small></h3><div class="mcp-meta">${esc(s.transport)} · ${s.scope==='custom'?'指定节点':'全部节点'} · ${s.enabled?'启用':'停用'}${s.url?' · '+esc(s.url):s.command?' · '+esc(s.command):''}</div><div class="mcp-actions"><button type="button" onclick="editMCP('${esc(s.id)}')">编辑</button><button type="button" onclick="deleteMCP('${esc(s.id)}')">删除</button></div></div>`).join("")||'<div class="mcp-meta">暂无 MCP 服务配置。</div>';
} }
function resetMCPForm(){ function resetMCPForm(){
mcpEditingId=""; $("#mcpEditor").hidden=false; $("#mcpId").disabled=false; ["mcpId","mcpName","mcpCommand","mcpUrl"].forEach(id=>$("#"+id).value=""); $("#mcpTransport").value="stdio"; $("#mcpEnabled").value="1"; $("#mcpArgs").value="[]"; $("#mcpHeaders").value="{}"; $("#mcpEnv").value="{}"; $("#mcpScope").value="all"; $("#mcpStatus").textContent=""; $("#mcpNodes").querySelectorAll("input").forEach(x=>x.checked=false); mcpEditingId=""; $("#mcpEditor").hidden=false; $("#mcpId").disabled=false; ["mcpId","mcpName","mcpCommand","mcpUrl"].forEach(id=>$("#"+id).value=""); $("#mcpTransport").value="stdio"; $("#mcpEnabled").value="1"; $("#mcpArgs").value="[]"; $("#mcpHeaders").value="{}"; $("#mcpEnv").value="{}"; $("#mcpScope").value="all"; $("#mcpStatus").textContent=""; $("#mcpTestResult").hidden=true; $("#mcpTestResult").textContent=""; $("#mcpNodes").querySelectorAll("input").forEach(x=>x.checked=false);
} }
async function editMCP(id){ async function editMCP(id){
const services=await api("/mcp/services"); const s=services.find(x=>x.id===id); if(!s)return; resetMCPForm(); mcpEditingId=id; $("#mcpId").value=s.id; $("#mcpId").disabled=true; $("#mcpName").value=s.name||""; $("#mcpTransport").value=s.transport; $("#mcpEnabled").value=s.enabled?"1":"0"; $("#mcpCommand").value=s.command||""; $("#mcpUrl").value=s.url||""; $("#mcpArgs").value=s.args_json||"[]"; $("#mcpHeaders").value=s.headers_json||"{}"; $("#mcpEnv").value=s.env_json||"{}"; $("#mcpScope").value=s.scope||"all"; let nodes=[];try{nodes=JSON.parse(s.target_nodes_json||"[]")}catch(e){};$("#mcpNodes").querySelectorAll("input").forEach(x=>x.checked=nodes.includes(x.value)); const services=await api("/mcp/services"); const s=services.find(x=>x.id===id); if(!s)return; resetMCPForm(); mcpEditingId=id; $("#mcpId").value=s.id; $("#mcpId").disabled=true; $("#mcpName").value=s.name||""; $("#mcpTransport").value=s.transport; $("#mcpEnabled").value=s.enabled?"1":"0"; $("#mcpCommand").value=s.command||""; $("#mcpUrl").value=s.url||""; $("#mcpArgs").value=s.args_json||"[]"; $("#mcpHeaders").value=s.headers_json||"{}"; $("#mcpEnv").value=s.env_json||"{}"; $("#mcpScope").value=s.scope||"all"; let nodes=[];try{nodes=JSON.parse(s.target_nodes_json||"[]")}catch(e){};$("#mcpNodes").querySelectorAll("input").forEach(x=>x.checked=nodes.includes(x.value));
} }
async function deleteMCP(id){if(!confirm(`确认删除 MCP 服务 [${id}]?`))return;try{await api("/mcp/service?id="+encodeURIComponent(id),{method:"DELETE"});await loadMCPServices()}catch(e){alert("删除失败: "+e.message)}} async function deleteMCP(id){if(!confirm(`确认删除 MCP 服务 [${id}]?`))return;try{await api("/mcp/service?id="+encodeURIComponent(id),{method:"DELETE"});await loadMCPServices()}catch(e){alert("删除失败: "+e.message)}}
$("#mcpNew").onclick=resetMCPForm; $("#mcpCancel").onclick=()=>$("#mcpEditor").hidden=true; $("#mcpNew").onclick=resetMCPForm; $("#mcpCancel").onclick=()=>$("#mcpEditor").hidden=true;
$("#mcpSave").onclick=async()=>{try{const scope=$("#mcpScope").value;const body={id:$("#mcpId").value.trim(),name:$("#mcpName").value.trim(),transport:$("#mcpTransport").value,command:$("#mcpCommand").value.trim(),url:$("#mcpUrl").value.trim(),scope,enabled:$("#mcpEnabled").value==="1",args:JSON.parse($("#mcpArgs").value||"[]"),headers:JSON.parse($("#mcpHeaders").value||"{}"),env:JSON.parse($("#mcpEnv").value||"{}"),target_nodes:[...$("#mcpNodes").querySelectorAll("input:checked")].map(x=>x.value)};if(!body.id||!body.name)throw Error("服务标识和显示名称不能为空");await api("/mcp/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});$("#mcpStatus").textContent="已保存并向在线节点同步。";await loadMCPServices()}catch(e){$("#mcpStatus").textContent="保存失败: "+e.message}}; $("#mcpSave").onclick=async()=>{
mcpClearErrors();
try{
const transport=$("#mcpTransport").value;
const body={id:$("#mcpId").value.trim(),name:$("#mcpName").value.trim(),transport,command:$("#mcpCommand").value.trim(),url:$("#mcpUrl").value.trim(),scope:$("#mcpScope").value,enabled:$("#mcpEnabled").value==="1",args:parseMCPField("mcpArgs","Arguments","数组"),headers:parseMCPField("mcpHeaders","Headers","对象"),env:parseMCPField("mcpEnv","环境变量","对象"),target_nodes:[...$("#mcpNodes").querySelectorAll("input:checked")].map(x=>x.value)};
if(!body.id){mcpFieldError("mcpId","服务标识不能为空。");return}
if(!body.name){mcpFieldError("mcpName","显示名称不能为空。");return}
if(transport==="stdio"&&!body.command){mcpFieldError("mcpCommand","stdio 模式必须填写 Command。");return}
if(transport!=="stdio"&&!body.url){mcpFieldError("mcpUrl","HTTP/SSE 模式必须填写 URL。");return}
await api("/mcp/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});
showMCPToast("MCP ["+body.id+"] 已保存并同步到在线节点");
$("#mcpEditor").hidden=true;
await loadMCPServices();
}catch(e){if(!$("#mcpStatus").textContent)$("#mcpStatus").textContent="保存失败: "+e.message}
};
$("#mcpTest").onclick=async()=>{
mcpClearErrors();
const result=$("#mcpTestResult"); result.hidden=false; result.className="mcp-test-result"; result.textContent="正在测试连通性…";
try{
const transport=$("#mcpTransport").value;
const service={id:$("#mcpId").value.trim(),name:$("#mcpName").value.trim(),transport,command:$("#mcpCommand").value.trim(),url:$("#mcpUrl").value.trim(),args:parseMCPField("mcpArgs","Arguments","数组"),headers:parseMCPField("mcpHeaders","Headers","对象"),env:parseMCPField("mcpEnv","环境变量","对象")};
if(transport==="stdio"&&!service.command){mcpFieldError("mcpCommand","stdio 模式必须填写 Command。");result.hidden=true;return}
if(transport!=="stdio"&&!service.url){mcpFieldError("mcpUrl","HTTP/SSE 模式必须填写 URL。");result.hidden=true;return}
let node=$("#mcpTestNode").value;
if(node==="auto"||!node){const ds=(await api("/devices")).filter(d=>d.status==="online");node=ds.find(d=>!d.is_local)?.name||"local"}
const x=await api("/mcp/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device:node,service})});
if(!x.success)throw Error((x.error&&x.error.message)||"连通失败");
result.className="mcp-test-result ok";
result.innerHTML="<strong>✓ 连通成功!</strong> "+esc(x.device)+" · "+esc(x.transport)+" · "+x.duration_ms+"ms · 检测到 "+x.tool_count+" 个可用工具";
if(x.tool_count){result.innerHTML+='<ul class="mcp-test-tools">'+x.tools.map(t=>"<li><code>"+esc(t.name||"")+"</code>"+(t.description?" — "+esc(t.description):"")+"</li>").join("")+"</ul>"}
}catch(e){
result.className="mcp-test-result fail";
result.innerHTML='<strong>✗ 连通失败</strong><div class="mcp-test-detail">'+esc(e.message)+"</div>";
}
};
$("#mcpTransport").onchange=()=>{const stdio=$("#mcpTransport").value==="stdio";$("#mcpCommand").parentElement.style.display=stdio?"":"none";$("#mcpArgs").parentElement.style.display=stdio?"":"none";$("#mcpUrl").parentElement.style.display=stdio?"none":""}; $("#mcpTransport").onchange=()=>{const stdio=$("#mcpTransport").value==="stdio";$("#mcpCommand").parentElement.style.display=stdio?"":"none";$("#mcpArgs").parentElement.style.display=stdio?"":"none";$("#mcpUrl").parentElement.style.display=stdio?"none":""};
loadMCPServices().catch(console.error); loadMCPServices().catch(console.error);
async function loadSecuritySettings(){const x=await api("/security/settings"),nodes=x.nodes||[],effective=x.effective||{},configured=new Map(nodes.map(n=>[n.node,n.mode])),devices=await api("/devices");$("#globalSecurity").value=x.global||"medium";$("#securityNodes").innerHTML=devices.map(d=>{const mode=configured.get(d.name)||"inherit",eff=effective[d.name]||x.global||"medium";return `<tr><td>${esc(d.name)}</td><td><select data-security-node="${esc(d.name)}"><option value="inherit" ${mode==='inherit'?'selected':''}>跟随全局</option><option value="low" ${mode==='low'?'selected':''}>低 · Low</option><option value="medium" ${mode==='medium'?'selected':''}>中 · Medium</option><option value="high" ${mode==='high'?'selected':''}>高 · High</option></select></td><td>${esc(eff)}</td><td><button type="button" onclick="saveNodeSecurity('${esc(d.name)}')">保存</button></td></tr>`}).join("")}
async function saveNodeSecurity(node){const el=document.querySelector(`[data-security-node="${CSS.escape(node)}"]`);if(!el)return;try{await api("/security/settings/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({node,mode:el.value})});$("#securityStatus").textContent=`${node} 策略已保存。`;await loadSecuritySettings()}catch(e){$("#securityStatus").textContent="保存失败: "+e.message}}
$("#saveGlobalSecurity").onclick=async()=>{try{await api("/security/settings/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({global:$("#globalSecurity").value})});$("#securityStatus").textContent="全局安全策略已保存。";await loadSecuritySettings()}catch(e){$("#securityStatus").textContent="保存失败: "+e.message}};$("#securityRefresh").onclick=()=>loadSecuritySettings().catch(console.error);loadSecuritySettings().catch(console.error);
let webhookEditingId = "";
async function loadWebhooks() {
const list = await api("/notifications/webhooks");
const el = $("#webhookList");
if (!el) return;
if (!list || list.length === 0) {
el.innerHTML = '<div class="mcp-meta">暂无 Webhook 配置。</div>';
return;
}
el.innerHTML = list.map(x => `
<div class="mcp-item">
<h3>${esc(x.name)} <small>${esc(x.id)}</small></h3>
<div class="mcp-meta">
${esc(x.type)} · ${x.enabled ? '<span style="color:var(--dot-online)">启用</span>' : '<span style="color:var(--text-muted)">停用</span>'}<br>
<code>${esc(x.url)}</code>
</div>
<div class="mcp-actions">
<button type="button" onclick="editWebhook('${esc(x.id)}')">编辑</button>
<button type="button" onclick="deleteWebhook('${esc(x.id)}')">删除</button>
</div>
</div>
`).join("");
}
function resetWebhookForm() {
webhookEditingId = "";
const editor = $("#webhookEditor");
if (!editor) return;
editor.hidden = false;
$("#webhookId").disabled = false;
$("#webhookId").value = "";
$("#webhookName").value = "";
$("#webhookType").value = "wecom";
$("#webhookEnabled").value = "1";
$("#webhookUrl").value = "";
$("#webhookConfig").value = "{}";
$("#webhookStatus").textContent = "";
}
async function editWebhook(id) {
const list = await api("/notifications/webhooks");
const item = list.find(x => x.id === id);
if (!item) return;
resetWebhookForm();
webhookEditingId = id;
$("#webhookId").value = item.id;
$("#webhookId").disabled = true;
$("#webhookName").value = item.name || "";
$("#webhookType").value = item.type || "wecom";
$("#webhookEnabled").value = item.enabled ? "1" : "0";
$("#webhookUrl").value = item.url || "";
$("#webhookConfig").value = item.config_json || "{}";
}
async function deleteWebhook(id) {
if (!confirm(`确认删除 Webhook [${id}]?`)) return;
try {
await api("/notifications/webhook/delete?id=" + encodeURIComponent(id), { method: "DELETE" });
await loadWebhooks();
} catch (e) {
alert("删除失败: " + e.message);
}
}
if ($("#webhookNew")) $("#webhookNew").onclick = resetWebhookForm;
if ($("#webhookCancel")) $("#webhookCancel").onclick = () => {
const editor = $("#webhookEditor");
if (editor) editor.hidden = true;
};
if ($("#webhookSave")) $("#webhookSave").onclick = async () => {
try {
const id = $("#webhookId").value.trim();
const name = $("#webhookName").value.trim();
const url = $("#webhookUrl").value.trim();
if (!id) throw Error("标识 (ID) 不能为空");
if (!name) throw Error("名称不能为空");
if (!url) throw Error("Webhook URL 不能为空");
let cfg = {};
try {
cfg = JSON.parse($("#webhookConfig").value || "{}");
} catch (e) {
throw Error("配置 JSON 格式不正确");
}
const body = {
id: id,
name: name,
type: $("#webhookType").value,
url: url,
config_json: JSON.stringify(cfg),
enabled: $("#webhookEnabled").value === "1"
};
await api("/notifications/webhook/update", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
$("#webhookStatus").textContent = "Webhook [" + id + "] 已保存。";
const editor = $("#webhookEditor");
if (editor) editor.hidden = true;
await loadWebhooks();
} catch (e) {
$("#webhookStatus").textContent = "保存失败: " + e.message;
}
};
if ($("#webhookTest")) $("#webhookTest").onclick = async () => {
try {
const id = $("#webhookId").value.trim();
const name = $("#webhookName").value.trim();
const url = $("#webhookUrl").value.trim();
if (!url) throw Error("Webhook URL 不能为空");
let cfg = {};
try {
cfg = JSON.parse($("#webhookConfig").value || "{}");
} catch (e) {
throw Error("配置 JSON 格式不正确");
}
const body = {
id: id || "test",
name: name || "测试目标",
type: $("#webhookType").value,
url: url,
config_json: JSON.stringify(cfg),
enabled: true
};
$("#webhookStatus").textContent = "正在发送测试消息...";
await api("/notifications/webhook/test", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
$("#webhookStatus").textContent = "✓ 测试消息发送成功!";
} catch (e) {
$("#webhookStatus").textContent = "✗ 测试失败: " + e.message;
}
};
if ($("#notificationRefresh")) $("#notificationRefresh").onclick = () => loadWebhooks().catch(console.error);
// 开启 5 秒平滑实时自动轮询
let devicePollTimer = null;
function startDevicePolling() {
if (devicePollTimer) clearInterval(devicePollTimer);
devicePollTimer = setInterval(() => {
if (!document.hidden) {
loadDevices().catch(console.error);
}
}, 5000);
}
startDevicePolling();
document.addEventListener("visibilitychange", () => {
if (!document.hidden) {
loadDevices().catch(console.error);
}
});
loadWebhooks().catch(console.error);
// 开启 5 秒平滑实时自动轮询
let devicePollTimer = null;
function startDevicePolling() {
if (devicePollTimer) clearInterval(devicePollTimer);
devicePollTimer = setInterval(() => {
if (!document.hidden) {
loadDevices().catch(console.error);
}
}, 5000);
}
startDevicePolling();
document.addEventListener("visibilitychange", () => {
if (!document.hidden) {
loadDevices().catch(console.error);
}
});
+38 -2
View File
@@ -1,2 +1,38 @@
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander</title><link rel="stylesheet" href="/static/app.css"></head><body><header><div class="brand-wrap"><img src="/static/icon.png" alt="logo" class="brand-logo"><div><strong>VPS-Commander</strong><span>Private Infrastructure Console</span></div></div><div class="header-actions"><button id="themeToggle" type="button" class="btn-icon" title="切换主题" aria-label="切换主题"><svg class="theme-svg svg-sun" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg><svg class="theme-svg svg-moon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></button><button id="logout" type="button">退出</button></div></header><main><section class="grid"><article class="card wide"><div class="cardhead"><h2>设备看板</h2><button id="refresh" type="button">刷新</button></div><div id="devices" class="devices"></div></article><article class="card"><h2>Actions 向导</h2><p>当前 Hub 的 OpenAPI Schema:</p><div class="actions"><button id="copySchema" type="button">复制 Schema 地址</button><button id="copyPrompt" type="button">复制 System Prompt</button><button id="rotateKey" type="button">轮换 API Key</button></div><pre id="schemaHint">/openapi.json</pre><pre id="newKey"></pre></article><article class="card wide"><div class="mcp-toolbar"><h2>MCP 挂载</h2><button id="mcpNew" type="button">新增 MCP</button></div><div id="mcpList" class="mcp-grid"></div><div id="mcpEditor" hidden><div class="mcp-form"><label>服务标识<input id="mcpId" placeholder="docker"></label><label>显示名称<input id="mcpName" placeholder="Docker 容器管理"></label><label>传输类型<select id="mcpTransport"><option value="stdio">命令行 / stdio</option><option value="http">HTTP / Streamable HTTP</option><option value="sse">SSE</option></select></label><label>启用<select id="mcpEnabled"><option value="1">启用</option><option value="0">停用</option></select></label><label class="full">Command<input id="mcpCommand" placeholder="docker-mcp"></label><label class="full">Arguments(JSON 数组)<textarea id="mcpArgs">[]</textarea></label><label class="full">URL<input id="mcpUrl" placeholder="http://127.0.0.1:8080/mcp"></label><label class="full">Headers(JSON 对象,可选)<textarea id="mcpHeaders">{}</textarea></label><label class="full">环境变量(JSON 对象,可选)<textarea id="mcpEnv">{}</textarea></label><label>生效范围<select id="mcpScope"><option value="all">全部节点</option><option value="custom">指定节点</option></select></label><div><span>指定节点</span><div id="mcpNodes" class="mcp-nodes"></div></div></div><div class="mcp-actions"><button id="mcpSave" type="button">保存并热更新</button><button id="mcpCancel" type="button">取消</button></div><div id="mcpStatus" class="mcp-status"></div></div></article> <!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander</title><link rel="stylesheet" href="/static/app.css"></head><body><header><div class="brand-wrap"><img src="/static/icon.png" alt="logo" class="brand-logo"><div><strong>VPS-Commander</strong><span>Private Infrastructure Console</span></div></div><div class="header-actions"><button id="themeToggle" type="button" class="btn-icon" title="切换主题" aria-label="切换主题"><svg class="theme-svg svg-sun" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg><svg class="theme-svg svg-moon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></button><button id="logout" type="button">退出</button></div></header><main><section class="grid"><article class="card wide"><div class="cardhead"><h2>设备看板</h2><button id="refresh" type="button">刷新</button></div><div id="devices" class="devices"></div></article><article class="card"><h2>Actions 向导</h2><p>当前 Hub 的 OpenAPI Schema:</p><div class="actions"><button id="copySchema" type="button">复制 Schema 地址</button><button id="copyPrompt" type="button">复制 System Prompt</button><button id="rotateKey" type="button">轮换 API Key</button></div><pre id="schemaHint">/openapi.json</pre><pre id="newKey"></pre></article><article class="card wide"><div class="mcp-toolbar"><h2>MCP</h2><button id="mcpNew" type="button">新增 MCP</button></div><div id="mcpList" class="mcp-grid"></div><div id="mcpEditor" hidden><div class="mcp-form"><label>服务标识<input id="mcpId" placeholder="docker"></label><label>显示名称<input id="mcpName" placeholder="Docker 容器管理"></label><label>传输类型<select id="mcpTransport"><option value="stdio">命令行 / stdio</option><option value="http">HTTP / Streamable HTTP</option><option value="sse">SSE</option></select></label><label>启用<select id="mcpEnabled"><option value="1">启用</option><option value="0">停用</option></select></label><label class="full">Command<input id="mcpCommand" placeholder="docker-mcp"></label><label class="full">Arguments(JSON 数组)<textarea id="mcpArgs">[]</textarea></label><label class="full">URL<input id="mcpUrl" placeholder="http://127.0.0.1:8080/mcp"></label><label class="full">Headers(JSON 对象,可选)<textarea id="mcpHeaders">{}</textarea></label><label class="full">环境变量(JSON 对象,可选)<textarea id="mcpEnv">{}</textarea></label><label>生效范围<select id="mcpScope"><option value="all">全部节点</option><option value="custom">指定节点</option></select></label><div><span>指定节点</span><div id="mcpNodes" class="mcp-nodes"></div></div><label>测试节点<select id="mcpTestNode"><option value="local">Hub 本机</option></select></label></div><div class="mcp-actions"><button id="mcpSave" type="button">保存并热更新</button><button id="mcpTest" type="button">测试连通性</button><button id="mcpCancel" type="button">取消</button></div><div id="mcpStatus" class="mcp-status"></div><div id="mcpTestResult" class="mcp-test-result" hidden></div></div></article>
<article class="card wide"><div class="cardhead"><h2>快速控制台</h2><select id="device"></select></div><textarea id="command" placeholder="输入 Shell 命令,例如 uname -a"></textarea><div><button id="run" type="button">执行</button></div><pre id="output"></pre></article><article class="card wide"><div class="cardhead"><h2>审计日志</h2><button id="auditRefresh" type="button">刷新</button></div><div class="tablewrap"><table><thead><tr><th>时间</th><th>设备</th><th>动作</th><th>命令/路径</th><th>退出码</th><th>耗时</th><th>来源</th></tr></thead><tbody id="audits"></tbody></table></div></article></section></main><script src="/static/app.js"></script></body></html> <article class="card wide"><div class="cardhead"><h2>快速控制台</h2><select id="device"></select></div><textarea id="command" placeholder="输入 Shell 命令,例如 uname -a"></textarea><div><button id="run" type="button">执行</button></div><pre id="output"></pre></article><article class="card wide"><div class="cardhead"><h2>安全</h2><button id="securityRefresh" type="button">刷新</button></div><div class="security-grid"><label>全局安全等级<select id="globalSecurity"><option value="low">低 · Low</option><option value="medium">中 · Medium</option><option value="high">高 · High</option></select></label><button id="saveGlobalSecurity" type="button">保存全局策略</button></div><div class="tablewrap"><table><thead><tr><th>节点</th><th>单机策略</th><th>有效策略</th><th>操作</th></tr></thead><tbody id="securityNodes"></tbody></table></div><p id="securityStatus"></p></article><article class="card wide">
<div class="mcp-toolbar">
<h2>通知</h2>
<div style="display:flex;gap:8px">
<button id="webhookNew" type="button">新增 Webhook</button>
<button id="notificationRefresh" type="button">刷新</button>
</div>
</div>
<div id="webhookList" class="mcp-grid"></div>
<div id="webhookEditor" hidden style="margin-top:14px;border-top:1px solid var(--border);padding-top:14px">
<div class="mcp-form">
<label>标识 (ID)<input id="webhookId" placeholder="如 openclaw-wecom"></label>
<label>名称<input id="webhookName" placeholder="如 运维告警群"></label>
<label>类型
<select id="webhookType">
<option value="wecom">企业微信 (WeCom)</option>
<option value="telegram">Telegram</option>
<option value="generic">通用 JSON Webhook</option>
</select>
</label>
<label>状态
<select id="webhookEnabled">
<option value="1">启用</option>
<option value="0">停用</option>
</select>
</label>
<label class="full">Webhook URL<input id="webhookUrl" placeholder="https://qyapi.weixin.qq.com/..."></label>
<label class="full">配置 JSON (Telegram 需填 {"chat_id":"-100..."})<textarea id="webhookConfig">{}</textarea></label>
</div>
<div class="mcp-actions">
<button id="webhookSave" type="button">保存 Webhook</button>
<button id="webhookTest" type="button">测试连通性</button>
<button id="webhookCancel" type="button">取消</button>
</div>
<div id="webhookStatus" class="mcp-status"></div>
</div>
</article><article class="card wide"><div class="cardhead"><h2>日志</h2><button id="auditRefresh" type="button">刷新</button></div><div class="tablewrap"><table><thead><tr><th>时间</th><th>设备</th><th>动作</th><th>命令/路径</th><th>退出码</th><th>耗时</th><th>来源</th></tr></thead><tbody id="audits"></tbody></table></div></article></section></main><script src="/static/app.js"></script></body></html>
+1 -1
View File
@@ -1 +1 @@
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander Login</title><link rel="stylesheet" href="/static/app.css"></head><body class="login"><form id="login"><h1>VPS-Commander</h1><p>Private Infrastructure Console</p><input id="password" type="password" placeholder="面板密码" autocomplete="current-password"><button type="submit">登录</button><div id="error"></div></form><script>document.querySelector("#login").onsubmit=async e=>{e.preventDefault();let r=await fetch("/panel/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:document.querySelector("#password").value})});if(r.ok)location.href="/";else document.querySelector("#error").textContent="密码错误或未配置面板密码"};</script></body></html> <!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander Login</title><link rel="stylesheet" href="/static/app.css"></head><body class="login"><form id="login"><h1>VPS-Commander</h1><p>Private Infrastructure Console</p><input id="password" type="password" placeholder="面板密码" autocomplete="current-password"><button type="submit">登录</button><div id="error"></div></form><script>document.querySelector("#login").onsubmit=async e=>{e.preventDefault();let r=await fetch("/panel/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:document.querySelector("#password").value})});if(r.ok)location.href="/panel";else document.querySelector("#error").textContent="密码错误或未配置面板密码"};</script></body></html>
+506
View File
@@ -0,0 +1,506 @@
:root {
--bg-main: #0c0e14;
--bg-card: rgba(22, 27, 34, 0.7);
--bg-card-hover: rgba(28, 35, 45, 0.85);
--border: rgba(255, 255, 255, 0.08);
--border-hover: rgba(255, 255, 255, 0.16);
--text-main: #f0f6fc;
--text-muted: #8b949e;
--text-dim: #6e7681;
--accent: #58a6ff;
--online: #3fb950;
--online-bg: rgba(63, 185, 80, 0.12);
--offline: #f85149;
--offline-bg: rgba(248, 81, 73, 0.12);
--warn: #d29922;
--warn-bg: rgba(210, 153, 34, 0.12);
--font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace;
--radius-lg: 14px;
--radius-md: 8px;
--radius-sm: 6px;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: var(--bg-main);
background-image:
radial-gradient(at 15% 15%, rgba(56, 139, 253, 0.05) 0px, transparent 50%),
radial-gradient(at 85% 85%, rgba(63, 185, 80, 0.04) 0px, transparent 50%);
background-attachment: fixed;
color: var(--text-main);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
font-size: 14px;
line-height: 1.5;
min-height: 100vh;
-webkit-font-smoothing: antialiased;
}
.layout {
max-width: 1440px;
margin: 0 auto;
padding: 24px 20px 40px;
display: flex;
flex-direction: column;
min-height: 100vh;
}
/* 导航栏 */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
flex-wrap: wrap;
gap: 16px;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.logo-dot {
width: 14px;
height: 14px;
background: linear-gradient(135deg, #58a6ff, #1f6feb);
border-radius: 4px;
box-shadow: 0 0 12px rgba(88, 166, 255, 0.5);
}
.brand-text h1 {
font-size: 20px;
font-weight: 700;
letter-spacing: -0.02em;
color: #fff;
display: inline-block;
margin-right: 8px;
}
.brand-text .sub {
font-size: 13px;
color: var(--text-muted);
}
.controls {
display: flex;
align-items: center;
gap: 12px;
}
.summary-badge {
display: flex;
align-items: center;
gap: 8px;
background: rgba(255, 255, 255, 0.04);
border: 1px solid var(--border);
padding: 5px 12px;
border-radius: 20px;
font-size: 12px;
color: var(--text-muted);
}
.dot-online {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--online);
box-shadow: 0 0 8px rgba(63, 185, 80, 0.6);
animation: pulse 2.5s infinite;
}
@keyframes pulse {
0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(63, 185, 80, 0.7); }
70% { transform: scale(1); box-shadow: 0 0 0 6px rgba(63, 185, 80, 0); }
100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(63, 185, 80, 0); }
}
.view-switch {
display: flex;
background: rgba(22, 27, 34, 0.8);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: 3px;
gap: 2px;
}
.view-switch .btn {
display: flex;
align-items: center;
gap: 6px;
background: transparent;
border: none;
color: var(--text-muted);
padding: 5px 12px;
border-radius: var(--radius-sm);
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: all 0.15s ease;
}
.view-switch .btn:hover {
color: var(--text-main);
}
.view-switch .btn.active {
background: rgba(255, 255, 255, 0.1);
color: #fff;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}
/* 卡片视图 */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(330px, 1fr));
gap: 16px;
}
.node-card {
background: var(--bg-card);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 18px;
display: flex;
flex-direction: column;
gap: 16px;
transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}
.node-card:hover {
border-color: var(--border-hover);
background: var(--bg-card-hover);
transform: translateY(-2px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
}
.card-top {
display: flex;
justify-content: space-between;
align-items: flex-start;
}
.node-title {
display: flex;
flex-direction: column;
gap: 4px;
}
.node-name-wrap {
display: flex;
align-items: center;
gap: 8px;
}
.node-name {
font-size: 16px;
font-weight: 700;
color: #fff;
letter-spacing: -0.01em;
}
.local-badge {
font-size: 10px;
padding: 1px 6px;
border-radius: 4px;
background: rgba(88, 166, 255, 0.15);
color: var(--accent);
border: 1px solid rgba(88, 166, 255, 0.25);
font-weight: 600;
}
.node-meta {
font-size: 12px;
color: var(--text-dim);
display: flex;
align-items: center;
gap: 8px;
}
.meta-pill {
background: rgba(255, 255, 255, 0.04);
padding: 2px 6px;
border-radius: 4px;
}
.status-badge {
font-size: 11px;
font-weight: 600;
padding: 3px 8px;
border-radius: 12px;
display: flex;
align-items: center;
gap: 5px;
}
.status-badge.online {
background: var(--online-bg);
color: var(--online);
border: 1px solid rgba(63, 185, 80, 0.2);
}
.status-badge.offline {
background: var(--offline-bg);
color: var(--offline);
border: 1px solid rgba(248, 81, 73, 0.2);
}
.status-badge .dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
/* 进度条指标区域 */
.metrics-bars {
display: flex;
flex-direction: column;
gap: 12px;
}
.metric-item {
display: flex;
flex-direction: column;
gap: 4px;
}
.metric-header {
display: flex;
justify-content: space-between;
font-size: 12px;
}
.metric-label {
color: var(--text-muted);
font-weight: 500;
}
.metric-value {
color: var(--text-main);
font-family: var(--font-mono);
font-weight: 600;
}
.progress-track {
height: 6px;
background: rgba(255, 255, 255, 0.06);
border-radius: 3px;
overflow: hidden;
position: relative;
}
.progress-fill {
height: 100%;
border-radius: 3px;
transition: width 0.4s ease, background 0.3s ease;
}
.progress-fill.normal {
background: linear-gradient(90deg, #238636, #3fb950);
}
.progress-fill.warn {
background: linear-gradient(90deg, #9e6a03, #d29922);
}
.progress-fill.danger {
background: linear-gradient(90deg, #da3633, #f85149);
}
/* 统计卡片底部小部件 */
.card-stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
background: rgba(0, 0, 0, 0.2);
border-radius: var(--radius-md);
padding: 10px;
border: 1px solid rgba(255, 255, 255, 0.03);
}
.stat-box {
display: flex;
flex-direction: column;
gap: 2px;
}
.stat-title {
font-size: 11px;
color: var(--text-dim);
}
.stat-desc {
font-size: 12px;
color: var(--text-muted);
font-family: var(--font-mono);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.stat-desc b {
color: var(--text-main);
font-weight: 500;
}
.traffic-in { color: #58a6ff !important; }
.traffic-out { color: #bc8cff !important; }
/* 表格视图 */
.table-wrapper {
background: var(--bg-card);
backdrop-filter: blur(12px);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
overflow-x: auto;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}
.probe-table {
width: 100%;
min-width: 960px;
border-collapse: collapse;
text-align: left;
}
.probe-table th {
background: rgba(0, 0, 0, 0.25);
padding: 12px 16px;
font-size: 12px;
font-weight: 600;
color: var(--text-muted);
border-bottom: 1px solid var(--border);
white-space: nowrap;
}
.probe-table td {
padding: 14px 16px;
border-bottom: 1px solid rgba(255, 255, 255, 0.04);
font-size: 13px;
vertical-align: middle;
}
.probe-table tr:last-child td {
border-bottom: none;
}
.probe-table tr:hover td {
background: rgba(255, 255, 255, 0.02);
}
.col-mono {
font-family: var(--font-mono);
font-size: 12px;
}
.mini-bar-wrap {
display: flex;
align-items: center;
gap: 8px;
min-width: 110px;
}
.mini-bar {
flex: 1;
height: 5px;
background: rgba(255, 255, 255, 0.08);
border-radius: 3px;
overflow: hidden;
}
.mini-bar-fill {
height: 100%;
border-radius: 3px;
}
.table-node {
display: flex;
flex-direction: column;
}
.table-node .name {
font-weight: 600;
color: #fff;
}
.table-node .sub {
font-size: 11px;
color: var(--text-dim);
}
/* 页脚 */
.footer {
margin-top: auto;
padding-top: 36px;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 12px;
color: var(--text-dim);
border-top: 1px solid var(--border);
}
.update-time {
font-family: var(--font-mono);
}
/* 错误提示 */
.error-msg {
text-align: center;
padding: 40px;
color: var(--offline);
background: var(--bg-card);
border: 1px dashed rgba(248, 81, 73, 0.3);
border-radius: var(--radius-lg);
}
/* 响应式调整 (Mobile) */
@media (max-width: 768px) {
.layout {
padding: 16px 12px 28px;
}
.navbar {
margin-bottom: 16px;
}
.brand-text h1 {
font-size: 18px;
}
.controls {
width: 100%;
justify-content: space-between;
}
.card-grid {
grid-template-columns: 1fr;
gap: 12px;
}
.node-card {
padding: 14px;
gap: 12px;
}
.card-stats-grid {
grid-template-columns: 1fr;
gap: 6px;
}
.footer {
flex-direction: column;
gap: 8px;
text-align: center;
padding-top: 24px;
}
}
+46
View File
@@ -0,0 +1,46 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>VPS Probe - 节点监控探针</title>
<link rel="stylesheet" href="/static/probe.css?v=20260929">
</head>
<body>
<div class="layout">
<header class="navbar">
<div class="brand">
<div class="logo-dot"></div>
<div class="brand-text">
<h1>VPS Probe</h1>
<span class="sub">服务器集群实时监控</span>
</div>
</div>
<div class="controls">
<div class="summary-badge" id="clusterSummary">
<span class="dot-online"></span>
<span id="summaryText">检测中...</span>
</div>
<div class="view-switch">
<button id="cardBtn" class="btn active" title="卡片视图">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>
卡片
</button>
<button id="compactBtn" class="btn" title="表格视图">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
表格
</button>
</div>
</div>
</header>
<main id="content" class="card-view"></main>
<footer class="footer">
<span>VPS-Commander Cluster Monitor</span>
<span id="lastUpdated" class="update-time">自动刷新中...</span>
</footer>
</div>
<script src="/static/probe.js?v=20260929"></script>
</body>
</html>
+289
View File
@@ -0,0 +1,289 @@
(() => {
const root = document.querySelector('#content');
const summaryEl = document.querySelector('#summaryText');
const lastUpdatedEl = document.querySelector('#lastUpdated');
const fmtBytes = n => {
if (!Number.isFinite(n) || n <= 0) return '0 B';
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0, v = n;
while (v >= 1024 && i < u.length - 1) {
v /= 1024;
i++;
}
return `${v.toFixed(i === 0 ? 0 : 1)} ${u[i]}`;
};
const fmtRate = n => `${fmtBytes(n)}/s`;
const fmtUp = n => {
let s = Math.max(0, Math.floor(n || 0));
if (s <= 0) return '--';
const d = Math.floor(s / 86400);
s %= 86400;
const h = Math.floor(s / 3600);
s %= 3600;
const m = Math.floor(s / 60);
if (d > 0) return `${d}天 ${h}时`;
if (h > 0) return `${h}小时 ${m}分`;
return `${m} 分钟`;
};
const esc = s => String(s ?? '-').replace(/[&<>"']/g, c => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
}[c]));
const getFlag = (cc, country) => {
if (!cc || typeof cc !== 'string' || cc.length !== 2) return '';
const code = cc.toUpperCase();
const flag = String.fromCodePoint(...[...code].map(c => 0x1F1E6 - 65 + c.charCodeAt(0)));
const title = country ? `${country} (${code})` : code;
return `<span class="flag-icon" title="${esc(title)}">${flag}</span>`;
};
const getStatusLevel = pct => {
const val = Number(pct || 0);
if (val >= 85) return 'danger';
if (val >= 65) return 'warn';
return 'normal';
};
let mode = localStorage.getItem('vpc_probe_view') || 'card';
const setMode = m => {
mode = m;
localStorage.setItem('vpc_probe_view', m);
render(window.__data || []);
};
document.querySelector('#cardBtn').onclick = () => setMode('card');
document.querySelector('#compactBtn').onclick = () => setMode('compact');
const renderCard = d => {
const p = d.profile || {};
const isOnline = d.status === 'online';
const cpuPct = p.cpu_usage_percent != null ? Number(p.cpu_usage_percent) : 0;
const memPct = p.mem_percent != null ? Number(p.mem_percent) : 0;
const diskPct = p.disk_percent != null ? Number(p.disk_percent) : 0;
const loadStr = [p.load_1m, p.load_5m, p.load_15m].map(x => Number(x || 0).toFixed(2)).join(', ');
return `
<div class="node-card">
<div class="card-top">
<div class="node-title">
<div class="node-name-wrap">
${getFlag(d.country_code, d.country)}
<span class="node-name">${esc(d.name)}</span>
${d.is_local ? '<span class="local-badge">本机</span>' : ''}
</div>
<div class="node-meta">
<span class="meta-pill">${p.cpu_cores || 1} 核</span>
<span class="meta-pill">${esc(d.os || 'Linux')}</span>
<span>${fmtUp(p.uptime_seconds)}</span>
</div>
</div>
<div class="status-badge ${isOnline ? 'online' : 'offline'}">
<span class="dot"></span>
${isOnline ? '在线' : '离线'}
</div>
</div>
<div class="metrics-bars">
<div class="metric-item">
<div class="metric-header">
<span class="metric-label">CPU 负载</span>
<span class="metric-value">${p.cpu_usage_percent != null ? `${cpuPct}%` : '--'}</span>
</div>
<div class="progress-track">
<div class="progress-fill ${getStatusLevel(cpuPct)}" style="width: ${Math.min(100, Math.max(0, cpuPct))}%"></div>
</div>
</div>
<div class="metric-item">
<div class="metric-header">
<span class="metric-label">内存 (空闲 ${esc(p.mem_available || '--')})</span>
<span class="metric-value">${p.mem_percent != null ? `${memPct}%` : '--'}</span>
</div>
<div class="progress-track">
<div class="progress-fill ${getStatusLevel(memPct)}" style="width: ${Math.min(100, Math.max(0, memPct))}%"></div>
</div>
</div>
<div class="metric-item">
<div class="metric-header">
<span class="metric-label">磁盘 (空闲 ${esc(p.disk_free || '--')})</span>
<span class="metric-value">${p.disk_percent != null ? `${diskPct}%` : '--'}</span>
</div>
<div class="progress-track">
<div class="progress-fill ${getStatusLevel(diskPct)}" style="width: ${Math.min(100, Math.max(0, diskPct))}%"></div>
</div>
</div>
</div>
<div class="card-stats-grid">
<div class="stat-box">
<span class="stat-title">实时网络 (↓ / ↑)</span>
<span class="stat-desc">
<b class="traffic-in">↓ ${fmtRate(p.net_rx_rate)}</b> /
<b class="traffic-out">↑ ${fmtRate(p.net_tx_rate)}</b>
</span>
</div>
<div class="stat-box">
<span class="stat-title">总流量 (↓ / ↑)</span>
<span class="stat-desc">
↓ ${fmtBytes(p.net_rx_total)} / ↑ ${fmtBytes(p.net_tx_total)}
</span>
</div>
<div class="stat-box">
<span class="stat-title">系统平均负载 (1/5/15m)</span>
<span class="stat-desc">${loadStr}</span>
</div>
<div class="stat-box">
<span class="stat-title">IO PSI / Docker</span>
<span class="stat-desc">${p.io_psi != null ? Number(p.io_psi).toFixed(2) : '0.00'} / ${p.docker ? '有' : '无'}</span>
</div>
</div>
</div>
`;
};
const renderTable = list => {
const rows = list.map(d => {
const p = d.profile || {};
const isOnline = d.status === 'online';
const cpuPct = p.cpu_usage_percent != null ? Number(p.cpu_usage_percent) : 0;
const memPct = p.mem_percent != null ? Number(p.mem_percent) : 0;
const diskPct = p.disk_percent != null ? Number(p.disk_percent) : 0;
const loadStr = [p.load_1m, p.load_5m, p.load_15m].map(x => Number(x || 0).toFixed(2)).join(' / ');
return `
<tr>
<td>
<div class="table-node">
<span class="name">
${getFlag(d.country_code, d.country)}
${esc(d.name)}
${d.is_local ? '<span class="local-badge">本机</span>' : ''}
</span>
<span class="sub">${p.cpu_cores || 1}核 | ${esc(d.os || 'Linux')}</span>
</div>
</td>
<td>
<span class="status-badge ${isOnline ? 'online' : 'offline'}">
<span class="dot"></span>
${isOnline ? '在线' : '离线'}
</span>
</td>
<td class="col-mono">${fmtUp(p.uptime_seconds)}</td>
<td class="col-mono">${loadStr}</td>
<td>
<div class="mini-bar-wrap">
<div class="mini-bar">
<div class="mini-bar-fill progress-fill ${getStatusLevel(cpuPct)}" style="width: ${Math.min(100, Math.max(0, cpuPct))}%"></div>
</div>
<span class="col-mono">${p.cpu_usage_percent != null ? `${cpuPct}%` : '--'}</span>
</div>
</td>
<td>
<div class="mini-bar-wrap">
<div class="mini-bar">
<div class="mini-bar-fill progress-fill ${getStatusLevel(memPct)}" style="width: ${Math.min(100, Math.max(0, memPct))}%"></div>
</div>
<span class="col-mono">${p.mem_percent != null ? `${memPct}%` : '--'}</span>
</div>
</td>
<td class="col-mono">
<span class="traffic-in">↓ ${fmtRate(p.net_rx_rate)}</span><br>
<span class="traffic-out">↑ ${fmtRate(p.net_tx_rate)}</span>
</td>
<td class="col-mono">
↓ ${fmtBytes(p.net_rx_total)}<br>
↑ ${fmtBytes(p.net_tx_total)}
</td>
<td>
<div class="mini-bar-wrap">
<div class="mini-bar">
<div class="mini-bar-fill progress-fill ${getStatusLevel(diskPct)}" style="width: ${Math.min(100, Math.max(0, diskPct))}%"></div>
</div>
<span class="col-mono">${p.disk_percent != null ? `${diskPct}%` : '--'}</span>
</div>
</td>
</tr>
`;
}).join('');
return `
<div class="table-wrapper">
<table class="probe-table">
<thead>
<tr>
<th>节点名称</th>
<th>状态</th>
<th>运行时间</th>
<th>负载 (1/5/15m)</th>
<th>CPU</th>
<th>内存</th>
<th>实时网速</th>
<th>累计流量</th>
<th>磁盘</th>
</tr>
</thead>
<tbody>
${rows}
</tbody>
</table>
</div>
`;
};
function render(data) {
document.querySelector('#cardBtn').classList.toggle('active', mode === 'card');
document.querySelector('#compactBtn').classList.toggle('active', mode === 'compact');
const total = data.length;
const onlineCount = data.filter(x => x.status === 'online').length;
if (summaryEl) {
summaryEl.textContent = `${onlineCount} / ${total} 节点在线`;
}
if (!data || data.length === 0) {
root.innerHTML = '<div class="error-msg">暂无节点数据</div>';
return;
}
if (mode === 'card') {
root.className = 'card-view';
root.innerHTML = `<div class="card-grid">${data.map(renderCard).join('')}</div>`;
} else {
root.className = 'table-view';
root.innerHTML = renderTable(data);
}
}
async function load() {
try {
const r = await fetch('/probe/summary', { cache: 'no-store' });
if (!r.ok) throw Error();
let rawData = await r.json();
if (Array.isArray(rawData)) {
rawData.sort((a, b) => {
if (a.is_local && !b.is_local) return -1;
if (!a.is_local && b.is_local) return 1;
return String(a.name || "").localeCompare(String(b.name || ""));
});
}
window.__data = rawData;
render(window.__data);
if (lastUpdatedEl) {
const now = new Date();
const timeStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
lastUpdatedEl.textContent = `更新于 ${timeStr}`;
}
} catch (e) {
root.innerHTML = '<div class="error-msg">探针数据暂时不可用,正在重试...</div>';
}
}
load();
setInterval(load, 5000);
})();